Exemple #1
0
class Config(Base):
    "This is the basic config class"

    security = ClassSecurityInfo()
    meta_type = 'Config'
    configureable = 0

    security.declarePrivate('__init__')
    def __init__(self, id, dict=None):
        "Initialize the class"
        self.id = id
        if dict is not None and hasattr(dict, 'items'):
            for i, j in dict.items():
                if isinstance(j, types.DictType):
                    self.addEntry(i, j) 

    security.declarePrivate('addEntry')
    def addEntry(self, name, dict):
        "Add an entry to this config"
        if name == 'id':
            name = 'showId'
        self.setObject(name, Entry(name, dict))

    security.declarePrivate('classUpgrader')
    def classUpgrader(self):
        "upgrade this class"
        self.removeData()
        self.setParentObjectConfig()

    security.declarePrivate('setParentObjectConfig')
    def setParentObjectConfig(self):
        "set the parent objectConfig"
        self.aq_parent.setObject('objectConfig', self.convertToDict())
    setParentObjectConfig = utility.upgradeLimit(setParentObjectConfig, 141)
    
    security.declarePrivate('removeData')
    def removeData(self):
        "remove the data member of this object"
        if 'data' in self.__dict__:
            if hasattr(self.data, 'items'):
                for key, object in self.data.items():
                    if key == 'id':
                        key = 'showId'

                    if hasattr(object, 'meta_type') and object.meta_type == 'Entry':
                        self.setObject(key, object)
                        getattr(self, key).upgrader()
                    else:
                        self.addEntry(key, object)
            self.delObjects(['data'])
    removeData = utility.upgradeLimit(removeData, 141)
    
    security.declarePrivate('convertToDict')
    def convertToDict(self):
        "Convert this object to the new dict config format"
        temp = {}
        for name, entry in self.objectItems('Entry'):
            temp[name] = entry.value
        return temp
Exemple #2
0
class Button(UserObject):
    "Input text class"

    meta_type = "Button"
    security = ClassSecurityInfo()
    overwrite = 1
    buttonTitle = "Submit Changes"

    classConfig = {'buttonTitle': {'name': 'Button Title', 'type': 'string'}}

    updateReplaceList = ('buttonTitle', )

    security.declareProtected('View management screens', 'edit')

    def edit(self, *args, **kw):
        "Inline edit short object"
        return self.create_button(self.buttonTitle, self.buttonTitle)

    security.declarePrivate('classUpgrader')

    def classUpgrader(self):
        "upgrade this class"
        self.getTitleFromObjectConfig()

    security.declarePrivate('getTitleFromObjectConfig')

    def getTitleFromObjectConfig(self):
        "if we have objectConfig try and get the title from it and use it for the button title"
        if 'objectConfig' in self.__dict__:
            self.setObject('buttonTitle', self.objectConfig['title'])
            del self.objectConfig['title']

    getTitleFromObjectConfig = utility.upgradeLimit(getTitleFromObjectConfig,
                                                    141)
class MultiSimpleEmbed(SimpleEmbed, MixAddRegistered):
    "uses a container to give access to a view of many compounddocs using simpleembed"

    meta_type = "MultiSimpleEmbed"
    security = ClassSecurityInfo()

    editDisplayName = ''
    viewDisplayName = ''

    security.declarePrivate('instance')
    instance = (('CreationAssistant',('create', 'CreationAssistant')),)

    security.declarePrivate('PrincipiaSearchSource')
    def PrincipiaSearchSource(self):
        "This is the basic search function"
        return ''    
    
    classConfig = {}
    classConfig['editDisplayName'] = {'name':'Display for editing:', 'type':'string'}
    classConfig['viewDisplayName'] = {'name':'Display for viewing:', 'type':'string'}
    classConfig['path'] = {'name':'Path:', 'type':'string'}   
    
    security.declarePrivate('observerUpdate')
    def observerUpdate(self, object=None):
        "Process what you were observing"
        object = self.getCompoundDoc().restrictedTraverse(self.path,None)

        useObjects = object.getUseObjects()

        simplemethodobjects = self.objectValues('SimpleEmbed')
        if object:
            if useObjects is not None:
                for i in useObjects:
                    path = i.getPath()
                    if not hasattr(aq_base(self), path):
                        embed = SimpleEmbed(path)
                        embed.path = path
                        self.setObject(path, embed)
        else:
            self.delObjects(self.objectIds('SimpleEmbed'))
            return None

        useObjects = object.getUseObjects()

        if useObjects is not None:
            paths = [i.getPath() for i in useObjects]
            for embed in simplemethodobjects:
                if embed.embedded() is not None:
                    path = embed.getId()
                    if path not in paths:
                        self.delObjects([path])
                else:
                    self.delObjects([embed.getId()])

    def after_manage_edit(self, dict):
        "Process edits."
        try:
            object = self.getCompoundDoc().restrictedTraverse(self.path)
        except KeyError:
            object = None
        if object is not None:
            object.observerAttached(self)

    security.declareProtected('View management screens', 'edit')
    def edit(self, *args, **kw):
        "Inline edit view"
        self.setDrawMode('edit')
        format = '<p>ID:%s</p> %s'
        return ''.join([format % (id, object.edit()) for id,object in self.objectItems('SimpleEmbed')])

    security.declareProtected('View', 'view')
    def view(self):
        "Inline draw view"
        object = self.getCompoundDoc().restrictedTraverse(self.path,None)
        if object is not None and object.limitOkay():
            return ''.join([object.view() for object in self.objectValues('SimpleEmbed')])
        return ''

    security.declarePrivate('classUpgrader')
    def classUpgrader(self):
        "upgrade this class"
        self.removeOldAttributes()
        self.fixupObservation()

    security.declarePrivate('removeOldAttributes')
    def removeOldAttributes(self):
        "remove attributes that are no longer needed"
        self.delObjects(['editDTML', 'viewDTML', 'CreationAssistantString'])
    removeOldAttributes = utility.upgradeLimit(removeOldAttributes, 141)
    
    security.declarePrivate('fixupObservation')
    def fixupObservation(self):
        "fix the observation stuff"
        try:
            object = self.getCompoundDoc().restrictedTraverse(self.path)
        except KeyError:
            object = None
        if object is not None:
            object.observerAttached(self)
            if object.inuse == []:
                self.delObjects(self.objectIds('SimpleEmbed'))        
    fixupObservation = utility.upgradeLimit(fixupObservation, 141)
class DisplayManager(base.Base):
    "DisplayManager manages all displays"

    meta_type = "DisplayManager"
    security = ClassSecurityInfo()
    overwrite = 1

    data = ''
    defaultEdit = ''
    defaultView = ''
    get_default = {'edit': 'defaultEdit', 'view': 'defaultView'}
    usageMapping = None

    security.declarePrivate('render')

    def render(self, purpose, display=None):
        "Please render an item with this purpose"
        get_default = self.get_default

        try:
            return getattr(self, display).view()
        except (AttributeError, TypeError):
            pass

        try:
            return getattr(self, getattr(self, get_default[purpose])).view()
        except (AttributeError, KeyError):
            pass

    security.declareProtected('View management screens', 'edit')

    def edit(self, *args, **kw):
        "Inline edit view"
        temp = [self.addDeleteObjectsEdit()]
        editDisplays = self.displayUsage('edit')
        if editDisplays:
            temp.append(
                '<p>Default Display for editing: %s</p>' % self.option_select(
                    editDisplays, 'defaultEdit', [self.defaultEdit]))
        viewDisplays = self.displayUsage('view')
        if viewDisplays:
            temp.append(
                '<p>Default Display for viewing: %s</p>' % self.option_select(
                    viewDisplays, 'defaultView', [self.defaultView]))
        return ''.join(temp)

    security.declarePrivate('restrictedUserObject')

    def restrictedUserObject(self):
        "Return a list of the types that are allowed to be added or deleted from this object by a user"
        return ['Display']

    security.declarePrivate('displayUsage')

    def displayUsage(self, usage):
        "Return all objects that match this usage"
        if self.usageMapping is None:
            return []
        return self.usageMapping.get(usage, [])

    security.declarePrivate('performUpdate')

    def performUpdate(self):
        "Update object to newest version"
        if not self.checkShared():
            super(DisplayManager, self).performUpdate()

    security.declarePrivate('performUpgrade')

    def performUpgrade(self):
        "perform the upgrade on this object and its children"
        if not self.checkShared():
            super(DisplayManager, self).performUpgrade()

    security.declarePrivate('beforeProfileLoad')

    def beforeProfileLoad(self):
        "run this action before loading the object with profile information"
        self.delObjects(self.objectIds('Display'))
        self.performUpdate()

    security.declarePrivate('classUpgrader')

    def classUpgrader(self):
        "upgrade this class"
        self.removeBadEditName()
        self.fixupCurrentEdit()
        for i in self.objectValues('Display'):
            i.performUpgrade()
        self.fixupDefaultEdit()
        self.fixupDefaultView()
        self.addUsageMapping()
        self.fixedDefaultDisplay()

    security.declarePrivate('fixupDefaultEdit')

    def fixupDefaultEdit(self):
        "fix the defaultEdit attribute"
        if self.defaultEdit == '':
            temp = self.displayUsage('edit')
            if len(temp):
                self.setObject('defaultEdit', temp[0])

    fixupDefaultEdit = utility.upgradeLimit(fixupDefaultEdit, 141)

    security.declarePrivate('fixupDefaultView')

    def fixupDefaultView(self):
        "fixup the defaultView attribute"
        if self.defaultView == '':
            temp = self.displayUsage('view')
            if len(temp):
                self.setObject('defaultView', temp[0])

    fixupDefaultView = utility.upgradeLimit(fixupDefaultView, 141)

    security.declarePrivate('fixupCurrentEdit')

    def fixupCurrentEdit(self):
        "remove the currentEdit attribute"
        if 'currentEdit' in self.__dict__:
            self.delObjects(['currentEdit'])

    fixupCurrentEdit = utility.upgradeLimit(fixupCurrentEdit, 141)

    security.declarePrivate('removeBadEditName')

    def removeBadEditName(self):
        "remvoe a bad edit name from this object"
        badName = self.getId() + 'edit'
        if badName in self.__dict__:
            self.delObjects([badName])

    removeBadEditName = utility.upgradeLimit(removeBadEditName, 141)

    security.declarePrivate('addUsageMapping')

    def addUsageMapping(self):
        """add a usage mapping object to look up usages faster and so displays don't need to
        be opened that are not needed should reduce memory usage and increase speed at the
        cost of a little disk space"""
        if self.usageMapping is None:
            self.usageMapping = {}
            for name, display in self.objectItems('Display'):
                self.usageMapping.setdefault(display.usage, []).append(name)
            self._p_changed = 1

    addUsageMapping = utility.upgradeLimit(addUsageMapping, 144)

    security.declarePrivate('fixDefaultDisplay')

    def fixedDefaultDisplay(self):
        "fix the defaultEdit and defaultView items if they are set to non existant items"
        if self.defaultEdit and self.defaultEdit not in self.usageMapping.get(
                'edit', []):
            self.setObject('defaultEdit', '')
        if self.defaultView and self.defaultView not in self.usageMapping.get(
                'view', []):
            self.setObject('defaultView', '')
        self.setAutoDisplay()

    fixedDefaultDisplay = utility.upgradeLimit(fixedDefaultDisplay, 145)

    security.declarePrivate('afterDeleteRegisteredObject')

    def afterDeleteRegisteredObject(self, name):
        "do something after a registered object is deleted"
        for defaultDisplay in self.get_default.itervalues():
            if name == getattr(self, defaultDisplay):
                self.setObject(defaultDisplay, '')
        self.removeMapping(name)
        self.setAutoDisplay()

    security.declarePrivate('removeMapping')

    def removeMapping(self, name):
        "remove a mapping item"
        for usage, displays in self.usageMapping.iteritems():
            if name in displays:
                displays.remove(name)
                self._p_changed = 1

    security.declarePrivate('addMapping')

    def addMapping(self, name):
        "add a mapping"
        display = getattr(self, name)
        if self.usageMapping is None:
            self.usageMapping = {}
        displayUsage = display.usage
        displays = self.usageMapping.setdefault(displayUsage, [])
        if name not in displays:
            displays.append(name)
            self._p_changed = 1
        for usage, displays in self.usageMapping.iteritems():
            if usage != displayUsage and name in displays:
                displays.remove(name)
                self._p_changed = 1

    security.declarePrivate('cleanupDefaultDisplays')

    def cleanupDefaultDisplays(self, display):
        "make sure our default displays exist and are for the usage they have been set for"
        for usage, defaultDisplay in self.get_default.iteritems():
            displayName = getattr(self, defaultDisplay)
            if displayName == display.getId() and usage != display.usage:
                self.setObject(defaultDisplay, '')
        self.setAutoDisplay()

    #need to check if an item currently being g =used is missing or non existent
    #and then see if any of our current items could do that job

    security.declarePrivate("setAutoDisplay")

    def setAutoDisplay(self):
        "set the default filter to a filter if one is not already set"
        for usage, defaultDisplay in self.get_default.iteritems():
            displayName = getattr(self, defaultDisplay)
            if not displayName:
                displays = self.displayUsage(usage)
                if displays:
                    self.setObject(defaultDisplay, displays[0])

    security.declarePrivate('checkShared')

    def checkShared(self):
        "return true if we are in a shared object"
        cdoc = self.getCompoundDoc()
        return cdoc.masterLocation is not None and cdoc.masterLocation != cdoc.getPath(
        )
Exemple #5
0
class Entry(Base):
    "This is the entry class"

    security = ClassSecurityInfo()
    meta_type = 'Entry'
    configureable = 0

    security.declarePrivate('__init__')

    def __init__(self, id, dict=None):
        self.id = id
        self.name = ""
        self.value = ""
        if dict:
            for i, j in dict.items():
                self.setObject(i, j)

    security.declarePrivate('classUpgrader')

    def classUpgrader(self):
        "upgrade this class"
        self.cleanupData()
        self.cleanupId()
        self.upgraderEntryType()
        self.cleanupType()
        self.cleanupValues()

    security.declarePrivate('upgraderEntryType')

    def upgraderEntryType(self):
        "upgrade config objects to use the optional type system"
        try:
            config = self.aq_parent.aq_parent.classConfig
        except AttributeError:
            return None
        id = self.getId()
        if id in config and 'type' in config[id] and getattr(
                self, 'type', None) != config[id]['type']:
            self.setObject('type', config[id]['type'])

    upgraderEntryType = utility.upgradeLimit(upgraderEntryType, 141)

    security.declarePrivate('cleanupData')

    def cleanupData(self):
        "clean up the data attribute"
        if 'data' in self.__dict__:
            if hasattr(self.data, 'items'):
                for key, object in self.data.items():
                    self.setObject(key, object)
            del self.data

    cleanupData = utility.upgradeLimit(cleanupData, 141)

    security.declarePrivate('cleanupId')

    def cleanupId(self):
        "clean up the id of this object"
        if 'name' in self.__dict__:
            if self.name == 'id':
                self.name == 'showId'
        if not self.getId():
            self.id = self.name
        if self.getId() == 'id':
            self.id = 'showId'

    cleanupId = utility.upgradeLimit(cleanupId, 141)

    security.declarePrivate('cleanupType')

    def cleanupType(self):
        "set type to None if we have it and it has no info"
        if 'type' in self.__dict__ and self.type is None:
            self.delObjects(['type'])

    cleanupType = utility.upgradeLimit(cleanupType, 141)

    security.declarePrivate('cleanupValues')

    def cleanupValues(self):
        "set the values to None if we have it and it has no info"
        if 'values' in self.__dict__ and not self.values:
            self.delObjects(['values'])

    cleanupValues = utility.upgradeLimit(cleanupValues, 141)
