Example #1
0
 def setTitle(self, title):
     """
     Allows one to set the title as a string
     """
     if toUnicode(title) != toUnicode(self._title):
         self._title = title
         self.package.isChanged = True
Example #2
0
 def _loadPackage(self, client, filename, newLoad=True,
                  destinationPackage=None):
     """Load the package named 'filename'"""
     try:
         encoding = sys.getfilesystemencoding()
         if encoding is None:
             encoding = 'utf-8'
         filename2 = toUnicode(filename, encoding)
         log.debug("filename and path" + filename2)
         # see if the file exists AND is readable by the user
         try:
             open(filename2, 'rb').close()
         except IOError:
             filename2 = toUnicode(filename, 'utf-8')
             try:
                 open(filename2, 'rb').close()
             except IOError:
                 client.alert(_(u'File %s does not exist or is not readable.') % filename2)
                 return None
         package = Package.load(filename2, newLoad, destinationPackage)
         if package is None:
             raise Exception(_("Couldn't load file, please email file to [email protected]"))
     except Exception, exc:
         if log.getEffectiveLevel() == logging.DEBUG:
             client.alert(_(u'Sorry, wrong file format:\n%s') % unicode(exc))
         else:
             client.alert(_(u'Sorry, wrong file format'))
         log.error(u'Error loading package "%s": %s' % (filename2, unicode(exc)))
         log.error(u'Traceback:\n%s' % traceback.format_exc())
         raise
Example #3
0
 def setTitle(self, title):
     """
     Allows one to set the title as a string
     """
     if toUnicode(title) != toUnicode(self._title):
         self._title = title
         self.package.isChanged = True
Example #4
0
 def getTitle(self):
     """
     Returns our title as a string
     """
     if self._title:
         return toUnicode(self._title)
     else:
         return _(toUnicode(self.package.levelName(self.level - 1)))
Example #5
0
 def upgradeToVersion4(self):
     """
     Puts properties in their place
     Also called to upgrade from 0.8 release
     """
     self._name = toUnicode(self.__dict__['name'])
     self._author = toUnicode(self.__dict__['author'])
     self._description = toUnicode(self.__dict__['description'])
 def upgradeToVersion4(self):
     """
     Puts properties in their place
     Also called to upgrade from 0.8 release
     """
     self._name = toUnicode(self.__dict__['name'])
     self._author = toUnicode(self.__dict__['author'])
     self._description = toUnicode(self.__dict__['description'])
Example #7
0
    def render_POST(self, request=None):
        log.debug("render_POST")

        lang_only = False

        data = {}
        try:
            clear = False
            if 'clear' in request.args:
                clear = True
                request.args.pop('clear')
            if 'lang_only' in request.args:
                lang_only = True
                request.args.pop('lang_only')
            if 'lom_general_title_string1' in request.args:
                if clear:
                    self.package.setLomDefaults()
                else:
                    self.setLom(request.args)
            elif 'lomes_general_title_string1' in request.args:
                if clear:
                    self.package.setLomEsDefaults()
                else:
                    self.setLomes(request.args)
            else:
                items = request.args.items()
                if 'pp_lang' in request.args:
                    value = request.args['pp_lang']
                    item = ('pp_lang', value)
                    items.remove(item)
                    items.insert(0, item)
                for key, value in items:
                    obj, name = self.fieldId2obj(key)
                    if key in self.booleanFieldNames:
                        setattr(obj, name, value[0] == 'true')
                    else:
                        if key in self.imgFieldNames:
                            path = Path(toUnicode(value[0]))
                            if path.isfile():
                                setattr(obj, name, path)
                                data[key] = getattr(obj, name).basename()
                            else:
                                if getattr(obj, name):
                                    if getattr(obj, name).basename() != path:
                                        setattr(obj, name, None)
                        else:
                            #if name=='docType': common.setExportDocType(toUnicode(value[0]))

                            setattr(obj, name, toUnicode(value[0]))

        except Exception as e:
            log.exception(e)
            return json.dumps({'success': False, 'errorMessage': _("Failed to save properties")})

        if not self.package.isTemplate or not lang_only:
            self.package.isChanged = True

        return json.dumps({'success': True, 'data': data})
