TutorialTopic.py :  » Web-Frameworks » Zope » Zope-2.6.0 » lib » python » Products » ZopeTutorial » Python Open Source

Home
Python Open Source
1.3.1.2 Python
2.Ajax
3.Aspect Oriented
4.Blog
5.Build
6.Business Application
7.Chart Report
8.Content Management Systems
9.Cryptographic
10.Database
11.Development
12.Editor
13.Email
14.ERP
15.Game 2D 3D
16.GIS
17.GUI
18.IDE
19.Installer
20.IRC
21.Issue Tracker
22.Language Interface
23.Log
24.Math
25.Media Sound Audio
26.Mobile
27.Network
28.Parser
29.PDF
30.Project Management
31.RSS
32.Search
33.Security
34.Template Engines
35.Test
36.UML
37.USB Serial
38.Web Frameworks
39.Web Server
40.Web Services
41.Web Unit
42.Wiki
43.Windows
44.XML
Python Open Source » Web Frameworks » Zope 
Zope » Zope 2.6.0 » lib » python » Products » ZopeTutorial » TutorialTopic.py
##############################################################################
#
# Copyright (c) 2001 Zope Corporation and Contributors. All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.0 (ZPL).  A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE
#
##############################################################################
import OFS.Folder
from HelpSys.HelpTopic import TextTopic
from Globals import HTML,DTMLFile,MessageDialog
import DateTime
import DocumentTemplate
import StructuredText
import  re


pre_pat=re.compile(r'<PRE>(.+?)</PRE>', re.IGNORECASE|re.DOTALL)
tutorialExamplesFile='ZopeTutorialExamples.zexp'

class TutorialTopic(TextTopic):
    """
    A Tutorial Help Topic
    """

    def __init__(self, id, title, text):
        self.id=id
        self.title=title
        text=str(StructuredText.HTML(text))
        self.obj=HTML(pre_pat.sub(clean_pre, text))

    index_html=DTMLFile('dtml/lessonView', globals())

    def checkInstallation(self, REQUEST):
        """
        Returns false if the tutorial examples are not correctly
        installed. Also sets the 'hide_next' variable in the request
        if the examples are not installed.
        """
        ok=0
        if REQUEST.has_key('tutorialExamplesURL'):
            url=REQUEST['tutorialExamplesURL']
            base=REQUEST['BASE1']
            if url.index(base) == 0:
                url=url[len(base):]
                try:
                    self.getPhysicalRoot().unrestrictedTraverse(url)
                    ok=1
                except:
                    pass

        if not ok:
            REQUEST.set('hide_next', 1)
        return ok

    def lessonURL(self, id, REQUEST):
        """
        URL of the examples for a lesson
        """
        try:
            return '%s/lesson%d' % (REQUEST['tutorialExamplesURL'], id)
        except KeyError:
            return ""

    def tutorialShowLesson(self, id, REQUEST):
        """
        Navigate management frame to a given lesson's screen.
        """
        url=self.lessonURL(id, REQUEST)
        if not url or not self.checkInstallation(REQUEST):
            REQUEST.set('hide_next', 0)
            return """\
<p class="warning">
Zope cannot find the tutorial examples.
You should install the tutorial examples before
continuing. Choose "Zope Tutorial" from the product
add list in the Zope management screen to install
the examples.
</p>
<p class="warning">
If you have already installed the tutorial, you can either
follow along manually, or reinstall the tutorial examples.
Note: make sure that you have cookies turned on in your browser.
</p>
"""

        return """\
<SCRIPT LANGUAGE="javascript">
<!--
window.open("%s/manage_main", "manage_main");
//-->
</SCRIPT>
<p class="information">
<a href="%s/manage_main" target="manage_main"
onClick="javascript:window.open('%s/manage_main', 'manage_main').focus()"
>Show lesson examples</a> in another window.
</p>""" % (url, url, url)


    tutorialNavigation=DTMLFile('dtml/tutorialNav', globals())


