Exemple #1
0
 def actions(self):
     """
     gives us the action dict of the object
     """
     try:
         objId = getUtility(IIntIds).getId(self.context)
     except:
         objId = 1000
     retList = []
     if appsetup.getConfigContext().hasFeature('devmode') and \
        checkPermission('org.ict_ok.components.host.Edit', self.context):
         quoter = URLQuote(self.request.getURL())
         tmpDict = {}
         tmpDict['oid'] = u"c%strigger_online" % objId
         tmpDict['title'] = _(u"Trigger online")
         tmpDict['href'] = u"%s/@@trigger_online?nextURL=%s" % \
                (zapi.absoluteURL(self.context, self.request),
                 quoter.quote())
         retList.append(tmpDict)
         tmpDict = {}
         tmpDict['oid'] = u"c%strigger_offline" % objId
         tmpDict['title'] = _(u"Trigger offline")
         tmpDict['href'] = u"%s/@@trigger_offline?nextURL=%s" % \
                (zapi.absoluteURL(self.context, self.request),
                 quoter.quote())
         retList.append(tmpDict)
         tmpDict = {}
         tmpDict['oid'] = u"c%strigger_not1" % objId
         tmpDict['title'] = _(u"Trigger notification1")
         tmpDict['href'] = u"%s/@@trigger_not1?nextURL=%s" % \
                (zapi.absoluteURL(self.context, self.request),
                 quoter.quote())
         retList.append(tmpDict)
     return retList
Exemple #2
0
 def actions(self):
     """
     gives us the action dict of the object
     """
     try:
         objId = getUtility(IIntIds).getId(self.context)
     except:
         objId = 1000
     retList = []
     if appsetup.getConfigContext().hasFeature('devmode') and \
        checkPermission('org.ict_ok.components.host.Edit', self.context):
         quoter = URLQuote(self.request.getURL())
         tmpDict = {}
         tmpDict['oid'] = u"c%spoweroff" % objId
         tmpDict['title'] = _(u"Power off")
         tmpDict['href'] = u"%s/@@poweroff.html?nextURL=%s" % \
                (zapi.absoluteURL(self.context, self.request),
                 quoter.quote())
         retList.append(tmpDict)
         tmpDict = {}
         tmpDict['oid'] = u"c%spoweron" % objId
         tmpDict['title'] = _(u"Power on")
         tmpDict['href'] = u"%s/@@poweron.html?nextURL=%s" % \
                (zapi.absoluteURL(self.context, self.request),
                 quoter.quote())
         retList.append(tmpDict)
     return SuperHostDetails.actions(self) + retList
Exemple #3
0
 def actions(self):
     """
     gives us the action dict of the object
     """
     try:
         objId = getUtility(IIntIds).getId(self.context)
     except KeyError:
         objId = 1000
     retList = []
     adapSize = ISized(self.context)
     if checkPermission('org.ict_ok.admin_utils.supervisor.ReindexDB',
                        self.context):
         quoter = URLQuote(self.request.getURL())
         tmpDict = {}
         tmpDict['oid'] = u"c%sreindex_db" % objId
         tmpDict['title'] = _(u"reindex database")
         tmpDict['href'] = u"%s/@@reindex_db?nextURL=%s" % \
                (zapi.absoluteURL(self.context, self.request),
                 quoter.quote())
         tmpDict['tooltip'] = _(u"will reindex the catalogs of all "\
                                u"tables in database")
         retList.append(tmpDict)
     if checkPermission('org.ict_ok.admin_utils.supervisor.PackDB',
                        self.context):
         quoter = URLQuote(self.request.getURL())
         tmpDict = {}
         tmpDict['oid'] = u"c%spack_db" % objId
         tmpDict['title'] = _(u"pack database")
         tmpDict['href'] = u"%s/@@pack_db?nextURL=%s" % \
                (zapi.absoluteURL(self.context, self.request),
                 quoter.quote())
         tmpDict['tooltip'] = _(u"will pack the database and delete "\
                                u"all backups")
         retList.append(tmpDict)
     return retList
Exemple #4
0
 def actions(self):
     """
     gives us the action dict of the object
     """
     try:
         objId = getUtility(IIntIds).getId(self.context)
     except KeyError:
         objId = 1000
     retList = []
     if checkPermission('org.ict_ok.admin_utils.reports.generate.pdf',
                        self.context):
         tmpDict = {}
         tmpDict['oid'] = u"c%sgenerate_test_pdf" % objId
         tmpDict['title'] = _(u"generate test pdf")
         tmpDict['href'] = u"%s/@@generate_test_pdf" % \
                (zapi.absoluteURL(self.context, self.request))
         tmpDict['tooltip'] = _(u"will generate a test pdf file")
         retList.append(tmpDict)
     if checkPermission('org.ict_ok.admin_utils.reports.generate.pdf',
                        self.context):
         tmpDict = {}
         tmpDict['oid'] = u"c%sgenerate_all_pdf" % objId
         tmpDict['title'] = _(u"generate all pdf")
         tmpDict['href'] = u"%s/@@generate_all_pdf" % \
                (zapi.absoluteURL(self.context, self.request))
         tmpDict['tooltip'] = _(u"will generate a all pdf file")
         retList.append(tmpDict)
     return retList
Exemple #5
0
 def actions(self):
     """
     gives us the action dict of the object
     """
     try:
         objId = getUtility(IIntIds).getId(self.context)
     except KeyError:
         objId = 1000
     retList = []
     if checkPermission('org.ict_ok.admin_utils.esx_vim.Admin',
                        self.context) and\
        zapi.queryMultiAdapter((self.context, self.request),
                               name='shutdown.html') is not None:
         tmpDict = {}
         tmpDict['oid'] = u"c%sshutdown" % objId
         tmpDict['title'] = _(u"shutdown")
         tmpDict['href'] = u"%s/@@shutdown.html?nextURL=%s" % \
                (zapi.absoluteURL(self.context, self.request),
                 quoter.quote())
         tmpDict['tooltip'] = _(u"shutdow the virtual machine")
         retList.append(tmpDict)
     if checkPermission('org.ict_ok.admin_utils.esx_vim.Admin',
                        self.context) and\
        zapi.queryMultiAdapter((self.context, self.request),
                               name='convertobj.html') is not None:
         tmpDict = {}
         tmpDict['oid'] = u"c%sconvertobj" % objId
         tmpDict['title'] = _(u"convert to intern")
         tmpDict['href'] = u"%s/@@convertobj.html?nextURL=%s" % \
                (zapi.absoluteURL(self.context, self.request),
                 quoter.quote())
         tmpDict['tooltip'] = _(u"convert to internal object")
         retList.append(tmpDict)
     return retList
Exemple #6
0
    def getCollectionAttributes(self, obj_arg):
        additionalAttributes = ''
        if type(obj_arg) is tuple:
            (attributeName, displayTitle, obj) = obj_arg
            appendUrl = '?getAttr&attrName=%s' % attributeName
        else:
            appendUrl = ''
            obj = obj_arg

        parentItem = zapi.getParent(obj)
        parent_url = urlparse(zapi.absoluteURL(parentItem, self.request))
        obj_url = urlparse(zapi.absoluteURL(obj, self.request))
        if type(obj_arg) is tuple:
            xml_title = displayTitle
            additionalAttributes += ' expable="" '
            attrList = getattr(obj, attributeName, None)
            iklen = len(attrList)
        else:
            try:
                xml_title = obj.getDcTitle()
            except ForbiddenAttribute:
                xml_title = _('[top]')
            iklen = len(obj)
        name = obj_url.path.split('/')[-1] + appendUrl
        stateIconUrl = self.getStateIconUrl(obj)
        stateValue = self.getStateValue(obj)
        stateOverview = self.getStateOverview(obj)
        item_ppath = parent_url.path + u'/'
        item_ppath = item_ppath.replace('//', '/')
        if item_ppath[0] == "/":
            item_ppath = item_ppath[1:]
        return (xml_title, name, item_ppath, iklen, stateIconUrl, stateValue,
                stateOverview, additionalAttributes)