class DataRecorder(base.Base):
    "DataRecorder class"

    meta_type = "DataRecorder"
    security = ClassSecurityInfo()
    fieldList = None
    records = None
    recordsLength = None
    archive = None
    archiveLength = None
    allowArchive = 1
    allowClear = 1
    startTime = None
    stopTime = None
    orderHeaderPath = ''
    catalogPath = ''
    catalogArchivePath = ''
    recordScriptPath = ''
    recordRenderScriptPath = ''

    fieldOrder = None  #just to make it easier to remove from instances

    HTMLDataFilter = HTMLDataFilter('HTMLDataFilter')
    CSVDataFilter = CSVDataFilter('CSVDataFilter')
    SeperatorDataFilter = SeperatorDataFilter('SeperatorDataFilter')

    classConfig = {}
    classConfig['allowArchive'] = {
        'name': 'Allow Archiving?:',
        'type': 'radio'
    }
    classConfig['allowClear'] = {'name': 'Allow Clearing?:', 'type': 'radio'}
    classConfig['orderHeaderPath'] = {
        'name': 'Path to Default Config Script',
        'type': 'path'
    }
    classConfig['catalogPath'] = {'name': 'Path to Catalog', 'type': 'path'}
    classConfig['catalogArchivePath'] = {
        'name': 'Path to Archive Catalog',
        'type': 'path'
    }
    classConfig['recordScriptPath'] = {
        'name': 'Path to record modifier script',
        'type': 'path'
    }
    classConfig['recordRenderScriptPath'] = {
        'name': 'Path to record rendering script',
        'type': 'path'
    }

    drawDict = base.Base.drawDict.copy()
    drawDict['showRecords'] = 'showRecords'
    drawDict['showArchive'] = 'showArchive'
    drawDict['showFieldList'] = 'showFieldList'
    drawDict['AdvancedEdit'] = 'advancedEdit'

    updateReplaceList = ('catalogPath', 'catalogArchivePath',
                         'orderHeaderPath', 'allowArchive', 'allowClear')

    security.declarePrivate('getCatalog')

    def getCatalog(self, archive=None):
        "get the current catalog if there is one"
        if archive is not None:
            path = self.getConfig('catalogArchivePath')
        else:
            path = self.getConfig('catalogPath')
        if path:
            obj = self.getCompoundDoc().restrictedTraverse(path, None)
            if obj is not None and obj.meta_type == 'ZCatalog':
                return obj

    security.declarePrivate('getRecordScript')

    def getRecordScript(self):
        "get the record modifier script"
        recordScriptPath = self.recordScriptPath
        if recordScriptPath:
            return self.restrictedTraverse(recordScriptPath, None)

    def getRender(self, name):
        "get the default recordRendering script"
        if self.recordRenderScriptPath:
            script = self.getCompoundDocContainer().restrictedTraverse(
                self.recordRenderScriptPath, None)
            if script is not None:
                return script(name)

    security.declareProtected('View management screens', 'showRecords')

    def showRecords(self):
        "show the records"
        return self.showRecordsCommon(archive=0)

    security.declareProtected('View management screens', 'showFieldList')

    def showFieldList(self):
        "show the fieldList as a view"
        return self.unorderedList(self.fieldList or [])

    security.declareProtected('View management screens', 'showArchive')

    def showArchive(self):
        "show the records"
        return self.showRecordsCommon(archive=1)

    security.declarePrivate('showRecordsCommon')

    def showRecordsCommon(self, archive):
        "common function for showing records/archives"
        path = '_'.join(self.getPhysicalPath())
        format = '''<div>%s<span id="%s_loadMenu_%s"></span></div>
        <div id="%s_showDocument_%s"></div>
        '''
        return format % (self.getPrimaryMenu(archive=archive), path, archive,
                         path, archive)

    security.declareProtected('View management screens', 'loadRecord')

    def loadRecord(self, archive, selectedDocument, merge=0):
        "load this record and return it for AJAX"
        name, data = self.getSelectedDocument(
            archive=archive, selectedDocument=selectedDocument, merge=merge)
        doc = 'Can Not Load Document'
        if name is not None and data is not None:
            doc = Record(name=name,
                         data=data,
                         script=self.getRecordScript(),
                         parent=self).__of__(self).index_html()
        return doc

    security.declarePrivate('getMenu')

    def getPrimaryMenu(self, archive=0):
        "return the menu for these documents this is used in selectOne mode"
        if archive:
            records = self.archive
        else:
            records = self.records

        if records is None:
            return ''

        temp = []

        path = '_'.join(self.getPhysicalPath())
        js = '''onchange="loadRecord(this, '#%s_loadMenu_%s','%s/getSecondaryMenu?archive:int=%s&start:int=')"''' % (
            path, archive, self.absolute_url(), archive)
        seq = [(idx * 100, DateTime.DateTime(i)) for idx, i in enumerate(
            itertools.islice(records.keys(), None, None, 100))]
        seq.insert(0, ('', 'Load Document'))
        temp.append(
            self.option_select(seq,
                               'selectedDocument',
                               dataType='list:ignore_empty',
                               events=js))
        return ''.join(temp)

    security.declareProtected('View management screens', 'getSecondaryMenu')

    def getSecondaryMenu(self, start=0, archive=0):
        "return the menu for these documents this is used in selectOne mode"
        if archive:
            records = self.archive
        else:
            records = self.records

        if records is None:
            return ''

        temp = []

        path = '_'.join(self.getPhysicalPath())
        js = '''onchange="loadRecord(this, '#%s_showDocument_%s','%s/loadRecord?archive:int=%s&selectedDocument=')"''' % (
            path, archive, self.absolute_url(), archive)
        seq = [(repr(i), DateTime.DateTime(i))
               for i in itertools.islice(records.keys(), start, start + 100)]
        seq.insert(0, ('', 'Load Document'))
        temp.append(
            self.option_select(seq,
                               'selectedDocument',
                               dataType='list:ignore_empty',
                               events=js))
        return ''.join(temp)

    security.declarePrivate('getSelectedDocument')

    def getSelectedDocument(self, archive=0, selectedDocument=None, merge=0):
        "get the currently selected document"
        if merge:
            records = BTrees.OOBTree.OOBTree()
            if self.records is not None:
                records.update(self.records)
            if self.archive is not None:
                records.update(self.archive)
        elif archive:
            records = self.archive
        else:
            records = self.records

        if selectedDocument is not None:
            selectedDocument = float(selectedDocument)
            try:
                return selectedDocument, records[selectedDocument]
            except KeyError:
                pass
        return None, None

    security.declarePublic('__bobo_traverse__')

    def __bobo_traverse__(self, REQUEST, name):
        "getattr method"
        try:
            recordName = float(name)
        except ValueError:
            recordName = None
        if self.records is not None and self.records.has_key(recordName):
            "object has an object with name return that"
            data = self.records[recordName]
            doc = Record(name=name,
                         data=data,
                         script=self.getRecordScript(),
                         parent=self).__of__(self)
            return doc
        if self.archive is not None and self.archive.has_key(recordName):
            "object has an object with name return that"
            data = self.archive[recordName]
            doc = Record(name=name,
                         data=data,
                         script=self.getRecordScript(),
                         parent=self).__of__(self)
            return doc
        guard = object()
        item = getattr(self, name, guard)
        if item is not guard:
            return item

    security.declareProtected('View management screens', "edit")

    def edit(self, dateFormat='jQueryUIDate', *args, **kw):
        "Inline edit short object"
        format = """%s<div>%s%s%s</div><p>Find Items Between:%s and %s</p><p>%s</p>"""

        lenArchive = self.archiveLength(
        ) if self.archiveLength is not None else 0
        lenRecords = self.recordsLength(
        ) if self.recordsLength is not None else 0

        rows = [('', 'Number of records'), ('Inbox', lenRecords),
                ('Archive', lenArchive)]

        clear = ''
        archive = ''
        archiveClear = ''
        if self.getConfig('allowClear'):
            clear = self.create_button('clear', "Clear")

        if self.getConfig('allowArchive'):
            archive = self.create_button('archive', "Archive")
            archiveClear = self.create_button('archiveClear',
                                              "Archive & Clear")
        if self.startTime is None:
            self.addRegisteredObject('startTime', 'Date')
            self.startTime.clearDateTime()
        if self.stopTime is None:
            self.addRegisteredObject('stopTime', 'Date')
            self.stopTime.clearDateTime()

        yearsBefore, yearsAfter = self.getYearsBeforeAndAfter()

        return format % (self.createTable(rows), archiveClear, archive, clear,
                         self.startTime(mode='edit',
                                        format=dateFormat,
                                        yearsBefore=yearsBefore,
                                        yearsAfter=yearsAfter),
                         self.stopTime(
                             mode='edit',
                             format=dateFormat,
                             yearsBefore=yearsBefore,
                             yearsAfter=yearsAfter), self.submitChanges())

    security.declareProtected('View management screens', "advancedEdit")

    def advancedEdit(self, *args, **kw):
        "a better more advanced editing control"
        url = self.absolute_url_path()
        temp = []
        temp.append(
            com.javascript.document_ready([
                com.javascript.tabs_init('dataRecorderTab'),
            ]))

        tabs = (
            (url + '/' + 'editStartTable', 'Start'),
            (url + '/' + 'editRecordsTable', 'Inbox'),
            (url + '/' + 'editArchivesTable', 'Archives'),
            (url + '/' + 'editDownloadTable', 'Download'),
        )

        temp.append(com.javascript.tabs_html("dataRecorderTab", tabs))
        return ''.join(temp)

    def editStartTable(self):
        "edit interface for the start tab of the new editing interface"
        return self.edit()

    def editDownloadTable(self):
        "create the download table"
        return '''<div>
            <h2>Data Access</h2><br />
            Your data is available three ways:<br />
            (1) Left click on "unix", "windows" or "mac" to view as a 'comma separated values' (CSV) file.<br />
            (2) Right click on"unix", "windows" or "mac" to download, then choose "Save Target as..." and name the file: [filename].CSV<br />
            so you can "open" it in a spreadsheet or "import" it into a database.<br />
            %s</div>
            ''' % self.CSVDataFilter(mode='view', tableHeader=1)

    security.declareProtected('View management screens', "editRecordsTable")

    def editRecordsTable(self):
        "edit records table"
        return self.editTable('recordsTable', 'recordsTable')

    security.declareProtected('View management screens', "editArchivesTable")

    def editArchivesTable(self):
        "edit the archives table"
        return self.editTable('archiveTable', 'archiveTable')

    security.declarePrivate('editTable')

    def editTable(self, tableId, tableDataFunc):
        "create the edit interface for a DataTable"
        headers = []
        for name, displayName in self.HTMLDataFilter.getFieldOrder():
            headers.append('<th>%s</th>' % displayName)
        disableSort = ','.join((len(headers) - 1) * ['{ "bSortable": false }'])
        temp = []
        temp.append(
            '''<script type="text/javascript" charset="utf-8"> 
            $(document).ready(function() {
                $('#%s').dataTable( {
                    "bProcessing": true,
                    "sDom": '<"top"iflp<"clear">>rt<"bottom"iflp<"clear">>',
                    "bServerSide": true,
                    "bJQueryUI": true,
                    "bFilter": false,"aoColumns": [
                        { "bSortable": true, "sType": "Date" },
                        %s
                    ],
                    "sAjaxSource": "%s/%s"
                } );
            } );
        </script>''' %
            (tableId, disableSort, self.absolute_url_path(), tableDataFunc))
        temp.append('''<style>
        #%s p {overflow-y: hidden; height:4em;}
        </style>
        ''' % tableId)
        temp.append(
            '''<table cellpadding="0" cellspacing="0" border="0" class="display" id="%s"><thead><tr>'''
            % tableId)
        temp.extend(headers)
        temp.append('''</tr></thead><tbody><tr> 
            <td colspan="%s" class="dataTables_empty">Loading data from server</td> 
        </tr></tbody><tfoot><tr>''' % len(headers))
        temp.extend(headers)
        temp.append('''</tr></tfoot></table>''')

        return ''.join(temp)

    security.declareProtected('View management screens', "recordsTable")

    def recordsTable(self):
        "get data for the records DataTable"
        return self.getJSONDataTable(lengthRecords=self.recordsLength,
                                     archive=0)

    security.declareProtected('View management screens', "archiveTable")

    def archiveTable(self):
        "get data for the records DataTable"
        return self.getJSONDataTable(lengthRecords=self.archiveLength,
                                     archive=1)

    security.declarePrivate('getJSONDataTAble')

    def getJSONDataTable(self, lengthRecords, archive):
        "get the information for DataTable in json format"
        data = {}
        sortOrder = self.REQUEST.form.get('sSortDir_0', 'asc')
        start = int(self.REQUEST.form.get('iDisplayStart', 0))
        length = int(self.REQUEST.form.get('iDisplayLength', 10))
        data['iTotalRecords'] = lengthRecords(
        ) if lengthRecords is not None else 0
        data['iTotalDisplayRecords'] = data['iTotalRecords']
        data['sEcho'] = self.REQUEST.form.get('sEcho', 0)

        if sortOrder == 'asc':
            start = start
            stop = start + length
        elif sortOrder == 'desc':
            stop = -start
            start = -(start + length)
            if not stop:
                stop = data['iTotalRecords']

        encoding = self.getEncoding()
        clean = utility.cleanEncodingSeq
        escape_html_seq = utility.escape_html_seq
        format = u'''<p onclick="javascript:$.colorbox({href:'%s/loadRecord?archive:int=%s&selectedDocument=%s', innerWidth:'600px', maxWidth:'85%%', maxHeight:'85%%', innerHeight:'600px', onComplete:function(){$('#cboxLoadedContent').css('background-color', 'white');}});">%s</p>'''
        baseUrl = self.absolute_url_path()

        aaData = self.HTMLDataFilter.getDataRecords(
            self.HTMLDataFilter.getFieldOrder(),
            header=0,
            archive=archive,
            sliceStart=start,
            sliceStop=stop,
            keys=1)
        aaData = ((key, clean(record)) for key, record in aaData)
        aaData = ((key, escape_html_seq(record)) for key, record in aaData)
        aaData = ([
            format % (baseUrl, archive, repr(key), entry) for entry in record
        ] for key, record in aaData)

        data['aaData'] = list(aaData)
        if sortOrder == 'desc':
            data['aaData'].reverse()
        return json.dumps(data).encode(encoding, 'xmlcharrefreplace')

    security.declarePrivate('getYearsBeforeAndAfter')

    def getYearsBeforeAndAfter(self):
        "find the number of years on either side of the entries we have in records and archives from now"
        minRecord = None
        maxRecord = None
        minArchive = None
        maxArchive = None

        if self.records is not None:
            minRecord = DateTime.DateTime(self.records.minKey())
            maxRecord = DateTime.DateTime(self.records.maxKey())

        if self.archive is not None:
            minArchive = DateTime.DateTime(self.archive.minKey())
            maxArchive = DateTime.DateTime(self.archive.maxKey())
        nowYear = DateTime.DateTime().year()

        #need to make sure the items are not None
        minRecordYear = minRecord.year() if minRecord is not None else nowYear
        maxRecordYear = maxRecord.year() if maxRecord is not None else nowYear
        minArchiveYear = minArchive.year(
        ) if minArchive is not None else nowYear
        maxArchiveYear = maxArchive.year(
        ) if maxArchive is not None else nowYear
        minYear = max((nowYear - min(minRecordYear, minArchiveYear)), 1)
        maxYear = max((max(maxRecordYear, maxArchiveYear) - nowYear), 1)
        return minYear, maxYear

    security.declarePrivate('configAddition')

    def configAddition(self):
        "addendum to the default config screen"
        add = self.create_button('addRecords', "Add All Records To Catalog")
        addArchive = self.create_button('addRecordsArchive',
                                        "Add All Archive Records To Catalog")
        return '<p>%s</p><p>%s</p>' % (add, addArchive)

    security.declarePrivate('processRecorderChanges')

    def processRecorderChanges(self, form):
        "process the recorder changes"
        if self.getConfig('allowClear') and form.pop('clear', None):
            self.clearRecords()

        if form.pop('addRecords', None):
            self.addRecordsToCatalog()

        if form.pop('addRecordsArchive', None):
            self.addRecordsToCatalogArchive()
        elif self.getConfig('allowArchive') and form.pop('archive', None):
            self.addRecordsToArchive()

        elif self.getConfig('allowArchive') and form.pop('archiveClear', None):
            self.addRecordsToArchive()
            self.clearRecords()

    security.declarePrivate('addRecordsToArchive')

    def addRecordsToArchive(self):
        "add the current records to the archive"
        if self.records is not None:
            self.addMainRecordsToCatalogArchive()

            if self.archive is None:
                self.setObject('archive', BTrees.OOBTree.OOBTree())
            if self.archiveLength is None:
                self.setObject('archiveLength', BTrees.Length.Length())

            #have to do this as a set of seperation operations
            #so I know which are actually being copied over to change the length
            archive = self.archive
            change = self.archiveLength.change
            for key, value in self.records.items():
                if key not in archive:
                    archive[key] = persistent.mapping.PersistentMapping(value)
                    change(1)

    security.declarePrivate('clearRecords')

    def clearRecords(self):
        "clear the current records object and the catalog entries for it"
        if self.records is not None:
            catalog = self.getCatalog()
            if catalog is not None:
                uncatalog_object = catalog.uncatalog_object
                docPath = self.getPath()
                for key in self.records.keys():
                    path = '/'.join([docPath, repr(key)])
                    uncatalog_object(path)
            self.setObject('records', None)
            self.setObject('recordsLength', None)

    security.declarePrivate('addRecordsToCatalog')

    def addRecordsToCatalog(self):
        "add the current records to the catalog"
        self.addRecordsToCatalogShared(records=self.records)

    security.declarePrivate('addRecordsToCatalogArchive')

    def addRecordsToCatalogArchive(self):
        "add the current records to the catalog"
        self.addRecordsToCatalogShared(archive=1, records=self.archive)

    security.declarePrivate('addMainRecordsToCatalogArchive')

    def addMainRecordsToCatalogArchive(self):
        "add the current records to the catalog"
        self.addRecordsToCatalogShared(archive=1, records=self.records)

    security.declarePrivate('addRecordsToCatalogShared')

    def addRecordsToCatalogShared(self, archive=None, records=None):
        "add the current records to the catalog"
        catalog = self.getCatalog(archive)

        if catalog is not None and records is not None:
            catalog_object = catalog.catalog_object
            docPath = self.getPath()
            for key, value in records.items():
                data = copy.deepcopy(value)
                doc = Record(name=repr(key),
                             data=data,
                             script=self.getRecordScript(),
                             parent=self).__of__(self)
                path = '/'.join([docPath, repr(key)])
                catalog_object(doc, uid=path)

    security.declarePrivate('before_manage_edit')

    def before_manage_edit(self, form):
        "process the edits"
        self.processRecorderChanges(form)

    security.declareProtected('View', 'view')

    def view(self):
        "Render page"
        return self.HTMLDataFilter.view()

    security.declarePrivate("getDataFilters")

    def getDataFilters(self):
        "Return a list of all available filters"
        return (self.HTMLDataFilter, self.CSVDataFilter,
                self.SeperatorDataFilter)

    #security.declarePrivate('instance')
    #instance = (('HTMLDataFilter', ('create', 'HTMLDataFilter')),
    #    ('CSVDataFilter', ('create', 'CSVDataFilter')),
    #    ('SeperatorDataFilter', ('create', 'SeperatorDataFilter')))

    security.declareProtected('Python Record Addition', 'addDictObject')

    def addDictObject(self, dict, entryTime=None):
        "Add a dict like object and copy its contents into the records list update fileldMap also"
        temp = copy.deepcopy(dict)

        fieldList = self.fieldList
        if fieldList is None:
            fieldList = []

        for key in dict:
            if key not in fieldList:
                fieldList.append(key)
        if fieldList:
            self.fieldList = fieldList
        if temp:
            if entryTime is None:
                entryTime = time.time()
            if self.records is None:
                self.setObject('records', BTrees.OOBTree.OOBTree())
            if self.recordsLength is None:
                self.setObject('recordsLength', BTrees.Length.Length())

            data = persistent.mapping.PersistentMapping(temp)

            self.records[entryTime] = data
            self.recordsLength.change(1)
            catalog = self.getCatalog()
            if catalog is not None:
                data = temp
                doc = Record(name=repr(entryTime),
                             data=data,
                             script=self.getRecordScript(),
                             parent=self).__of__(self)
                path = '/'.join([self.getPath(), repr(entryTime)])
                catalog.catalog_object(doc, uid=path)

    security.declareProtected('Python Record Access', 'getListDict')

    def getListDict(self,
                    start=None,
                    stop=None,
                    query=None,
                    archive=None,
                    keys=None):
        "Return the list that has all the dicts in it for python script use only"
        allowed = self.getAllowedRecords(query)

        if archive is not None:
            records = self.archive
        else:
            records = self.records

        if records is not None:

            if keys:
                subTrans = com.db.subTransDeactivateKeyValue
            else:
                subTrans = com.db.subTransDeactivate

            if allowed is None:
                if keys:
                    seq = records.items(start, stop)
                else:
                    seq = records.values(start, stop)
                results = subTrans(seq, 100, self.getPhysicalRoot())
            else:
                if keys:
                    recordsGen = ((key, records[key])
                                  for key in self.allowedKeys(
                                      records, start, stop, allowed))
                else:
                    recordsGen = (records[key] for key in self.allowedKeys(
                        records, start, stop, allowed))
                results = subTrans(recordsGen, 100, self.getPhysicalRoot())

            if keys:
                return [(key, dict(record)) for key, record in results]
            else:
                return [dict(record) for record in results]

        return []

    security.declareProtected('Python Record Modification', 'addDataToRecords')

    def addDataToRecords(self,
                         script,
                         start=None,
                         stop=None,
                         query=None,
                         archive=None):
        "Return the list that has all the dicts in it for python script use only"
        allowed = self.getAllowedRecords(query)

        if archive is not None:
            records = self.archive
        else:
            records = self.records

        if records is not None:
            if allowed is None:
                for key, value in com.db.subTrans(records.items(start, stop),
                                                  100):
                    newData = script(value)
                    newData.update(value)
                    newData = persistent.mapping.PersistentMapping(newData)
                    records[key] = newData
            else:
                for key in com.db.subTrans(
                        self.allowedKeys(records, start, stop, allowed), 100):
                    data = records[key]
                    newData = script(data)
                    newData.update(data)
                    newData = persistent.mapping.PersistentMapping(newData)
                    records[key] = newData
        return []

    security.declarePrivate("getAllowedRecords")

    def getAllowedRecords(self, query):
        "get the allowed records based on this query"
        if query is not None:
            catalog = self.getCatalog()
            if catalog is not None:
                return BTrees.OOBTree.OOTreeSet(
                    float(record.record_id) for record in catalog(query))

    security.declarePrivate("allowedKeys")

    def allowedKeys(self, records, start, stop, allowed):
        "return the allowed keys"
        if start is not None or stop is not None:
            keyRange = BTrees.OOBTree.OOTreeSet(
                records.keys(min=start, max=stop))
            return BTrees.OOBTree.intersection(keyRange, allowed)
        else:
            return BTrees.OOBTree.intersection(records, allowed)

    security.declareProtected('Python Record Access', 'getFieldList')

    def getFieldList(self):
        "Return the field list for python script use only"
        if self.fieldList is not None:
            return copy.copy(self.fieldList)
        return []

    security.declarePrivate("PrincipiaSearchSource")

    def PrincipiaSearchSource(self):
        "This is the basic search function"
        return ''

    security.declarePrivate('classUpgrader')

    def classUpgrader(self):
        "upgrade this class"
        self.changeListDictDataRecorder()
        self.changeListDictDataRecorderArchive()
        self.removeNotUsed()
        self.removeNotNeededFilters()
        self.createBTreeLength()
        self.convertDictToPersistentMapping()

    security.declarePrivate('changeListDictDataRecorder')

    def changeListDictDataRecorder(self):
        "Change the list to a dict in the DataRecorder"
        if isinstance(self.records, types.ListType):
            temp = BTrees.OOBTree.OOBTree()
            for i in self.records:
                temp[time.time()] = i
            self.setObject('records', temp)

    changeListDictDataRecorder = utility.upgradeLimit(
        changeListDictDataRecorder, 141)

    security.declarePrivate('changeListDictDataRecorderArchive')

    def changeListDictDataRecorderArchive(self):
        "Change the list to a dict in the DataRecorder archive item"
        if isinstance(self.archive, types.ListType):
            temp = BTrees.OOBTree.OOBTree()
            for i in self.archive:
                temp[time.time()] = i
            self.setObject('archive', temp)

    changeListDictDataRecorderArchive = utility.upgradeLimit(
        changeListDictDataRecorderArchive, 141)

    security.declarePrivate('removeNotUsed')

    def removeNotUsed(self):
        "remove fieldOrder and archive,fieldList,records if not being used"
        toRemove = ['fieldOrder', 'fileNameBase']

        if not self.fieldList:
            toRemove.append('fieldList')
        if self.archive is not None and not self.archive:
            toRemove.append('archive')
        if self.records is not None and not self.records:
            toRemove.append('records')
        self.delObjects(toRemove)

    removeNotUsed = utility.upgradeLimit(removeNotUsed, 157)

    security.declarePrivate('removeNotNeededFilters')

    def removeNotNeededFilters(self):
        "remove Filters that are not being used"
        toRemove = []

        if getattr(self.CSVDataFilter, 'visible', None) is None:
            toRemove.append('CSVDataFilter')
        if getattr(self.HTMLDataFilter, 'visible', None) is None:
            toRemove.append('HTMLDataFilter')
        if getattr(self.SeperatorDataFilter, 'visible', None) is None:
            toRemove.append('SeperatorDataFilter')
        self.delObjects(toRemove)

    removeNotNeededFilters = utility.upgradeLimit(removeNotNeededFilters, 163)

    security.declarePrivate('createBTreeLength')

    def createBTreeLength(self):
        "remove Filters that are not being used"
        if self.records is not None:
            length = BTrees.Length.Length()
            length.set(len(self.records))
            self.setObject('recordsLength', length)

        if self.archive is not None:
            length = BTrees.Length.Length()
            length.set(len(self.archive))
            self.setObject('archiveLength', length)

    createBTreeLength = utility.upgradeLimit(createBTreeLength, 164)

    security.declarePrivate('convertDictToPersistentMapping')

    def convertDictToPersistentMapping(self):
        "convert the dictionaries we have stored to persistent mapping so they can be deactivated"
        if self.records is not None:
            for key, value in com.db.subTrans(self.records.items(), 500):
                self.records[key] = persistent.mapping.PersistentMapping(value)

        if self.archive is not None:
            for key, value in com.db.subTrans(self.archive.items(), 500):
                self.archive[key] = persistent.mapping.PersistentMapping(value)

    convertDictToPersistentMapping = utility.upgradeLimit(
        convertDictToPersistentMapping, 167)
class ImageFilter(BasePicture):
    "Image class"

    security = ClassSecurityInfo()
    meta_type = "ImageFilter"
    image = None
    data = None
    location = ''
    fileSize = ''
    imagesrc = ''  #obsolete
    imagesrc_template = ''
    thumbnail = None
    url = ''

    classConfig = BasePicture.classConfig.copy()
    classConfig['location'] = {'name': 'Location of Image:', 'type': 'string'}

    updateReplaceList = (
        'format',
        'color',
        'location',
    )

    configurable = BasePicture.configurable + ('deletion', 'location')
    attr_notified = set(['format', 'color', 'width', 'height'])

    security.declareProtected('View management screens', 'edit')

    def edit(self, *args, **kw):
        "Inline edit short object"
        temp = []
        if self.exists():
            object = self.image
            width, height = object.width, object.height
            size = self.getFileSize()
            if not size:
                self.setFileSize()
                size = self.getFileSize()
            imageType = self.image.content_type
            format = '<p>Preview: %s  (%s px/%s px) %s %s </p>'
            temp.append(format %
                        (self.small(), width, height, size, imageType))
        temp.append(
            '<p>These heights and widths will be used as closely as possible and keep aspect ratio.</p>'
        )
        width = self.editSingleConfig('width', format='%(form)s')
        height = self.editSingleConfig('height', format='%(form)s')
        temp.append(
            '<p class="imageSize">Suggested Width:%s px  Height:%s px</p>' %
            (width, height))
        return ''.join(temp)

    security.declarePrivate('setFileSize')

    def setFileSize(self):
        "Store the file size of this object"
        try:
            fileSize = utility.fileSizeString(self.image.size)
            self.setObject('fileSize', fileSize)
        except AttributeError:
            pass

    security.declarePrivate('post_process_location')

    def post_process_location(self, before, after):
        "if the location is changed we need to ensure we unhook from the old picture"
        #detach old picture
        picture = self.getRemoteImage(before)
        if picture is not None:
            picture.observerDetached(self)

        #attach new picture
        picture = self.getRemoteImage(after)
        if picture is not None:
            picture.observerAttached(self)
            self.observerUpdate(picture)

    security.declarePrivate('after_manage_edit')

    def after_manage_edit(self, dict):
        "cache some information after this object has been modified"
        if self.hasBeenModified() and not self.getConfig('scriptChangePath'):
            self.regenImages()

    security.declarePrivate('getRemoteImage')

    def getRemoteImage(self, location=None):
        "Get the remote image"
        location = location if location is not None else self.getConfig(
            'location')
        return self.getRemoteObject(location, 'Picture')

    security.declarePrivate('PrincipiaSearchSource')

    def PrincipiaSearchSource(self):
        "This is the basic search function"
        return ''

    security.declarePrivate('observerUpdate')

    def observerUpdate(self, pic):
        "Process what you were observing"
        self.regenImages(pic)

    security.declareProtected('Change CompoundDoc', 'regenImages')

    def regenImages(self, pic=None):
        "regenerate the image and thumbnail"
        #this handles the case where we can't find the remote object we should be attached to
        remote = self.getRemoteImage()
        if remote is None and self.getConfig('location'):
            self.clear()

        #this is the normal case
        pic = pic if pic is not None else self.getRemoteImage()
        if pic is not None and pic.exists():
            if 'UpdateCacheOnly' in self.REQUEST.other:
                self.updateImageSrcCache(remote=pic)
            else:
                self.generateImage(pic)
        else:
            self.clear()

    security.declareProtected('Change CompoundDoc', 'clear')

    def clear(self):
        "clear this image"
        self.delObjects(
            ['image', 'thumbnail', 'fileSize', 'imagesrc_template'])

    security.declareProtected('Change CompoundDoc', 'resaveExistingImage')

    def resaveExistingImage(self):
        "reisze existing images"
        if self.exists():
            filename, remove_after = utility.createTempFile(self.image.data)
            content_type = magicfile.magic(filename)
            if content_type.startswith('image'):
                temp_file, x, y = utility.resaveExistingImage(filename)
                beforeSize = utility.fileSizeToInt(self.getFileSize())
                if temp_file is not None and os.stat(
                        temp_file.name)[stat.ST_SIZE] < beforeSize:
                    self.image.manage_upload(temp_file)
                    self.image.width = x
                    self.image.height = y
                    #have to redo the content_type after we modify the image in case it has changed
                    content_type = magicfile.magic(temp_file.name)
                    temp_file.close()
                    self.setFileSize()
                    self.image.content_type = content_type
            utility.removeTempFile(filename, remove_after)

    security.declarePrivate('generateImage')

    def generateImage(self, pic):
        "generate an image and thumbnail based on this data"
        filename, remove_after = utility.createTempFile(pic.data.data)
        content_type = magicfile.magic(filename)
        if content_type.startswith('image'):
            self.genImage(filename)
            self.updateImageSrcCache(pic)
        self.makeThumbnail(filename)
        utility.removeTempFile(filename, remove_after)

    security.declarePrivate('updateImageSrcCache')

    def updateImageSrcCache(self, remote=None):
        "update the imagesrc cache string"
        if self.exists():
            decode = {}
            decode['height'] = self.image.height
            decode['width'] = self.image.width

            remote = remote if remote is not None else self.getRemoteImage()
            if remote is None:
                alt = ''
                tags = ''
            else:
                alt = remote.alt
                tags = remote.tags
                self.setObject('url', remote.url)

            if com.detection.no_dtml(alt):
                decode['alt'] = self.convert(alt)
            else:
                decode['alt'] = alt

            decode['tags'] = tags

            self.setObject('imagesrc_template',
                           image_template.safe_substitute(decode))

    security.declarePrivate('genImage')

    def genImage(self, filename):
        "generate this image"
        image = PIL.Image.open(filename)
        if image.mode != self.getConfig('color'):
            image = image.convert(self.getConfig('color'))
        crop_left = self.getConfig('crop_left')
        crop_upper = self.getConfig('crop_upper')
        crop_right = self.getConfig('crop_right')
        crop_lower = self.getConfig('crop_lower')
        if crop_right and crop_lower:
            image = image.crop((crop_left, crop_upper, crop_right, crop_lower))
        (x, y) = image.size
        if x > self.width:
            y = y * self.width / x
            x = self.width
        if y > self.height:
            x = x * self.height / y
            y = self.height
        if x == 0:
            x = 1
        if y == 0:
            y = 1
        image = image.resize((x, y))
        tempFile = utility.saveImage(image, self.getConfig('format'))
        if not self.image:
            self.manage_addProduct['Image'].manage_addImage(
                'image', tempFile, 'image')
        else:
            self.image.manage_upload(tempFile)
        self.image.width = int(x)
        self.image.height = int(y)
        self.setFileSize()

    security.declareProtected('View', 'view')

    def view(self,
             urlCallable=None,
             parent=None,
             additionalAttributes='',
             drawHref=1,
             url_data=None):
        "Render page"
        #parent = parent if parent is not None else self.getRemoteImage()
        parent = parent if parent is not None else self.getCompoundDoc()

        if self.exists():
            decode = {}
            decode['url'] = self.absolute_url_path_extension()
            decode['additionalAttributes'] = additionalAttributes
            if not self.imagesrc_template:
                self.REQUEST.other['okayToRunNotification'] = 0
                self.updateImageSrcCache()
                self.delObjects(['imagesrc'])
            image = Template(self.imagesrc_template).safe_substitute(decode)

            url_data = url_data if url_data is not None else self.url
            if drawHref and url_data:
                href = com.html.generate_url(url_data,
                                             parent,
                                             self.REQUEST,
                                             url_callable=urlCallable)
                if href is not None:
                    image = '<a href="%s">%s</a>' % (href, image)
            return image
        return ''

    security.declareProtected("Access contents information", 'exists')

    def exists(self):
        "Check if object has data in it"
        try:
            #just seeing if that image exists
            self.image.image
            return True
        except AttributeError:
            return False

    security.declarePrivate('classUpgrader')

    def classUpgrader(self):
        "upgrade this class"
        self.save_pic_url()

    security.declarePrivate('save_pic_url')

    def save_pic_url(self):
        "put the picture url in the imagefilter so we don't have to load a picture to draw an imagefilter"
        if self.scriptChangePath:  #if we have a notification script the only way we can update our data is to run it
            self.REQUEST.other['UpdateCacheOnly'] = 1
            self.runChangeNotificationScript()
            del self.REQUEST.other['UpdateCacheOnly']
        else:
            self.updateImageSrcCache()
        self.delObjects(['imagesrc'])

    save_pic_url = utility.upgradeLimit(save_pic_url, 176)
