def test_in_a_recipe():
    from tiddlyweb.config import config
    store = get_store(config)
    bag = Bag('hi')
    store.put(bag)
    tiddler = Tiddler('thing1', 'hi')
    tiddler.tags = ['research']
    store.put(tiddler)
    tiddler = Tiddler('thing2', 'hi')
    store.put(tiddler)

    recipe1 = Recipe('oi')
    recipe1.set_recipe([('hi', 'mselect=tag:research')])
    recipe1.store = store
    recipe2 = Recipe('coi')
    recipe2.set_recipe([('hi', 'select=tag:research')])
    recipe2.store = store
    recipe3 = Recipe('boi')
    recipe3.set_recipe([('hi', '')])
    recipe3.store = store
    environ = {'tiddlyweb.store': store}
    tiddlers = list(control.get_tiddlers_from_recipe(recipe1, environ))
    assert len(tiddlers) == 1
    tiddlers = list(control.get_tiddlers_from_recipe(recipe2, environ))
    assert len(tiddlers) == 1
    tiddlers = list(control.get_tiddlers_from_recipe(recipe3, environ))
    assert len(tiddlers) == 2
예제 #2
0
def safe_mode(environ, start_response):
    """
    Serve up a space in safe mode. Safe mode means that
    non-required plugins are turned off and plugins that
    duplicate those in the core bags (system and tiddlyspace)
    are deleted from the store of the space in question.
    """

    http_host, _ = determine_host(environ)
    space_name = determine_space(environ, http_host)
    recipe_name = determine_space_recipe(environ, space_name)
    if recipe_name != '%s_private' % space_name:
        raise HTTP403('membership required for safe mode')

    if environ['REQUEST_METHOD'] == 'GET':
        return _send_safe_mode(environ, start_response)

    store = environ['tiddlyweb.store']

    # Get the list of core plugins
    core_plugin_tiddler_titles = _get_core_plugins(store)

    # Delete those plugins in the space's recipes which
    # duplicate the core plugins
    recipe = _delete_duplicates(environ, core_plugin_tiddler_titles,
            recipe_name, space_name)

    # Process the recipe. For those tiddlers which do not have a bag
    # in CORE_RECIPE, remove the systemConfig tag.
    try:
        candidate_tiddlers = control.get_tiddlers_from_recipe(recipe, environ)
    except NoBagError, exc:
        raise HTTP404('recipe %s lists an unknown bag: %s' %
                (recipe.name, exc))
예제 #3
0
 def generate_html(self, plugin_name, plugins, base_tiddlers):
     """
     recurse through the template stack and generate the HTML on the way back out.
     """
     plugin_html = {}
     if isinstance(plugins, dict):
         for template in plugins:
             recipe_data = plugins[template].split('?', 1)
             recipe = _get_recipe(self.environ, recipe_data[0])
             plugin_tiddlers = control.get_tiddlers_from_recipe(recipe, self.environ)
             if len(recipe_data) == 2:
                 filters = parse_for_filters(recipe_data[1])[0]
                 plugin_tiddlers = recursive_filter(filters, plugin_tiddlers)
             try:
                 plugin_plugins = self.environ['tiddlyweb.config']['tw_pages_serializers'][template]['plugins']
                 plugin_html[template] = self.generate_html(template, plugin_plugins, plugin_tiddlers)
             except KeyError:
                 #there is no plugin by that name, so try a (non TiddlyWebPages) serializer instead
                 plugin_html[template] = self.pass_through_external_serializer(template, plugin_tiddlers)
     server_prefix = self.get_server_prefix()
     try:
         self.template.set_template(plugin_name)
         content = self.template.render(tiddlers=base_tiddlers, extra=plugin_html, prefix=server_prefix, query=self.query, root_vars=self.environ['tiddlyweb.recipe_template'])
     except KeyError:
         content = self.pass_through_external_serializer(plugin_name, base_tiddlers)
     return content
예제 #4
0
def test_get_tiddlers():
    """
    Get all the tiddlers produced by this recipe.
    """

    tiddlers = control.get_tiddlers_from_recipe(recipe)
    assert len(tiddlers) == 3, 'tiddler list should be length 3, is %s' % len(tiddlers)
예제 #5
0
 def tiddler_as(self, tiddler):
     logging.debug("###################################\nDOING TIDDLER_AS\n\n\n###################################")
     """
     Take the single tiddler provided and inject it into
     a TiddlyWiki.
     """
     environ = self.environ
     store = self.environ["tiddlyweb.store"]
     try:
       recipe_name =tiddler.recipe
       tiddler_as_name = tiddler.title
       resource = Recipe(recipe_name)
       resource= store.get(resource)
       tiddlers = control.get_tiddlers_from_recipe(resource)
       bag =Bag("tmp",tmpbag=True)
       logging.debug("have tiddlers %s"%tiddlers)
       for a_tiddler in tiddlers:
         a_tiddler.recipe = recipe_name
         a_tiddler = store.get(a_tiddler)
         if a_tiddler.title == "DefaultTiddlers":
           a_tiddler.text = "[[%s]]"%tiddler_as_name
           logging.debug("tiddler_as overriding DefaultTiddlers")
         bag.add_tiddler(a_tiddler)
         
     except AttributeError:
       resource = Bag(tiddler.bag)
       bag = store.get(resource)
       
     self._prepare_twp(bag)
     
     return self.build_non_js_version(bag,default=[tiddler])