Exemple #7
0
    def cmd(self):
        """
        commnds for objmq
        """
        obj = self.context
        print "cmd/objmq"
        print "path: %s" % (zapi.absoluteURL(obj, self.request))
        action = self.request.get('cmd', default=None)
        if action:
            if action == 'start':
                obj.status2Master = u"connecting"
                #print "start"
                #print "obj.oidSlave: %s" % (obj.oidSlave)
                #obj.appendSlaveUid(u"bc6ae87821e43509dc3a5152a030951b0")
                #print "dir(obj.oidSlave): %s" % dir(obj.oidSlave)
                #print "obj.oidSlave: %s" % (obj.oidSlave)
                mq_utility = zapi.getUtility(IAdmUtilObjMQ)
                my_data = {
                    'cmd': 'connect',
                    'nodename': unicode(obj.getNodeName())
                }
                my_data['header'] = {'from_oid': obj.objectID,
                                     'from_ip': obj.ipv4My,
                                     'from_path': getPath(obj),
                                     'to_oid': obj.oidMaster,
                                     'to_ip': obj.ipv4Master,
                                     'to_path': u"/++etc++site/default"+\
                                     "/AdmUtilSupervisor"
                                 }
                mq_utility.sendPerMq(my_data)

                #python_pickle = pickle.dumps(my_data)
                ##print "toxml: %s" % toxml(python_pickle)
                #mq_utility.sendPerMq(toxml(python_pickle))
                #mq_utility = zapi.getUtility(IMailDelivery, 'ikObjTransportQueue')
                #from_adr = u"http://%s@%s:8080%s" % \
                #(obj.objectID, obj.ipv4My, zapi.absoluteURL(obj, self.request))
                #to_adr = u"http://%s@%s:8080/++etc++site/default/AdmUtilSupervisor" % \
                #(str(obj.oidMaster), str(obj.ipv4Master))
                #mq_utility.send(from_adr, [to_adr], "msg_start")

            elif action == 'stop':
                print "stop"
                mq_utility = zapi.getUtility(IMailDelivery,
                                             'ikObjTransportQueue')
                from_adr = u"http://%s@%s:8080%s" % \
                         (obj.objectID, obj.ipv4My, zapi.absoluteURL(obj, self.request))
                to_adr = u"http://%s@%s:8080/++etc++site/"+\
                       "default/AdmUtilSupervisor" % \
                         (str(obj.oidMaster), str(obj.ipv4Master))
                mq_utility.send(from_adr, [to_adr], "msg_stop")
            elif action == 'ping':
                obj.sendPing()
            else:
                pass
        return self.request.response.redirect('./@@objmq')
Exemple #8
0
 def actions(self):
     """
     gives us the action dict of the object
     """
     retList = []
     if checkPermission('org.ict_ok.admin_utils.notifier.Edit',
                        self.context):
         quoter = URLQuote(self.request.getURL())
         if self.context.enableConnector:
             tmpDict = {}
             #tmpDict['oid'] = u"c%s" % objId
             tmpDict['oid'] = u"c000stop_connector"
             tmpDict['title'] = _(u"stop jabber-connector")
             tmpDict['href'] = u"%s/@@stop_connector?nextURL=%s" % \
                    (zapi.absoluteURL(self.context, self.request),
                     quoter.quote())
             tmpDict['tooltip'] = _(u"stops the jabber-connector (as user:%s)"\
                                    % self.request.principal.title)
             retList.append(tmpDict)
             tmpDict = {}
             tmpDict['oid'] = u"c000get_isup"
             tmpDict['title'] = _(u"is jabber-connector up")
             tmpDict['href'] = u"%s/@@get_isup?nextURL=%s" % \
                    (zapi.absoluteURL(self.context, self.request),
                     quoter.quote())
             tmpDict['tooltip'] = _(
                 u"ask the jabber-connector for watchdog")
             retList.append(tmpDict)
             tmpDict = {}
             tmpDict['oid'] = u"c000send_test"
             tmpDict['title'] = _(u"send test message")
             tmpDict['href'] = u"%s/@@send_test?nextURL=%s" % \
                    (zapi.absoluteURL(self.context, self.request),
                     quoter.quote())
             tmpDict['tooltip'] = _(u"send test message to im-server")
             retList.append(tmpDict)
         else:
             tmpDict = {}
             #tmpDict['oid'] = u"c%s" % objId
             tmpDict['oid'] = u"c000start_connector"
             tmpDict['title'] = _(u"start jabber-connector")
             tmpDict['href'] = u"%s/@@start_connector?nextURL=%s" % \
                    (zapi.absoluteURL(self.context, self.request),
                     quoter.quote())
             tmpDict['tooltip'] = _(u"starts the jabber-connector (as user:%s)"\
                                    % self.request.principal.title)
             retList.append(tmpDict)
     #tmpDict = {}
     #tmpDict['oid'] = u"a12345"
     #tmpDict['title'] = u"ich bin ein Titel"
     #tmpDict['href'] = u"http://www.essen.de"
     #tmpDict['tooltip'] = u"ich bin der \"aa\" 'bb' dazugehörige Tooltip Essen"
     #retList.append(tmpDict)
     return retList
Exemple #9
0
 def actions(self):
     """
     gives us the action dict of the object
     """
     try:
         objId = getUtility(IIntIds).getId(self.context)
     except KeyError:
         objId = 1000
     retList = []
     adapSize = ISized(self.context)
     # adapSize.sizeForSorting() returns ('item', n)
     if checkPermission('org.ict_ok.components.host.Add', self.context) and \
        (adapSize.sizeForSorting()[1] < 1):
         tmpDict = {}
         tmpDict['oid'] = u"c%sstart_scanner" % objId
         tmpDict['title'] = _(u"start scanner")
         tmpDict['href'] = u"%s/@@start_scanner.html" % \
                zapi.absoluteURL(self.context, self.request)
         tmpDict['tooltip'] = _(u"starts the network scanner (as user:%s)"\
                                % self.request.principal.title)
         retList.append(tmpDict)
     #tmpDict = {}
     #tmpDict['oid'] = u"a%s" % objId
     #tmpDict['title'] = u"ich bin ein Titel"
     #tmpDict['href'] = u"http://www.essen.de"
     #tmpDict['tooltip'] = u"ich bin der \"aa\" 'bb' dazugehörige T"
     #retList.append(tmpDict)
     return retList
    def update(self):
        message = self.applyUpdates()

        self.configBase = zapi.absoluteURL(zapi.getSiteManager(), self.request)

        registrations = self.context.info()

        # This is OK because registrations is just a list of dicts
        registrations = removeSecurityProxy(registrations)

        inactive = 1
        for info in registrations:
            if info['active']:
                inactive = None
            else:
                info['active'] = False

            reg = info['registration']
            info['summary'] = reg.implementationSummary()
            info['id'] = zapi.getPath(reg)

        # Add a dummy registration since the stack removes trailing None.
        registrations.append({"active": False,
                              "id": "disable",
                              "summary": ""})

        self.inactive = inactive
        self.registrations = registrations

        self.message = message