class ContainerCompoundController(ObjectCompoundController):
    "uses a container to give access to a view of many compounddocs"

    meta_type = "ContainerCompoundController"
    security = ClassSecurityInfo()
    prepend = ''
    randomId = 0
    cdocName = ""
    folderSwap = 0
    allowAddRemove = 1
    autoNumber = 1
    sorton = ''
    cdocIsContainer = 0
    enableCutCopyPaste = 0
    enableShowOne = 0
    alternateDropDownAttributeName = ''
    folderType = 'Folder'
    drawControls = 1
    dropDownPath = ''
    autoType = ''
    cdocAutoAddTypes = ('timestamp', 'counter')

    folderTypes = (('Folder', 'Default Folder'), ('BTree', 'BTreeFolder2'))

    classConfig = {}
    classConfig['autoNumber'] = {
        'name': 'Number the items on the page?',
        'type': 'radio'
    }
    classConfig['cdocName'] = {
        'name': 'Name of CompoundDoc if folder Swap is set:',
        'type': 'string'
    }
    classConfig['folderSwap'] = {
        'name': 'Swap CompoundDoc name for Folder Name:',
        'type': 'radio'
    }
    classConfig['allowAddRemove'] = {
        'name': 'Allow Documents to be added and removed?:',
        'type': 'radio'
    }
    classConfig['prepend'] = {'name': 'Prepend Name:', 'type': 'string'}
    classConfig['sorton'] = {'name': 'Sort on attribute:', 'type': 'string'}
    classConfig['cdocIsContainer'] = {
        'name':
        'Make this cdoc the container instead of its containing folder?:',
        'type': 'radio'
    }
    classConfig['enableCutCopyPaste'] = {
        'name': 'Enable Cut/Copy/Paste support?:',
        'type': 'radio'
    }
    classConfig['enableShowOne'] = {
        'name': 'Show only one document at a time:',
        'type': 'radio'
    }
    classConfig['alternateDropDownAttributeName'] = {
        'name':
        'Name of an attribute to use for alternate sorting in the drop down:',
        'type': 'string'
    }
    classConfig['folderType'] = {
        'name': 'Type of Folder to use',
        'type': 'list',
        'values': folderTypes
    }
    classConfig['drawControls'] = {
        'name': 'Draw the individual document controls?:',
        'type': 'radio'
    }
    classConfig['dropDownPath'] = {
        'name': 'Path to the Drop Down Configuration:',
        'type': 'path'
    }
    classConfig['autoType'] = {
        'name': 'Auto Cdoc Naming',
        'type': 'list',
        'values': ('', ) + cdocAutoAddTypes
    }

    security.declarePrivate('PrincipiaSearchSource')

    def PrincipiaSearchSource(self):
        "This is the basic search function"
        return ''

    security.declarePrivate('before_manage_edit')

    def before_manage_edit(self, form):
        "handle the copy support before we do other stuff"
        if 'jump' in form:
            del form['jump']
        if 'selectedDocument' in form:
            selected = form['selectedDocument']
            for i in selected:
                if i:
                    selected = i
                    break
            else:
                selected = ''
            self.setSelectedDocument(selected)
        copysupport = form.pop('copysupport', None)
        if self.enableCutCopyPaste and copysupport is not None:
            container = self.getCompoundDocContainer().restrictedTraverse(
                form['tempEditFullPath'], None)
            self.handleCopySupport(copysupport, container)

    security.declarePrivate('after_manage_edit')

    def after_manage_edit(self, form):
        "Call this function after the editing has been processed so that additional things can be done like caching"
        tempEditFullPath = form.get('tempEditFullPath', None)
        folder = None
        if tempEditFullPath is not None:
            folder = self.getCompoundDocContainer().restrictedTraverse(
                tempEditFullPath, None)
        if folder is None:
            folder = self.getEditFolder()
        if folder is not None and self.allowAddRemove:
            profile = self.editProfile
            if not profile and 'profile' in form:
                profile = form['profile']

            if 'add' in form:
                name = form.get('addName', '')
                cdocName = folderSwap = None
                if self.folderSwap and self.cdocName:
                    cdocName = self.cdocName
                    folderSwap = 1
                autoType = self.getConfig('autoType')
                if name or autoType:
                    cdoc = folder.manage_addProduct[
                        'CompoundDoc'].manage_addCompoundDoc(
                            name,
                            profile=profile,
                            redir=0,
                            prepend=self.prepend,
                            cdocName=cdocName,
                            folderCreate=folderSwap,
                            returnObject=1,
                            autoType=autoType)

                    if (form.get('singleMode', None)
                            or self.enableShowOne) and cdoc is not None:
                        self.setSelectedDocument(cdoc.getId())
            if 'del' in form and 'delName' in form and form['delName']:
                folder.manage_delObjects([
                    form['delName'],
                ])

    def handleCopySupport(self, form, container):
        "handle the copy and paste stuff"
        if form.pop('cut', None) and 'ids' in form and self.allowAddRemove:
            cp = container.manage_cutObjects(form['ids'])
            resp = self.REQUEST.RESPONSE
            resp.setCookie('__cp', cp, path='%s' % cookie_path(self.REQUEST))
            self.REQUEST['__cp'] = cp

        if form.pop('copy', None) and 'ids' in form:
            cp = container.manage_copyObjects(form['ids'])
            resp = self.REQUEST.RESPONSE
            resp.setCookie('__cp', cp, path='%s' % cookie_path(self.REQUEST))
            self.REQUEST['__cp'] = cp

        if form.pop('paste',
                    None) and self.allowAddRemove and self.cb_dataValid(
                    ):  #part of CopySupport
            container.manage_pasteObjects(self.REQUEST['__cp'])

    security.declareProtected("Access contents information", 'getEditFolder')

    def getEditFolder(self):
        "get the folder this object is using for editing"
        return self.getFolder('editFullPath')

    security.declareProtected("Access contents information", 'getViewFolder')

    def getViewFolder(self):
        "get the folder this object is using for viewing"
        return self.getFolder('viewFullPath')

    security.declarePrivate('getFolder')

    def getFolder(self, pathName):
        "get the folder we are supposed to be using and create it if it does not exist"
        path = getattr(self, pathName)
        cdocContainer = self.getContainer()
        folder = cdocContainer.restrictedTraverse(path, None)
        if folder is None:
            pathList = path.split('/')
            self.setObject(
                pathName, '/'.join(
                    utility.drawFolderPath(pathList, cdocContainer,
                                           self.folderType)))
            folder = cdocContainer.restrictedTraverse(path, None)
        return folder

    security.declarePrivate('getContainer')

    def getContainer(self):
        "return the continer we are using as an origin"
        if self.cdocIsContainer:
            return self.getCompoundDoc()
        return self.getCompoundDocContainer()

    security.declareProtected('View management screens', 'edit')

    def edit(self,
             dropDownScript=None,
             loadFolder=1,
             drawMenu=1,
             container=None,
             profile=None,
             *args,
             **kw):
        "Inline edit view"
        temp = []

        folder = container or self.getFolder('editFullPath')
        if folder is not None:
            if loadFolder:
                objects = self.getObjectsToWorkWith(folder, profile)
                if dropDownScript or not self.dropDownPath:
                    self.sortObjects(objects, **kw)
            else:
                objects = tuple()

            if self.allowAddRemove:
                temp.extend(self.addRemoveDocument(folder, objects, profile))
            if self.enableCutCopyPaste:
                temp.extend(self.addCutCopyPasteControls())
            temp.extend(
                self.drawDocuments(objects, dropDownScript, drawMenu, folder,
                                   profile, **kw))
        return ''.join(temp)

    def addCutCopyPasteControls(self):
        "add the cut/copy/paste controls"
        temp = []
        if self.allowAddRemove:
            temp.append(
                self.create_button('cut', 'Cut', containers=('copysupport', )))
        temp.append(
            self.create_button('copy', 'Copy', containers=('copysupport', )))
        if self.cb_dataValid():  #part of CopySupport
            temp.append(
                self.create_button('paste',
                                   'Paste',
                                   containers=('copysupport', )))
        return temp

    security.declarePrivate('drawDocuments')

    def drawDocuments(self,
                      objects,
                      dropDownScript=None,
                      drawMenu=1,
                      container=None,
                      profile=None,
                      **kw):
        "draw these documents"
        drawOne = kw.get('selectOne', None)
        if drawOne is None:
            drawOne = self.enableShowOne
        if drawOne:
            return self.drawOne(objects, dropDownScript, container, profile,
                                **kw)
        else:
            return self.drawMany(objects, drawMenu, container, profile, **kw)

    security.declarePrivate('drawOne')

    def drawOne(self,
                objects,
                dropDownScript=None,
                container=None,
                profile=None,
                **kw):
        "draw only one object for editing"
        temp = [
            self.input_hidden('tempEditFullPath',
                              '/'.join(container.getPhysicalPath())),
            self.input_hidden('singleMode', 1)
        ]

        control = '<div>%s %s</div>'
        showName = ''
        selectBox = ''

        mymode = kw.get('docMode', None) or self.editMode
        view = kw.get('docRender', None) or self.editName
        path = self.editObjectPath
        profile = profile or self.editProfile
        drawid = self.editId
        drawControls = self.drawControls
        cdoc = self.getCompoundDoc()

        doc = self.getSelectedDocument(container)
        temp.append('<div>%s</div>' %
                    self.getMenu(objects, dropDownScript, **kw))
        if doc is not None and doc is not cdoc:
            name = doc.getId()
            if self.enableCutCopyPaste:
                selectBox = self.check_box('ids',
                                           name,
                                           containers=('copysupport', ),
                                           formType='list')
            if drawid:
                showName = name
            if drawControls:
                temp.append(control % (selectBox, showName))
            data = self.embedRemoteObject(doc, path, mymode, view, profile, 0)
            if data is not None:
                temp.append(data)
            else:
                temp.append(
                    '<p>For some reason the document you selected could not be shown. Please report this problem.</p>'
                )

        return temp

    security.declarePrivate('getSelectedDocument')

    def getSelectedDocument(self, container=None):
        "get the currently selected document"
        name = self.REQUEST.form.get('selectedDocument', None)
        if name is not None:
            container = container or self.getEditFolder()
            return getattr(container, name, None)

    security.declarePrivate('drawMany')

    def drawMany(self,
                 objects,
                 drawMenu=1,
                 container=None,
                 profile=None,
                 **kw):
        "draw many of the compounddocs for editing"
        temp = [
            self.input_hidden('tempEditFullPath',
                              '/'.join(container.getPhysicalPath())),
            self.input_hidden('singleMode', 0)
        ]

        control = '<div id="%s">%s %s %s/%s %s</div>'
        controlNoNumber = '<div id="%s">%s %s %s</div>'
        showName = ''
        numberOfDocuments = len(objects)
        if drawMenu:
            jsMenu = self.getJSMenu(objects)
        else:
            jsMenu = ''
        selectBox = ''

        mymode = kw.get('docMode', None) or self.editMode
        view = kw.get('docRender', None) or self.editName
        path = self.editObjectPath
        profile = profile or self.editProfile
        drawid = self.editId
        drawControls = self.drawControls
        cdoc = self.getCompoundDoc()
        autoNumber = kw.get('autoNumber', None) or self.autoNumber

        for index, (name, doc) in enumerate(objects):
            if doc is not cdoc:
                if self.enableCutCopyPaste:
                    selectBox = self.check_box('ids',
                                               name,
                                               containers=('copysupport', ),
                                               formType='list')
                if drawid:
                    showName = name
                if drawControls:
                    if autoNumber:
                        temp.append(control %
                                    (name, selectBox, showName, index + 1,
                                     numberOfDocuments, jsMenu))
                    else:
                        temp.append(controlNoNumber %
                                    (name, selectBox, showName, jsMenu))
                temp.append(
                    self.embedRemoteObject(doc, path, mymode, view, profile,
                                           0))
        return temp

    security.declarePrivate('addRemoveDocument')

    def addRemoveDocument(self, folder, objects, profile=None):
        "draw the add remove document interface"
        temp = []
        profile = profile or self.editProfile
        objects = [''] + [name for name, i in objects]

        temp.append(self.create_button('add', 'Add Document'))
        if not self.getConfig('autoType'):
            temp.append(self.input_text('addName', ''))

        if not profile:
            temp.append(
                self.option_select(utility.getStoredProfileNames(), 'profile',
                                   ['Default']))
        else:
            temp.append(self.input_hidden('profile', profile))
        doc = self.getSelectedDocument(folder)
        selected = None
        if doc is not None:
            selected = [doc.getId()]
        temp.append(self.option_select(objects, 'delName', selected=selected))
        temp.append(self.create_button('del', 'Delete Document'))
        return temp

    security.declarePrivate('drawAlternateDropDown')

    def drawAlternateDropDown(self, docs):
        "draw the alternate drop down"
        js = 'onchange="submit()"'
        alternate = self.alternateDropDownAttributeName
        if alternate:
            seq = ((getattr(i, alternate, ''), name) for (name, i) in docs)
            seq = ((method, name) for method, name in seq if callable(method))
            seq = ((method(mode='view'), name) for method, name in seq)
            seq = sorted(seq)
            seq = ((name, method) for method, name in seq)
            seq = list(seq)
            if seq:
                seq.insert(0, ('', 'Load Document'))
                return self.option_select(seq,
                                          'selectedDocument',
                                          dataType='list:ignore_empty',
                                          events=js)
        return ''

    security.declarePrivate('getJSMenu')

    def getJSMenu(self, documents):
        "return the javascript menu for these documents"
        numberOfDocuments = len(documents)
        format = '%s/%s&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;%s'
        seq = [(name, format % (index + 1, numberOfDocuments, name))
               for index, (name, i) in enumerate(documents)]
        seq.insert(0, ('jump', 'Jump To Document'))
        temp = [
            self.option_select(seq,
                               'jump',
                               selected=['jump'],
                               events='onchange="jumpTo(this)"')
        ]

        alternate = self.alternateDropDownAttributeName
        if alternate:
            seq = ((getattr(i, alternate, ''), name)
                   for (name, i) in documents)
            seq = ((method, name) for method, name in seq if callable(method))
            seq = sorted((method(mode='view'), name) for method, name in seq)
            seq = [(name, method) for method, name in seq]
            if seq:
                seq.insert(0, ('jump', 'Jump To Document'))
                temp.append(
                    self.option_select(seq,
                                       'jump',
                                       selected=['jump'],
                                       events='onchange="jumpTo(this)"'))

        return ''.join(temp)

    security.declarePrivate('getObjectsToWorkWith')

    def getObjectsToWorkWith(self, folder, profile=None):
        "get the objects we should work with from this folder"
        objects = folder.objectItems('CompoundDoc')
        profile = profile or self.editProfile

        if profile:
            objects = [(name, i) for name, i in objects
                       if i.profile == profile]

        return list(objects)

    security.declarePrivate('sortObjects')

    def sortObjects(self, objects, **kw):
        "sort these objects based on the sorton attribute"
        sorton = kw.get('sorton', None) or self.sorton
        sort = lambda o: None
        if sorton:

            def sort(o):
                cdoc = o[1]
                obj = getattr(cdoc, sorton, None)
                if obj is not None:
                    return obj(mode='view')

        objects.sort(key=sort)

    security.declareProtected('View', 'view')

    def view(self):
        "Inline draw view"
        temp = []

        mymode = self.viewMode
        view = self.viewName
        path = self.viewObjectPath
        profile = self.viewProfile
        drawid = self.viewId
        cdoc = self.getCompoundDoc()

        folder = self.getFolder('viewFullPath')
        if folder is not None:
            for i in folder.objectValues('CompoundDoc'):
                if i is not cdoc:
                    temp.append(
                        self.embedRemoteObject(i, path, mymode, view, profile,
                                               drawid))
        return ''.join(temp)

    security.declarePrivate('classUpgrader')

    def classUpgrader(self):
        "upgrade this class"
        self.removeRandomId()

    security.declarePrivate('makeDataASequence')

    def removeRandomId(self):
        "remove the randomId and stick timestamp in autotype if randomId is set"
        if self.randomId:
            self.setObject('autoType', 'timestamp')
            self.delObjects([
                'randomId',
            ])

    removeRandomId = utility.upgradeLimit(removeRandomId, 160)