예제 #6
0
def tiddler(context, *args):
    base = context.var_get_text("$BASE_URL")
    path =""
    if not context.environ:
      return ""
    
    store = get_store(config)
    logging.debug("in tiddler macro")
    try:
        environ = context.environ
    except NoAttributeError:
        return _throw_error()
    try:
        tid = context.tiddler
    except NoAttributeError:
        return ""
    if tid.recipe:
        tids = control.get_tiddlers_from_recipe(store.get(Recipe(tid.recipe)))
    elif tid.bag:
        bag = store.get(Bag(tid.bag))
        tids = bag.list_tiddlers()
    else:
        return ""
    try:
        tiddler_requested = args[0].text
        for tiddler in tids:
            if tiddler.title == tiddler_requested:
                tiddler = store.get(tiddler)
    except Exception:
        tiddler = context.tiddler
    if tiddler:
        text = wikitext_to_wikklyhtml(base,path, tiddler.text, environ,tiddler=context.tiddler)
        return "%s"%text
    else:
        return ""#no tiddler with that name
예제 #7
0
파일: recipe.py 프로젝트: 24king/tiddlyweb
def get_tiddlers(environ, start_response):
    """
    Handle ``GET`` on a tiddlers-within-a-recipe URI.

    Get a list representation of the :py:class:`tiddlers
    <tiddlyweb.model.tiddler.Tiddler>` generated from a :py:class:`recipe
    <tiddlyweb.model.recipe.Recipe>`.

    The information sent is dependent on the serialization chosen
    via :py:mod:`tiddlyweb.web.negotiate`.
    """
    usersign = environ['tiddlyweb.usersign']
    store = environ['tiddlyweb.store']
    filters = environ['tiddlyweb.filters']
    recipe = _determine_recipe(environ)
    title = 'Tiddlers From Recipe %s' % recipe.name
    title = environ['tiddlyweb.query'].get('title', [title])[0]

    # check the recipe can be read
    recipe.policy.allows(usersign, 'read')

    # check the bags in the recipe can be read
    try:
        template = control.recipe_template(environ)
        for bag_name, _ in recipe.get_recipe(template):
            bag = Bag(bag_name)
            bag = store.get(bag)
            bag.policy.allows(usersign, 'read')
    except NoBagError as exc:
        raise HTTP404('recipe %s lists an unknown bag: %s' %
                (recipe.name, exc))

    # from this point forward we know the tiddlers are
    # readable

    # get the tiddlers from the recipe and uniquify them
    try:
        candidate_tiddlers = control.get_tiddlers_from_recipe(recipe, environ)
    except NoBagError as exc:
        raise HTTP404('recipe %s lists an unknown bag: %s' %
                (recipe.name, exc))
    except FilterError as exc:
        raise HTTP400('malformed filter: %s' % exc)

    tiddlers = Tiddlers(title=title)
    if not filters:
        tiddlers.store = store
    tiddlers.recipe = recipe.name

    for tiddler in candidate_tiddlers:
        tiddler.recipe = recipe.name
        tiddlers.add(tiddler)

    tiddlers.link = '%s/tiddlers' % web.recipe_url(environ, recipe,
            full=False)

    return send_tiddlers(environ, start_response, tiddlers=tiddlers)
예제 #8
0
def get_tiddlers(environ, start_response):
    """
    Handle ``GET`` on a tiddlers-within-a-recipe URI.

    Get a list representation of the :py:class:`tiddlers
    <tiddlyweb.model.tiddler.Tiddler>` generated from a :py:class:`recipe
    <tiddlyweb.model.recipe.Recipe>`.

    The information sent is dependent on the serialization chosen
    via :py:mod:`tiddlyweb.web.negotiate`.
    """
    usersign = environ['tiddlyweb.usersign']
    store = environ['tiddlyweb.store']
    filters = environ['tiddlyweb.filters']
    recipe = _determine_recipe(environ)
    title = 'Tiddlers From Recipe %s' % recipe.name
    title = environ['tiddlyweb.query'].get('title', [title])[0]

    # check the recipe can be read
    recipe.policy.allows(usersign, 'read')

    # check the bags in the recipe can be read
    try:
        template = control.recipe_template(environ)
        for bag_name, _ in recipe.get_recipe(template):
            bag = Bag(bag_name)
            bag = store.get(bag)
            bag.policy.allows(usersign, 'read')
    except NoBagError as exc:
        raise HTTP404('recipe %s lists an unknown bag: %s' %
                      (recipe.name, exc))

    # from this point forward we know the tiddlers are
    # readable

    # get the tiddlers from the recipe and uniquify them
    try:
        candidate_tiddlers = control.get_tiddlers_from_recipe(recipe, environ)
    except NoBagError as exc:
        raise HTTP404('recipe %s lists an unknown bag: %s' %
                      (recipe.name, exc))
    except FilterError as exc:
        raise HTTP400('malformed filter: %s' % exc)

    tiddlers = Tiddlers(title=title)
    if not filters:
        tiddlers.store = store
    tiddlers.recipe = recipe.name

    for tiddler in candidate_tiddlers:
        tiddler.recipe = recipe.name
        tiddlers.add(tiddler)

    tiddlers.link = '%s/tiddlers' % web.recipe_url(environ, recipe, full=False)

    return send_tiddlers(environ, start_response, tiddlers=tiddlers)
def test_get_remote_weird():
    recipe = Recipe('stuff')
    recipe.set_recipe([(REMOTE_HTML, '')])
    store.put(recipe)

    tiddlers = control.get_tiddlers_from_recipe(recipe, environ)
    assert len(tiddlers) == 1
    assert tiddlers[0].title == 'The Computer as Tool: From Interaction To Augmentation'
    tiddler = store.get(tiddlers[0])
    assert 'Humans are likely to grant intention to someone or something that performs actions in a way that is difficult to understand.' in tiddler.text