Exemple #11
0
 def traverse4DotGeneratorBody(self,
                               cfgFile,
                               level=0,
                               comments=True,
                               signalsOutput=False,
                               recursive=True):
     """generate body-text in graphviz dot-file"""
     if comments:
         print >> cfgFile, "%s// Body (%s,%d) - " \
               "SuperclassGenGraphvizDot" \
               % ("\t" * level, self.context.__name__, level)
     print >> cfgFile, '%s"%s" [' % ("\t" * level, self.context.objectID)
     print >> cfgFile, '%sshape = "box",' % ("\t" * (level + 1))
     print >> cfgFile, '%sstyle = "filled,setlinewidth(0)",' \
           % ("\t" * (level + 1))
     print >> cfgFile, '%sfillcolor = chartreuse2,' % ("\t" * (level + 1))
     print >> cfgFile, '%smargin = 0,' % ("\t" * (level + 1))
     print >> cfgFile, '%shref = "%s/@@details.html",' \
           % ("\t" * (level + 1), zapi.absoluteURL(self.context, self.request))
     print >> cfgFile, '%slabel = <<TABLE BORDER = "0" CELLBORDER = "0" ' \
           'CELLPADDING = "0" CELLSPACING = "0"><TR><TD>' \
           '<IMG SRC = "/home/markus/Projekte/IKOMtrol-hp/apple-red.png"/>' \
           '</TD></TR><TR><TD><FONT FACE = "Arial" POINT-SIZE = "10">%s' \
           '</FONT></TD></TR></TABLE>>' \
           % ("\t" * (level + 1), self.context.ikName)
     print >> cfgFile, '%s]; // %s' % ("\t" * level, self.context.__name__)
Exemple #12
0
 def __str__(self):
     if IContainmentRoot.providedBy(self.context):
         return ""
     name = self.context.__name__
     url = zapi.absoluteURL(zapi.getParent(self.context), self.request)
     url += "/" + name
     return url
Exemple #13
0
 def manageEvaluations(self, obj, cfgFile, level, request=None):
     if hasattr(obj, "getEvaluationsDone"):
         evals = obj.getEvaluationsDone()
         if len(evals) > 0:
             table_list = [(_("Evaluation"), _("Evaluator"), _("Value"))]
             for eval in evals:
                 #table_list.append((eval.ikName, eval.evaluator.title, eval.value+' <img src="%s/lib/python/org/ict_ok/skin/pics/mini/tick.gif">' % os.getcwd()))
                 table_list.append(
                     (eval.ikName, eval.evaluator.title, eval.value))
             tmpID = "tmp%s" % generateOid()
             dot_str = '%s"%s" [' % ("\t" * level, tmpID)
             dot_str += 'shape="note", '
             dot_str += 'label=<%s>, ' % self.__htmlTable(table_list)
             dot_str += 'fontsize=10.0'
             if request:
                 dot_str += ', \nURL="%s/evaluations_done.html"' % zapi.absoluteURL(
                     obj, request)
             dot_str += '];\n'
             dot_str += '%s"%s" -- "%s";' % ("\t" * level, tmpID,
                                             obj.objectID)
             print >> cfgFile, dot_str
     if hasattr(obj, "getEvaluationsTodo"):
         reqs = obj.getEvaluationsTodo()
         if len(reqs) > 0:
             pass
Exemple #14
0
 def update(self):
     model = self.model
     
     self.contents = Batch(list(self.context.values()), size=model.pageSize, request=self.request)
     self.came_from = zapi.absoluteURL(self, self.request)
     qs = self.request.get('QUERY_STRING')
     if qs:
         self.came_from = '%s?%s' % (self.came_from, qs)
Exemple #15
0
 def convertobj(self):
     """
     converts this esx object to an internal object
     """
     print("EsxVimVirtualMachineDetails.convertobj")
     r_obj = self.context.convertobj()
     return self.request.response.redirect(zapi.absoluteURL(r_obj, self.request)+\
                                           '/@@details.html')
Exemple #16
0
    def nextURL(self):
        v = zapi.queryMultiAdapter(
            (self.added_object, self.request), name="addRegistration.html")
        if v is not None:
            url = zapi.absoluteURL(self.added_object, self.request)
            return url + "/addRegistration.html"

        return super(UtilityAdding, self).nextURL()
Exemple #17
0
 def getInterfaceURL(self, name):
     sm = zapi.getSiteManager(self.context)
     try:
         getInterface(self.context, name)
         url = zapi.absoluteURL(sm, self.request)
     except ComponentLookupError:
         return ""
     return "%s/interfacedetail.html?id=%s" % (url, name)
Exemple #18
0
 def actions(self):
     """
     gives us the action dict of the object
     """
     try:
         objId = getUtility(IIntIds).getId(self.context)
     except:
         objId = 1000
     retList = []
     if appsetup.getConfigContext().hasFeature('devmode') and \
        checkPermission('org.ict_ok.components.host.Edit', self.context):
         quoter = URLQuote(self.request.getURL())
         tmpDict = {}
         tmpDict['oid'] = u"c%strigger_online" % objId
         tmpDict['title'] = _(u"Trigger online")
         tmpDict['href'] = u"%s/@@trigger_online?nextURL=%s" % \
                (zapi.absoluteURL(self.context, self.request),
                 quoter.quote())
         retList.append(tmpDict)
         tmpDict = {}
         tmpDict['oid'] = u"c%strigger_offline" % objId
         tmpDict['title'] = _(u"Trigger offline")
         tmpDict['href'] = u"%s/@@trigger_offline?nextURL=%s" % \
                (zapi.absoluteURL(self.context, self.request),
                 quoter.quote())
         retList.append(tmpDict)
         tmpDict = {}
         tmpDict['oid'] = u"c%strigger_not1" % objId
         tmpDict['title'] = _(u"Trigger notification1")
         tmpDict['href'] = u"%s/@@trigger_not1?nextURL=%s" % \
                (zapi.absoluteURL(self.context, self.request),
                 quoter.quote())
         retList.append(tmpDict)
     adapSize = ISized(self.context)
     if checkPermission('org.ict_ok.components.interface.Add', self.context) and \
        (adapSize.sizeForSorting()[1] < 1):
         tmpDict = {}
         tmpDict['oid'] = u"c%sstart_snmp_if_scanner" % objId
         tmpDict['title'] = _(u"start snmp interface scanner")
         tmpDict['href'] = u"%s/@@start_snmp_if_scanner.html" % \
                zapi.absoluteURL(self.context, self.request)
         tmpDict['tooltip'] = _(u"starts the interface scanner with snmp scan (as user:%s)"\
                                % self.request.principal.title)
         retList.append(tmpDict)
     return retList
 def registrationInfo(self):
     """Render View for each directives."""
     return [
         {'name': name,
          'url': zapi.absoluteURL(reg, self.request),
          'active': reg.status == ActiveStatus,
          'details': zapi.queryMultiAdapter((reg, self.request),
                                            name='details')}
         for name, reg in self.context.items()]
 def registrations(self):
     registered = interfaces.registration.IRegistered(self.context)
     return [
         {'name': zapi.name(reg),
          'url': zapi.absoluteURL(reg, self.request),
          'status': reg.status,
          'details': zapi.queryMultiAdapter((reg, self.request),
                                            name='details')}
         for reg in registered.registrations()]
    def registration(self):
        """Return the first registration.

        If there are no registrations, raises an error.
        """
        return {'url': zapi.absoluteURL(self.registrations[0], self.request),
                'details': zapi.queryMultiAdapter(
                    (self.registrations[0], self.request), name='details')
                }