class DisplayFilter(base.Base):
    "DisplayFilter apply this to an object to change how it outputs"

    meta_type = "DisplayFilter"
    security = ClassSecurityInfo()
    overwrite = 1

    code = ''
    codeScript = None
    codetype = 'PythonScript'
    language = 'en'
    wrapperHeader = 'return context.standard_html_header()'
    wrapperHeaderScript = None
    wrapperFooter = 'return context.standard_html_footer()'
    wrapperFooterScript = None
    wrapperHeaderDTML = '<dtml-var standard_html_header>'
    wrapperFooterDTML = '<dtml-var standard_html_footer>'
    flags = None

    security.declarePrivate('instance')
    instance = (('UserAgent', ('create', 'DisplayUserAgent')), )

    security.declareProtected('View', 'view')

    def view(self):
        "Inline draw view"
        if self.codetype == 'DTML':
            return self.getCompoundDoc().gen_html(self.code)
        elif self.codetype == 'Static':
            return self.code
        elif self.codetype == 'PythonScript':
            return self.codeScript.__of__(self.getCompoundDoc())()
        return ''

    security.declareProtected('View management screens', 'edit')

    def edit(self, *args, **kw):
        "Inline edit view"
        temp = []
        temp.append('''<script type="text/javascript">
            $(function() {
            $("#tabsMode").tabs({ cache: false , ajaxOptions: { cache: false }});
            });
            </script>
            ''')
        temp.append('<div id="tabsMode"><ul>')

        url = self.absolute_url_path()
        temp.append('<li><a href="%s/%s">%s</a></li>' %
                    (url, 'editCode', 'Code'))
        temp.append('<li><a href="%s/%s">%s</a></li>' %
                    (url, 'editSettings', 'Settings'))
        temp.append('<li><a href="%s/%s">%s</a></li>' %
                    (url, 'editObjects', 'Objects'))
        temp.append('</ul></div>')
        temp.append(self.submitChanges())
        return ''.join(temp)

    security.declareProtected('View management screens', 'editObjects')

    def editObjects(self):
        "return a table of object listings with id and meta_type sorted by id"
        self.REQUEST.RESPONSE.setHeader(
            'Content-Type', 'text/html; charset=%s' % self.getEncoding())
        temp = []
        temp.append('<div>')
        items = self.getCompoundDoc().objectItems()
        table = sorted((key, value.meta_type) for key, value in items)
        temp.append(self.createTable(table))
        temp.append('</div>')
        return ''.join(temp)

    security.declareProtected('View management screens', 'editCode')

    def editCode(self):
        "draw the code edit interface"
        self.REQUEST.RESPONSE.setHeader(
            'Content-Type', 'text/html; charset=%s' % self.getEncoding())
        temp = []
        temp.append('<div>')
        if self.codetype == 'PythonScript' and self.codeScript:
            temp.append(self.drawScriptErrorsAndWarnings(self.codeScript))
        temp.append(self.text_area('code', self.code))
        temp.append('</div>')
        return ''.join(temp)

    security.declareProtected('View management screens', 'editSettings')

    def editSettings(self):
        "draw the settings edit interface"
        self.REQUEST.RESPONSE.setHeader(
            'Content-Type', 'text/html; charset=%s' % self.getEncoding())
        temp = []
        temp.append('<div>')
        temp.append("<p>Type is :</p>%s\n" % self.option_select(
            self.getAllowedTypes(), 'codetype', [self.codetype]))
        temp.append("<p>Language is :</p>%s\n" % self.option_select(
            UserAgent.getAllowedLanguages, 'language', [self.language]))

        if self.codetype == 'PythonScript' and self.wrapperHeaderScript:
            temp.append(
                self.drawScriptErrorsAndWarnings(self.wrapperHeaderScript))
        temp.append('<p>Header:</p>%s' %
                    self.input_text('wrapperHeader', self.wrapperHeader))

        if self.codetype == 'PythonScript' and self.wrapperFooterScript:
            temp.append(
                self.drawScriptErrorsAndWarnings(self.wrapperFooterScript))
        temp.append('<p>Footer:</p>%s' %
                    self.input_text('wrapperFooter', self.wrapperFooter))
        temp.append(self.UserAgent.edit())
        temp.append('</div>')
        return ''.join(temp)

    def drawScriptErrorsAndWarnings(self, script):
        "draw the script errors and warnings for this script"
        temp = []
        if script.errors:
            temp.append(
                '<p>Errors Found</p><pre class="scriptErrors">%s</pre>' %
                cgi.escape('\n'.join(script.errors), 1))
        if script.warnings:
            temp.append(
                '<p>Warnings Found</p><pre class="scriptWarnings">%s</pre>' %
                cgi.escape('\n'.join(script.warnings), 1))
        return ''.join(temp)

    security.declarePrivate('after_manage_edit')

    def after_manage_edit(self, form):
        "recompile the python script if we have one"
        if self.codetype == 'PythonScript':
            for i in ('code', 'wrapperHeader', 'wrapperFooter'):
                self.recompileScript(i)

    security.declarePrivate('recompileScript')

    def recompileScript(self, baseName):
        "recompile python script"
        scriptName = '%sScript' % baseName
        pyscript = getattr(self, scriptName, None)
        if pyscript is None:
            pyscript = PythonScript(scriptName)
            self.setObject(scriptName, pyscript)
        pyscript.ZPythonScript_edit('', getattr(self, baseName))

    security.declarePrivate('PrincipiaSearchSource')

    def PrincipiaSearchSource(self):
        "Return what can be search which is nothing"
        return ''

    security.declarePrivate("getAllowed")

    def getAllowedTypes(self):
        "Return the allowed types as a tuple"
        return ('DTML', 'PythonScript', 'Static')

    security.declarePrivate('willRender')

    def willRender(self):
        "return true if I can render given the current client language etc"
        Agent = self.getUserAgent()
        return [
            Agent.checkClientCompat(self.UserAgent.getClients(),
                                    self.UserAgent.operatingSystems),
            Agent.checkClientLanguage(self.language), self
        ]

    security.declarePrivate('getWrappers')

    def getWrappers(self):
        "return the header and footer wrapper"
        if self.codetype == 'PythonScript':
            return (self.wrapperHeaderScript(), self.wrapperFooterScript())
        gen_html = self.getCompoundDoc().gen_html
        return (gen_html(self.wrapperHeader), gen_html(self.wrapperFooter))

    security.declarePrivate('getClients')

    def getClients(self):
        "Get the clients of this object"
        return getattr(aq_base(self), 'clients', None)

    security.declarePrivate('setClients')

    def setClients(self, clients):
        "set the clients for this object"
        self.setObject('clients', clients)

    security.declarePrivate('classUpgrader')

    def classUpgrader(self):
        "upgrade this class"
        self.upgraderChangeUserAgentTuple()
        self.upgraderChangeTupleTreeAgent()
        self.upgraderFixAgents()
        self.removeOldVars()
        self.cleanupPythonScript()
        self.oldDTMLDefaultWrappers()
        self.correctIdOfScripts()

    security.declarePrivate('removeOldVars')

    def removeOldVars(self):
        "remove some old vars that are no longer needed"
        if 'optional' in self.__dict__:
            self.delObjects(['optional'])
        if 'required' in self.__dict__:
            self.delObjects(['required'])

    removeOldVars = utility.upgradeLimit(removeOldVars, 141)

    security.declarePrivate('cleanupPythonScript')

    def cleanupPythonScript(self):
        "cleanup the python script objects"
        if self.codetype == 'PythonScript':
            self.delObjects(['script', 'footerScript', 'headerScript'])
            if not self.objectIds('Script (Python)'):
                for i in ('code', 'wrapperHeader', 'wrapperFooter'):
                    self.recompileScript(i)

    cleanupPythonScript = utility.upgradeLimit(cleanupPythonScript, 141)

    security.declarePrivate('correctIdOfScripts')

    def correctIdOfScripts(self):
        "Fix the id of scripts so they don't just say script"
        for name, script in self.objectItems('Script (Python)'):
            if script.id != name:
                script.id = name

    correctIdOfScripts = utility.upgradeLimit(correctIdOfScripts, 141)

    security.declarePrivate('oldDTMLDefaultWrappers')

    def oldDTMLDefaultWrappers(self):
        "add a dtml wrapper as default for an old dtml display filter"
        if self.codetype == 'DTML':
            wrapperHeader = self.__dict__.get('wrapperHeader', None)
            if wrapperHeader is None:
                self.setObject('wrapperHeader', self.wrapperHeaderDTML)
            wrapperFooter = self.__dict__.get('wrapperFooter', None)
            if wrapperFooter is None:
                self.setObject('wrapperFooter', self.wrapperFooterDTML)

    oldDTMLDefaultWrappers = utility.upgradeLimit(oldDTMLDefaultWrappers, 141)

    security.declarePrivate('upgraderChangeUserAgentTuple')

    def upgraderChangeUserAgentTuple(self, clients=None):
        "Change the user agent to the newer tuple format for detection"
        if not clients:
            clients = self.getClients()
        lookup = {
            'Konqueror/2.2': ('Mozilla/5', 'Konqueror', '2', '2'),
            'Konqueror': ('Mozilla/5', 'Konqueror', '', ''),
            'MSIE': ('Mozilla/4', 'MSIE', '', ''),
            'MSIE 6': ('Mozilla/4', 'MSIE', '6', ''),
            'MSIE 6.0': ('Mozilla/4', 'MSIE', '6', '0'),
            'MSIE 5': ('Mozilla/4', 'MSIE', '5', ''),
            'MSIE 4': ('Mozilla/4', 'MSIE', '4', ''),
            'MSIE 3': ('Mozilla/3', 'MSIE', '3', ''),
            'MSIE 2': ('Mozilla/2', 'MSIE', '2', ''),
            'MSIE 5.5': ('Mozilla/4', 'MSIE', '5', '5'),
            'MSIE 5.0': ('Mozilla/4', 'MSIE', '5', '0'),
            'Opera': ('', 'Opera', '', ''),
            'Opera/6': ('', 'Opera', '6', ''),
            'Opera/6.0': ('', 'Opera', '6', '0'),
            'Opera/5': ('', 'Opera', '5', ''),
            'Opera/5.0': ('', 'Opera', '5', '0')
        }
        if operator.isSequenceType(clients):
            list = [lookup[i] for i in clients if i in lookup]
            if len(list):
                self.setClients(tuple(list))

    upgraderChangeUserAgentTuple = utility.upgradeLimit(
        upgraderChangeUserAgentTuple, 141)

    security.declarePrivate('upgraderChangeTupleTreeAgent')

    def upgraderChangeTupleTreeAgent(self):
        "Change the tuple structure to a tree"
        clients = self.getClients()
        if operator.isSequenceType(clients):
            self.setClients(utility.mergeSequenceTree(clients))

    upgraderChangeTupleTreeAgent = utility.upgradeLimit(
        upgraderChangeTupleTreeAgent, 141)

    security.declarePrivate('upgraderFixAgents')

    def upgraderFixAgents(self):
        "Fix the useragent detection vars to use the newer DisplayUserAgent object"
        if self.hasObject('clients') and self.clients is not None:
            self.gen_vars()
            mapping = self.UserAgent.clientSetMapping()
            for key, value in mapping.items():
                if key and value:
                    mapping[key] = getattr(self.UserAgent, value)()
                else:
                    del mapping[key]
            for setname, clients in mapping.items():
                if self.clients == clients:
                    self.UserAgent.setused = setname
                    self.delObjects(['clients'])
                    break
            if self.hasObject('clients') and self.clients is not None:
                self.UserAgent.setClients(self.clients)
                self.delObjects(['clients'])

    upgraderFixAgents = utility.upgradeLimit(upgraderFixAgents, 141)
Exemple #10
0
class BaseTab(Base):
    "Basic item to make multi tabbed interfaces"

    meta_type = "BaseTab"
    security = ClassSecurityInfo()
    overwrite = 1
    displayType = 'edit'
    tabMapping = None
    tabOrder = None
    renderer = 'Horizontal'
    columns = 0
    configScript = ''
    active = 1

    classConfig = {}
    classConfig['renderer'] = {
        'name': 'Rendering Output',
        'type': 'list',
        'values': NestedListURL.lookup.keys()
    }
    classConfig['configScript'] = {
        'name': 'Path to script configuration for tabs',
        'type': 'path'
    }
    classConfig['active'] = {
        'name': 'Activate the tab manager?',
        'type': 'radio'
    }

    configurable = ('configScript', 'active', 'renderer', 'tabOrder',
                    'tabMapping')

    security.declarePrivate('getTabMapping')

    def getTabMapping(self, name):
        "get the tabMapping from this name"
        if self.tabMapping is not None:
            return self.tabMapping.get(name, name)
        return name

    security.declareProtected('View management screens', 'edit')

    def edit(self, *args, **kw):
        "Inline edit view"
        temp = []
        typeformat = '<div>Id: %s Display:%s</div>'
        cdoc = self.getCompoundDoc()
        displays = ['']
        if cdoc.DisplayManager is not None:
            displays.extend(cdoc.DisplayManager.displayUsage(self.displayType))
        if cdoc.displayMap is not None:
            displays.extend(cdoc.displayMap.keys())

        tabOrder = self.tabOrder
        if tabOrder is None:
            tabOrder = []

        neededEntries = len(tabOrder) + 1
        temp.append(self.editSingleConfig('renderer'))
        temp.append(NestedListURL.editRenderer(self.renderer, self))

        tabMapping = self.tabMapping
        if tabMapping is None:
            tabMapping = {}

        for index in xrange(neededEntries):
            try:
                nameValue = tabOrder[index]
                displayValue = tabMapping[nameValue]
            except (IndexError, KeyError):
                nameValue = ''
                displayValue = ''

            temp.append(
                typeformat %
                (self.input_text(
                    'name', nameValue, containers=('tabMapping', str(index))),
                 self.option_select(displays,
                                    'display', [displayValue],
                                    containers=('tabMapping', str(index)))))
        return ''.join(temp)

    security.declarePrivate('before_manage_edit')

    def before_manage_edit(self, dict):
        "Process edits."
        tabMapping = dict.pop('tabMapping', None)
        if tabMapping is not None:
            temp = {}
            for i, j in tabMapping.items():
                temp[int(i)] = j
            temp = ((dictionary['name'].strip(), dictionary['display'].strip())
                    for index, dictionary in sorted(temp.iteritems()))
            cleaned = [(name, display) for name, display in temp
                       if name and display]
            if len(cleaned):
                tabOrder = [name for name, value in cleaned]
                self.setObject('tabOrder', tabOrder)
                temp = {}
                for name, display in cleaned:
                    temp[name] = display
                self.setObject('tabMapping', temp)
            else:
                self.delObjects(('tabOrder', 'tabMapping'))

    security.declarePrivate('getTabOrder')

    def getTabOrder(self, doc=None, tabScript=None):
        "get the tabOrder list structure"
        doc = doc or self.getCompoundDoc()
        query = utility.getQueryDict(
            self.REQUEST.environ.get('QUERY_STRING', ''))
        configScript = tabScript or self.getConfigScript()
        if configScript is not None:
            return self.correctScriptTabOrder(configScript(doc), query)

        tabOrder = self.getConfig('tabOrder')
        if tabOrder is not None:
            return [(name, name, '', {}, query) for name in tabOrder]

        return []

    security.declarePrivate('correctScriptTabOrder')

    def correctScriptTabOrder(self, seq, query):
        "correct the script tabOrder to account for the dictionary that can be used to pass in vars"
        temp = []
        for item in seq:
            try:
                url, link, cssClasses = item
                queryDict = {}
            except ValueError:
                url, link, cssClasses, queryDict = item
            temp.append([url, link, cssClasses, queryDict, query])
        return temp

    security.declarePrivate('getConfigScript')

    def getConfigScript(self):
        "return the config script object"
        configScript = self.getConfig('configScript')
        script = None
        if configScript:
            script = self.getCompoundDocContainer().restrictedTraverse(
                configScript, None)
        return script

    security.declarePrivate('getTabActive')

    def getTabActive(self):
        "return True only if we are set as active and we have data"
        return self.getConfig('active') and (self.getConfig('tabMapping')
                                             is not None
                                             or self.getConfig('configScript'))

    security.declarePrivate('beforeProfileLoad')

    def beforeProfileLoad(self):
        "run this action before loading the object with profile information"
        self.performUpdate()

    security.declarePrivate('classUpgrader')

    def classUpgrader(self):
        "upgrade this class"
        self.fixTabOrder()

    security.declarePrivate('fixTabOrder')

    def fixTabOrder(self):
        "fix the tabOrder object"
        if not self.hasObject('tabOrder'):
            if self.tabMapping is not None:
                keys = sorted(self.tabMapping.keys())
            else:
                keys = None
            self.setObject('tabOrder', keys)

    fixTabOrder = utility.upgradeLimit(fixTabOrder, 141)
class SimpleEmbed(UserObject, mixremoteembed.MixRemoteEmbed):
    "Base for all objects that embed remote objects"

    meta_type = "SimpleEmbed"
    security = ClassSecurityInfo()
    overwrite = 1
    path = ''

    security.declareProtected('View', 'embedded')

    def embedded(self):
        "return the object"
        item = getattr(self, 'embed', None)
        if item is not None:
            return item
        if not self.path:
            return None
        item = self.restrictedTraverse(self.path, None)
        if item is not None:
            self.setObject('embed', aq_base(item))
            return item

    security.declarePrivate('PrincipiaSearchSource')

    def PrincipiaSearchSource(self):
        "Return what can be search which is nothing"
        return ''

    security.declareProtected('View management screens', 'edit')

    def edit(self, *args, **kw):
        "Inline edit view"
        self.setDrawMode('edit')
        item = self.embedded()
        if item is not None and getattr(item, 'meta_type',
                                        None) == 'CompoundDoc':
            return item.__of__(self).gen_html(
                item.render(mode='edit', name=self.editDisplayName))
        else:
            return ''

    security.declareProtected('View', 'view')

    def view(self):
        "Inline draw view"
        self.setDrawMode('view')
        item = self.embedded()
        if item is not None and getattr(item, 'meta_type',
                                        None) == 'CompoundDoc':
            return item.__of__(self).gen_html(
                item.render(mode='view', name=self.viewDisplayName))
        else:
            return ''

    security.declarePrivate('classUpgrader')

    def classUpgrader(self):
        "upgrade this class"
        self.removeDTMLAttributes()

    security.declarePrivate('removeDTMLAttributes')

    def removeDTMLAttributes(self):
        "remove the DTML attributes"
        self.delObjects(['editDTML', 'viewDTML'])

    removeDTMLAttributes = utility.upgradeLimit(removeDTMLAttributes, 141)

    security.declarePrivate('performUpgrade')

    def performUpgrade(self):
        "perform the upgrade on this object but do no descend to the children"
        self.upgrader()
class CatalogManager(Selection, basemanager.BaseManager):
    "CatalogManager manages all displays"

    meta_type = "CatalogManager"
    security = ClassSecurityInfo()
    overwrite = 1
    multipleSelect = 1
    rowsVisible = 10
    allowClear = 1
    UserObject = 0
    catalogScriptPath = ""

    classConfig = {}
    classConfig['catalogScriptPath'] = {
        'name': 'Path to Catalog Script',
        'type': 'path'
    }

    security.declarePrivate('getChoices')

    def getChoices(self):
        'get the available choices to select from'
        for i in self.superValues('ZCatalog'):
            name = i.getId()
            if name != 'CDocUpgrader':
                yield name

    security.declarePrivate('event_data')

    def event_data(self, data):
        "unindex this object if the data is different then what we already have"
        if self.data != data:
            self.unindex_object()

    security.declarePrivate('getSelectedItems')

    def getSelectedItems(self):
        "get the currently selected items"
        return self

    security.declarePrivate('classUpgrader')

    def classUpgrader(self):
        "upgrade this class"
        self.updateCatalogConfig()

    security.declarePrivate('getCatalogs')

    def getCatalogs(self, doc):
        "get the catalog objects"
        if self.catalogScriptPath:
            return self.getCatalogsScript(doc)
        cdoc = self.getCompoundDoc()

        catalogs = (getattr(cdoc, name, None) for name in self if name)
        return [catalog for catalog in catalogs if catalog is not None]

    security.declarePrivate('getCatalogsScript')

    def getCatalogsScript(self, doc):
        "get the catalogs from the script"
        path = self.catalogScriptPath
        if path:
            script = self.getCompoundDocContainer().restrictedTraverse(
                path, None)
            if script is not None:
                return script(doc)
        return []

    security.declarePrivate('updateCatalogConfig')

    def updateCatalogConfig(self):
        "take the info we need from CatalogConfig objects and then remove them"
        for item in self.objectValues('CatalogConfig'):
            name = item.useCatalog
            if name and name not in self:
                self.append(name)
        self.delObjects(self.objectIds('CatalogConfig'))

    updateCatalogConfig = utility.upgradeLimit(updateCatalogConfig, 141)
Exemple #13
0
class SimpleList(UserObject):
    "SimpleList object"

    security = ClassSecurityInfo()
    meta_type = "SimpleList"
    radioOptions = (('append', 'Add'), ('remove', 'Remove'), ('replace',
                                                              'Replace'))

    entry = None

    security.declareProtected('CompoundDoc: Modify SimpleList', 'addEntries')

    def addEntries(self, items):
        "add these items to our current list of items"
        if self.entry is None:
            self.replaceEntries(items)
        for item in items:
            if not self.entry.has_key(item):
                self.entry.insert(item)

    security.declareProtected('CompoundDoc: Modify SimpleList',
                              'removeEntries')

    def removeEntries(self, items):
        "removes these items from the current set of entries"
        if self.entry is not None:
            for item in items:
                if self.entry.has_key(item):
                    self.entry.remove(item)

    security.declareProtected('CompoundDoc: Modify SimpleList',
                              'replaceEntries')

    def replaceEntries(self, items):
        "replace all the entries with these ones"
        self.entry = OOTreeSet()
        for item in items:
            self.entry.insert(item)

    security.declareProtected('CompoundDoc: View SimpleList',
                              'drawViewWindows')

    def drawViewWindows(self):
        "draw the list of addresses in windows format"
        return '\r\n'.join(self.getEntries())

    security.declareProtected('CompoundDoc: View SimpleList', 'drawViewMac')

    def drawViewMac(self):
        "draw the list of addresses in mac format"
        return '\r'.join(self.getEntries())

    security.declareProtected('CompoundDoc: View SimpleList', 'drawViewUnix')

    def drawViewUnix(self):
        "draw the list of addresses in unix format"
        return '\n'.join(self.getEntries())

    radioLookup = {
        'append': addEntries,
        'remove': removeEntries,
        'replace': replaceEntries
    }

    security.declareProtected('CompoundDoc: Add List Item', 'addEntry')

    def addEntry(self, item):
        "Add an entry to the list"
        if self.entry is None:
            self.entry = OOTreeSet()
        self.entry.insert(item)

    security.declareProtected('CompoundDoc: Del List Item', 'delEntry')

    def delEntry(self, item):
        "Remove an entry form the list"
        if self.entry.has_key(item):
            self.entry.remove(item)
            if not len(self.entry):
                self.entry = None

    security.declareProtected('CompoundDoc: Has List Item', 'hasEntry')

    def hasEntry(self, item):
        "Do we have this item"
        if self.entry is not None:
            return self.entry.has_key(item)

    security.declareProtected('CompoundDoc: Get List Items', 'getEntries')

    def getEntries(self):
        "Return all the entries as a list"
        if self.entry is not None:
            return self.entry.keys()
        return OOTreeSet()

    security.declareProtected('CompoundDoc: Get List Items', 'getTree')

    def getTree(self):
        "Return all the entries as the native format"
        if self.entry is not None:
            return self.entry
        return OOTreeSet()

    security.declareProtected('CompoundDoc: Clear List Items', 'clearEntries')

    def clearEntries(self):
        "Remove all the entries from the object"
        self.entry = None

    security.declarePrivate('before_manage_edit')

    def before_manage_edit(self, dict):
        "process the edits"
        if 'editAdd' in dict and 'editAddName' in dict:
            self.addEntries(dict['editAddName'])
        if 'editDel' in dict and 'editDelName' in dict:
            self.removeEntries(dict['editDelName'])
        if 'editClear' in dict:
            self.clearEntries()

        data = dict.pop('data', None)
        if data is not None:
            temp = data.read().split()
            self.radioLookup[dict['fileSettings']](self, temp)

    security.declareProtected('View management screens', 'edit')

    def edit(self, *args, **kw):
        "Inline edit short object"
        temp = []
        append = temp.append
        append(self.text_area('editAddName', '', formType="tokens"))
        append('<p>%s</p>' % self.create_button("editAdd", "Add Entries"))
        append(self.text_area('editDelName', '', formType="tokens"))
        append('<p>%s</p>' % self.create_button("editDel", "Delete Entries"))

        append('<p>Upload File:')
        append(self.input_file('data'))
        temp.extend(
            self.radio_list('fileSettings',
                            self.radioOptions,
                            selected='append'))
        append('</p>')

        append(self.create_button("editClear", "Clear All Entries"))

        append('<p>View Email Addresses:')
        path = self.absolute_url_path()
        format = ' <a href="%s">%s</a> '
        append(format % (os.path.join(path, 'drawViewWindows'), 'Windows'))
        append(format % (os.path.join(path, 'drawViewUnix'), 'Unix'))
        append(format % (os.path.join(path, 'drawViewMac'), 'Mac'))
        append('</p>')

        return ''.join(temp)

    security.declareProtected('View', 'view')

    def view(self):
        "Inline draw view"
        return self.unorderedList(self.getEntries())

    security.declarePrivate('PrincipiaSearchSource')

    def PrincipiaSearchSource(self):
        "This is the basic search function"
        return ' '.join(self.getEntries())

    security.declarePrivate('classUpgrader')

    def classUpgrader(self):
        "upgrade this class"
        self.convertListToOOTreeSet()

    security.declarePrivate('convertListToOOTreeSet')

    def convertListToOOTreeSet(self):
        "conver the list object to an OOTreeSet"
        if len(self.entry) and isinstance(self.entry, types.ListType):
            temp = OOTreeSet()
            for i in self.entry:
                temp.insert(i)
            self.setObject('entry', temp)

    convertListToOOTreeSet = utility.upgradeLimit(convertListToOOTreeSet, 141)