Example #8
0
 def getTitle(self):
     """
     Returns our title as a string
     """
     if hasattr(self, '_title') and self._title:
         return toUnicode(self._title)
     elif hasattr(self, '_package') and self.package is not None:
         return _(toUnicode(self.package.levelName(self.level - 1)))
     else:
         return u'Unknown Node [no title or package]'
Example #9
0
 def getTitle(self):
     """
     Returns our title as a string
     """
     if hasattr(self, '_title') and self._title:
         return toUnicode(self._title)
     elif hasattr(self, '_package') and self.package is not None:
         return _(toUnicode(self.package.levelName(self.level - 1)))
     else:
         return u'Unknown Node [no title or package]'
Example #10
0
    def recieveFieldData(self, client, fieldId, value, total, onDone=None):
        """
        Called by client to give us a value from a certain field
        """
        total = int(total)
        self.fieldsReceived.add(fieldId)
        obj, name = self.fieldId2obj(fieldId)
        # Decode the value
        decoded = ''
        toSearch = value

        def getMatch():
            if toSearch and toSearch[0] == '%':
                match1 = self.reUni.search(toSearch)
                match2 = self.reChr.search(toSearch)
                if match1 and match2:
                    if match1.start() < match2.start():
                        return match1
                    else:
                        return match2
                else:
                    return match1 or match2
            else:
                return self.reRaw.search(toSearch)

        match = getMatch()
        while match:
            num = match.groups()[-1]
            if len(num) > 1:
                decoded += unichr(int(num, 16))
            else:
                decoded += num
            toSearch = toSearch[match.end():]
            match = getMatch()
        # Check the field type
        if fieldId in self.booleanFieldNames:
            setattr(obj, name, decoded[0].lower() == 't')
        elif fieldId in self.imgFieldNames:
            if not decoded.startswith("resources"):
                setattr(obj, name, toUnicode(decoded))
        else:
            # Must be a string
            setattr(obj, name, toUnicode(decoded))
        client.sendScript(
            js('document.getElementById("%s").style.color = "black"' %
               fieldId))
        if len(self.fieldsReceived) == total:
            self.fieldsReceived = set()
            client.sendScript(
                js.alert((u"%s" % _('Settings saved')).encode('utf8')))
            if onDone:
                client.sendScript(js(onDone))
Example #11
0
 def recieveFieldData(self, client, fieldId, value, total, onDone=None):
     """
     Called by client to give us a value from a certain field
     """
     total = int(total)
     self.fieldsReceived.add(fieldId)
     obj, name = self.fieldId2obj(fieldId)
     # Decode the value
     decoded = ''
     toSearch = value
     def getMatch():
         if toSearch and toSearch[0] == '%':
             match1 = self.reUni.search(toSearch)
             match2 = self.reChr.search(toSearch)
             if match1 and match2:
                 if match1.start() < match2.start():
                     return match1
                 else:
                     return match2
             else:
                 return match1 or match2
         else:
             return self.reRaw.search(toSearch)
     match = getMatch()
     while match:
         num = match.groups()[-1]
         if len(num) > 1:
             decoded += unichr(int(num, 16))
         else:
             decoded += num
         toSearch = toSearch[match.end():]
         match = getMatch()
     # Check the field type
     if fieldId in self.booleanFieldNames:
         setattr(obj, name, decoded[0].lower() == 't')
     elif fieldId in self.imgFieldNames:
         if not decoded.startswith("resources"):
             setattr(obj, name, toUnicode(decoded))
     else:
         # Must be a string
         setattr(obj, name, toUnicode(decoded))
     client.sendScript(js(
         'document.getElementById("%s").style.color = "black"' % fieldId))
     if len(self.fieldsReceived) == total:
         self.fieldsReceived = set()
         client.sendScript(js.alert(
             (u"%s" % _('Settings saved')).encode('utf8')))
         if onDone:
             client.sendScript(js(onDone))