Exemple #22
0
 def fsearch(self):
     utilSupervisor = getUtility(IAdmUtilSupervisor,
                                 name='AdmUtilSupervisor')
     if self.request.has_key('QUERY_STRING'):
         queryString = '?%s' % self.request['QUERY_STRING']
     else:
         queryString = ''
     return self.request.response.redirect(\
         zapi.absoluteURL(utilSupervisor, self.request)+\
         '/@@fsearch.html%s' % queryString)
Exemple #23
0
 def getHrefTitle(self, obj, displayShort=False):
     href = zapi.absoluteURL(obj, self.request)
     if hasattr(obj, 'getDisplayTitle'):
         title = obj.getDisplayTitle()
     else:
         title = obj.ikName
     if displayShort and hasattr(obj, 'shortName'):
         return u'<a href="%s">%s [%s]</a>' % (href, title, obj.shortName)
     else:
         return u'<a href="%s">%s</a>' % (href, title)
Exemple #24
0
    def findAllClasses(self):

        """Find all classes

        Examples::
          >>> from zope.app import zapi
          >>> from zope.app.apidoc.codemodule.class_ import Class
          >>> from zope.app.apidoc.interfaces import IDocumentationModule


          >>> cm = zapi.getUtility(IDocumentationModule, 'Code')
          >>> mod = cm['zope']['app']['apidoc']['codemodule']['browser']

          Setup a couple of classes and register them.

          >>> class Foo(object):
          ...     pass
          >>> mod._children['Foo'] = Class(mod, 'Foo', Foo)
          >>> class Foo2(object):
          ...     pass
          >>> mod._children['Foo2'] = Class(mod, 'Foo2', Foo2)
          >>> class Blah(object):
          ...     pass
          >>> mod._children['Blah'] = Class(mod, 'Blah', Blah)

          Setup the view.

          >>> from zope.app.apidoc.codemodule.browser.menu import Menu
          >>> from zope.publisher.browser import TestRequest
          >>> menu = Menu()
          >>> menu.context = None

          Testing the method with various inputs.

          >>> menu.request = TestRequest(form={'path': 'Foo'})
          >>> info = menu.findAllClasses()

          >>> len(info) > 3
          True
        """
        classModule = zapi.getUtility(IDocumentationModule, "Code")
        classModule.setup() # run setup if not yet done
        results = []
        counter = 0
        for p in classRegistry.keys():
            klass = zapi.traverse(classModule, p.replace('.', '/'))
            results.append(
                {'path': p,
                 'url': zapi.absoluteURL(klass, self.request),
                 'counter': counter
                 })
            counter += 1

        results.sort(lambda x, y: cmp(x['path'], y['path']))
        return results
Exemple #25
0
 def getToolInstances(self, tool):
     """Find every registered utility for a given tool configuration."""
     regManager = self.getSiteManagementFolder(tool).registrationManager
     return [
         {'name': reg.name,
          'url': zapi.absoluteURL(reg.component, self.request),
          'rename': tool is self.activeTool and reg.name in self.renameList,
          'active': reg.status == u'Active'
         }
         for reg in regManager.values()
         if (zapi.isinstance(reg, site.UtilityRegistration) and
             reg.provided.isOrExtends(tool.interface))]
Exemple #26
0
 def getScannerObjs(self):
     """
     get list of Scanner-Tupel (name, obj)
     """
     retList = []
     for name, scanner in self.context.getScannerObjs():
         retDict = {}
         retDict['name'] = name
         retDict['href'] = zapi.absoluteURL(scanner,
                                            self.request) + '/@@status'
         retList.append(retDict)
     return retList
Exemple #27
0
 def getAllNotifierObjs(self):
     """
     get list of Notifier-Tupel (name, obj)
     """
     retList = []
     for name, notifier in self.context.getAllNotifierObjs():
         retDict = {}
         retDict['name'] = name
         retDict['href'] = zapi.absoluteURL(
             notifier, self.request) + '/@@details.html'
         retList.append(retDict)
     return retList
    def thumbnail(self, context=None, size='thumbnail'):
        if not context:
            context = self.context

        for key, doc in context.items():
            if not IImage.providedBy(doc):
                continue

            scale = getMultiAdapter((doc, self.request), name=u'scale')
            thumb = scale.publishTraverse(self.request, size)
            if thumb.getSize():
                return zapi.absoluteURL(doc, self.request)
        return ''
Exemple #29
0
 def findByIds(self, ids):
     """Do a find for the `ids` listed in `ids`, which is a string."""
     finder = IFind(self.context)
     ids = ids.split()
     # if we don't have any ids listed, don't search at all
     if not ids:
         return []
     request = self.request
     result = []
     for object in finder.find([SimpleIdFindFilter(ids)]):
         url = zapi.absoluteURL(object, request)
         result.append({ 'id': getName(object), 'url': url})
     return result
Exemple #30
0
    def action(self):
        # Some locations (eg ++etc++process) throw a TypeError exception when
        # finding their absoluteurl, if this happens catch the error and
        # redirect the browser to the site root "/@@errorRedirect.html"
        # to handle redirection to the site error logger instead
        try:
            err = zapi.getUtility(IErrorReportingUtility)
            url = zapi.absoluteURL(err, self.request)
        except TypeError:
            url = self.request.getApplicationURL() + "/@@errorRedirect.html"
        else:
            url = url + "/@@SelectedManagementView.html"

        self.request.response.redirect(url)
Exemple #31
0
    def attributes(self):
        context = removeSecurityProxy(self.context)
        attrs = [{'name': (ns and context.prefixes[ns]+':' or '') + name,
                  'value': value, 'url': None, 'values': []}
                 for (ns, name), value in context.attrs.items()]

        names = context.schema.names(True)
        rootURL = zapi.absoluteURL(findDocModule(self), self.request)
        for attr in attrs:
            name = (attr['name'] in names) and attr['name'] or attr['name']+'_'
            field = context.schema.get(name)

            if zapi.isinstance(field, (GlobalObject, GlobalInterface)):
                attr['url'] = self.objectURL(attr['value'], field, rootURL)

            elif zapi.isinstance(field, Tokens):
                field = field.value_type
                values = attr['value'].strip().split()
                if len(values) == 1:
                    attr['value'] = values[0]
                    attr['url'] = self.objectURL(values[0], field, rootURL)
                else:
                    for value in values:
                        if zapi.isinstance(field,
                                           (GlobalObject, GlobalInterface)):
                            url = self.objectURL(value, field, rootURL)
                        else:
                            break
                        attr['values'].append({'value': value, 'url': url})

        # Make sure that the attributes are in the same order they are defined
        # in the schema.
        fieldNames = getFieldNamesInOrder(context.schema)
        fieldNames = [name.endswith('_') and name[:-1] or name
                      for name in fieldNames]
        attrs.sort(lambda x, y: _compareAttrs(x, y, fieldNames))

        if not IRootDirective.providedBy(context):
            return attrs

        xmlns = []
        for uri, prefix in context.prefixes.items():
            name = prefix and ':'+prefix or ''
            xmlns.append({'name': 'xmlns'+name,
                          'value': uri,
                          'url': None,
                          'values': []})

        xmlns.sort(lambda x, y: cmp(x['name'], y['name']))
        return xmlns + attrs