def test_get_recipe_filters():
    recipe = Recipe('thing')
    recipe.set_recipe([(REMOTE_BAG, 'select=tag:alpha')])
    store.put(recipe)

    tiddlers = control.get_tiddlers_from_recipe(recipe, environ)
    assert len(tiddlers) == 1
    assert tiddlers[0].title == 'alpha'

    assert tiddlers[0].bag == REMOTE_BAG
    assert tiddlers[0].text == 'alpha'
예제 #11
0
def test_in_a_recipe():
    bag = Bag('hi')
    store.put(bag)
    tiddler = Tiddler('thing1', 'hi')
    tiddler.tags = ['research']
    store.put(tiddler)
    tiddler = Tiddler('thing2', 'hi')
    store.put(tiddler)

    recipe1 = Recipe('oi')
    recipe1.set_recipe([('hi', 'select=tag:research')])
    recipe1.store = store
    recipe2 = Recipe('boi')
    recipe2.set_recipe([('hi', '')])
    recipe2.store = store
    environ = {'tiddlyweb.store': store}
    tiddlers = list(control.get_tiddlers_from_recipe(recipe1, environ))
    assert len(tiddlers) == 1
    tiddlers = list(control.get_tiddlers_from_recipe(recipe2, environ))
    assert len(tiddlers) == 2
예제 #12
0
    def get_tiddlers_bag_for_recipe(self,recipe_name):
        store = self.environ['tiddlyweb.store'] 
        recipe = store.get(Recipe(recipe_name))
        list_tiddlers = control.get_tiddlers_from_recipe(recipe)
    
        tiddlers = []

        tempbag = Bag("tempbag",tmpbag=True)
    
        tempbag.add_tiddlers(list_tiddlers)
        return tempbag
def test_get_recipe():
    recipe = Recipe('thing')
    recipe.set_recipe([(REMOTE_BAG, '')])
    store.put(recipe)

    tiddlers = control.get_tiddlers_from_recipe(recipe, environ)
    titles = [tiddler.title for tiddler in tiddlers]
    for title in ['alpha', 'beta', 'gamma']:
        assert title in titles

    assert tiddlers[0].bag == REMOTE_BAG
    assert tiddlers[0]._text == None
예제 #14
0
def test_get_tiddlers_limited():
    """
    Using a different recipe get different tiddlers.
    """

    short_recipe = Recipe(name='foobar')
    short_recipe.set_recipe([
        [bagone, ''],
        [bagfour, 'select=tag:tagone']
        ])
    tiddlers = control.get_tiddlers_from_recipe(short_recipe)
    assert len(tiddlers) == 2, 'tiddler list should be length 2, is %s' % len(tiddlers)
예제 #15
0
def test_bag_object_in_recipe():
    bag = Bag('fwoop')
    store.put(bag)
    tiddler = Tiddler('swell', 'fwoop')
    tiddler.text = 'hi'
    store.put(tiddler)

    recipe = Recipe('heyo')
    recipe.set_recipe([(bag, '')])
    recipe.store = store
    tiddlers = list(get_tiddlers_from_recipe(recipe, environ))
    assert len(tiddlers) == 1
    assert tiddlers[0].title == 'swell'
    assert tiddlers[0].bag == 'fwoop'
예제 #16
0
def user_page(environ, start_response): 
    print(environ)
    name = environ['wsgiorg.routing_args'][1].get('name', 'default')
    recipe = Recipe('tmp')
    recipe.set_recipe([
        [name, '']
   	     ]) 
    # establish the store on the recipe so that get_tiddlers_from_recipe
    # will load the bags and their tiddler lists from the store
    recipe.store = environ['tiddlyweb.store']
    tiddlers = control.get_tiddlers_from_recipe(recipe, environ)
    bag = Bag('tmp', tmpbag=True)
    bag.add_tiddlers(tiddlers)
    return send_tiddlers(environ, start_response, bag)
예제 #17
0
def test_bag_object_in_recipe():
    bag = Bag('fwoop')
    store.put(bag)
    tiddler = Tiddler('swell', 'fwoop')
    tiddler.text = 'hi'
    store.put(tiddler)

    recipe = Recipe('heyo')
    recipe.set_recipe([(bag, '')])
    recipe.store = store
    tiddlers = list(get_tiddlers_from_recipe(recipe, environ))
    assert len(tiddlers) == 1
    assert tiddlers[0].title == 'swell'
    assert tiddlers[0].bag == 'fwoop'