Exemple #14
0
class Selection(UserObject):
    "Input text class"

    security = ClassSecurityInfo()
    meta_type = "Selection"

    data = None
    selection = None
    scriptPath = ""
    multipleSelect = 0
    rowsVisible = 1
    allowClear = 0
    outputFormat = 'list'
    dataType = 'string'
    scriptChangePath = ''

    outputValues = (('list', 'Drop Down List'),
                    ('radioinline', 'Radio Box Inline'), ('radioblock',
                                                          'Radio Box Block'),
                    ('checkinline', 'CheckBox Inline'), ('checkblock',
                                                         'CheckBox Block'))
    dateTypes = ('string', 'int', 'float')

    classConfig = {}
    classConfig['scriptPath'] = {'name': 'Path to Script', 'type': 'path'}
    classConfig['multipleSelect'] = {
        'name': 'Enable Multiple Selection',
        'type': 'radio'
    }
    classConfig['rowsVisible'] = {
        'name': 'Number of Rows Visible for Selection',
        'type': 'int'
    }
    classConfig['allowClear'] = {
        'name': 'Enable the clear button',
        'type': 'radio'
    }
    classConfig['outputFormat'] = {
        'name': 'Output Format',
        'type': 'list',
        'values': outputValues
    }
    classConfig['dataType'] = {
        'name': 'Type of Date Stored',
        'type': 'list',
        'values': dateTypes
    }
    classConfig['scriptChangePath'] = {
        'name': 'Path to change notification script',
        'type': 'path'
    }

    updateReplaceList = (
        'scriptPath',
        'multipleSelect',
        'rowsVisible',
        'allowClear',
        'outputFormat',
        'dataType',
    )

    configurable = (
        'dataType',
        'allowClear',
        'outputFormat',
        'multipleSelect',
        'rowsVisible',
        'scriptPath',
    )

    security.declarePrivate('validate_data')

    def validate_data(self, value):
        "validate this value for the new value for the data attribute and then return what is okay"
        if isinstance(value, basestring):
            value = [
                value,
            ]
        temp = []
        allowed = set(self.getChoiceValues())
        checker = validators.getChecker(self.getConfig('dataType'))
        for i in value:
            i = checker(i)
            if i is not None and i in allowed:
                temp.append(i)
        if temp:
            return temp

    security.declarePrivate('post_process_dataType')

    def post_process_dataType(self, before, after):
        "if the dataType is changed we need to ensure that all items in data fall in this new data type"
        self.revalidateData()

    security.declarePrivate('revalidateData')

    def revalidateData(self):
        "revalidate this data object"
        data = self.data
        if data is not None:
            self.setObject('data', self.validate_data(data))

    security.declareProtected('View management screens', 'edit')

    def edit(self, outputFormat=None, *args, **kw):
        "Inline edit short object"
        clear = ''
        if self.getConfig('allowClear'):
            clear = self.create_button('clear',
                                       'Clear %s' % self.getId()) + '<br>'
        return clear + self.getEditControl(outputFormat)

    security.declarePrivate('getEditControl')

    def getEditControl(self, outputFormat=None):
        "get the edit control"
        choices = self.getChoices()
        data = self.data
        if data is None:
            data = []
        outputFormat = outputFormat or self.getConfig('outputFormat')
        if outputFormat == 'list':
            return self.option_select(
                choices,
                'data',
                data,
                multiple=self.getConfig('multipleSelect'),
                size=self.getConfig('rowsVisible'),
                dataType='list')
        if outputFormat == 'radioinline':
            return self.radio_box_inline(choices, 'data', data)
        if outputFormat == 'radioblock':
            return self.radio_box_block(choices, 'data', data)
        if outputFormat == 'checkinline':
            return self.checkbox_inline(choices, 'data', data)
        if outputFormat == 'checkblock':
            return self.checkbox_block(choices, 'data', data)
        return ''

    security.declarePrivate('before_manage_edit')

    def before_manage_edit(self, dict):
        "process the edits"
        clear = dict.pop('clear', None)
        if clear is not None:
            self.clear()
            try:
                del dict['data']
            except KeyError:
                pass

    security.declareProtected("Access contents information", 'getChoices')

    def getChoices(self):
        'get the available choices to select from'
        temp = []
        scriptPath = self.getConfig('scriptPath')
        if scriptPath:
            script = self.getCompoundDocContainer().restrictedTraverse(
                scriptPath, None)
            if script is not None:
                temp = self.changeCallingContext(script)()
        return temp

    security.declareProtected("Access contents information", 'getChoiceValues')

    def getChoiceValues(self):
        'get the available choices to select from'
        for i in self.getChoices():
            if isinstance(i, basestring):
                yield i
            else:
                try:
                    yield i[0]
                except (TypeError, ValueError):
                    yield i

    security.declarePrivate('getSelectedItems')

    def getSelectedItems(self):
        "get the currently selected items"
        data = self.data
        if data is None:
            if self.getConfig('multipleSelect'):
                return []
            else:
                return ''
        if self.getConfig('multipleSelect'):
            return data
        else:
            return data[0]

    security.declareProtected('View', 'view')

    def view(self):
        "Inline draw view"
        return self.getSelectedItems()


#List behavior stuff

    security.declareProtected("Access contents information", "__getitem__")

    def __getitem__(self, i):
        if self.data:
            return self.data[i]
        raise IndexError

    security.declareProtected("Access contents information", "__getslice__")

    def __getslice__(self, i, j):
        i = max(i, 0)
        j = max(j, 0)
        for i in self.data[i:j]:
            yield i

    security.declareProtected("Access contents information", "__iter__")

    def __iter__(self):
        if self.data:
            for i in self.data:
                yield i

    security.declareProtected("Access contents information", "__len__")

    def __len__(self):
        if self.data:
            return len(self.data)
        return 0

    security.declareProtected('Change CompoundDoc', '__setitem__',
                              '__guarded_setitem__')

    def __setitem__(self, i, item):
        if self.data:
            self.data[i] = item
        self._p_changed = 1

    __guarded_setitem__ = __setitem__

    security.declareProtected('Change CompoundDoc', '__delitem__',
                              '__guarded_delitem__')

    def __delitem__(self, i):
        if self.data:
            del self.data[i]
            if not len(self.data):
                self.data = None
            self._p_changed = 1

    __guarded_delitem__ = __delitem__

    #For some reason through the web code can't call this method so disabling it
    #security.declareProtected('Change CompoundDoc', '__setslice__')
    #def __setslice__(self, i, j, other):
    #    i = max(i, 0); j = max(j, 0)
    #    if self.data:
    #        for index in range(i,j):
    #            self.data[index] = other[index]

    #For some reason through the web code can't call this method so disabling it
    #security.declareProtected('Change CompoundDoc', '__delslice__')
    #def __delslice__(self, i, j):
    #    i = max(i, 0); j = max(j, 0)
    #    if self.data:
    #        items = self.data[i:j]
    #        del self.data[i:j]
    #        for i in items:
    #            self.deleteRegisteredObject(i.getId(), [])
    #        if not len(self.data):
    #            self.data=None
    #        self._p_changed = 1

    security.declareProtected('Access contents information', '__contains__')

    def __contains__(self, name):
        if self.data:
            return name in self.data
        return False

    security.declareProtected('Change CompoundDoc', 'append')

    def append(self, item):
        if not self.data:
            self.data = []
        self.data.append(item)
        self._p_changed = 1

    security.declareProtected('Change CompoundDoc', 'insert')

    def insert(self, i, item):
        if not self.data:
            self.data = []
        self.data.insert(i, item)
        self._p_changed = 1

    security.declareProtected('Change CompoundDoc', 'pop')

    def pop(self, i=-1):
        if self.data:
            item = self[i]
            del self[i]
            return item

    security.declareProtected('Change CompoundDoc', 'reverse')

    def reverse(self):
        if self.data:
            self.data.reverse()
            self._p_changed = 1

    security.declareProtected('Change CompoundDoc', 'clear')

    def clear(self):
        self.setObject('data', None, runValidation=0)

    security.declareProtected('Change CompoundDoc', 'store')

    def store(self, items, runValidation=1):
        self.setObject('data', items, runValidation)

    #End list behavior stuff

    security.declarePrivate('classUpgrader')

    def classUpgrader(self):
        "upgrade this class"
        self.makeDataASequence()
        self.clearSelection()
        self.removeScriptEnabled()
        self.fixupData()

    security.declarePrivate('makeDataASequence')

    def makeDataASequence(self):
        "turn data into a sequence if it is not one already"
        data = self.data
        if data is not None and isinstance(data, basestring):
            self.data = [data]

    makeDataASequence = utility.upgradeLimit(makeDataASequence, 141)

    security.declarePrivate('clearSelection')

    def clearSelection(self):
        "clear the selection variable it is no longer used"
        self.setObject('selection', None)

    clearSelection = utility.upgradeLimit(clearSelection, 141)

    security.declarePrivate('removeScriptEnabled')

    def removeScriptEnabled(self):
        "remove the scriptEnabled attribute since it is not needed anymore"
        self.delObjects([
            'scriptEnabled',
        ])

    removeScriptEnabled = utility.upgradeLimit(removeScriptEnabled, 144)

    security.declarePrivate('fixupData')

    def fixupData(self):
        "if the data attribute is a string turn it into a list"
        self.setObject('data', self.validate_data(self.data))

    fixupData = utility.upgradeLimit(fixupData, 146)

    security.declarePrivate('populatorInformation')

    def populatorInformation(self):
        "return a string that this metods pair can read back to load data in this object"
        if self.data:
            return ' /-\ '.join(itertools.imap(str, self.data))
        return ''

    security.declarePrivate('populatorLoader')

    def populatorLoader(self, string):
        "load the data into this object if it matches me"
        string = string.strip()
        if string:
            items = string.split(' /-\ ')
            items = map(str.strip, items)
            if items:
                self.setObject('data', items)
class LookupTable(base.Base):
    "LookupTable class"

    meta_type = "LookupTable"
    security = ClassSecurityInfo()
    records = None
    recordsLength = None

    drawDict = base.Base.drawDict.copy()
    drawDict['drawTable'] = 'drawTable'

    security.declareProtected('View management screens', 'edit')

    def edit(self, *args, **kw):
        "Inline edit short object"
        format = "<p>Currently there are %s records</p><div>%s</div>"
        if self.records is None:
            self.records = OOBTree()
        lenRecords = self.recordsLength(
        ) if self.recordsLength is not None else 0
        return format % (lenRecords, self.create_button('clear', "Clear"))

    security.declarePrivate('processRecorderChanges')

    def processRecorderChanges(self, form):
        "process the recorder changes"
        clear = form.pop('clear', None)
        if clear is not None:
            self.clear()

    security.declarePrivate('after_manage_edit')

    def before_manage_edit(self, form):
        "process the edits"
        self.processRecorderChanges(form)

    security.declareProtected('View management screens', "drawTable")

    def drawTable(self):
        "Render page"
        temp = []
        format = '<p>%s:%s</p>'
        if self.records is not None:
            for key, value in self.records.items():
                temp.append(format % (repr(key), repr(value)))
        return ''.join(temp)

    security.declareProtected('Python Record Modification', 'insert')

    def insert(self, key, value):
        "modify this key and value into the OOBTree"
        if self.records is None:
            self.records = OOBTree()
        if self.recordsLength is None:
            self.setObject('recordsLength', BTrees.Length.Length())

        if key not in self.records:
            self.recordsLength.change(1)
        self.records.insert(key, value)

    security.declareProtected('Python Record Modification', 'add')

    def add(self, key, value):
        "this this key and value into the OOBTree"
        if self.records is None:
            self.records = OOBTree()
        if self.recordsLength is None:
            self.setObject('recordsLength', BTrees.Length.Length())

        if key not in self.records:
            self.recordsLength.change(1)
        self.records[key] = value

    security.declareProtected('Python Record Access', 'items')

    def items(self, min=None, max=None):
        "return the items in this OOBTree"
        if self.records is None:
            return []
        return self.records.items(min, max)

    security.declareProtected('Python Record Access', 'values')

    def values(self, min=None, max=None):
        "return the values of this OOBTree"
        if self.records is None:
            return []
        return self.records.values(min, max)

    security.declareProtected('Python Record Modification', 'update')

    def update(self, collection):
        "update our OOBTree with the data in collection"
        if self.records is None:
            self.records = OOBTree()
        if self.recordsLength is None:
            self.setObject('recordsLength', BTrees.Length.Length())

        records = self.records
        change = self.recordsLength.change
        for key, value in collection.items():
            if key not in records:
                change(1)
            records[key] = value

    security.declareProtected('Python Record Access', 'keys')

    def keys(self, min=None, max=None):
        "return the keys of this OOBTree"
        if self.records is None:
            return []
        return self.records.keys(min, max)

    security.declareProtected('Python Record Modification', '__delitem__')

    def __delitem__(self, key):
        "delete this key from the OOBTree"
        if self.records is not None:
            del self.records[key]
            self.recordsLength.change(-1)

    security.declareProtected('Python Record Modification', 'remove')

    def remove(self, key):
        "delete this key from the OOBTree"
        if self.records is not None:
            del self.records[key]
            self.recordsLength.change(-1)

    security.declareProtected('Python Record Modification', '__setitem__')

    def __setitem__(self, key, value):
        "set this key and value in the OOBTree"
        if self.records is None:
            self.records = OOBTree()
        self.records[key] = value

    security.declareProtected('Python Record Access', '__getitem__')

    def __getitem__(self, index):
        "get this item from the OOBTree"
        if self.records is not None:
            return self.records[index]
        raise KeyError, index

    security.declareProtected('Python Record Access', 'get')

    def get(self, key, default=None):
        "get this item from the OOBTree"
        if self.records is not None:
            return self.records.get(key, default)
        return default

    security.declareProtected('Python Record Access', 'has_key')

    def has_key(self, key):
        "see if we have this key in the OOBTree"
        if self.records is not None:
            return self.records.has_key(key)
        return False

    security.declareProtected('Python Record Modification', 'clear')

    def clear(self):
        "clear the OOBTree"
        self.setObject('records', None)
        self.setObject('recordsLength', None)

    security.declarePrivate("PrincipiaSearchSource")

    def PrincipiaSearchSource(self):
        "This is the basic search function"
        return ''

    security.declarePrivate('classUpgrader')

    def classUpgrader(self):
        "upgrade this class"
        self.createBTreeLength()

    security.declarePrivate('createBTreeLength')

    def createBTreeLength(self):
        "remove Filters that are not being used"
        if self.records is not None:
            length = BTrees.Length.Length()
            length.set(len(self.records))
            self.setObject('recordsLength', length)

    createBTreeLength = utility.upgradeLimit(createBTreeLength, 165)
Exemple #16
0
class File(UserObject):
    "File Class"

    meta_type = "File"
    security = ClassSecurityInfo()
    data = None
    fileSize = ''
    openFileInNewWindow = 0
    deletion = 1
    showPreview = 1
    showOpenInNewWindow = 0
    urlExtension = ''
    title = 'Download File'
    filename = 'file'
    fileUrl = ''

    classConfig = {}
    classConfig['deletion'] = {'name': 'deletion', 'type': 'radio'}
    classConfig['showPreview'] = {'name': 'preview', 'type': 'radio'}
    classConfig['showOpenInNewWindow'] = {
        'name': 'showOpenInNewWindow',
        'type': 'radio'
    }
    classConfig['openFileInNewWindow'] = {
        'name': 'openFileInNewWindow',
        'type': 'radio'
    }
    classConfig['urlExtension'] = {'name': 'urlExtension', 'type': 'tokens'}
    classConfig['title'] = {'name': 'title', 'type': 'string'}
    classConfig['filename'] = {'name': 'filename', 'type': 'string'}
    classConfig['fileUrl'] = {'name': 'File Url', 'type': 'string'}

    updateReplaceList = ('deletion', 'showPreview', 'showOpenInNewWindow',
                         'urlExtension', 'openFileInNewWindow')

    configurable = ('openFileInNewWindow', )

    security.declarePrivate('validate_title')

    def validate_title(self, value):
        "remove all leading and trailing whitespace"
        temp = value
        try:
            temp = value.strip()
        except AttributeError:
            pass
        if not temp:
            temp = 'Download File'
        return temp

    security.declarePrivate('validate_filename')

    def validate_filename(self, value):
        "remove all leading and trailing whitespace"
        temp = value
        try:
            temp = value.strip()
        except AttributeError:
            pass
        if not temp:
            temp = 'file'
        return temp

    security.declarePrivate('validate_urlExtension')

    def validate_urlExtension(self, value):
        "make sure we get rid of this if the value is false"
        if value:
            return value
        else:
            return ''

    security.declarePublic("__bobo_traverse__")

    def __bobo_traverse__(self, REQUEST, name):
        "__bobo_traverse__"
        if name.startswith('ver_'):
            return Wrapper(name, self)
        extensions = []
        if self.getConfig('urlExtension'):
            extensions = self.getConfig('urlExtension')
        stack = self.REQUEST.TraversalRequestNameStack
        if stack and stack[0] in extensions:
            extension = stack[0]
            self.REQUEST.TraversalRequestNameStack = []
            return getattr(self, extension)
        if self.exists() and name == self.filename:
            if self.fileUrl:
                return self.redir
            object = self.data
            type = object.content_type
            if type == 'application/msword' or type == "":
                type = 'application/octet-stream'
                object.content_type = type
            self.REQUEST.RESPONSE.setHeader('Content-Type', type)
            return object.index_html
        elif hasattr(self, name):
            return getattr(self, name)

    security.declareProtected('View', 'redirect_file_url')

    def redirect_file_url(self):
        "redirect to the real file"
        return self.REQUEST.RESPONSE.redirect(
            self.getUrlWithExtension(disableExtension=1))

    security.declareProtected('View', 'redir')

    def redir(self):
        "redirect to the real file"
        return self.REQUEST.RESPONSE.redirect(self.fileUrl)

    security.declareProtected('View management screens', 'edit')

    def edit(self, *args, **kw):
        "Inline edit short object"
        temp = []
        if self.showPreview:
            preview = self.preview()
            if preview:
                temp.append(preview)
        temp.append(self.editSingleConfig('title'))
        temp.append(self.editSingleConfig('filename'))
        temp.append(self.editSingleConfig('fileUrl'))
        temp.append('<p>%s</p>' % self.input_file('data'))
        if self.exists() and self.deletion:
            temp.append('<p>Delete Current File: %s </p>' %
                        self.check_box('_del', 'Y'))
        if self.showOpenInNewWindow:
            temp.append(
                '<p>Open File in New Window: %s </p>' % self.true_false(
                    'openFileInNewWindow', self.openFileInNewWindow, 0))
        return ''.join(temp)

    security.declarePrivate('before_manage_edit')

    def before_manage_edit(self, dict):
        "This is the object specific edit stuff"
        delFile = dict.pop('_del', None)
        if delFile == 'Y':
            self.delObjects(('data', 'fileSize'))

        data = dict.pop('data', None)
        if data:  #files are always uploaded but if the file has no data in it the test is false
            try:
                if not self.data:
                    self.manage_addProduct['File'].manage_addFile('data', data)
                else:
                    self.data.manage_upload(data)
                self.setFileSize()
                self.updateFileContentType()
            except ValueError:  #catches no file uploaded
                pass

    def updateFileContentType(self):
        "Update the content type of the installed file"
        if self.exists():
            if self.hasObject('data'):
                file_obj = aq_base(self.data)
                if hasattr(file_obj, 'data'):
                    filename, remove_after = utility.createTempFile(
                        file_obj.data)
                    file_obj.content_type = magicfile.magic(filename)
                    utility.removeTempFile(filename, remove_after)

    def storeContentType(self, content_type):
        "store the content type for to this object"
        if self.exists():
            self.data.content_type = content_type

    security.declareProtected('View', 'getFileSize')

    def getFileSize(self):
        "Return the file size of this object"
        return self.fileSize

    security.declareProtected('View', 'view')

    def view(self,
             title='',
             extension='',
             disableExtension=None,
             query=None,
             url=None,
             showSize=1,
             openFileInNewWindow=None):
        "Render page"
        queryString = ''
        if query is not None:
            queryString = '?' + urllib.urlencode(query)
        if not self.fileUrl and self.data == None:
            pass
        else:
            if not title:
                title = self.title
            if url is None:
                url = self.getUrlWithExtension(extension, disableExtension)
            openFileInNewWindow = openFileInNewWindow if openFileInNewWindow is not None else self.getConfig(
                'openFileInNewWindow')
            if openFileInNewWindow:
                target = 'target="_blank"'
            else:
                target = ''
            if self.fileUrl:
                fileSize = ''
            elif showSize:
                fileSize = self.getFileSize()
                if fileSize:
                    fileSize = '(%s)' % fileSize
            else:
                fileSize = ''
            return '<a href="%s%s" %s class="file">%s</a> %s' % (
                url, queryString, target, title, fileSize)
        return ""

    security.declareProtected('View', 'getUrlWithExtension')

    def getUrlWithExtension(self, extension='', disableExtension=None):
        "process for a url extension and make sure it goes to a valid location otherwise just give back our current url"
        urlExtension = self.getConfig('urlExtension')
        if urlExtension and not (extension and extension in urlExtension):
            extension = urlExtension[0]
        if extension and not disableExtension:
            try:
                self.getCompoundDocContainer().restrictedTraverse(extension)
                return urllib.quote(
                    os.path.join(self.absolute_url_path(), self.filename,
                                 extension))
            except KeyError:
                pass

        if self.fileUrl:
            return self.fileUrl
        else:
            version = 'ver_%s' % int(
                self.data.bobobase_modification_time().timeTime())
            return os.path.join(self.absolute_url_path(), version,
                                urllib.quote(self.filename))

    security.declarePrivate('setFileSize')

    def setFileSize(self):
        "Store the file size of this object"
        try:
            #0 length files should not have this field set
            size = self.data.size
            if size:
                fileSize = utility.fileSizeString(size)
                self.setObject('fileSize', fileSize)
        except AttributeError:
            pass

    security.declareProtected("Access contents information", 'exists')

    def exists(self):
        "Check if object has data in it"
        try:
            return bool(self.data and hasattr(aq_base(self.data), 'data')
                        or self.fileUrl)
        except AttributeError:
            return 0

    security.declareProtected('View management screens', 'preview')

    def preview(self):
        "Preview of a file"
        if self.exists():
            if self.fileUrl:
                url = self.fileUrl
                fileType = ''
                fileSize = ''
            else:
                version = 'ver_%s' % int(
                    self.data.bobobase_modification_time().timeTime())
                url = os.path.join(self.absolute_url_path(), version,
                                   urllib.quote(self.filename))
                fileType = self.data.content_type
                fileSize = self.getFileSize()
            title = self.title

            return '<p>Preview: <a href="%s">%s</a> (%s) %s</p>' % (
                url, title, fileSize, fileType)
        return ""

    security.declarePrivate("PrincipiaSearchSource")

    def PrincipiaSearchSource(self):
        "This is the basic search function"
        obj = self.data
        search = [self.title, self.filename]
        if self.exists() and not self.fileUrl and obj.content_type.count(
                "text"):
            if isinstance(obj.data, ZODB.blob.Blob):
                search.append(obj.data.open('r').read())
            else:
                search.append(str(obj.data))
        return ' '.join(search)

    security.declarePrivate('dataLoader')

    def dataLoader(self, dict):
        "load the data from this dict into this object"
        self.before_manage_edit(dict)
        self.filename.manage_edit(dict['filename'])
        self.title.manage_edit(dict['title'])

    security.declarePrivate('classUpgrader')

    def classUpgrader(self):
        "upgrade this class"
        self.updateTitle()
        self.updateFilename()
        self.updatePreview()
        self.removeAttributeText()
        self.changeUrlExtension()
        self.fixFileId()
        self.fixBlankFileName()
        self.fixBlankTitle()
        self.fixBlankFile()

    security.declarePrivate('updateTitle')

    def updateTitle(self):
        "update the title object from a string to an AttributeText"
        if isinstance(self.title, basestring):
            return
        if getattr(self.title, 'meta_type', None) != 'AttributeText':
            if 'title' in self.objectConfig and hasattr(
                    self.objectConfig.title, 'value'):
                self.addRegisteredObject('title',
                                         'AttributeText',
                                         data=self.title,
                                         title=self.objectConfig.title.value)
            else:
                self.addRegisteredObject('title', 'AttributeText', data='')

    updateTitle = utility.upgradeLimit(updateTitle, 141)

    security.declarePrivate('updateFilename')

    def updateFilename(self):
        "update the filename object from a string to an AttributeText"
        if getattr(self.filename, 'meta_type',
                   None) != 'AttributeText' and hasattr(
                       self.objectConfig.filename, 'value'):
            self.addRegisteredObject('filename',
                                     'AttributeText',
                                     data=self.filename,
                                     title=self.objectConfig.filename.value)
        if getattr(self.filename, 'meta_type', None) != 'AttributeText':
            self.addRegisteredObject('filename', 'AttributeText', data='')

    updateFilename = utility.upgradeLimit(updateFilename, 141)

    security.declarePrivate('updatePreview')

    def updatePreview(self):
        "fix the preview setting up"
        if 'preview' in self.__dict__:
            self.setObject('showPreview', self.preview)
            self.delObjects(('preview', ))

    updatePreview = utility.upgradeLimit(updatePreview, 141)

    security.declarePrivate('removeAttributeText')

    def removeAttributeText(self):
        "remove the attributetext items and replace them with basic attributes"
        self.fixupTitle()
        self.fixupFileName()

    removeAttributeText = utility.upgradeLimit(removeAttributeText, 150)

    security.declarePrivate('fixupFileName')

    def fixupFileName(self):
        "fixup the filename attribute"
        try:
            filename = self.filename.data
            self.delObjects(('filename', ))
            self.setObject('filename', filename)
        except AttributeError:
            pass

    security.declarePrivate('fixupTitle')

    def fixupTitle(self):
        "fixup the title attribute"
        try:
            title = self.title.data
            self.delObjects(('title', ))
            self.setObject('title', title)
        except AttributeError:
            pass

    security.declarePrivate('changeUrlExtension')

    def changeUrlExtension(self):
        "change urlExtension to a sequence"
        if self.urlExtension:
            self.setObject('urlExtension', self.urlExtension.split())

    changeUrlExtension = utility.upgradeLimit(changeUrlExtension, 151)

    security.declarePrivate('fixFileId')

    def fixFileId(self):
        "change urlExtension to a sequence"
        if self.data:
            self.data.__name__ = 'data'

    fixFileId = utility.upgradeLimit(fixFileId, 152)

    security.declarePrivate('fixBlankFileName')

    def fixBlankFileName(self):
        "change urlExtension to a sequence"
        if not self.filename:
            self.filename = 'file'

    fixBlankFileName = utility.upgradeLimit(fixBlankFileName, 170)

    security.declarePrivate('fixBlankTitle')

    def fixBlankTitle(self):
        "change urlExtension to a sequence"
        if not self.title:
            self.title = 'Download File'

    fixBlankTitle = utility.upgradeLimit(fixBlankTitle, 173)

    security.declarePrivate('fixBlankFile')

    def fixBlankFile(self):
        "fix a bug where an empy file is uploaded"
        if self.fileSize == '0.0 B':  #we don't want to load the child object if we can avoid it
            if self.data is None or not self.data.size:
                self.delObjects(('data', 'fileSize'))

    fixBlankFile = utility.upgradeLimit(fixBlankFile, 177)