Example #12
0
 def upgradeToVersion6(self):
     """
     Upgrades for v0.18
     """
     self.defaultImage = toUnicode(G.application.config.webDir/'images'/DEFAULT_IMAGE)
     for question in self.questions:
         question.setupImage(self)
Example #13
0
 def upgradeToVersion6(self):
     """
     Upgrades for v0.18
     """
     self.defaultImage = toUnicode(G.application.config.webDir/'images'/DEFAULT_IMAGE)
     for question in self.questions:
         question.setupImage(self)
Example #14
0
 def getResources(self):
     """
     Return the resource files used by this node
     """
     log.debug(u"getResources ")
     resources = {}
     for idevice in self.idevices:
         reses = [toUnicode(res.storageName, 'utf8') for res in idevice.userResources]
         for resource in (idevice.systemResources + reses):
             resources[resource] = True
     return resources.keys()
Example #15
0
 def getResources(self):
     """
     Return the resource files used by this node
     """
     log.debug(u"getResources ")
     resources = {}
     for idevice in self.idevices:
         reses = [toUnicode(res.storageName, 'utf8') for res in idevice.userResources]
         for resource in (idevice.systemResources + reses):
             resources[resource] = True
     return resources.keys()
Example #16
0
 def render_POST(self, request=None):
     log.debug("render_POST")
     
     data = {}
     try:
         for key, value in request.args.items():
             obj, name = self.fieldId2obj(key)
             if key in self.booleanFieldNames:
                 setattr(obj, name, value[0] == 'true')
             else:
                 if key in self.imgFieldNames:
                     path = Path(value[0])
                     if path.isfile():
                         setattr(obj, name, toUnicode(value[0]))
                         data[key] = getattr(obj, name).basename()
                 else:
                     setattr(obj, name, toUnicode(value[0]))
     except Exception as e:
         log.exception(e)
         return json.dumps({'success': False, 'errorMessage': _("Failed to save properties")})
     return json.dumps({'success': True, 'data': data})
Example #17
0
 def _loadPackage(self, client, filename):
     """Load the package named 'filename'"""
     try:
         encoding = sys.getfilesystemencoding()
         if encoding is None:
             encoding = 'utf-8'
         filename2 = toUnicode(filename, encoding)
         log.debug("filename and path" + filename2)
         package = Package.load(filename2)
         if package is None:
             filename2 = toUnicode(filename, 'utf-8')
             package = Package.load(filename2)
             if package is None:
                 raise Exception(_("Couldn't load file, please email file to [email protected]"))
     except Exception, exc:
         if log.getEffectiveLevel() == logging.DEBUG:
             client.alert(_(u'Sorry, wrong file format:\n%s') % unicode(exc))
         else:
             client.alert(_(u'Sorry, wrong file format'))
         log.error(u'Error loading package "%s": %s' % (filename2, unicode(exc)))
         log.error(u'Traceback:\n%s' % traceback.format_exc())
         raise
 def _loadPackage(self,
                  client,
                  filename,
                  newLoad=True,
                  destinationPackage=None):
     """Load the package named 'filename'"""
     try:
         encoding = sys.getfilesystemencoding()
         if encoding is None:
             encoding = 'utf-8'
         filename2 = toUnicode(filename, encoding)
         log.debug("filename and path" + filename2)
         # see if the file exists AND is readable by the user
         try:
             open(filename2, 'rb').close()
         except IOError:
             filename2 = toUnicode(filename, 'utf-8')
             try:
                 open(filename2, 'rb').close()
             except IOError:
                 client.alert(
                     _(u'File %s does not exist or is not readable.') %
                     filename2)
                 return None
         package = Package.load(filename2, newLoad, destinationPackage)
         if package is None:
             raise Exception(
                 _("Couldn't load file, please email file to [email protected]"
                   ))
     except Exception, exc:
         if log.getEffectiveLevel() == logging.DEBUG:
             client.alert(
                 _(u'Sorry, wrong file format:\n%s') % unicode(exc))
         else:
             client.alert(_(u'Sorry, wrong file format'))
         log.error(u'Error loading package "%s": %s' %
                   (filename2, unicode(exc)))
         log.error(u'Traceback:\n%s' % traceback.format_exc())
         raise