Exemple #32
0
 def traverse4DotGeneratorBody(self,
                               cfgFile,
                               level=0,
                               comments=True,
                               request=None,
                               alreadySeenList=None):
     """graphviz configuration data of object
     """
     if comments:
         print >> cfgFile, "%s// Body (%s,%d) - RptDot" \
               % ("\t" * level, self.context, level)
     dot_str = '%s"%s" [' % ("\t" * level, self.context.objectID)
     dot_str += 'shape="diamond", '
     dot_str += 'label=<%s>,' % (self.context.ikName)
     dot_str += 'fontsize=10.0,'
     dot_str += 'fonttype="Sans"'
     if request:
         dot_str += ', \nURL="%s"' % zapi.absoluteURL(self.context, request)
     dot_str += '];'
     print >> cfgFile, dot_str
     if alreadySeenList == None:
         alreadySeenList = []
     alreadySeenList.append(self.context)
     itemNav = INavigation(self.context)
     tuplelist = itemNav.getContextObjList()
     for (attrName, viewTitle, contextObj) in tuplelist:
         if attrName is not None and viewTitle is not None:
             if type(attrName) is not type("str"):
                 raise TypeError("Nav_tuple_wrong: %s" % type(attrName))
             objList = getattr(contextObj, attrName)
             if objList.__class__ != list:
                 objList = [objList]
             for obj in objList:
                 if obj not in alreadySeenList:
                     try:
                         adapterGenGraphvizDot = IGenGraphvizDot(obj)
                     except TypeError:
                         adapterGenGraphvizDot = None
                     if adapterGenGraphvizDot:
                         adapterGenGraphvizDot.setParent(self.context)
                         adapterGenGraphvizDot.traverse4DotGenerator(\
                             cfgFile,
                             level+1,
                             comments,
                             request,
                             alreadySeenList)
     self.manageEvaluations(self.context, cfgFile, level, request)
     if self.parent != None:
         print >> cfgFile, '%s"%s" -- "%s";' \
               % ("\t" * level, self.parent.objectID, self.context.objectID)
Exemple #33
0
    def thumbnail(self, context=None, size='thumbnail', from_parent=False):
        if not context:
            context = self.context

        for key, doc in context.items():
            if key == 'icon.png':
                continue
            if not IImage.providedBy(doc):
                continue

            scale = getMultiAdapter((doc, self.request), name=u'scale')
            try:
                thumb = scale.publishTraverse(self.request, size)
            except Exception, err:
                thumb = ''
            if thumb and thumb.getSize():
                return zapi.absoluteURL(doc, self.request)
Exemple #34
0
    def actions(self):
        """
        gives us the action dict of the object
        """
        try:
            objId = getUtility(IIntIds).getId(self.context)
        except KeyError:
            objId = 1000
        retList = []
#        if checkPermission('org.ict_ok.admin_utils.compliance.generate.pdf',
#                           self.context):
#            tmpDict = {}
#            tmpDict['oid'] = u"c%sgenerate_all_pdf" % objId
#            tmpDict['title'] = _(u"generate all pdf")
#            tmpDict['href'] = u"%s/@@generate_all_pdf" % \
#                   (zapi.absoluteURL(self.context, self.request))
#            tmpDict['tooltip'] = _(u"will generate a all pdf file")
#            retList.append(tmpDict)
#        if checkPermission('org.ict_ok.admin_utils.compliance.Import',
#                           self.context):
#            tmpDict = {}
#            tmpDict['oid'] = u"c%simport requirements" % objId
#            tmpDict['title'] = _(u"import requirements")
#            tmpDict['href'] = u"%s/@@import_requirements" % \
#                   (zapi.absoluteURL(self.context, self.request))
#            tmpDict['tooltip'] = _(u"will import requirements")
#            retList.append(tmpDict)
        if checkPermission('org.ict_ok.admin_utils.compliance.Match',
                           self.context):
            tmpDict = {}
            tmpDict['oid'] = u"c%smatch requirements" % objId
            tmpDict['title'] = _(u"match requirements/categories")
            tmpDict['href'] = u"%s/@@match_requirements" % \
                   (zapi.absoluteURL(self.context, self.request))
            tmpDict['tooltip'] = _(u"will match requirements over categories")
            retList.append(tmpDict)
        if checkPermission('org.ict_ok.admin_utils.compliance.Delete',
                           self.context):
            tmpDict = {}
            tmpDict['oid'] = u"c%sdelete requirements" % objId
            tmpDict['title'] = _(u"delete all requirements")
            tmpDict['href'] = u"./@@deleteReqs.html"
            tmpDict['tooltip'] = _(u"will match requirements over categories")
            retList.append(tmpDict)
        return retList
Exemple #35
0
    def __call__(self):
        context = self.context
        request = self.request
        response = request.response

        r = []
        url = zapi.absoluteURL(context, request)
        r.append('url:%s' % url)
        adapted = IReadFile(context)

        if hasattr(adapted, 'contentType'):
            # Although IReadFile declares contentType,
            # the default adapter for File doesn't seem
            # to provide it.
            r.append('content_type:%s' % adapted.contentType)

        # There's no such thing as a meta_type
        # in Zope3, so we try to get as far as we can
        # using IContentType, which is a marker interface

        # Had to use removeSecurityProxy because
        # I was getting unauthorized on __iro__
        meta_type = queryType(removeSecurityProxy(context), IContentType)
        if meta_type:
            r.append('meta_type:%s' % meta_type.__name__)

        auth = request._auth

        if auth is not None:
            if auth.endswith('\n'):
                auth = auth[:-1]
            r.append('auth:%s' % auth)

        r.append('cookie:%s' % request._environ.get('HTTP_COOKIE', ''))

        # TODO: Once we have lock, add the lock token here

        r.append('')

        response.setHeader('Pragma', 'no-cache')

        r.append(adapted.read())

        response.setHeader('Content-Type', 'application/x-zope-edit')
        return '\n'.join(r)
Exemple #36
0
 def getEntries(self, columns=True):
     """Return info objects for all modules and classes in this module."""
     entries = [{'name': name,
                 # only for interfaces; should be done differently somewhen
                 'path': getPythonPath(removeAllProxies(obj)),
                 'url': zapi.absoluteURL(obj, self.request),
                 'ismodule': zapi.isinstance(obj, Module),
                 'isinterface': zapi.isinstance(
                      removeAllProxies(obj), InterfaceClass),
                 'isclass': zapi.isinstance(obj, Class),
                 'isfunction': zapi.isinstance(obj, Function),
                 'istextfile': zapi.isinstance(obj, TextFile),
                 'iszcmlfile': zapi.isinstance(obj, ZCMLFile)}
                for name, obj in self.context.items()]
     entries.sort(lambda x, y: cmp(x['name'], y['name']))
     if columns:
         entries = columnize(entries)
     return entries