예제 #18
0
def recent(environ, start_response):
    bag_name = environ['tiddlyweb.query'].get('bag', [None])[0]
    recipe_name = environ['tiddlyweb.query'].get('recipe', [None])[0]
    since = environ['tiddlyweb.query'].get('since', [None])[0]

    store = environ['tiddlyweb.store']
    tiddlers = []
    title_string = "nothing"
    if recipe_name:
        recipe = Recipe(recipe_name)
        recipe = store.get(recipe)
        tiddlers = control.get_tiddlers_from_recipe(recipe, environ)
        title_string = 'recipe %s' % recipe_name
    if bag_name:
        bag = store.get(Bag(bag_name))
        tiddlers = bag.list_tiddlers()
        title_string = 'bag %s' % bag_name
    matching_tiddlers = []
    if since:
        modified_string = since
    else:
        time_object = datetime.utcnow() - timedelta(30)
        modified_string = unicode(time_object.strftime('%Y%m%d%H%M%S'))

    def reify_revision(tiddler, revision_id):
        revision = Tiddler(tiddler.title, tiddler.bag)
        revision.revision = revision_id
        return store.get(revision)

    selector = select_parse('modified:>%s' % modified_string)
    tiddlers = [store.get(tiddler) for tiddler in tiddlers]
    tiddlers = selector(tiddlers)
    for tiddler in tiddlers:
        revisions = [
            reify_revision(tiddler, id)
            for id in store.list_tiddler_revisions(tiddler)
        ]
        matching_tiddlers.extend(selector(revisions))

    tiddlers = sort_by_attribute('modified', matching_tiddlers, reverse=True)

    environ['tiddlyweb.title'] = 'Recent changes for %s' % title_string

    return [
        '%s:%s:%s:%s<br/>' %
        (tiddler.title, tiddler.revision, tiddler.modified, tiddler.modifier)
        for tiddler in tiddlers
    ]
예제 #19
0
def dyna(environ, start_response):
    name = environ['wsgiorg.routing_args'][1].get('name', 'default')
    username = environ['tiddlyweb.usersign']['name']
    recipe = Recipe('tmp')
    recipe.set_recipe([
        [BASE_BAG_NAME, ''],
        [name, ''],
        [username, '']
        ])
    # establish the store on the recipe so that get_tiddlers_from_recipe
    # will load the bags and their tiddler lists from the store
    recipe.store = environ['tiddlyweb.store']
    tiddlers = control.get_tiddlers_from_recipe(recipe, environ)
    bag = Bag('tmp', tmpbag=True)
    bag.add_tiddlers(tiddlers)
    return send_tiddlers(environ, start_response, bag)
예제 #20
0
def get_tiddlers(environ, start_response):
    """
    Get the list of tiddlers produced by this
    recipe.
    """
    usersign = environ["tiddlyweb.usersign"]
    store = environ["tiddlyweb.store"]
    recipe = _determine_recipe(environ)

    recipe.policy.allows(usersign, "read")

    # get the tiddlers from the recipe and uniquify them
    try:
        tiddlers = control.get_tiddlers_from_recipe(recipe, environ)
    except NoBagError, exc:
        raise HTTP404("recipe %s lists an unknown bag: %s" % (recipe.name, exc))
예제 #21
0
def test_recipes():
    store.put(Bag('alpha'))
    store.put(Bag('beta'))

    tiddler = Tiddler('steak', 'alpha')
    tiddler.text = 'rare'
    store.put(tiddler)
    tiddler = Tiddler('liver', 'beta')
    tiddler.text = 'icky'
    store.put(tiddler)
    tiddler = Tiddler('steak', 'beta')
    tiddler.text = 'medium'
    store.put(tiddler)

    recipec = Recipe('cow')
    recipec.desc = 'a meaty melange'
    recipec.policy.accept.append('cdent')
    recipec.set_recipe([
        ('alpha', 'select=tag:systemConfig'),
        ('beta', '')])

    store.put(recipec)

    recipes = list(store.list_recipes())
    assert len(recipes) == 1
    reciped = store.get(recipes[0])

    assert reciped.name == recipec.name
    assert reciped.desc == recipec.desc
    recipe_list = reciped.get_recipe()

    assert recipe_list[0] == ['alpha', 'select=tag:systemConfig']
    assert recipe_list[1] == ['beta', '']

    tiddlers = list(get_tiddlers_from_recipe(reciped, environ=environ))

    assert len(tiddlers) == 2
    for tiddler in tiddlers:
        assert tiddler.bag == 'beta'
        if tiddler.title == 'alpha':
            tiddler = store.get(tiddler)
            assert tiddler.text == 'medium'

    store.delete(reciped)

    recipes = list(store.list_recipes())
    assert len(recipes) == 0
예제 #22
0
def test_recipe_with_special():
    recipe = Recipe('special')
    recipe.set_recipe([('normal', ''), ('Xnine', '')])
    recipe.store = store

    tiddlers = list(get_tiddlers_from_recipe(recipe, environ))

    assert len(tiddlers) == 4
    assert 'thing' in [tiddler.title for tiddler in tiddlers]
    assert 'alpha' in [tiddler.title for tiddler in tiddlers]
    assert 'beta' in [tiddler.title for tiddler in tiddlers]
    assert 'gamma' in [tiddler.title for tiddler in tiddlers]

    # roundtrip the recipes with a special
    store.put(recipe)
    recipe2 = store.get(Recipe('special'))

    assert recipe.get_recipe() == recipe2.get_recipe()