Example #19
0
 def _copyFile(self, resourceFile):
     """
     copy the resourceFile given into our package's resourceDir
     """
     log.debug(u"copyFile %s" % resourceFile)
     self._storageName = toUnicode(resourceFile.basename())
     uniqueId = 1
     while (self._package.resourceDir/self._storageName).exists():
         nameBase, ext = os.path.splitext(self._storageName)
         self._storageName = "%s%d%s" % (nameBase, uniqueId, ext)
         uniqueId += 1
     log.debug(u"storageName=%s" % self._storageName)
     resourceFile.copyfile(self._package.resourceDir/self._storageName)
Example #20
0
 def __init__(self, package, resourceFile):
     """
     Initialize a resource object, and copy the file into the package's
     resouceDir unless it is already there
     """
     log.debug(u"init resourceFile=%s" % resourceFile)
     self._package     = package
     self._storageName = toUnicode(resourceFile.basename())
     if not hasattr(package, "resourceDir"):
         log.debug(u"package doesn't have a resourceDir, must be upgrading")
     elif resourceFile.dirname() == package.resourceDir:
         log.debug(u"storageName=%s was already in package resources" % 
                   self._storageName)
     else:
         self._copyFile(resourceFile)
    def __init__(self, story="", defaultImage=None):
        """
        Initialize 
        """
        Idevice.__init__(self,
                         x_(u"Case Study"),
                         x_(u"University of Auckland"), 
                         x_(u"""A case study is a device that provides learners 
with a simulation that has an educational basis. It takes a situation, generally 
based in reality, and asks learners to demonstrate or describe what action they 
would take to complete a task or resolve a situation. The case study allows 
learners apply their own knowledge and experience to completing the tasks 
assigned. when designing a case study consider the following:<ul> 
<li>	What educational points are conveyed in the story</li>
<li>	What preparation will the learners need to do prior to working on the 
case study</li>
<li>	Where the case study fits into the rest of the course</li>
<li>	How the learners will interact with the materials and each other e.g.
if run in a classroom situation can teams be setup to work on different aspects
of the case and if so how are ideas feed back to the class</li></ul>"""), 
                         "",
                         u"casestudy")
        self.emphasis     = Idevice.SomeEmphasis
        self.short_desc = x_("Template for providing a case study text, activity and feedback")
        
        self._storyInstruc = x_(u"""Create the case story. A good case is one 
that describes a controversy or sets the scene by describing the characters 
involved and the situation. It should also allow for some action to be taken 
in order to gain resolution of the situation.""")
        self.storyTextArea = TextAreaField(x_(u'Story:'), self._storyInstruc, story)
        self.storyTextArea.idevice = self


        self.questions    = []
        self._questionInstruc = x_(u"""Describe the activity tasks relevant 
to the case story provided. These could be in the form of questions or 
instructions for activity which may lead the learner to resolving a dilemma 
presented. """)
        self._feedbackInstruc = x_(u"""Provide relevant feedback on the 
situation.""")
        if defaultImage is None:
            defaultImage = G.application.config.webDir/'images'/DEFAULT_IMAGE
        self.defaultImage = toUnicode(defaultImage)
        self.addQuestion()