Exemple #37
0
    def action(self, type_name='', id=''):
        if not type_name:
            raise UserError(_(u"You must select the type of object to add."))

        if type_name.startswith('@@'):
            type_name = type_name[2:]

        if '/' in type_name:
            view_name = type_name.split('/', 1)[0]
        else:
            view_name = type_name

        if zapi.queryMultiAdapter((self, self.request),
                                  name=view_name) is not None:
            url = "%s/%s=%s" % (
                zapi.absoluteURL(self, self.request), type_name, id)
            self.request.response.redirect(url)
            return

        if not self.contentName:
            self.contentName = id

        # TODO: If the factory wrapped by LocationProxy is already a Proxy,
        #       then ProxyFactory does not do the right thing and the
        #       original's checker info gets lost. No factory that was
        #       registered via ZCML and was used via addMenuItem worked
        #       here. (SR)
        factory = zapi.getUtility(IFactory, type_name)
        if not type(factory) is zope.security.checker.Proxy:
            factory = LocationProxy(factory, self, type_name)
            factory = zope.security.checker.ProxyFactory(factory)
        content = factory()

        # Can't store security proxies.
        # Note that it is important to do this here, rather than
        # in add, otherwise, someone might be able to trick add
        # into unproxying an existing object,
        content = removeSecurityProxy(content)

        notify(ObjectCreatedEvent(content))

        self.add(content)
        self.request.response.redirect(self.nextURL())
    def __call__(self):
        """See zope.app.browser.interfaces.form.IBrowserWidget"""
        # Render as a link to the component
        field = self.context
        context = field.context
        if interfaces.registration.IRegistration.providedBy(context):
            # It's a registration object. Just get the corresponding attr
            component = getattr(context, field.__name__)
            path = zapi.getPath(component)
        else:
            # It must be a component that is about to be configured.
            component = context
            # Always use a relative path (just the component name)
            path = zapi.name(context)

        url = zapi.absoluteURL(component, self.request)

        return ('<a href="%s/@@SelectedManagementView.html">%s</a>'
                % (url, path))
Exemple #39
0
    def PUT(self):
        request = self.request

        body = request.bodyStream
        name = self.context.name
        container = self.context.container

        # Find the extension
        ext_start = name.rfind('.')
        if ext_start > 0:
            ext = name[ext_start:]
        else:
            ext = "."

        # Get a "directory" surrogate for the container
        # TODO: Argh. Why don't we have a unioned Interface for that?!?
        dir_write = IWriteDirectory(container)
        dir_read = IReadDirectory(container)

        # Now try to get a custom factory for he container
        factory = queryAdapter(container, IFileFactory, ext)

        # Fall back to a non-custom one
        if factory is None:
            factory = IFileFactory(container)

        # TODO: Need to add support for large files
        data = body.read()

        newfile = factory(name, request.getHeader('content-type', ''), data)
        notify(ObjectCreatedEvent(newfile))

        dir_write[name] = newfile
        # Ickyness with non-predictable support for containment: 
        #   make sure we get a containment proxy
        newfile = dir_read[name]

        request.response.setStatus(201)
        request.response.setHeader(
            'Location', zapi.absoluteURL(newfile, request))
        return ''
Exemple #40
0
 def url(self):
     directive = removeSecurityProxy(self.context)
     subDirective = None
     # Sub-directives are not directly documented, so use parent
     parent = zapi.getParent(directive)
     if not (IRootDirective.providedBy(parent) or
             IRootDirective.providedBy(directive)):
         subDirective = directive
         directive = parent
     ns, name = directive.name
     # Sometimes ns is `None`, especially in the slug files, where no
     # namespaces are used.
     ns = quoteNS(ns or 'ALL')
     zcml = zapi.getUtility(IDocumentationModule, 'ZCML')
     if name not in zcml[ns]:
         ns = 'ALL'
     link = '%s/../ZCML/%s/%s/index.html' %(
         zapi.absoluteURL(findDocModule(self), self.request), ns, name)
     if subDirective:
         link += '#' + subDirective.name[1]
     return link
Exemple #41
0
 def actions(self):
     """
     gives us the action dict of the object
     """
     try:
         objId = getUtility(IIntIds).getId(self.context)
     except KeyError:
         objId = 1000
     retList = []
     if checkPermission('org.ict_ok.admin_utils.event.Send', self.context):
         quoter = URLQuote(self.request.getURL())
         tmpDict = {}
         tmpDict['oid'] = u"c%ssend_event" % objId
         tmpDict['title'] = _(u"send it")
         tmpDict['href'] = u"%s/@@send_event.html?nextURL=%s" % \
                (zapi.absoluteURL(self.context, self.request),
                 quoter.quote())
         tmpDict['tooltip'] = _(
             u"sends an the event to the list of receivers")
         retList.append(tmpDict)
     return retList
Exemple #42
0
 def _listClasses(self, classes):
     """Prepare a list of classes for presentation."""
     info = []
     codeModule = zapi.getUtility(IDocumentationModule, "Code")
     for cls in classes:
         # We need to removeAllProxies because the security checkers for
         # zope.app.container.contained.ContainedProxy and
         # zope.app.i18n.messagecatalog.MessageCatalog prevent us from
         # accessing __name__ and __module__.
         unwrapped_cls = removeAllProxies(cls)
         path = getPythonPath(unwrapped_cls)
         url = None
         try:
             klass = zapi.traverse(codeModule, path.replace('.', '/'))
             url = zapi.absoluteURL(klass, self.request)
         except TraversalError:
             # If one of the classes is implemented in C, we will not
             # be able to find it.
             pass
         info.append({'path': path or None, 'url': url})
     return info
Exemple #43
0
 def actions(self):
     """
     gives us the action dict of the object
     """
     try:
         objId = getUtility(IIntIds).getId(self.context)
     except KeyError:
         objId = 1000
     retList = []
     if checkPermission('org.ict_ok.admin_utils.notifier.Send',
                        self.context):
         quoter = URLQuote(self.request.getURL())
         tmpDict = {}
         tmpDict['oid'] = u"c%snotifier_send" % objId
         tmpDict['title'] = _(u"send test")
         tmpDict['href'] = u"%s/@@send_test?nextURL=%s" % \
                (zapi.absoluteURL(self.context, self.request),
                 quoter.quote())
         tmpDict['tooltip'] = _(u"will send a test message "\
                                u"by the selected notifier")
         retList.append(tmpDict)
     return retList
Exemple #44
0
    def nextURL(self):
        """
        >>> from zope.publisher.browser import TestRequest
        >>> from zope.app.testing.placelesssetup import setUp, tearDown
        >>> setUp()
        >>> rqst = TestRequest()
        >>> class Base(object):
        ...     def __init__(self, request):
        ...         self.request = request
        ...         self.context = self
        ...         self.contentName = 'new srcipt'
        ...     def __getitem__(self, key):
        ...         return None
        ...     def nextURL(self):
        ...         return "www.zeomega.com"

        >>> class V(SQLScriptAdd, Base):
        ...     pass
        >>> 
        >>> rqst = TestRequest()
        >>> dc = V(rqst)
        >>> dc.nextURL()
        'www.zeomega.com'
        >>> d = {'add_test': True}
        >>> rqst1 = TestRequest(form = d)
        >>> dc1 = V(rqst1)
        >>> dc1.nextURL()
        'http://127.0.0.1/test.html'
        """
        if 'add_test' in self.request:
            name = self.context.contentName
            container = self.context.context
            obj = container[name]
            url = zapi.absoluteURL(obj, self.request)
            url = '%s/test.html' % url
            return url
        else:
            return super(SQLScriptAdd, self).nextURL()