예제 #23
0
def recent(environ, start_response):
    bag_name = environ['tiddlyweb.query'].get('bag', [None])[0]
    recipe_name = environ['tiddlyweb.query'].get('recipe', [None])[0]
    since = environ['tiddlyweb.query'].get('since', [None])[0]

    store = environ['tiddlyweb.store']
    tiddlers = []
    title_string = "nothing"
    if recipe_name:
        recipe = Recipe(recipe_name)
        recipe = store.get(recipe)
        tiddlers = control.get_tiddlers_from_recipe(recipe, environ)
        title_string = 'recipe %s' % recipe_name
    if bag_name:
        bag = store.get(Bag(bag_name))
        tiddlers = bag.list_tiddlers()
        title_string = 'bag %s' % bag_name
    matching_tiddlers = []
    if since:
        modified_string = since
    else:
        time_object = datetime.utcnow() - timedelta(30)
        modified_string = unicode(time_object.strftime('%Y%m%d%H%M%S'))

    def reify_revision(tiddler, revision_id):
        revision = Tiddler(tiddler.title, tiddler.bag)
        revision.revision = revision_id
        return store.get(revision)

    selector = select_parse('modified:>%s' % modified_string)
    tiddlers = [store.get(tiddler) for tiddler in tiddlers]
    tiddlers = selector(tiddlers)
    for tiddler in tiddlers:
        revisions = [reify_revision(tiddler, id) for id
                in store.list_tiddler_revisions(tiddler)]
        matching_tiddlers.extend(selector(revisions))

    tiddlers = sort_by_attribute('modified', matching_tiddlers, reverse=True)

    environ['tiddlyweb.title'] = 'Recent changes for %s' % title_string

    return ['%s:%s:%s:%s<br/>' %
            (tiddler.title, tiddler.revision, tiddler.modified, tiddler.modifier)
            for tiddler in tiddlers]
예제 #24
0
def get_tiddlers(environ, start_response):
    """
    Get the list of tiddlers produced by this
    recipe.
    """
    filter_string = web.filter_query_string(environ)
    usersign = environ['tiddlyweb.usersign']
    store = environ['tiddlyweb.store']
    recipe = _determine_recipe(environ)

    recipe.policy.allows(usersign, 'read')

    # get the tiddlers from the recipe and uniquify them
    try:
        tiddlers = control.get_tiddlers_from_recipe(recipe, environ)
        tmp_bag = Bag('tmp_bag1', tmpbag=True)
        tmp_bag.add_tiddlers(tiddlers)
    except NoBagError, exc:
        raise HTTP404('recipe %s lists an unknown bag: %s' % (recipe.name, exc))
예제 #25
0
def test_recipe_with_special():
    recipe = Recipe('special')
    recipe.set_recipe([
        ('normal', ''),
        ('Xnine', '')])
    recipe.store = store

    tiddlers = list(get_tiddlers_from_recipe(recipe, environ))

    assert len(tiddlers) == 4
    assert 'thing' in [tiddler.title for tiddler in tiddlers]
    assert 'alpha' in [tiddler.title for tiddler in tiddlers]
    assert 'beta' in [tiddler.title for tiddler in tiddlers]
    assert 'gamma' in [tiddler.title for tiddler in tiddlers]

    # roundtrip the recipes with a special
    store.put(recipe)
    recipe2 = store.get(Recipe('special'))

    assert recipe.get_recipe() == recipe2.get_recipe()
예제 #26
0
def recent_changes(tiddler, environ):
    """
    Display recent changes for the wiki. RecentChanges is handled
    as a SPECIAL_PAGES, described below.

    Recent changes are simply the 30 most recently modified tiddlers
    from the recipe. We make a list of those tiddlers and provide
    them to the changes.html template.
    """
    # XXX to be strict we should do permissions checking
    # on the bags of all the tiddlers returned.
    store = environ["tiddlyweb.store"]
    recipe = _get_recipe(environ)
    recipe = store.get(Recipe(recipe))
    tiddlers = Tiddlers()
    for tiddler in control.get_tiddlers_from_recipe(recipe, environ):
        tiddlers.add(tiddler)
    tiddlers = control.filter_tiddlers(tiddlers, "sort=-modified;limit=30")
    template = get_template(environ, "changes.html")
    environ["tiddlyweb.title"] = "Recent Changes"
    return template.generate(tiddlers=(store.get(tiddler) for tiddler in tiddlers))
예제 #27
0
	def _no_script(self, url):
		"""
		returns static HTML representation of a list of tiddlers
		"""
		try:
			static_index = self.environ["tiddlyweb.config"]["static_index"]
		except KeyError: # default
			static_index = default_static_index

		store = self.environ["tiddlyweb.store"]
		routing_args = self.environ["wsgiorg.routing_args"][1]

		try: # recipe
			recipe = routing_args["recipe_name"]
			recipe = Recipe(recipe)
			recipe = store.get(recipe)
			tiddlers = control.get_tiddlers_from_recipe(recipe, self.environ)
		except KeyError: # bag
			bag = routing_args["bag_name"]
			bag = Bag(bag)
			bag = store.get(bag)
			tiddlers = control.get_tiddlers_from_bag(bag)
		tiddlers = dict([(tiddler.title, tiddler) for tiddler in tiddlers])

		static_tiddlers = []
		try:
			index_tiddler = tiddlers[static_index]
			for title in _read_bracketed_list(index_tiddler.text):
				tiddler = tiddlers.get(title)
				try:
					text = render_wikitext(tiddler, self.environ)
					static_tiddlers.append(tiddler_template %
						(tiddler.title, text))
				except AttributeError: # tiddler does not exist
					pass
		except KeyError: # static_index tiddler does not exist
			pass

		intro = super(Serialization, self)._no_script(url)
		return "%s\n%s" % (intro, "\n".join(static_tiddlers))
예제 #28
0
def tiddler(context, *args):
    base = context.var_get_text("$BASE_URL")
    path = ""
    if not context.environ:
        return ""

    store = get_store(config)
    logging.debug("in tiddler macro")
    try:
        environ = context.environ
    except NoAttributeError:
        return _throw_error()
    try:
        tid = context.tiddler
    except NoAttributeError:
        return ""
    if tid.recipe:
        tids = control.get_tiddlers_from_recipe(store.get(Recipe(tid.recipe)))
    elif tid.bag:
        bag = store.get(Bag(tid.bag))
        tids = bag.list_tiddlers()
    else:
        return ""
    try:
        tiddler_requested = args[0].text
        for tiddler in tids:
            if tiddler.title == tiddler_requested:
                tiddler = store.get(tiddler)
    except Exception:
        tiddler = context.tiddler
    if tiddler:
        text = wikitext_to_wikklyhtml(base,
                                      path,
                                      tiddler.text,
                                      environ,
                                      tiddler=context.tiddler)
        return "%s" % text
    else:
        return ""  #no tiddler with that name