class GlossaryTopic(TutorialTopic):
    """
    A Tutorial Glossary Help Topic
    """

    def __init__(self, id, title, text):
        self.id=id
        self.title=title
        self.obj=HTML(text)

    index_html=DTMLFile('dtml/glossaryView', globals())

    def formatted_content(self, REQUEST):
        """
        Custom stx formatting for tutorial topics
        """
        text=self.obj(self, REQUEST)
        text=str(StructuredText.HTML(text))
        pre_pat.sub(clean_pre, text)
        return text

    def apiLink(self, klass, REQUEST):
        """
        Returns the URL to a API documentation for a given class.
        """
        names=klass.split('.')
        url="%s/Control_Panel/Products/%s/Help/%s.py#%s" % (REQUEST['SCRIPT_NAME'],
                names[0], names[1], names[2])
        return '<a href="%s">API Documentation</a>' % url

    def dtmlLink(self, tag, REQUEST):
        """
        Returns the URL to a DTML Reference page for a given tag.
        """
        url="%s/Control_Panel/Products/OFSP/Help/dtml-%s.stx" % (REQUEST['SCRIPT_NAME'], tag)
        return '<a href="%s">DTML Reference</a>' % url


addTutorialForm=DTMLFile('dtml/tutorialAdd', globals())

def addTutorial(self, id, REQUEST=None, RESPONSE=None):
    """
    Install tutorial examples.
    """
    id=str(id)
    ob=OFS.Folder.Folder()
    ob.id=id
    ob.title='Zope Tutorial Examples'
    id=self._setObject(id, ob)
    folder=getattr(self, id)

    # make sure that Gadfly is initialized
    try:
        from Products.ZGadflyDA.DA import data_sources
        data_sources()
    except:
        raise 'Bad Request', 'The ZGadflyDA product must be installed!'

    # work around old Zope bug in importing
    try:
        folder.manage_importObject(tutorialExamplesFile)
    except:
        folder._p_jar=self.Destination()._p_jar
        folder.manage_importObject(tutorialExamplesFile)

    # acquire REQUEST if necessary
    if REQUEST is None:
        REQUEST=self.REQUEST

    # Set local roles on examples
    changeOwner(folder, REQUEST['AUTHENTICATED_USER'])

    # Run lesson setup methods -- call Setup.setup methods in lesson folders
    examples=folder.examples
    for lesson in examples.objectValues():
        if hasattr(lesson, 'Setup'):
            lesson.Setup.setup(lesson.Setup, REQUEST)

    if RESPONSE is not None:
        e=(DateTime.DateTime('GMT') + 365).rfc822()
        RESPONSE.setCookie('tutorialExamplesURL', folder.absolute_url() + '/examples',
                path='/',
                expires=e)
        RESPONSE.redirect(folder.absolute_url() + '/examples')


def changeOwner(obj, owner):
    """
    Recursively changes the Owner of an object and all its subobjects.
    """
    for user, roles in obj.get_local_roles():
        if 'Owner' in roles:
            obj.manage_delLocalRoles([user])
            break
    obj.manage_setLocalRoles(owner.getId(), ['Owner'])
    for subobj in obj.objectValues():
        changeOwner(subobj, owner)

def clean_pre(match):
    """
    Reformat a pre tag to get rid of extra indentation
    and extra blank lines.
    """
    lines=match.group(1).split('\n')
    nlines=[]

    min_indent=None
    for line in lines:
        indent=len(line) - len(line.lstrip())
        if min_indent is None or indent < min_indent:
            if line.strip():
                min_indent=indent
    for line in lines:
        nlines.append(line[min_indent:])

    while 1:
        if not nlines[0].strip():
            nlines.pop(0)
        else:
            break

    while 1:
        if not nlines[-1].strip():
            nlines.pop()
        else:
            break

    return "<PRE>%s</PRE>" % '\n'.join(nlines)
www.java2java.com | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.