Exemple #45
0
    def getBreadCrumbs(self):
        """Create breadcrumbs for the module path.

        We cannot reuse the the system's bread crumbs, since they go all the
        way up to the root, but we just want to go to the root module."""
        names = self.context.getPath().split('.')
        crumbs = []
        module = self.context
        # I really need the class here, so remove the proxy.
        while removeSecurityProxy(module).__class__ is Module:
            crumbs.append(
                {'name': zapi.name(module),
                 'url': zapi.absoluteURL(module, self.request)}
                )
            module = zapi.getParent(module)

        crumbs.append(
            {'name': _('[top]'),
             'url': zapi.getMultiAdapter(
                      (module, self.request), name='absolute_url')()} )

        crumbs.reverse()
        return crumbs
Exemple #46
0
 def actions(self):
     """
     gives us the action dict of the object
     """
     try:
         objId = getUtility(IIntIds).getId(self.context)
     except KeyError:
         objId = 1000
     retList = []
     if True:
     #if checkPermission('org.ict_ok.admin_utils.generators.nagios.View',
                        #self.context) and\
        #zapi.queryMultiAdapter((self.context, self.request),
                               #name='shutdown.html') is not None:
         quoter = URLQuote(self.request.getURL())
         tmpDict = {}
         tmpDict['oid'] = u"c%sgenerate" % objId
         tmpDict['title'] = _(u"generate")
         tmpDict['href'] = u"%s/@@generate.html?nextURL=%s" % \
                (zapi.absoluteURL(self.context, self.request),
                 quoter.quote())
         tmpDict['tooltip'] = _(u"generate nagios cfg")
         retList.append(tmpDict)
     return retList
Exemple #47
0
    def traverse4DotGeneratorBody(self, \
                                  cfgFile, \
                                  level=0, \
                                  comments=True,
                                  signalsOutput=False,
                                  recursive=True):
        """Pre-Text in graphviz dot-file"""
        if comments:
            print >> cfgFile, "%s// Body (%s,%d) - SupernodeGenGraphvizDot" \
                  % ("\t" * level, self.context.__name__, level)

        print >> cfgFile, '%s"%s" [' % ("\t" * level, self.context.objectID)
        print >> cfgFile, '%sshape="plaintext",' % ("\t" * (level + 1))
        print >> cfgFile, '%sstyle="filled,setlinewidth(0)",' \
              % ("\t" * (level + 1))
        print >> cfgFile, '%sfillcolor = chartreuse2,' % ("\t" * (level + 1))
        print >> cfgFile, '%smargin = 0,' % ("\t" * (level + 1))
        print >> cfgFile, '%shref = "%s/@@details.html",' \
              % ("\t" * (level + 1), zapi.absoluteURL(self.context, self.request))

        #print >> cfgFile, '%slabel = <<TABLE BORDER = "0" CELLBORDER = "0" ' \
              #'CELLPADDING = "0" CELLSPACING = "0"><TR><TD>' \
              #'<IMG SRC = "/home/markus/Projekte/IKOMtrol-hp/apple-red.png"/>' \
              #'</TD></TR><TR><TD><FONT FACE = "Arial" POINT-SIZE = "10">%s' \
              #'</FONT></TD></TR></TABLE>>' \
              #% ("\t" * (level + 1), self.context.ikName)

        print >> cfgFile, '%slabel = <' % ("\t" * (level + 1))
        print >> cfgFile, '%s<TABLE BORDER="0" CELLBORDER="1" CELLPADDING = "2" CELLSPACING = "0">' % ("\t" * (level + 1))
        print >> cfgFile, '%s<TR><TD WIDTH="120px">%s</TD></TR>' % ("\t" * (level + 1), self.context.ikName)
        if signalsOutput:
            allInpNamesDict = self.context.getAllInpEventNames()
            for inpName in allInpNamesDict.keys():
                print >> cfgFile, '%s<TR><TD ALIGN="LEFT" PORT="%s" '\
                      'BGCOLOR="yellow">%s</TD></TR>' % \
                      ("\t" * (level + 1), inpName, inpName)
            allOutNamesDict = self.context.getAllOutEventNames()
            for outName in allOutNamesDict.keys():
                print >> cfgFile, '%s<TR><TD ALIGN="RIGHT" PORT="%s" '\
                      'BGCOLOR="orange">%s</TD></TR>' % \
                      ("\t" * (level + 1), outName, outName)
        #print >> cfgFile, '%s<TR><TD ALIGN="LEFT" PORT="sig_inp1" BGCOLOR="yellow">sig_inp1</TD></TR>' % ("\t" * (level + 1))
        #print >> cfgFile, '%s<TR><TD ALIGN="LEFT" PORT="sig_inp2" BGCOLOR="yellow">sig_inp2</TD></TR>' % ("\t" * (level + 1))
        #print >> cfgFile, '%s<TR><TD ALIGN="RIGHT" PORT="sig_out1" BGCOLOR="orange">sig_out1</TD></TR>' % ("\t" * (level + 1))
        print >> cfgFile, '%s</TABLE>>' % ("\t" * (level + 1))
        print >> cfgFile, '%s]; // %s' % ("\t" * level, self.context.__name__)
        if recursive:
            its = self.context.items()
        else:
            its = []
        for (dummy_name, oobj) in its:
            if ISuperclass.providedBy(oobj):
                try:
                    adapterGenGraphvizDot = IGenGraphvizDot(oobj)
                    if adapterGenGraphvizDot:
                        adapterGenGraphvizDot.setParent(self.context)
                        adapterGenGraphvizDot.traverse4DotGenerator(\
                            cfgFile, level + 1, comments, signalsOutput)
                except TypeError, err:
                    logging.error("Error in AdmUtilGraphviz::getRootDot()"\
                                  % err)
Exemple #48
0
 def getDownloadHref(self):
     href = zapi.absoluteURL(self.context, self.request)
     title = self.context.ikName
     return u'<a href="%s/@@download.html">-> %s</a>' % (href, title)
Exemple #49
0
 def nextURL(self):
     """See zope.app.container.interfaces.IAdding"""
     return zapi.absoluteURL(self.context, self.request)+'/@@editschema.html'
Exemple #50
0
 def failHref(self):
     return "%s/evaluations_done.html" % zapi.absoluteURL(
         self.context, self.request)
Exemple #51
0
 def todoHref(self):
     return "%s/evaluations_todo.html" % zapi.absoluteURL(
         self.context, self.request)