예제 #29
0
def tiddlers(context, *args):
    base = context.var_get_text("$BASE_URL")
    path = ""

    if not context.environ:
        return ""
    else:
        environ = context.environ

    store = get_store(config)

    tid = context.tiddler
    if tid.recipe:
        tids = control.get_tiddlers_from_recipe(store.get(Recipe(tid.recipe)))
    elif tid.bag:
        bag = store.get(Bag(tid.bag))
        tids = list(bag.list_tiddlers())
    else:
        return u""

    tiddlerTemplate = args[0].text
    templateText = ""
    for tid in tids:
        tid = store.get(tid)
        if tid.title == tiddlerTemplate:
            templateText = tid.text
    p = parseParams(args)
    if "filter" in p:
        filterBag = Bag("filter", tmpbag=True)
        filterBag.add_tiddlers(tids)
        filtered_tiddlers = filter_tiddlers(filterBag, p["filter"])
        output = u""
        for filtered_tiddler in filtered_tiddlers:
            output += u"%s" % wikitext_to_wikklyhtml(
                base, path, templateText, environ, tiddler=filtered_tiddler)
        return "<html>%s</html>" % output
    else:
        return u""
 def generate_html(self, plugin_name, plugins, base_tiddlers):
     """
     recurse through the template stack and generate the HTML on the way back out.
     """
     plugin_html = {}
     if isinstance(plugins, dict):
         for template in plugins:
             recipe_data = plugins[template].split('?', 1)
             recipe = _get_recipe(self.environ, recipe_data[0])
             plugin_tiddlers = control.get_tiddlers_from_recipe(
                 recipe, self.environ)
             if len(recipe_data) == 2:
                 filters = parse_for_filters(recipe_data[1])[0]
                 plugin_tiddlers = recursive_filter(filters,
                                                    plugin_tiddlers)
             try:
                 plugin_plugins = self.environ['tiddlyweb.config'][
                     'tw_pages_serializers'][template]['plugins']
                 plugin_html[template] = self.generate_html(
                     template, plugin_plugins, plugin_tiddlers)
             except KeyError:
                 #there is no plugin by that name, so try a (non TiddlyWebPages) serializer instead
                 plugin_html[
                     template] = self.pass_through_external_serializer(
                         template, plugin_tiddlers)
     server_prefix = self.get_server_prefix()
     try:
         self.template.set_template(plugin_name)
         content = self.template.render(
             tiddlers=base_tiddlers,
             extra=plugin_html,
             prefix=server_prefix,
             query=self.query,
             root_vars=self.environ['tiddlyweb.recipe_template'])
     except KeyError:
         content = self.pass_through_external_serializer(
             plugin_name, base_tiddlers)
     return content
예제 #31
0
def tiddlers(context, *args):
    base = context.var_get_text("$BASE_URL")
    path = ""
    
    if not context.environ:
        return ""
    else:
      environ = context.environ
    
    store = get_store(config)
    
    tid = context.tiddler
    if tid.recipe:
        tids = control.get_tiddlers_from_recipe(store.get(Recipe(tid.recipe)))
    elif tid.bag:
        bag = store.get(Bag(tid.bag))
        tids = list(bag.list_tiddlers())
    else:
        return u""
    
    tiddlerTemplate = args[0].text
    templateText = ""  
    for tid in tids:
        tid = store.get(tid)
        if tid.title == tiddlerTemplate:
            templateText = tid.text
    p = parseParams(args)
    if "filter" in p:
        filterBag = Bag("filter",tmpbag=True)
        filterBag.add_tiddlers(tids)
        filtered_tiddlers = filter_tiddlers(filterBag,p["filter"])
        output = u""
        for filtered_tiddler in filtered_tiddlers:
            output += u"%s"%wikitext_to_wikklyhtml(base,path, templateText, environ,tiddler=filtered_tiddler)
        return "<html>%s</html>"%output
    else:
        return u""
예제 #32
0
def form(environ, start_response):
    """
    Produce this named form to the web.
    """
    store = environ['tiddlyweb.store']
    bag_id = environ['wsgiorg.routing_args'][1]['formid']
    recipe_id, uuid = bag_id.rsplit('.', 1)
    logging.debug('getting form with bag %s using recipe %s' % (bag_id, recipe_id))

    bag = store.get(Bag(bag_id))
    _process_config_tiddler(store, bag)
    recipe = store.get(Recipe(recipe_id))
    base_tiddlers = control.get_tiddlers_from_recipe(recipe)
    # read the bag (again) to make sure we have all the tiddlers
    bag = store.get(bag)
    data_tiddlers = bag.list_tiddlers()
    tiddlers = base_tiddlers + data_tiddlers
    tmp_bag = Bag('tmp', tmpbag=True)
    for tiddler in tiddlers:
        store.get(tiddler)
        tmp_bag.add_tiddler(tiddler)
    logging.debug(['%s:%s' % (tiddler.bag, tiddler.title) for tiddler in tmp_bag.list_tiddlers()])
    environ['tiddlyweb.type'] = 'text/x-tiddlywiki'
    return send_tiddlers(environ, start_response, tmp_bag)