Example #22
0
    def recieveFieldData(self, client, fieldId, value, number, total):
        """
        Called by client to give us a value from a certain field
        """
        number = int(number)
        total = int(total)
        if number == 0:
            self.fieldsReceived = set([0])
        else:
            self.fieldsReceived.add(fieldId)
        obj, name = self.fieldId2obj(fieldId)
        decoded = ""
        toSearch = value

        def getMatch():
            if toSearch and toSearch[0] == "%":
                match1 = self.reUni.search(toSearch)
                match2 = self.reChr.search(toSearch)
                if match1 and match2:
                    if match1.start() < match2.start():
                        return match1
                    else:
                        return match2
                else:
                    return match1 or match2
            else:
                return self.reRaw.search(toSearch)

        match = getMatch()
        while match:
            num = match.groups()[-1]
            if len(num) > 1:
                decoded += unichr(int(num, 16))
            else:
                decoded += num
            toSearch = toSearch[match.end() :]
            match = getMatch()
        if fieldId in self.booleanFieldNames:
            setattr(obj, name, decoded[0].lower() == "t")
        else:
            setattr(obj, name, toUnicode(decoded))
        client.sendScript(js('document.getElementById("%s").style.color = "black"' % fieldId))
        if len(self.fieldsReceived) == total:
            client.sendScript(js.alert((u"%s" % _("Settings saved")).encode("utf8")))
Example #23
0
    def __init__(self, story="", defaultImage=None):
        """
        Initialize 
        """
        Idevice.__init__(self,
                         x_(u"Case Study"),
                         x_(u"University of Auckland"), 
                         x_(u"""A case study is a device that provides learners 
with a simulation that has an educational basis. It takes a situation, generally 
based in reality, and asks learners to demonstrate or describe what action they 
would take to complete a task or resolve a situation. The case study allows 
learners apply their own knowledge and experience to completing the tasks 
assigned. when designing a case study consider the following:<ul> 
<li>	What educational points are conveyed in the story</li>
<li>	What preparation will the learners need to do prior to working on the 
case study</li>
<li>	Where the case study fits into the rest of the course</li>
<li>	How the learners will interact with the materials and each other e.g.
if run in a classroom situation can teams be setup to work on different aspects
of the case and if so how are ideas feed back to the class</li></ul>"""), 
                         "",
                         u"casestudy")
        self.emphasis     = Idevice.SomeEmphasis
        
        self._storyInstruc = x_(u"""Create the case story. A good case is one 
that describes a controversy or sets the scene by describing the characters 
involved and the situation. It should also allow for some action to be taken 
in order to gain resolution of the situation.""")
        self.storyTextArea = TextAreaField(x_(u'Story:'), self._storyInstruc, story)
        self.storyTextArea.idevice = self


        self.questions    = []
        self._questionInstruc = x_(u"""Describe the activity tasks relevant 
to the case story provided. These could be in the form of questions or 
instructions for activity which may lead the learner to resolving a dilemma 
presented. """)
        self._feedbackInstruc = x_(u"""Provide relevant feedback on the 
situation.""")
        if defaultImage is None:
            defaultImage = G.application.config.webDir/'images'/DEFAULT_IMAGE
        self.defaultImage = toUnicode(defaultImage)
        self.addQuestion()
Example #24
0
 def set_description(self, value):
     self._description = toUnicode(value)
Example #25
0
 def set_author(self, value):
     self._author = toUnicode(value)
Example #26
0
 def set_title(self, value):
     self._title = toUnicode(value)
Example #27
0
 def set_name(self, value):
     self._name = toUnicode(value)
Example #28
0
 def __setattr__(self, name, value):
     self.__dict__[name] = toUnicode(value)
Example #29
0
 def set_email(self, value):
     self._email = toUnicode(value)
 def set_name(self, value):
     self._name = toUnicode(value)
 def set_description(self, value):
     self._description = toUnicode(value)
 def set_author(self, value):
     self._author = toUnicode(value)
 def set_title(self, value):
     self._title = toUnicode(value)
 def __setattr__(self, name, value):
     self.__dict__[name] = toUnicode(value)
Example #35
0
 def set_email(self, value):
     self._email = toUnicode(value)