Exemple #52
0
    def singleBranchTree2(self, root=''):
        """Return an XML document with the siblings and parents of an object.

        There is only one branch expanded, in other words, the tree is
        filled with the object, its siblings and its parents with
        their respective siblings.

        """
        result = ''
        oldItem = self.context
        try:
            oldItemOid = self.context.getObjectId()
        except:
            oldItemOid = "+++"

        vh = self.request.getVirtualHostRoot()
        if vh:
            #print "vh: ", vh
            vhrootView = zapi.getMultiAdapter((vh, self.request),
                                              name='absolute_url')
            baseURL = vhrootView() + '/'
            try:
                rootName = '[' + vh.__name__ + ']'
            except:
                # we got the containment root itself as the virtual host
                # and there is no name.
                rootName = _('[top]')
            parents = getParentsFromContextToObject(self.context, vh)
        else:
            rootName = _('[top]')
            baseURL = self.request.getApplicationURL() + '/'
            parents = getParents(self.context)
        rootName = translate(rootName, context=self.request, default=rootName)
        for item in parents:
            # skip skin if present
            if item == oldItem:
                continue
            if item is None:
                continue
            subItems = []
            if IReadContainer.providedBy(item):
                keys = list(item.keys())
            else:
                keys = []
            # include the site manager
            #keys.append(u'++etc++site')
            for name in keys:
                # Only include items we can traverse to
                try:
                    subItem = traverse(item, name, None)
                except ValueError:
                    subItem = None
                if subItem is None:
                    continue
                #if name == u'++etc++site' and \
                #not checkPermission(\
                #'org.ict_ok.admin_utils.supervisor.DataDump',
                #subItem):
                #continue
                iconUrl = self.getIconUrl(subItem)
                try:
                    subitem_len = len(
                        IContentList(self.context).getContentList())
                except TypeError:
                    try:
                        subitem_len = self.getLengthOf(subItem)
                    except TypeError:
                        subitem_len = 0
                    except AttributeError:
                        subitem_len = 0
                try:
                    dcAdapter = IGeneralDublinCore(subItem)
                except TypeError:
                    dcAdapter = None
                xml_title = name
                if dcAdapter:
                    if dcAdapter.title:
                        xml_title = dcAdapter.title
                stateIconUrl = self.getStateIconUrl(subItem)
                if zapi.getParent(subItem):
                    #                    item_ppath = zapi.canonicalPath(zapi.getParent(subItem)) \
                    #                               + u'/'
                    url = urlparse(
                        zapi.absoluteURL(zapi.getParent(subItem),
                                         self.request))
                    item_ppath = url.path + u'/'
                    item_ppath = item_ppath.replace('//', '/')
                else:
                    item_ppath = "/"
                try:
                    subItemOid = subItem.getObjectId()
                except:
                    subItemOid = "---"
                stateOverview = self.getStateOverview(item)
                if subitem_len > 0:
                    # the test below seems to be broken
                    # with the ++etc++site case
                    if subItem == oldItem:
                        if oldItemOid == subItemOid:  # focussed
                            subItems.append(
                                xmlEscapeWithCData(
                                    u'<collection isfocused="" title=%s name=%s '
                                    u'iklen=%s rem="2.1.1.1" '
                                    u'icon_url=%s isopen="" expable="" state_url=%s '
                                    u'path=%s state_val=%s>%s</collection>',
                                    xml_title, name, subitem_len, iconUrl,
                                    stateIconUrl, item_ppath, stateOverview,
                                    result))
                        else:
                            subItems.append(
                                xmlEscapeWithCData(
                                    u'<collection title=%s name=%s iklen=%s rem="2.1.1.2.4" '
                                    u'icon_url=%s isopen="" expable="" state_url=%s path=%s '
                                    u'state_val=%s>%s</collection>', xml_title,
                                    name, subitem_len, iconUrl, stateIconUrl,
                                    item_ppath, stateOverview, result))
                    else:
                        subItems.append(
                            xmlEscape(
                                u'<collection title=%s name=%s iklen=%s rem="2.1.2" '
                                u'icon_url=%s expable="" state_url=%s path=%s/>',
                                xml_title, name, subitem_len, iconUrl,
                                stateIconUrl, item_ppath))
                else:
                    if subItem == oldItem:
                        if oldItemOid == subItemOid:  # focussed
                            subItems.append(
                                xmlEscapeWithCData(
                                    u'<collection isfocused="" title=%s '
                                    u'name=%s iklen=%s rem="2.2.1.1" '
                                    u'icon_url=%s state_url=%s path=%s '
                                    u'state_val=%s>%s</collection>', xml_title,
                                    name, subitem_len, iconUrl, stateIconUrl,
                                    item_ppath, stateOverview, result))
                        else:
                            subItems.append(
                                xmlEscapeWithCData(
                                    u'<collection title=%s name=%s iklen=%s '
                                    u'icon_url=%s state_url=%s path=%s rem="2.2.1.2" '
                                    u'state_val=%s>%s</collection>', xml_title,
                                    name, subitem_len, iconUrl, stateIconUrl,
                                    item_ppath, stateOverview, result))
                    else:
                        subItems.append(
                            xmlEscape(
                                u'<collection title=%s name=%s iklen=%s rem="2.2.2" '
                                u'icon_url=%s state_url=%s path=%s/>',
                                xml_title, name, subitem_len, iconUrl,
                                stateIconUrl, item_ppath))

            result = u' '.join(subItems)
            oldItem = item

        # do not forget root folder
        iconUrl = self.getIconUrl(oldItem)
        xml_title = "ICT_Ok"
        rootName = "."

        if len(result) > 0:  # collection has content
            result = xmlEscapeWithCData(
                u'<collection title=%s name=%s baseURL=%s iklen=%s rem="3.1" '
                u'icon_url=%s path=%s isopen="" isroot="">%s</collection>',
                xml_title, rootName, baseURL, len(oldItem), iconUrl, "/",
                result)
        else:
            result = xmlEscapeWithCData(
                u'<collection title=%s name=%s baseURL=%s iklen=%s rem="3.2" '
                u'icon_url=%s path=%s expable="" '
                u'isroot="">%s</collection>', xml_title, rootName, baseURL,
                len(oldItem), iconUrl, "/", result)

        self.request.response.setHeader('Content-Type', 'text/xml')
        setNoCacheHeaders(self.request.response)
        title = translate(titleTemplate,
                          context=self.request,
                          default=titleTemplate)
        loading = translate(loadingMsg,
                            context=self.request,
                            default=loadingMsg)
        return xmlEscapeWithCData(
            u'<?xml version="1.0" encoding="ISO-8859-1"?>'
            u'<children title_tpl=%s title=%s '
            u'loading_msg=%s>%s</children>', title, title, loading, result)
Exemple #53
0
 def url(self):
     """See interfaces.IBreadcrumbInfo"""
     return zapi.absoluteURL(self.context, self.request)
Exemple #54
0
 def getValuePngHref(self):
     """get path of object as string
     """
     obj = removeAllProxies(self.context)
     return zapi.absoluteURL(obj, self.request)
Exemple #55
0
 def url(self):
     return '%s/%s'%(zapi.absoluteURL(self.context, self.request), 'harvest')
Exemple #56
0
 def getValuePngHref(self):
     """Url to picture"""
     obj = self.context
     return zapi.absoluteURL(obj, self.request)
Exemple #57
0
 def createBatchLink(self, batchStart):
     listing = self.context
     url = zapi.absoluteURL(listing, self.request).replace("%2F","/")
     url += "?"
     url += urlencode({'bstart':batchStart})
     return url
Exemple #58
0
def findAPIDocumentationRoot(obj, request):
    if zapi.isinstance(obj, APIDocumentation):
        return zapi.absoluteURL(obj, request)
    return findAPIDocumentationRoot(zapi.getParent(obj), request)
Exemple #59
0
 def getBaseURL(self):
     """Return the URL for the API Documentation Tool."""
     m = zapi.getUtility(IDocumentationModule, "Code")
     return zapi.absoluteURL(zapi.getParent(m), self.request)
 def nextURL(self):
     return zapi.absoluteURL(self.context, self.request)