class MethodManager(Base):
    "IMethod object which binds a remote callable object"

    security = ClassSecurityInfo()
    meta_type = "MethodManager"
    lookup = None

    security.declareProtected('View management screens', 'edit')

    def edit(self, *args, **kw):
        "Inline edit view"
        temp = []
        typeformat = '<div>name: %s path:%s</div>'
        lookup = sorted(self.getLookup().items())
        lookup.append(('', ''))
        for index, (nameValue, pathValue) in enumerate(lookup):
            temp.append(
                typeformat %
                (self.input_text(
                    'name', nameValue, containers=('lookup', str(index))),
                 self.input_text(
                     'path', pathValue, containers=('lookup', str(index)))))
        return ''.join(temp)

    security.declarePrivate('before_manage_edit')

    def before_manage_edit(self, dict):
        "Process edits."
        lookup = dict.pop('lookup', None)
        if lookup is not None:
            temp = {}
            for i, j in lookup.items():
                temp[int(i)] = j
            temp = ((dictionary['name'].strip(), dictionary['path'].strip())
                    for index, dictionary in sorted(temp.iteritems))
            cleaned = [(name, display) for name, display in temp
                       if name and display]
            if len(cleaned):
                temp = {}
                for name, display in cleaned:
                    temp[name] = display
                self.setObject('lookup', temp)
            else:
                self.delObjects(('lookup', ))

    security.declarePrivate('getMethod')

    def getMethod(self, name):
        "Inline draw view"
        cdoc = self.getCompoundDocContainer()
        path = self.getLookup()[name]
        item = cdoc.restrictedTraverse(path, None)
        if item is not None:
            return cdoc.changeCallingContext(item)

    security.declareProtected('Access contents information', '__contains__')

    def __contains__(self, name):
        "see if name is in me"
        return name in self.getLookup()

    security.declarePrivate('getLookup')

    def getLookup(self):
        "get the current lookup variable"
        if self.lookup is not None:
            return self.lookup
        return {}

    security.declarePrivate('classUpgrader')

    def classUpgrader(self):
        "upgrade this class"
        self.transferAndDelete()

    security.declarePrivate('transferAndDelete')

    def transferAndDelete(self):
        "transfer all the data to the LinkManager object and delete this one"
        cdoc = self.getCompoundDoc()
        link = cdoc.LinkManager
        for name, path in self.getLookup().items():
            link.addPath(path)
        cdoc.delObjects([self.getId()])

    transferAndDelete = utility.upgradeLimit(transferAndDelete, 147)
class DisplayUserAgent(Base):
    "DisplayFilter apply this to an object to change how it outputs"

    meta_type = "DisplayUserAgent"
    security = ClassSecurityInfo()
    overwrite = 1
    data = ''
    clients = None
    setused = ''
    operatingSystems = None

    security.declarePrivate('before_manage_edit')

    def before_manage_edit(self, dict):
        "process the edits"
        userAgentSelect = dict.pop('userAgentSelect', None)
        if userAgentSelect is not None:
            self.setClients({})
            try:
                del dict['userAgent']
            except KeyError:
                pass

        operatingSystems = dict.pop('operatingSystems', None)
        if operatingSystems is not None:
            allowedOS = useragent.UserAgent.getAllowedOperatingSystems
            temp = [i for i in operatingSystems if i in allowedOS]
            if temp:
                self.setObject('operatingSystems', temp)

        userAgent = dict.pop('userAgent', None)
        if userAgent is not None:
            seq = []
            for i in userAgent:
                i = i.split(' ')
                length = 4 - len(i)
                i.extend([''] * length)
                seq.append(tuple(i))
            clients = utility.mergeSequenceTree(seq)
            if clients:
                self.setClients(clients)

    security.declareProtected('View management screens', 'edit')

    def edit(self, *args, **kw):
        "Inline edit view"
        return "<p>UserAgent Set : %s</p>\n" % self.option_select(
            self.clientSets(), 'setused', [self.setused])

    security.declarePrivate('setClients')

    def setClients(self, clients):
        "set the clients for this object"
        if not clients:
            clients = None
        self.setObject('clients', clients)

    security.declarePrivate('getClients')

    def getClients(self):
        "Get the clients of this object"
        if self.setused:
            return self.getSetClients()
        if self.clients is not None:
            return self.clients
        return {}

    def clientSets(self):
        "returns a list of the client sets that we have"
        return self.clientSetMapping().keys()

    def clientSetMapping(self):
        "Return a dict of sets, funcname mappings"
        sets = {}
        sets['XHTML 1.0 CSS1'] = 'XHTML10CSS1'
        sets['XHTML 1.0 CSS2'] = 'XHTML10CSS2'
        sets['HTML4'] = 'HTML4'
        sets['MSIE 5 and 6'] = 'MSIE56'
        sets['No Detection'] = 'noDetection'
        sets[''] = ''
        return sets

    def getSetClients(self):
        "Return the clients that matches this set name"
        setname = self.setused
        if setname in self.clientSets():
            funcname = self.clientSetMapping()[setname]
            return getattr(self, funcname)()

    def XHTML10CSS1(self):
        "Opera 5 and 6, MSIE 5 and 6"
        return {
            '': {
                'Opera': {
                    '6': {
                        '': {}
                    },
                    '5': {
                        '': {}
                    }
                }
            },
            'Mozilla/4': {
                'MSIE': {
                    '6': {
                        '': {}
                    },
                    '5': {
                        '': {}
                    }
                }
            }
        }

    def XHTML10CSS2(self):
        "Mozilla/5 and the W3C_Validator selected"
        return {
            'Mozilla/5': {
                '': {
                    '': {
                        '': {}
                    }
                }
            },
            '': {
                'W3C_Validator': {
                    '': {
                        '': {}
                    }
                }
            }
        }

    def HTML4(self):
        "Mozilla/4 browsers selected"
        return {'Mozilla/4': {'': {'': {'': {}}}}}

    def MSIE56(self):
        "Only IE 5 and 6 selected"
        return {'Mozilla/4': {'MSIE': {'6': {'': {}}, '5': {'': {}}}}}

    def noDetection(self):
        "No UserAgents selected"
        return {}

    security.declarePrivate('classUpgrader')

    def classUpgrader(self):
        "upgrade this class"
        self.repairSetused()
        self.removeBlankOSClients()

    security.declarePrivate('repairSetused')

    def repairSetused(self):
        "fix the xhtml entry for set used"
        if self.setused == 'XTML 1.0 CSS2':
            self.setused = 'XHTML 1.0 CSS2'

    repairSetused = utility.upgradeLimit(repairSetused, 141)

    security.declarePrivate('removeBlankOSClients')

    def removeBlankOSClients(self):
        "remove blank operatingSystems and clients entries"
        if not self.clients:
            self.delObjects(['clients'])
        if not self.operatingSystems:
            self.delObjects(['operatingSystems'])

    removeBlankOSClients = utility.upgradeLimit(removeBlankOSClients, 161)
Exemple #19
0
class Display(base.Base):
    "This is a dispatcher for display filter objects based on the type of viewer request"

    meta_type = "Display"
    security = ClassSecurityInfo()
    overwrite = 1

    #quick hack remove later with a usage object
    security.declarePrivate('getAllowedUsages')

    def getAllowedUsages(self):
        "Get the allowed usages of a Display"
        return ['edit', 'view']

    description = ''
    usage = 'view'
    defaultFilter = ''

    security.declarePrivate('afterDeleteRegisteredObject')

    def afterDeleteRegisteredObject(self, name):
        "do something after a registered object is deleted"
        self.setAutoDefaultFilter()

    security.declarePrivate('afterAddRegisteredObject')

    def afterAddRegisteredObject(self, name, metatype):
        "do something after a registered object has been added"
        if metatype == 'DisplayFilter':
            self.setAutoDefaultFilter()

    security.declarePrivate('after_manage_edit')

    def after_manage_edit(self, dict):
        "after a display is edited notify the parent of our usage"
        self.DisplayManager.addMapping(self.getId())
        self.DisplayManager.cleanupDefaultDisplays(self)

    security.declareProtected('View', 'view')

    def view(self):
        "Inline draw view"
        filters = self.objectValues('DisplayFilter')
        if len(filters) == 1:
            f = filters[0]
            if not 'header' in self.REQUEST.other:  #used to check if a render is already default
                if not 'DisplayFilter' in self.REQUEST.other:
                    self.REQUEST.other['DisplayFilter'] = f
            return f.view()
        filters = sorted(i.willRender() for i in filters)
        if filters:
            first = filters.pop()
            #check for match on browser and language
            if first[0] != 0:
                filter = first.pop()
                if not 'DisplayFilter' in self.REQUEST.other:
                    self.REQUEST.other['DisplayFilter'] = filter
                return filter.view()
        if self.defaultFilter:
            filter = getattr(self, self.defaultFilter)
            if not 'DisplayFilter' in self.REQUEST.other:
                self.REQUEST.other['DisplayFilter'] = filter
            return filter.view()
        else:
            return ''

    security.declareProtected('View management screens', 'edit')

    def edit(self, *args, **kw):
        "Inline edit view"
        temp = [
            "<p>Usage is : %s</p>\n" %
            self.option_select(self.getAllowedUsages(), 'usage', [self.usage])
        ]
        displayIds = self.objectIds('DisplayFilter')
        if displayIds:
            temp.append("<p>Default Filter is : %s</p>\n" % self.option_select(
                displayIds, 'defaultFilter', [self.defaultFilter]))
        temp.append(self.addDeleteObjectsEdit())
        temp.append('<p>Description:</p>')
        temp.append(self.text_area('description', self.description))
        return ''.join(temp)

    security.declarePrivate('restrictedUserObject')

    def restrictedUserObject(self):
        "Return a list of the types that are allowed to be added or deleted from this object by a user"
        return ['DisplayFilter']

    security.declarePrivate('PrincipiaSearchSource')

    def PrincipiaSearchSource(self):
        "Return what can be search which is nothing"
        return ''

    security.declarePrivate("setAutoDefaultFilter")

    def setAutoDefaultFilter(self):
        "set the default filter to a filter if one is not already set"
        filters = self.objectIds('DisplayFilter')
        currentFilter = self.defaultFilter
        if currentFilter not in filters:
            currentFilter = None
        if not currentFilter and len(filters):
            self.setObject("defaultFilter", filters[0])

    security.declarePrivate('classUpgrader')

    def classUpgrader(self):
        "upgrade this class"
        self.upgraderChangeDisplayObjectRef()
        self.removeOldVars()

    security.declarePrivate('removeOldVars')

    def removeOldVars(self):
        "remove some old variables"
        self.delObjects(['alias', 'registeredFilters'])

    removeOldVars = utility.upgradeLimit(removeOldVars, 141)

    security.declarePrivate('upgraderChangeDisplayObjectRef')

    def upgraderChangeDisplayObjectRef(self):
        "Change the object refs in default edit to a name instead"
        id = self.getId()
        default = 'defaultFilter'
        self.delObjects([id + 'edit'])
        try:
            self.setObject(default, getattr(self, default).getId())
        except AttributeError:
            pass

    upgraderChangeDisplayObjectRef = utility.upgradeLimit(
        upgraderChangeDisplayObjectRef, 141)
Exemple #20
0
class TabManager(BaseTab):
    "TabManager manages multiple tabs in the edit interface"

    meta_type = "TabManager"
    security = ClassSecurityInfo()
    overwrite = 1
    displayType = 'edit'
    active = 0

    security.declarePrivate('PrincipiaSearchSource')

    def PrincipiaSearchSource(self):
        "This is the basic search function"
        return ''

    security.declareProtected('View', 'view')

    def view(self, doc=None, renderer=None, tabScript=None):
        "Inline draw view"
        if doc is None:
            doc = self.getCompoundDoc()
        renderer = renderer or self.getConfig('renderer')
        if self.getTabActive():
            editname = self.getDisplayName()
            menu = []
            url = doc.absolute_url_path()
            for name, clickableName, cssClass, queryDict, query in self.getTabOrder(
                    doc=doc, tabScript=tabScript):
                selected = 0
                if self.getTabMapping(
                        name) == editname and utility.dictInQuery(
                            queryDict, query):
                    selected = 1
                query = query.copy()
                query.update(queryDict)
                menu.append(('%s/manage_workspace/%s' % (url, name),
                             clickableName, selected, cssClass, query, ''))
            cssClass = ' class="tabControl"' if renderer != 'Themeroller Tabs' else ''
            return '<div%s>%s</div>' % (cssClass,
                                        NestedListURL.listRenderer(
                                            renderer, menu, self.columns))
        return ""

    security.declareProtected('View management screens', 'edit')

    def edit(self, *args, **kw):
        "Inline edit view"
        format = '<div class="outline"><p>%s</p>%s</div>'
        return format % (self.editSingleConfig('active'), BaseTab.edit(self))

    security.declarePrivate('classUpgrader')

    def classUpgrader(self):
        "upgrade this class"
        BaseTab.classUpgrader(self)
        self.fixupTabOrder()
        self.fixupTabMapping()

    security.declarePrivate('fixupTabOrder')

    def fixupTabOrder(self):
        "fixup the tabOrder attribute"
        if not self.tabOrder:
            self.setObject('tabOrder', None)

    fixupTabOrder = utility.upgradeLimit(fixupTabOrder, 141)

    security.declarePrivate('fixupTabMapping')

    def fixupTabMapping(self):
        "fixup the tabMapping attribute"
        if not self.tabMapping:
            self.setObject('tabMapping', None)

    fixupTabMapping = utility.upgradeLimit(fixupTabMapping, 141)
Exemple #21
0
class TextArea(UserObject):
    "TextArea class"

    meta_type = "TextArea"
    security = ClassSecurityInfo()

    data = ''
    renderCache = ''
    struct = 1
    structstate = 1

    configurable = ('structstate', )

    security.declareProtected('View management screens', 'edit')

    def edit(self, struct=None, *args, **kw):
        "Inline edit short object"
        temp = self.text_area('data', self.data)
        if struct is not None:
            struct = self.struct
        if struct:
            format = '<div>%s Click "No" if you don\'t want your text auto-formatted.</div>'
            temp = temp + format % self.editSingleConfig('structstate')
        return temp

    security.declareProtected('View', 'view')

    def view(self):
        "Render page"
        return self.renderCache or self.data

    security.declarePrivate('after_manage_edit')

    def after_manage_edit(self, form):
        "update the render cache after all other changes"
        self.updateCache()

    security.declarePrivate('updateCache')

    def updateCache(self):
        "update the cache of this object if applicable"
        if self.getConfig('structstate'):
            self.setObject('renderCache',
                           str(nocodestructured.HTML(self.data, header=0)))
        else:
            self.delObjects([
                'renderCache',
            ])

    classConfig = {}
    classConfig['struct'] = {'name': 'struct', 'type': 'radio'}
    classConfig['structstate'] = {
        'name': 'Structured Text Enabled',
        'type': 'radio'
    }

    security.declarePrivate('classUpgrader')

    def classUpgrader(self):
        "upgrade this class"
        self.upgraderReplaceStructured()
        self.fixRenderCache()

    security.declarePrivate('upgraderReplacedStructured')

    def upgraderReplaceStructured(self):
        "replace structured object attribute with structstate config"
        if self.hasObject('structured'):
            structured = self.structured
            if structured == 'Y':
                structured = 1
            elif structured == 'N':
                structured = 0
            self.setObject('structstate', int(structured))
            self.delObjects(['structured'])

    upgraderReplaceStructured = utility.upgradeLimit(upgraderReplaceStructured,
                                                     141)

    security.declarePrivate('fixRenderCache')

    def fixRenderCache(self):
        "remove renderCache if stx is not enabled"
        self.updateCache()

    fixRenderCache = utility.upgradeLimit(fixRenderCache, 154)

    configKeep = ('structstate', )

    security.declarePrivate('configLoader')

    def configLoader(self, config):
        "load the config object for this textarea object"
        if config.hasObject('meta_type') and config.meta_type == 'Config':
            config = config.convertToDict()
        replaceEntries = [key for key in config if key not in self.configKeep]
        for key in replaceEntries:
            self.setObject(key, config[key])

    security.declarePrivate('populatorInformation')

    def populatorInformation(self):
        "return a string that this metods pair can read back to load data in this object"
        return self.data.replace('\n', '\\n')

    security.declarePrivate('populatorLoader')

    def populatorLoader(self, string):
        "load the data into this object if it matches me"
        self.setObject('data', string.replace('\\n', '\n'))
        self.updateCache()

    security.declareProtected('Change CompoundDoc', 'store')

    def store(self, string):
        "set the calculation value of this object"
        self.setObject('data', str(string))
        self.updateCache()