예제 #33
0
def get_recipe_contents(recipe_name, store, env):
    recipe = Recipe(recipe_name)
    recipe = store.get(recipe)
    tiddlers = populate_tiddlers(control.get_tiddlers_from_recipe(recipe, env), store)
    return sort_tiddlers(tiddlers)
예제 #34
0
    try:
        template = control.recipe_template(environ)
        for bag_name, _ in recipe.get_recipe(template):
            bag = Bag(bag_name)
            bag = store.get(bag)
            bag.policy.allows(usersign, 'read')
    except NoBagError, exc:
        raise HTTP404('recipe %s lists an unknown bag: %s' %
                (recipe.name, exc))

    # from this point forward we know the tiddlers are
    # readable

    # get the tiddlers from the recipe and uniquify them
    try:
        candidate_tiddlers = control.get_tiddlers_from_recipe(recipe, environ)
    except NoBagError, exc:
        raise HTTP404('recipe %s lists an unknown bag: %s' %
                (recipe.name, exc))

    tiddlers = Tiddlers(title=title, store=store)

    for tiddler in candidate_tiddlers:
        tiddler.recipe = recipe.name
        tiddlers.add(tiddler)

    return send_tiddlers(environ, start_response, tiddlers=tiddlers)


def list_recipes(environ, start_response):
    """
    def add_magic_tiddler(bag, title, text):
        tiddler = Tiddler(title, 'tmp')
        tiddler.text = text
        tiddler.tags = ['excludeLists']
        bag.add_tiddler(tiddler)

    add_magic_tiddler(output_bag, 'MainMenu', '[[Back to TiddlyWeb|%s]]' % tiddler_url(environ, tiddler))
    add_magic_tiddler(output_bag, 'DefaultTiddlers', '[[%s]]' % tiddler_name)
    add_magic_tiddler(output_bag, 'SiteTitle', 'Editor for %s' % tiddler_name)
    add_magic_tiddler(output_bag, 'SiteSubtitle', '')
    add_magic_tiddler(output_bag, 'SideBarOptions', '')

    try:
      rule =environ['tiddlyweb.config']['tiddlyeditor_recipe']
      recipe = create_dynamic_recipe(environ,rule)
      tiddlers = control.get_tiddlers_from_recipe(recipe)
      for tid in tiddlers:
        output_bag.add_tiddler(tid)
    except KeyError:
      for required_tiddler in environ['tiddlyweb.config'].get('tiddlyeditor_tiddlers', []):
          r_tiddler = Tiddler(required_tiddler[1], required_tiddler[0])
          r_tiddler = store.get(r_tiddler)
          if 'excludeLists' not in r_tiddler.tags:
              r_tiddler.tags.append('excludeLists')
          output_bag.add_tiddler(r_tiddler)
            
    environ['tiddlyweb.type'] = 'text/x-tiddlywiki'
    return send_tiddlers(environ, start_response, output_bag)


original_footer_extra = HTMLPresenter.footer_extra
예제 #36
0
    try:
        template = control.recipe_template(environ)
        for bag_name, _ in recipe.get_recipe(template):
            bag = Bag(bag_name)
            bag = store.get(bag)
            bag.policy.allows(usersign, 'read')
    except NoBagError, exc:
        raise HTTP404('recipe %s lists an unknown bag: %s' %
                      (recipe.name, exc))

    # from this point forward we know the tiddlers are
    # readable

    # get the tiddlers from the recipe and uniquify them
    try:
        candidate_tiddlers = control.get_tiddlers_from_recipe(recipe, environ)
    except NoBagError, exc:
        raise HTTP404('recipe %s lists an unknown bag: %s' %
                      (recipe.name, exc))
    except FilterError, exc:
        raise HTTP400('malformed filter: %s' % exc)

    if filters:
        tiddlers = Tiddlers(title=title)
    else:
        tiddlers = Tiddlers(title=title, store=store)

    for tiddler in candidate_tiddlers:
        tiddler.recipe = recipe.name
        tiddlers.add(tiddler)
예제 #37
0
class Serialization(SerializationInterface):
    def __init__(self, environ):
        if not environ:
            environ = {}
        if 'tiddlyweb.query' not in environ:
            environ['tiddlyweb.query'] = {}
        environ['tiddlyweb.query']['fat'] = 'y'
        self.environ = environ
        self._bag_perms_cache = {}
        self.ATOM_CONFIG_TITLE = u"AtomSettings"

    def load(self, tiddler, type=False):
        return tiddler

    def tiddler_dump(self,
                     tiddler,
                     baseurl,
                     active_resource=False,
                     atomconfig={}):
        output = u""
        quoteTitle = urllib.quote(tiddler["title"].encode("utf-8"))
        bagname = tiddler["bag"]
        logging.debug("atom-custom:: doing a tiddler dump with %s" % tiddler)
        if "excludeAtom" in tiddler["tags"]:
            return ""
        mappings = {}
        if atomconfig:
            if bagname in atomconfig['bags']:
                bagmappings = atomconfig['bags'][bagname]
                for mapping in bagmappings:
                    mappings[mapping] = bagmappings[mapping]
            if active_resource:
                rtype, rname = active_resource.split("/")
                if rtype == 'recipes':
                    if rname in atomconfig['recipes']:
                        for single_mapping in atomconfig['recipes'][rname]:
                            mappings[single_mapping] = atomconfig['recipes'][
                                rname][single_mapping]

        serializer = self
        logging.debug(
            "atom-custom:: created mapping for tiddler %s \n\n atom-custom::as %s \n\n\n atom-custom::from config %s \n\n"
            % (tiddler, mappings, atomconfig))

        def mapper(atom_field_name, tiddler, default):
            logging.debug(
                "atom-custom:: doing a mapping on field %s \n atom-custom::with tiddler %s \n atom-custom::and config %s"
                % (atom_field_name, tiddler, mappings))
            tid = Tiddler(tiddler['title'], tiddler['bag'])
            tid = serializer.as_tiddler(tid, tiddler)
            try:
                tid.recipe = tiddler['recipe']
            except KeyError:
                pass
            if atom_field_name in mappings:
                val = mappings[atom_field_name]
                if atom_field_name == 'link' or atom_field_name == 'id' and val.startswith(
                        "/"):
                    sh = config['server_host']
                    val = u"%s://%s%s" % (sh['scheme'], sh['host'], val)
                    wikified = "http://%s" % wikitext_to_wikklyhtml(
                        baseurl,
                        '',
                        val[7:],
                        self.environ,
                        tiddler=tid,
                        wikiwords=False)
                else:
                    wikified = wikitext_to_wikklyhtml(baseurl,
                                                      '',
                                                      val,
                                                      self.environ,
                                                      tiddler=tid,
                                                      wikiwords=False)
                return cgi.escape(wikified).decode("utf-8")

            else:
                return default

        quoteBag = urllib.quote(bagname)
        url = "%s%s" % (baseurl, quoteTitle)
        mode = ''
        id = mapper("id", tiddler,
                    "%s/%s/%s" % (quoteBag, quoteTitle, tiddler['revision']))
        if 'modifier' in tiddler:
            modifier_string = u"<author><name>%s</name></author>" % mapper(
                'author', tiddler, tiddler['modifier'])
        else:
            modifier_string = u"<author><name></name></author>"
        if "type" in tiddler:
            if tiddler["type"] != "None":
                tidType = tiddler["type"]
                mode = 'mode="base64" '
            else:
                tidType = "html"
        else:
            tidType = "html"
        if "text" in tiddler:
            content = cgi.escape(tiddler["text"])
            content = mapper('content', tiddler, content)
            #print content
            text = u'<content %stype="%s">%s</content>' % (mode, tidType,
                                                           content)
        else:
            text = u""
        if 'modified' in tiddler:
            mod = tiddler["modified"]
            mask = "200108150000000"
            if len(mod) < len(mask):
                mod += mask[len(mod):]
                date = '%s-%s-%sT%s:%s:%sZ' % (mod[0:4], mod[4:6], mod[6:8],
                                               mod[8:10], mod[10:12],
                                               mod[12:14])
        else:
            date = ''
        entry_title = mapper('title', tiddler, cgi.escape(tiddler["title"]))
        entry_url = mapper('link', tiddler, url)
        logging.debug("atomplus::entry %s, %s" % (entry_title, entry_url))
        output += u"""<entry>
	<title>%s</title>
	<id>%s</id>
	<link rel="alternate" type="text/html" href="%s"/>
	%s
	%s
	<updated>%s</updated>