Exemple #22
0
class Picture(BasePicture):
    "Image class"

    meta_type = "Picture"
    security = ClassSecurityInfo()
    imagesrc = ''  #obsolete
    imagesrc_template = ''
    data = None
    image = None
    fileSize = ''
    deletion = 1
    preview = 1
    showTags = 1
    showAlt = 1
    showURL = 1
    url = ''
    alt = ''
    tags = ''
    thumbnail = None
    resizeOnUpload = 0
    resaveOnUpload = 1

    classConfig = BasePicture.classConfig.copy()
    classConfig['deletion'] = {'name': 'deletion', 'type': 'radio'}
    classConfig['preview'] = {'name': 'preview', 'type': 'radio'}
    classConfig['showTags'] = {'name': 'showTags', 'type': 'radio'}
    classConfig['resaveOnUpload'] = {
        'name': 'Resave Images on Upload',
        'type': 'radio'
    }
    classConfig['tags'] = {'name': 'tags', 'type': 'string'}
    classConfig['alt'] = {'name': 'alt', 'type': 'string'}
    classConfig['url'] = {'name': 'url', 'type': 'string'}
    classConfig['showAlt'] = {'name': 'showAlt', 'type': 'radio'}
    classConfig['showURL'] = {'name': 'showURL', 'type': 'radio'}
    classConfig['resizeOnUpload'] = {
        'name': 'Resize uploaded images?',
        'type': 'radio'
    }

    configurable = BasePicture.configurable + (
        'deletion', 'showAlt', 'showTags', 'showURL', 'preview',
        'scriptChangePath', 'resizeOnUpload', 'resaveOnUpload')
    attr_notified = set([
        'url', 'alt', 'tags', 'showUrl', 'showAlt', 'showTags', 'preview',
        'deletion', 'data'
    ])

    security.declareProtected('View management screens', 'edit')

    def edit(self,
             showTags=None,
             showAlt=None,
             showURL=None,
             preview=None,
             *args,
             **kw):
        "Inline edit short object"
        temp = []
        if preview is None:
            preview = self.getConfig('preview')
        if self.exists() and preview:
            object = self.data
            width, height = object.width, object.height
            size = self.getFileSize()
            if not size:
                self.setFileSize()
                size = self.getFileSize()
            type = object.content_type
            format = '<p>Preview: %s  (%s px/%s px) %s %s </p>'
            temp.append(format % (self.small(), width, height, size, type))

        if showTags is None:
            showTags = self.getConfig('showTags')
        if showTags:
            temp.append(self.editSingleConfig('tags'))

        if showAlt is None:
            showAlt = self.getConfig('showAlt')
        if showAlt:
            temp.append(self.editSingleConfig('alt'))

        if showURL is None:
            showURL = self.getConfig('showURL')
        if showURL:
            temp.append(self.editSingleConfig('url'))

        temp.append('<div>%s</div><p>Click [Browse] to enter the picture</p>' %
                    self.input_file('data'))
        if self.getConfig('deletion') and self.exists():
            temp.append('<p>Delete Current Image: %s </p>' %
                        self.check_box('_del', 'Y'))
        return ''.join(temp)

    security.declarePrivate('before_manage_edit')

    def before_manage_edit(self, dict):
        "This is the object specific edit stuff"
        if dict.pop('_del', None) == 'Y':
            self.clear()

        if dict.get('data',
                    None):  #don't process if data does not have anything in it
            filename, remove_after = utility.createTempFile(dict['data'])
            content_type = magicfile.magic(filename)
            if content_type.startswith('image'):
                if not self.data:
                    self.manage_addProduct['Image'].manage_addImage(
                        'data', '', 'data')
                if self.getConfig('resizeOnUpload'):
                    self.resizeImage(filename)
                elif self.getConfig('resaveOnUpload'):
                    temp_file, x, y = utility.resaveExistingImage(filename)
                    if temp_file is not None:
                        self.data.manage_upload(temp_file)
                        temp_file.close()
                        self.data.width = x
                        self.data.height = y
                    else:
                        self.data.manage_upload(open(filename, 'rb'))
                else:
                    self.data.manage_upload(open(filename, 'rb'))
                self.updateParentPaths(set(['data']))

                self.makeThumbnail(filename)
                self.setFileSize()
                self.storeContentType(content_type)
            utility.removeTempFile(filename, remove_after)
        try:
            del dict['data']
        except KeyError:
            pass

    security.declareProtected('Change CompoundDoc', 'clear')

    def clear(self):
        "clear this image"
        if self.getConfig('deletion'):
            self.delObjects(('data', 'imagesrc', 'thumbnail', 'fileSize',
                             'imagesrc_template'))

    security.declarePrivate('after_manage_edit')

    def after_manage_edit(self, dict):
        "cache some information after this object has been modified"
        if self.hasBeenModified():
            self.updateImageSrcCache()

    security.declareProtected('Change CompoundDoc', 'resizeImage')

    def resizeImage(self, filename):
        "generate this image"
        image = PIL.Image.open(filename)
        if image.mode != self.getConfig('color'):
            image = image.convert(self.getConfig('color'))
        maxWidth = self.getConfig('width')
        maxHeight = self.getConfig('height')
        crop_left = self.getConfig('crop_left')
        crop_upper = self.getConfig('crop_upper')
        crop_right = self.getConfig('crop_right')
        crop_lower = self.getConfig('crop_lower')
        if crop_right and crop_lower:
            image = image.crop((crop_left, crop_upper, crop_right, crop_lower))
        (x, y) = image.size
        if x > maxWidth:
            y = y * maxWidth / x
            x = maxWidth
        if y > maxHeight:
            x = x * maxHeight / y
            y = maxHeight
        if x == 0:
            x = 1
        if y == 0:
            y = 1
        image = image.resize((x, y))
        tempFile = utility.saveImage(image, self.getConfig('format'))
        self.data.manage_upload(tempFile)
        self.data.width = x
        self.data.height = y

    security.declareProtected('Change CompoundDoc', 'resaveExistingImage')

    def resaveExistingImage(self):
        "reisze existing images"
        if self.exists():
            filename, remove_after = utility.createTempFile(self.data.data)
            content_type = magicfile.magic(filename)
            if content_type.startswith('image'):
                if self.getConfig('resaveOnUpload'):
                    temp_file, x, y = utility.resaveExistingImage(filename)
                    beforeSize = utility.fileSizeToInt(self.getFileSize())
                    if temp_file is not None and os.stat(
                            temp_file.name)[stat.ST_SIZE] < beforeSize:
                        if not self.data:
                            self.manage_addProduct['Image'].manage_addImage(
                                'data', temp_file, 'data')
                        else:
                            self.data.manage_upload(temp_file)
                        self.data.width = x
                        self.data.height = y
                        #have to redo the content_type after we modify the image in case it has changed
                        content_type = magicfile.magic(temp_file.name)
                        temp_file.close()
                        self.setFileSize()
                        self.storeContentType(content_type)
            utility.removeTempFile(filename, remove_after)

    security.declareProtected('Change CompoundDoc', 'resizeExistingImage')

    def resizeExistingImage(self):
        "resize existing images"
        if self.exists():
            filename, remove_after = utility.createTempFile(self.data.data)
            content_type = magicfile.magic(filename)
            if content_type.startswith('image'):
                if self.getConfig('resizeOnUpload'):
                    self.resizeImage(filename)
                    #have to redo the content_type after we modify the image in case it has changed
                    content_type = magicfile.magic(filename)  #not correct
                    self.makeThumbnail(filename)
                    self.setFileSize()
                    self.storeContentType(content_type)
                    self.updateImageSrcCache()
            utility.removeTempFile(filename, remove_after)

    security.declareProtected('Change CompoundDoc', 'updateImageSrcCache')

    def updateImageSrcCache(self):
        "update the imagesrc cache string"
        if self.exists():
            decode = {}
            decode['height'] = self.data.height
            decode['width'] = self.data.width
            if com.detection.no_dtml(self.alt):
                decode['alt'] = self.convert(self.alt)
            else:
                decode['alt'] = self.alt

            decode['tags'] = self.tags

            self.setObject('imagesrc_template',
                           image_template.safe_substitute(decode))

    security.declareProtected('View', 'view')

    def view(self,
             urlCallable=None,
             parent=None,
             additionalAttributes='',
             drawHref=1,
             url_data=None):
        "Render page"
        parent = parent or self.getCompoundDocContainer()
        if self.exists():
            decode = {}
            decode['url'] = self.absolute_url_path_extension()
            decode['additionalAttributes'] = additionalAttributes
            if not self.imagesrc_template:
                self.REQUEST.other['okayToRunNotification'] = 0
                self.updateImageSrcCache()
                self.delObjects(['imagesrc'])
            image = Template(self.imagesrc_template).safe_substitute(decode)

            url_data = url_data if url_data is not None else self.url
            if drawHref and url_data:
                href = com.html.generate_url(url_data,
                                             parent,
                                             self.REQUEST,
                                             url_callable=urlCallable)
                if href is not None:
                    image = '<a href="%s">%s</a>' % (href, image)
            return image
        return ""

    security.declarePrivate('PrincipiaSearchSource')

    def PrincipiaSearchSource(self):
        "This is the basic search function"
        if self.exists():
            return str(self.alt)
        else:
            return ""

    security.declarePrivate('classUpgrader')

    def classUpgrader(self):
        "upgrade this class"
        self.fixupAlt()
        self.fixupUrl()
        self.fixupTags()
        self.removeAttributeText()
        self.fixFileId()
        self.convert_to_template()

    security.declarePrivate('fixupAlt')

    def fixupAlt(self):
        "fix up the alt attribute"
        alt = getattr(self, 'alt', '')
        if getattr(alt, 'meta_type', None) != 'AttributeText':
            self.addRegisteredObject('alt', 'AttributeText', data=alt)

    fixupAlt = utility.upgradeLimit(fixupAlt, 141)

    security.declarePrivate('fixupUrl')

    def fixupUrl(self):
        "fix up the url attribute"
        url = getattr(self, 'url', '')
        if getattr(url, 'meta_type', None) != 'AttributeText':
            self.addRegisteredObject('url', 'AttributeText', data=url)

    fixupUrl = utility.upgradeLimit(fixupUrl, 141)

    security.declarePrivate('fixupTags')

    def fixupTags(self):
        "fix up the tags attribute"
        tags = getattr(self, 'tags', '')
        if getattr(tags, 'meta_type', None) != 'AttributeText':
            self.addRegisteredObject('tags', 'AttributeText', data=tags)

    fixupTags = utility.upgradeLimit(fixupTags, 141)

    security.declarePrivate('removeAttributeText')

    def removeAttributeText(self):
        "remove the attributetext items and replace them with basic attributes"
        for name, value in self.objectItems('AttributeText'):
            self.delObjects((name, ))
            self.setObject(name, value.data)
        self.updateImageSrcCache()

    removeAttributeText = utility.upgradeLimit(removeAttributeText, 148)

    security.declarePrivate('convert_to_template')

    def convert_to_template(self):
        "convert to a template"
        self.updateImageSrcCache()
        self.delObjects(['imagesrc'])

    convert_to_template = utility.upgradeLimit(convert_to_template, 176)
Exemple #23
0
class MixUpgrader(BaseObject):
    "this is a mixin class to give objects a auto upgrade capability"

    meta_type = "MixUpgrader"
    security = ClassSecurityInfo()

    security.declarePrivate('upgrader')

    def upgrader(self):
        "performUpgrades to the objet"
        self.fixObjectIdAndName()
        self.fixConfigId()
        self.removeAttributeConfig()
        self.fixupCacheSystem()
        self.removeObjectAndStateAttributes()
        self.upgraderRepairAttributes()
        self.createMetaMapping()
        self.upgraderRemoveParentMCP()
        self.fixupObserverSystem()
        self.removeDataAttribute()
        self.upgradeObjectConfigOrRemoveIt()
        self.undoMasterSharing()
        self.doClassSpecificUpgrades()
        self.resetCreateConfigDefault()
        self.removeItemsSpecificToCompoundDoc()
        self.resetTextAreaCaches()
        self.updateFilePictureMetaInformation()
        self.removeEditCache()
        self.removeNestedListURLObjects()
        self.removeManageEditFormInstances()
        self.removeItemsThatAreDefault()
        self.mergeObjectConfigIntoObject()
        self.removeOwnerFromAttributes()

    security.declarePrivate('removeItemsThatAreDefault')

    def removeItemsThatAreDefault(self):
        "remove the items in this object that are the same as the class default items"
        for name, value in self.__dict__.items():
            if hasattr(self.__class__, name) and getattr(self.__class__,
                                                         name) == value:
                delattr(self, name)

    removeItemsThatAreDefault = utility.upgradeLimit(removeItemsThatAreDefault,
                                                     141)

    security.declarePrivate('mergeObjectConfigIntoObject')

    def mergeObjectConfigIntoObject(self):
        "remove objectConfig and merge its information into its parents object"
        if 'objectConfig' in self.__dict__:
            for name, value in self.objectConfig.items():
                if name in self.classConfig:
                    self.setObject(name, value)
            self.delObjects(['objectConfig'])

    mergeObjectConfigIntoObject = utility.upgradeLimit(
        mergeObjectConfigIntoObject, 141)

    security.declarePrivate('removeManageEditFormInstances')

    def removeManageEditFormInstances(self):
        "remove the mamange edit form objects from stuff that is not a CompoundDoc object"
        if self.meta_type != 'CompoundDoc':
            self.delObjects(self.objectIds('ManageEditForm'))

    removeManageEditFormInstances = utility.upgradeLimit(
        removeManageEditFormInstances, 141)

    security.declarePrivate('fixObjectIdAndName')

    def fixObjectIdAndName(self):
        "fix the id and __name__ attributes of an object"
        sdict = self.__dict__
        if not 'id' in sdict and '__name__' in sdict:
            self.id = self.__name__
            del self.__name__
        if '__name__' in sdict:
            del self.__name__

    fixObjectIdAndName = utility.upgradeLimit(fixObjectIdAndName, 141)

    security.declarePrivate('removeAttributeConfig')

    def removeAttributeConfig(self):
        "remove the config attribute if we have one"
        if 'config' in self.__dict__:
            del self.__dict__['config']

    removeAttributeConfig = utility.upgradeLimit(removeAttributeConfig, 141)

    security.declarePrivate('removeNestedListURLObjects')

    def removeNestedListURLObjects(self):
        "remove the config attribute if we have one"
        self.delObjects(self.objectIds('NestedListURL'))

    removeNestedListURLObjects = utility.upgradeLimit(
        removeNestedListURLObjects, 141)

    security.declarePrivate('fixupCacheSystem')

    def fixupCacheSystem(self):
        "fixed the editCache object if it is not the right type"
        self.delObjects(['cacheNameEdit'])

    fixupCacheSystem = utility.upgradeLimit(fixupCacheSystem, 141)

    security.declarePrivate('fixupObserverSystem')

    def fixupObserverSystem(self):
        "fix the observer system by"
        sdict = self.__dict__
        if 'observing' in sdict and not self.observing:
            self.delObjects(['observing'])
        if 'observed' in sdict:
            self.delObjects(['observed'])
        if 'observing' in sdict:
            self.upgraderRemoveDuplicateObservingEntries()
            self.upgraderChangeObservationPath()

    fixupObserverSystem = utility.upgradeLimit(fixupObserverSystem, 141)

    security.declarePrivate('removeDataAttribute')

    def removeDataAttribute(self):
        "removed the data attribute from all objects that should not have it"
        if self.meta_type in [
                'ControlPanel', 'ControlProfileManager',
                'ControlCatalogManager', 'ControlDebugObject',
                'ControlEditManager', 'ControlEventManager',
                'ControlViewManager', 'ControlConfigManger', 'ControlAddDel',
                'ControlRequest', 'ControlDisplayManager', 'ControlLicense',
                'ControlLog', 'ControlTabManager', 'Display', 'DisplayFilter',
                'DisplayManager', 'DisplayUserAgent'
        ]:
            self.delObjects(['data'])

    removeDataAttribute = utility.upgradeLimit(removeDataAttribute, 141)

    security.declarePrivate('doClassSpecificUpgrades')

    def doClassSpecificUpgrades(self):
        "do the upgrades specific to a class"
        if hasattr(aq_base(self), 'classUpgrader'):
            self.classUpgrader()

    security.declarePrivate('upgradeObjectConfigOrRemoveIt')

    def upgradeObjectConfigOrRemoveIt(self):
        "upgrade the objectConfig object where appropriate and remove it otherwise"
        if 'objectConfig' in self.__dict__ and self.meta_type not in [
                'Config', 'Entry'
        ]:
            if hasattr(aq_base(self), 'classConfig'):
                if hasattr(aq_base(self.objectConfig), 'classUpgrader'):
                    self.objectConfig.classUpgrader()
            else:
                self.delObjects(['objectConfig'])

    upgradeObjectConfigOrRemoveIt = utility.upgradeLimit(
        upgradeObjectConfigOrRemoveIt, 141)

    security.declarePrivate('undoMasterSharing')

    def undoMasterSharing(self):
        "copy the remove shared objects locally since we are not a master document"
        if self.meta_type == 'CompoundDoc':
            if self.masterLocation is not None:
                if self.masterLocation != self.getPath():
                    master = self.unrestrictedTraverse(self.masterLocation,
                                                       None)
                    if master is not None and master.meta_type == 'CompoundDoc':
                        self.setObject(
                            'CatalogManager',
                            aq_base(master.CatalogManager)._getCopy(master))
                        self.setObject(
                            'TabManager',
                            aq_base(master.TabManager)._getCopy(master))
                        self.setObject(
                            'EventManager',
                            aq_base(master.EventManager)._getCopy(master))

    undoMasterSharing = utility.upgradeLimit(undoMasterSharing, 141)

    security.declarePrivate('resetCreateConfigDefault')

    def resetCreateConfigDefault(self):
        "reset the var called createConfigDefault if it is not correct or should not exist"
        if 'createConfigDefault' in self.__dict__:
            self.delObjects(['createConfigDefault'])

    resetCreateConfigDefault = utility.upgradeLimit(resetCreateConfigDefault,
                                                    141)

    security.declarePrivate('removeItemsSpecificToCompoundDoc')

    def removeItemsSpecificToCompoundDoc(self):
        "remove items from various objects that only compounddoc objects should have"
        sdict = self.__dict__
        if self.meta_type != 'CompoundDoc':
            if self.objectIds('ManageEditForm'):
                self.upgraderRemoveManage()
            if 'objectVersion' in sdict:
                self.delObjects(['objectVersion'])
            if 'updateVersion' in sdict:
                self.delObjects(['updateVersion'])
            if 'userModificationTimeStamp' in sdict:
                self.delObjects(['userModificationTimeStamp'])

    removeItemsSpecificToCompoundDoc = utility.upgradeLimit(
        removeItemsSpecificToCompoundDoc, 141)

    security.declarePrivate('resetTextAreaCaches')

    def resetTextAreaCaches(self):
        "reset the caches of text areas"
        sdict = self.__dict__
        if self.meta_type in ['TextArea', 'SectionText']:
            if 'cachedSTX' in sdict:
                self.delObjects(['cachedSTX'])
            if not 'renderCache' in sdict:
                self.updateCache()

    resetTextAreaCaches = utility.upgradeLimit(resetTextAreaCaches, 141)

    security.declarePrivate('updateFilePictureMetaInformation')

    def updateFilePictureMetaInformation(self):
        "update the meta information attached to files and pictures"
        if self.meta_type in ['File', 'Picture']:
            self.setFileSize()
            self.updateFileContentType()

    updateFilePictureMetaInformation = utility.upgradeLimit(
        updateFilePictureMetaInformation, 141)

    security.declarePrivate('removeEditCache')

    def removeEditCache(self):
        "if we have a var called editCache remove it"
        self.delObjects(['editCache'])

    removeEditCache = utility.upgradeLimit(removeEditCache, 141)

    security.declarePrivate('fixConfigId')

    def fixConfigId(self):
        "Fix the id of the config object since a bug at one point allowed an entry to be called id"
        config = getattr(self, 'objectConfig', None)
        if config is not None and config == 'Config':
            if not 'id' in self.__dict__:
                config.id = 'objectConfig'
            if hasattr(config.id,
                       'meta_type') and config.id.meta_type == 'Entry':
                config.setObject('showId', aq_base(config.id))
                config.delObjects(['id'])
                config.id = 'objectConfig'

    fixConfigId = utility.upgradeLimit(fixConfigId, 141)

    security.declarePrivate('removeObjectAndStateAttributes')

    def removeObjectAndStateAttributes(self):
        "remove the object and state attributes"
        try:
            del self.object
        except (AttributeError, KeyError):
            pass

        try:
            del self.state
        except (AttributeError, KeyError):
            pass

    removeObjectAndStateAttributes = utility.upgradeLimit(
        removeObjectAndStateAttributes, 141)

    security.declarePrivate('createMetaMapping')

    def createMetaMapping(self):
        "Create a meta_type mapping for each object that has one to speed up lookups by type"
        #Items should be fixing their entires automatically and cleanup should not happen here
        #It screws up the ObjectRecords since they have entries that are in a subobject that
        #uses a getattr to catch those requests and this would remove those entries.
        temp = []
        for name, item in self.__dict__.items():
            if getattr(item, 'meta_type', None):
                temp.append({'id': name, 'meta_type': item.meta_type})
        if self.meta_type == 'ObjectRecorder':
            meta = self.recordType
            if meta is not None:
                for key in self.getRecordKeys():
                    temp.append({'id': key, 'meta_type': meta})

        temp = tuple(sorted(temp))
        if self._objects != temp:
            self.setObject('_objects', temp)

    createMetaMapping = utility.upgradeLimit(createMetaMapping, 141)

    security.declarePrivate('upgraderRepairAttributes')

    def upgraderRepairAttributes(self):
        "repair attributes that got created too soon and so caused the upgrader to abort"
        if self.meta_type in ['CompoundDoc', 'Config', 'Entry']:
            return None
        name = self.getId()

        trans = {}
        trans[name + 'data'] = 'data'
        trans[name + 'title'] = 'title'
        trans[name + 'filename'] = 'filename'
        trans[name + 'fileSize'] = 'fileSize'
        trans[name + 'tags'] = 'tags'
        trans[name + 'alt'] = 'alt'
        trans[name + 'principiaSearch'] = 'principiaSearch'
        trans[name + 'code'] = 'code'
        trans[name + 'codetype'] = 'codetype'
        trans[name + 'required'] = 'required'
        trans[name + 'optional'] = 'optional'
        trans[name + 'clients'] = 'clients'
        trans[name + 'language'] = 'language'
        trans[name + 'structured'] = 'structured'
        trans[name + 'cachedSTX'] = 'cachedSTX'
        trans[name + 'description'] = 'description'
        trans[name + 'alias'] = 'alias'
        trans[name + 'usage'] = 'usage'
        trans[name + 'registeredFilters'] = 'registeredFilters'
        trans[name + 'registered'] = 'registeredFilters'
        trans[name + 'defaultFilter'] = 'defaultFilter'
        trans[name + 'defaultEdit'] = 'defaultEdit'
        trans[name + 'defaultView'] = 'defaultView'
        trans[name] = 'data'
        trans[name + 'MCP'] = 'MCP'
        trans[name + 'Parents'] = 'Parents'
        trans[name + 'mode'] = 'mode'
        trans[name + 'objectPath'] = 'objectPath'
        trans[name + 'useCatalog'] = 'useCatalog'

        sdict = self.__dict__
        for oldName, newName in trans.items():
            if oldName in sdict:
                oldItem = getattr(self, oldName)
                self.delObjects([oldName])
                newItem = None
                if newName in sdict:
                    newItem = getattr(self, newName)
                if oldItem and newItem is None:
                    self.setObject(newName, oldItem)

    upgraderRepairAttributes = utility.upgradeLimit(upgraderRepairAttributes,
                                                    141)

    security.declarePrivate('upgraderRemoveParentMCP')

    def upgraderRemoveParentMCP(self):
        "This removes parent facing links and links to the main compounddoc"
        self.delObjects(['MCP', 'Parent'])

    upgraderRemoveParentMCP = utility.upgradeLimit(upgraderRemoveParentMCP,
                                                   141)

    security.declarePrivate('upgraderRemoveDuplicateObservingEntries')

    def upgraderRemoveDuplicateObservingEntries(self):
        "Remove the multiple entries that the previous observing code could get into"
        if 'observing' in self.__dict__:
            temp = list(set(self.observing))
            if self.observing != temp:
                self.observing = temp

    upgraderRemoveDuplicateObservingEntries = utility.upgradeLimit(
        upgraderRemoveDuplicateObservingEntries, 141)

    security.declarePrivate('upgraderChangeObservationPath')

    def upgraderChangeObservationPath(self):
        "Change the observation path for items in local cdocs to be locally relative"
        cdoc = self.getCompoundDoc()
        if 'observing' in self.__dict__:
            if [1 for i in self.observing if i[0] == '/']:
                temp = [
                    cdoc.unrestrictedTraverse(i, None) for i in self.observing
                ]
                temp = [i.getRelativePath(self) for i in temp if i is not None]
                if self.observing != temp:
                    self.observing = temp

    upgraderChangeObservationPath = utility.upgradeLimit(
        upgraderChangeObservationPath, 141)

    security.declarePrivate('upgraderRemoveManager')

    def upgraderRemoveManage(self):
        "remove the ManageEditForm object from all non compounddocs"
        self.delObjects(self.objectIds('ManageEditForm'))

    upgraderRemoveManage = utility.upgradeLimit(upgraderRemoveManage, 141)

    security.declarePrivate('removeOwnerFromAttribute')

    def removeOwnerFromAttributes(self):
        "remove _owner from all the non CompoundDoc attributes"
        if self.meta_type != 'CompoundDoc':
            self.delObjects(['_owner'])

    removeOwnerFromAttributes = utility.upgradeLimit(removeOwnerFromAttributes,
                                                     155)
Exemple #24
0
class ListMailer(UserObject):
    "ListMailer class"

    security = ClassSecurityInfo()
    meta_type = "ListMailer"

    listName = ''
    listFrom = ''
    subject = ''
    message = ''
    footer = ''
    header = ''
    server = 'localhost'

    security.declareProtected('View management screens', 'edit')

    def edit(self, *args, **kw):
        "Inline edit short object"
        temp = []
        format = '<p>%(name)s %(form)s</p>\n'
        list = [''] + [
            id for id, object in self.getCompoundDoc().objectItems()
            if utility.isinstance(object, SimpleList)
        ]
        temp.append(
            format % {
                'name': 'To',
                'form': self.option_select(list, 'listName', [self.listName])
            })
        temp.append(format % {
            'name': 'From',
            'form': self.input_text('listFrom', self.listFrom)
        })
        temp.append(format % {
            'name': 'Subject',
            'form': self.input_text('subject', self.subject)
        })
        temp.append(format % {
            'name': 'Header',
            'form': self.text_area('header', self.header)
        })
        temp.append(format % {
            'name': 'Message',
            'form': self.text_area('message', self.message)
        })
        temp.append(format % {
            'name': 'Footer',
            'form': self.text_area('footer', self.footer)
        })
        temp.append(format % {
            'name': 'Mail Server',
            'form': self.input_text('server', self.server)
        })
        temp.append(self.create_button("sendMail", "Send All Messages"))
        return ''.join(temp)

    security.declarePrivate('after_manage_edit')

    def after_manage_edit(self, form):
        "Call this function after the editing has been processed so that additional things can be done like caching"
        if 'sendMail' in form:
            self.sendAllMessages()

    security.declarePrivate('sendAllMessages')

    def sendAllMessages(self):
        "Send all the messages we have"
        listName = self.listName
        if listName:
            addresses = getattr(self.getCompoundDoc(), listName)
            message = '%s\r\n\r\n%s\r\n\r\n%s\r\n\r\n' % (
                self.header, self.message, self.footer)
            message = DTML(message)
            From = self.listFrom
            Subject = self.subject
            server = smtplib.SMTP(self.server)
            msg = ("From: %s\r\nTo: %s\r\nSubject: %s\r\n\r\n%s")
            for address in addresses.getEntries():
                message = message(self, self.REQUEST, address=address)
                server.sendmail(From, address,
                                msg % (From, address, Subject, message))
            server.quit()

    security.declarePrivate('classUpgrader')

    def classUpgrader(self):
        "upgrade this class"
        self.fixFrom()

    security.declarePrivate('fixFrom')

    def fixFrom(self):
        "fix the from attribute"
        if 'from' in self.__dict__:
            self.listFrom = getattr(self, 'from')
            self.delObjects(['from'])

    fixFrom = utility.upgradeLimit(fixFrom, 141)
Exemple #25
0
class DataFilter(UserObject):
    "DataFilter apply this to an a list of dicts to change how it outputs"

    meta_type = "DataFilter"
    security = ClassSecurityInfo()
    fieldMap = None
    order = None
    visible = None

    updateReplaceList = ('order', 'visible')

    security.declarePrivate('PrincipiaSearchSource')

    def PrincipiaSearchSource(self):
        "This is the basic search function"
        return ""

    security.declarePrivate('configAddition')

    def configAddition(self):
        "addendum to the default config screen"
        temp = []
        append = temp.append
        if self.fieldMap is not None and self.order is not None:
            fieldMapKeys = sorted(self.fieldMap.keys())
            dictMap = "fieldMap.%s"
            orderMap = "order.%s"

            elements = [['id', 'name', 'order']]
            for i in fieldMapKeys:
                mappedEdit = self.input_text(dictMap % i, self.fieldMap[i])
                orderEdit = self.input_float(orderMap % i, self.order[i])
                elements.append([i, mappedEdit, orderEdit])

            append(self.create_button('clear', 'Clear Visible Items'))
            append('<br>')
            append(
                self.option_select(self.fieldMap.keys(), 'visible',
                                   self.getVisible(), 1, 5))
            append(self.createTable(elements))
        append(self.customEdit())
        return ''.join(temp)

    security.declarePrivate('customEdit')

    def customEdit(self):
        "This is an edit piece that can be overridden by various custom editing features needed by other filters"
        return ""

    security.declarePrivate('before_manage_edit')

    def before_manage_edit(self, form):
        "process the edits"
        if 'clear' in form:
            self.delObjects(('visible', ))
            if 'visible' in form:
                del form['visible']

    security.declarePrivate('getFieldMapKeys')

    def getFieldMapKeys(self):
        "Get the keys to the fieldMap object"
        if self.fieldMap is not None:
            return self.fieldMap.keys()
        return []

    security.declarePrivate('getVisible')

    def getVisible(self):
        "get the visible items"
        if self.visible is not None:
            return self.visible
        return []

    security.declarePrivate('getOrderKeys')

    def getOrderKeys(self):
        "Get the keys to the fieldMap object"
        if self.order is not None:
            return self.order.keys()
        return []

    security.declarePrivate('getFieldOrder')

    def getFieldOrder(self):
        "get the current field order"
        path = self.aq_parent.getConfig('orderHeaderPath')
        script = None
        if path:
            script = self.restrictedTraverse(path, None)
            if script is not None:
                return script(self.getCompoundDoc())

        if self.order is not None and self.visible is not None and self.fieldMap is not None:
            order = sorted((value, key) for key, value in self.order.items())
            visible = set(self.visible)
            fieldMap = self.fieldMap
            return [(name, fieldMap[name]) for i, name in order
                    if name in visible]
        return []

    def getDataRecords(self,
                       order,
                       archive=None,
                       start=None,
                       stop=None,
                       header=None,
                       query=None,
                       merge=None,
                       sliceStart=None,
                       sliceStop=None,
                       keys=None):
        "get the records in this data recorder that match these constraints"
        if not order:
            return

        if merge is not None:
            records = BTrees.OOBTree.OOBTree()
            if self.records is not None:
                records.update(self.records)
            if self.archive is not None:
                records.update(self.archive)
        elif archive:
            records = self.archive
        else:
            records = self.records

        if records is None:
            return

        if start is None and self.startTime is not None:
            startTime = self.startTime(mode='view')
            if startTime:
                start = startTime.earliestTime()

        if stop is None and self.stopTime is not None:
            stopTime = self.stopTime(mode='view')
            if stopTime:
                stop = stopTime.latestTime()

        recordOrder, recordNames = zip(*order)

        allowed = None

        if query is not None:
            catalog = self.getCatalog(archive)
            if catalog is not None:
                allowed = BTrees.OOBTree.OOSet(
                    (float(record.record_id) for record in catalog(query)))

        if header:
            yield recordNames

        recordsGen = None
        if allowed is None:
            if sliceStart is not None and sliceStop is not None:
                recordsGen = records.items(start, stop)[sliceStart:sliceStop]
            else:
                recordsGen = records.items(start, stop)
        else:  #when searching with the catalog we need to seperate the Start,Stop case from not having those bounds
            #the slice case probably needs to be massively updated also
            if sliceStart is not None and sliceStop is not None:
                recordsGen = ((name, value) for name, value in records.items(
                    start, stop)[sliceStart:sliceStop] if name in allowed)
            elif start is not None or stop is not None:
                recordsGen = ((name, records[name])
                              for name in BTrees.OOBTree.intersection(
                                  BTrees.OOBTree.OOSet(
                                      records.keys(start, stop)), allowed))
            else:
                recordsGen = (
                    (name, records[name])
                    for name in BTrees.OOBTree.intersection(records, allowed))

        if recordsGen is not None:
            for key, record in com.db.subTransDeactivateKeyValue(
                    recordsGen, 100, self.getPhysicalRoot()):
                data = [str(record.get(name, '')) for name in recordOrder]
                if keys:
                    yield key, data
                else:
                    yield data

    security.declarePrivate('classUpgrader')

    def classUpgrader(self):
        "upgrade this class"
        self.removeNotUsed()

    security.declarePrivate('removeNotUsed')

    def removeNotUsed(self):
        "remove visible, fieldMap, order if not being used"
        toRemove = []
        if not self.visible:
            toRemove.append('visible')
        if not self.fieldMap:
            toRemove.append('fieldMap')
        if not self.order:
            toRemove.append('order')
        self.delObjects(toRemove)

    removeNotUsed = utility.upgradeLimit(removeNotUsed, 158)
Exemple #26
0
class ListText(base.Base):
    "ListText is a list of text objects"

    meta_type = "ListText"
    security = ClassSecurityInfo()
    updateAlways = 1
    data = ''
    sortedList = None
    listBegin = '<ul>'
    listEnd = '</ul>'
    addType = 'InputText'
    deleteButtonText = 'Delete List Entry'
    addButtonText = 'Add List Entry'
    scriptChangePath = ''
    
    
    allowedListTypes = ('InputText', 'TextArea', 'InputFloat', 
        'Date', 'File', 'InputInt', 'Money', 'Picture')

    classConfig = {}
    classConfig['addType'] = {'name':'Type of Objects in List', 'type':'list', 'values': allowedListTypes}
    classConfig['listBegin'] = {'name':'listBegin', 'type':'string'}
    classConfig['listEnd'] = {'name':'listEnd', 'type':'string'}
    classConfig['scriptChangePath'] = {'name':'Path to change notification script', 'type': 'path'}
    
    updateReplaceList = ('listBegin', 'listEnd', 'addType', 'deleteButtonText', 'addButtonText', )
    
    configurable = ('listBegin', 'listEnd', 'addType',)
    
    security.declarePrivate('add_delete_objects')
    def add_delete_objects(self, form):
        "Add new objects to the existing object"
        if form.get('removeme', "") != "":
            self.delListItem(form['removeme'])
        if 'Add' in form:
            self.addListItem()

    security.declarePrivate('PrincipiaSearchSource')
    def PrincipiaSearchSource(self):
        "This is the basic search function"
        temp = []
        if self.sortedList:
            for i in self:
                temp.append(i.PrincipiaSearchSource())
        return ' '.join(temp)            
            
    security.declareProtected('View', 'view')
    def view(self):
        "Inline draw view"
        temp = []
        listBegin = self.getConfig('listBegin')
        listEnd = self.getConfig('listEnd')
        if self.sortedList:
            temp.append(listBegin)
            for i in self:
                text = i.view()
                if text:
                    temp.append('<li>%s</li>' % text)
            temp.append(listEnd)
        return ''.join(temp)

    security.declareProtected('View management screens', 'edit')
    def edit(self, *args, **kw):
        "Inline edit short object"
        temp = ['<div class="outline">']
        temp.append(self.addDeleteObjectsEdit())
        if self.sortedList:
            format = '<div class="outline">%s</div>'
            for i in self:
                temp.append(format % i.edit())
        temp.append("</div>")
        return ''.join(temp)

    security.declarePrivate('getDeletionNames')
    def getDeletionNames(self,allowableTypes):
        "return the names are should be used for deletion"
        if self.sortedList:
            #do the count from 1 instead of 0
            return [""] + range(1,len(self)+1)
        return ()

    security.declarePrivate('getDeleteButtonName')
    def getDeleteButtonName(self,allowableTypes):
        "get the text for the delete button"
        return self.deleteButtonText

    security.declarePrivate('getAddButtonName')
    def getAddButtonName(self,allowableTypes):
        "get the text for the add button"
        return self.addButtonText

    security.declarePrivate('restrictedUserObject')
    def restrictedUserObject(self):
        "Return a list of the types that are allowed to be added or deleted from this object by a user"
        return [self.getConfig('addType')]

    security.declarePrivate('add_delete_objects_edit')
    def addDeleteObjectsEdit(self):
        "This is the form elements for adding and deleting objects without the form wrapper"
        return '%s %s' % (self.addObjectsEdit(autoId=1,autoType=1), self.deleteObjectsEdit())

    security.declarePrivate("getAvailableListsContents")
    def getAvailableListsContents(self):
        "Return a list of all available list items"
        if self.sortedList:
            return  [object.data for object in self]
        return []
    
    #List behavior stuff
    
    security.declareProtected("Access contents information", "__getitem__")
    def __getitem__(self, i):
        if self.sortedList is not None:
            return self.sortedList[i].__of__(self)
        raise IndexError
    
    security.declareProtected("Access contents information", "__getslice__")
    def __getslice__(self, i, j):
        i = max(i, 0); j = max(j, 0)
        for i in self.sortedList[i:j]:
            yield i.__of__(self)
    
    security.declareProtected("Access contents information", "__iter__")
    def __iter__(self):
        if self.sortedList:
            for i in self.sortedList:
                yield i.__of__(self)

    security.declareProtected("Access contents information", "__len__")
    def __len__(self):
        if self.sortedList:
            return len(self.sortedList)
        return 0 
    
    security.declareProtected('Change CompoundDoc', '__setitem__', '__guarded_setitem__')
    def __setitem__(self, i, item): 
        if self.sortedList:
            self.sortedList[i].__of__(self).populatorLoader(item)
        self._p_changed = 1
    __guarded_setitem__ = __setitem__
        
    security.declareProtected('Change CompoundDoc', '__delitem__', '__guarded_delitem__')
    def __delitem__(self, i):
        if self.sortedList: 
            objectId = self.sortedList[i].getId()
            self.deleteRegisteredObject(objectId, [])
            del self.sortedList[i]
            if not len(self.sortedList):
                self.sortedList=None
            self._p_changed = 1
    __guarded_delitem__ = __delitem__
    
    #For some reason through the web code can't call this method so disabling it
    #security.declareProtected('Change CompoundDoc', '__setslice__')
    #def __setslice__(self, i, j, other):
    #    i = max(i, 0); j = max(j, 0)
    #    if self.sortedList:
    #        for index in range(i,j):
    #            self.sortedList[index] = other[index]
    
    #For some reason through the web code can't call this method so disabling it
    #security.declareProtected('Change CompoundDoc', '__delslice__')
    #def __delslice__(self, i, j):
    #    i = max(i, 0); j = max(j, 0)
    #    if self.sortedList:
    #        items = self.sortedList[i:j]
    #        del self.sortedList[i:j]
    #        for i in items:
    #            self.deleteRegisteredObject(i.getId(), [])    
    #        if not len(self.sortedList):
    #            self.sortedList=None
    #        self._p_changed = 1
    
    security.declareProtected('Change CompoundDoc', 'append')
    def append(self, item):
        if not self.sortedList:
            self.sortedList = []
        obj = self.createNextItem()
        obj.populatorLoader(item)    
        self.sortedList.append(obj)
        self._p_changed = 1
    
    security.declareProtected('Change CompoundDoc', 'insert')
    def insert(self, i, item):
        if not self.sortedList:
            self.sortedList = []
        obj = self.createNextItem()
        obj.populatorLoader(item)
        self.sortedList.insert(i, obj)
        self._p_changed = 1 
    
    security.declareProtected('Change CompoundDoc', 'pop')
    def pop(self, i=-1): 
        if self.sortedList:
            item = self[i]
            del self[i]
            return item
    
    security.declareProtected('Change CompoundDoc', 'reverse')
    def reverse(self): 
        if self.sortedList:
            self.sortedList.reverse()
            self._p_changed = 1    
    
    #End list behavior stuff
    
    security.declarePrivate('createNextItem')
    def createNextItem(self):
        'create the next object we can use'
        name = utility.cleanRegisteredId(repr(time.time()).replace('.', '_'))
        self.updateRegisteredObject(name, self.getConfig('addType'))
        return aq_base(getattr(self,name))
    
    security.declarePrivate('addListItem')
    def addListItem(self):
        "add a new list item"
        obj = self.createNextItem()
        if not self.sortedList:
            self.sortedList = []
        self.sortedList.append(obj)
        self._p_changed=1

    security.declarePrivate('delListItem')
    def delListItem(self, name):
        "delete a list item"
        try:
            position = int(name)-1
            del self[position]
        except ValueError:
            pass

    security.declarePrivate("removeUnNeeded")
    def removeUnNeeded(self, list, typekeep):
        "Remove the UnNeeded items based on this list"
        pass

    security.declarePrivate('classUpgrader')
    def classUpgrader(self):
        "upgrade this class"
        self.removeListIndex()
        self.cleanupNames()
        self.repairSortedList()

    security.declarePrivate("removeListIndex")
    def removeListIndex(self):
        "remove the listIndex"
        if self.hasObject('listIndex'):
            self.delObjects(['listIndex'])
    removeListIndex = utility.upgradeLimit(removeListIndex, 141)
            
    security.declarePrivate("cleanupNames")
    def cleanupNames(self):
        "clean up the names in this listtext object"
        addType = self.getConfig('addType')
        if not reduce(operator.add,[name.count('_') for name in self.objectIds(addType)],0):
            oldobjects = []
            objectItems = self.objectItems(addType)
            objectItems.sort()
            for name,inputtext in objectItems:
                self.addListItem()
                #the last element i the list is what we want
                self.sortedList[-1].data = inputtext.data
                oldobjects.append(name)
            self.delObjects(oldobjects)
    cleanupNames = utility.upgradeLimit(cleanupNames, 141)
            
    security.declarePrivate("repairSortedList")
    def repairSortedList(self):
        "repair the sortedList object"
        if self.sortedList and len(self.sortedList) != len(self.objectIds(self.addType)):
            "sortedList is broken because it does not match the objects that should be in it regenerate it"
            addType = self.getConfig('addType')
            self.sortedList = [aq_base(inputtext) for inputtext in self.objectValues(addType)]
    repairSortedList = utility.upgradeLimit(repairSortedList, 141)
    
    security.declarePrivate('populatorInformation')
    def populatorInformation(self):
        "return a string that this metods pair can read back to load data in this object"
        if self.sortedList:
            return ' /-\ '.join([item.data.replace('\n','\\n') for item in self.sortedList])
        return ''

    security.declarePrivate('populatorLoader')
    def populatorLoader(self, string):
        "load the data into this object if it matches me"
        items = string.split(' /-\ ')
        total = 0
        if self.sortedList:
            total = len(self.sortedList)
        if len(items) < total:
            numberToDelete = total - len(items)
            self.delObjects([item.getId() for item in self.sortedList[-numberToDelete:]])
            self.sortedList = self.sortedList[0:-numberToDelete]
        elif len(items) > total:
            for i in xrange(len(items)-total):
                self.addListItem()
        for i in xrange(total):
            self.sortedList[i].__of__(self).setObject('data',items[i].replace('\\n','\n'))
Exemple #27
0
class EComControl(base.Base):
    "EComControl hooks up an object for ecommerece addition/subtraction"

    meta_type = "EComControl"
    security = ClassSecurityInfo()
    overwrite = 1
    data = '<a href="%(add)s">Add</a>/<a href="%(remove)s">Remove</a>'
    pathToShoppingCart = 'shoppingCart/cart'
    SessionManagerConfig = None

    configurable = ('data', 'pathToShoppingCart')

    security.declareProtected('View', 'view')

    def view(self):
        "Inline draw view"
        url = self.absolute_url()
        return self.getConfig('data') % {
            'add': url + '/add',
            'remove': url + '/remove'
        }

    security.declarePublic('remove')

    def remove(self, redirect=1, args=None, url=None):
        "if we have this cdoc in the sessionmanager remove it"
        path = self.getCompoundDoc().getPath()
        self.getShoppingCart().removeOrder(path, args)
        if redirect:
            return self.redirectBackToPage(url)

    security.declarePrivate('redirectBackToPage')

    def redirectBackToPage(self, url=None):
        "redirect back to the referring page and if we don't have one redirect back to the closest compounddoc"
        url = url or self.REQUEST.get('HTTP_REFERER', None)
        if url is None:
            url = self.getCompoundDoc().absolute_url()
        return self.REQUEST.RESPONSE.redirect(url)

    security.declarePublic('add')

    def add(self, redirect=1, quantity=1, args=None, url=None):
        "if we don't have this cdoc in the sessionmanager add it and set it to 1"
        quantity = validators.checkInt(quantity)
        if quantity is None:
            quantity = 1
        path = self.getCompoundDoc().getPath()
        self.getShoppingCart().addOrder(path, quantity, args)
        if redirect:
            return self.redirectBackToPage(url)

    security.declarePrivate('getShoppingCart')

    def getShoppingCart(self):
        "return the shopping cart object"
        return self.restrictedTraverse(self.getConfig('pathToShoppingCart'))

    security.declareProtected('View management screens', 'edit')

    def edit(self, *args, **kw):
        "Inline edit view"
        temp = [self.input_text('data', self.data)]
        temp.append(
            '<p>Where is the shopping cart located? %s</p>' %
            self.input_text('pathToShoppingCart', self.pathToShoppingCart))
        return ''.join(temp)

    security.declarePrivate('PrincipiaSearchSource')

    def PrincipiaSearchSource(self):
        "Return what can be search which is nothing"
        return ''

    security.declarePrivate('classUpgrader')

    def classUpgrader(self):
        "upgrade this class"
        self.removeSessionManagerConfig()

    security.declarePrivate('removeSessionManagerConfig')

    def removeSessionManagerConfig(self):
        "remove SessionManagerConfig"
        self.delObjects(['SessionManagerConfig'])

    removeSessionManagerConfig = utility.upgradeLimit(
        removeSessionManagerConfig, 156)
class SectionText(TextArea):
    "SectionText class"

    meta_type = "SectionText"
    security = ClassSecurityInfo()

    header = '2'
    heading = ''

    classConfig = {}
    classConfig['struct'] = {'name': 'struct', 'type': 'radio'}
    classConfig['structstate'] = {
        'name': 'Structured Text Enabled',
        'type': 'radio'
    }
    classConfig['header'] = {
        'name': 'header',
        'type': 'list',
        'values': ['1', '2', '3', '4', '5', '6']
    }
    classConfig['heading'] = {'name': 'heading', 'type': 'string'}

    configKeep = ('structstate', 'header')
    configurable = ('structstate', 'header')

    security.declareProtected('View management screens', 'edit')

    def edit(self, struct=None, *args, **kw):
        "Inline edit short object"
        temp = [
            self.editSingleConfig('heading'),
            self.text_area('data', self.data)
        ]
        if struct is not None:
            struct = self.struct
        if struct:
            format = '<div>%s Click "No" if you don\'t want your text auto-formatted.</div>'
            temp.append(format % self.editSingleConfig('structstate'))
        return ''.join(temp)

    security.declareProtected('View', 'view')

    def view(self):
        "Render page"
        if self.getConfig('structstate'):
            return self.renderCache
        else:
            return self.renderCache + self.data

    security.declarePrivate('updateCache')

    def updateCache(self):
        "update the cache of this object if applicable"
        string = ''
        heading = self.heading
        if heading:
            header = self.getConfig('header')
            string = '<h%s>%s</h%s>\n' % (header, heading, header)
        if self.getConfig('structstate'):
            string = string + str(nocodestructured.HTML(self.data, header=0))
        self.setObject('renderCache', string)

    security.declarePrivate('classUpgrader')

    def classUpgrader(self):
        "upgrade this class"
        self.upgradeStringToAttributeText()
        self.removeAttributeText()

    security.declarePrivate('upgradeStringToAttributeText')

    def upgradeStringToAttributeText(self):
        "upgrade a string header to an attributetext one"
        if isinstance(self.heading, types.StringType):
            self.addRegisteredObject('heading',
                                     'AttributeText',
                                     data=self.heading)

    upgradeStringToAttributeText = utility.upgradeLimit(
        upgradeStringToAttributeText, 141)

    security.declarePrivate('populatorInformation')

    def populatorInformation(self):
        "return a string that this metods pair can read back to load data in this object"
        return '%s /-\ %s' % (self.heading, self.data.replace('\n', '\\n'))

    security.declarePrivate('populatorLoader')

    def populatorLoader(self, string):
        "load the data into this object if it matches me"
        heading, data = string.split(' /-\ ', 1)
        self.setObject('data', data.replace('\\n', '\n'))
        self.setObject('heading', heading.replace('\\n', '\n'))
        self.updateCache()

    security.declarePrivate('removeAttributeText')

    def removeAttributeText(self):
        "remove the attributetext items and replace them with basic attributes"
        heading = self.heading.data
        self.delObjects(('heading', ))
        self.setObject('heading', heading)
        self.updateCache()

    removeAttributeText = utility.upgradeLimit(removeAttributeText, 149)

    security.declareProtected('Change CompoundDoc', 'store')

    def store(self, data, heading):
        "set the calculation value of this object"
        self.setObject('data', str(data))
        self.setObject('heading', str(heading))
        self.updateCache()