""" % (entry_title, id, entry_url, text, modifier_string, date)
        for tag in tiddler["tags"]:
            output += u'''	<category term="%s"/>
''' % cgi.escape(tag)

        if "geo.long" in tiddler["fields"] and "geo.lat" in tiddler["fields"]:
            lat = tiddler["fields"]["geo.lat"]
            lon = tiddler["fields"]["geo.long"]
            output += u"""	<georss:point>%s %s</georss:point>
	<geo:lat>%s</geo:lat>
	<geo:long>%s</geo:long>
""" % (lat, lon, lat, lon)
        output += '''
</entry>
'''
        return output

    def read_atom_settings(self, atom_setting_text, resource_uri=""):
        settings = {"feed": {}, "bags": {}, "recipes": {}}
        setting_lines = atom_setting_text.split("\n")
        active_resource = False
        ignore_following = False
        for setting_line in setting_lines:
            setting_line = setting_line.lstrip("     ")
            if setting_line.startswith("!"):  #bag definition
                try:
                    resource_type, resource_name = setting_line[1:].split("/")
                    settings[resource_type][resource_name] = {}
                    active_resource = [resource_type, resource_name]
                    ignore_following = False
                except ValueError:
                    ignore_following = True
                    active_resource = False
                    pass

            if not ignore_following:
                try:
                    name, val = setting_line.split(":")
                    name_resource_parent, name_resource_tag = name.split(".")
                    if name_resource_parent == 'feed':
                        if not active_resource or resource_uri == u"/".join(
                                active_resource):
                            settings["feed"][name_resource_tag] = val
                    elif active_resource and name_resource_parent == 'entry':
                        settings[active_resource[0]][
                            active_resource[1]][name_resource_tag] = val
                except ValueError:
                    pass
        return settings

    def get_atom_config(self, resource_type, resource_name):
        store = get_store(config)
        atomconfig = False
        if resource_type == 'bag':
            try:
                atomconfig = store.get(
                    Tiddler(self.ATOM_CONFIG_TITLE, resource_name))
            except NoTiddlerError, NoBagError:
                pass
        elif resource_type == 'recipe':
            try:
                tids = control.get_tiddlers_from_recipe(
                    store.get(Recipe(resource_name)))
                for tid in tids:
                    if tid.title == self.ATOM_CONFIG_TITLE:
                        atomconfig = store.get(tid)
            except NoRecipeError:
                pass