def wiki_setup(tc): wiki1 = WikiPage(tc.env) wiki1.name = 'TestPage' wiki1.text = '--' wiki1.save('joe', 'normal WikiPageNames', '::1', 42) wiki2 = WikiPage(tc.env) wiki2.name = 'Space 1 23' wiki2.text = '--' wiki2.save('joe', 'not a WikiPageNames', '::1', 42) wiki3 = WikiPage(tc.env) wiki3.name = u"C'est l'\xe9t\xe9" wiki3.text = '--' wiki3.save('joe', 'unicode WikiPageNames', '::1', 42) imt = WikiPage(tc.env) imt.name = u"InterMapTxt" imt.text = """ This is the InterMapTxt ---- {{{ MeatBall http://www.usemod.com/cgi-bin/mb.pl? # $1 in MeatBall... tsvn tsvn: complex http://server/$1/page/$2?format=txt # resource $2 in $1 }}} ---- {{{ nolink http://noweb }}} """ imt.save('joe', 'test InterWiki links', '::1', 42)
def _render_editor(self, req, page, action='edit', has_collision=False): if has_collision: if action == 'merge': page = WikiPage(self.env, page.name, version=None) req.perm(page.resource).require('WIKI_VIEW') else: action = 'collision' if page.readonly: req.perm(page.resource).require('WIKI_ADMIN') else: req.perm(page.resource).require('WIKI_MODIFY') original_text = page.text if 'text' in req.args: page.text = req.args.get('text') elif 'template' in req.args: template = self.PAGE_TEMPLATES_PREFIX + req.args.get('template') template_page = WikiPage(self.env, template) if template_page and template_page.exists and \ 'WIKI_VIEW' in req.perm(template_page.resource): page.text = template_page.text if action == 'preview': page.readonly = 'readonly' in req.args author = get_reporter_id(req, 'author') comment = req.args.get('comment', '') editrows = req.args.get('editrows') if editrows: pref = req.session.get('wiki_editrows', '20') if editrows != pref: req.session['wiki_editrows'] = editrows else: editrows = req.session.get('wiki_editrows', '20') data = self._page_data(req, page, action) data.update({ 'author': author, 'comment': comment, 'edit_rows': editrows, 'scroll_bar_pos': req.args.get('scroll_bar_pos', ''), 'diff': None, }) if action in ('diff', 'merge'): old_text = original_text and original_text.splitlines() or [] new_text = page.text and page.text.splitlines() or [] diff_data, changes = self._prepare_diff( req, page, old_text, new_text, page.version, '') data.update({'diff': diff_data, 'changes': changes, 'action': 'preview', 'merge': action == 'merge', 'longcol': 'Version', 'shortcol': 'v'}) self._wiki_ctxtnav(req, page) return 'wiki_edit.html', data, None
def wiki_setup(tc): tc.env.config.set('wiki', 'render_unsafe_content', True) # for #9712 now = datetime.now(utc) wiki0 = WikiPage(tc.env) wiki0.name = 'Main/Sub' wiki0.text = '--' wiki0.save('joe', 'subpage', '::1', now) wiki1 = WikiPage(tc.env) wiki1.name = 'TestPage' wiki1.text = '--' wiki1.save('joe', 'normal WikiPageNames', '::1', now) wiki2 = WikiPage(tc.env) wiki2.name = 'Space 1 23' wiki2.text = '--' wiki2.save('joe', 'not a WikiPageNames', '::1', now) wiki3 = WikiPage(tc.env) wiki3.name = u"C'est l'\xe9t\xe9" wiki3.text = '--' wiki3.save('joe', 'unicode WikiPageNames', '::1', now) imt = WikiPage(tc.env) imt.name = u"InterMapTxt" imt.text = """ This is the InterMapTxt ---- {{{ MeatBall http://www.usemod.com/cgi-bin/mb.pl? # $1 in MeatBall... tsvn tsvn: complex http://server/$1/page/$2?format=txt # resource $2 in $1 }}} ---- {{{ nolink http://noweb }}} """ imt.save('joe', 'test InterWiki links', '::1', now) w = WikiPage(tc.env) w.name = 'FirstLevel' w.text = '--' w.save('joe', 'first level of hierarchy', '::1', now) w = WikiPage(tc.env) w.name = 'FirstLevel/SecondLevel' w.text = '--' w.save('joe', 'second level of hierarchy', '::1', now) w = WikiPage(tc.env) w.name = 'FirstLevel/SecondLevel/ThirdLevel' w.text = '--' w.save('joe', 'third level of hierarchy', '::1', now) w = WikiPage(tc.env) w.name = 'FirstLevel/SecondLevel/OtherThirdLevel' w.text = '--' w.save('joe', 'other third level of hierarchy', '::1', now)
def test_index_wikis(self): self._insert_component('comp16') self._insert_component('comp20') wiki1 = WikiPage(self.env, name="Testwiki1", version="1") wiki1.text = "This is the wiki <comp20 open door> text content." wiki1.save('adeponte', 'My comment', '192.168.1.2') wiki2 = WikiPage(self.env, name="Testwiki2", version="1") wiki2.text = "This is the wiki <comp16 close door> text content." wiki2.save('bob', 'His Comment', '182.123.321.456') req_cache_sys = RequirementCacheSystem(self.env) req_cache_sys.index_wikis() req_wiki_cache = RequirementWikiCache(self.env, 'comp20', 'open', 'door', 'Testwiki1', '1') self.assertEqual(req_wiki_cache.exists, True) req_wiki_cache = RequirementWikiCache(self.env, 'comp16', 'close', 'door', 'Testwiki2', '1') self.assertEqual(req_wiki_cache.exists, True)
def setUp(self): wiki = WikiPage(self.env) wiki.name = 'WikiStart' wiki.text = '--' wiki.save('joe', 'Entry page', '::1', datetime.now(utc)) if self._setup: self._setup(self)
def import_wiki_pages(self, template_path): """Creates wiki pages from wiki.xml template file. Creates wiki pages inside the project using data extracted from an wiki.ml file. We don't set the author or version as that wouldn't be applicable to a new project. """ # open the wiki XML file, parse the data and create wiki pages full_path = os.path.join(template_path, 'wiki.xml') try: tree = ET.ElementTree(file=full_path) for page in tree.getroot(): if page.text: wikipage = WikiPage(self.env, page.attrib['name']) wikipage.readonly = int(page.attrib['readonly']) # we store as a string in xml wikipage.text = page.text wikipage.save(None, None, None) self.log.info("Wiki page %s created", page.attrib['name']) else: self.log.debug("Cannot create wiki pages with no text. " "Unable to import %s", wikipage) except IOError as exception: if exception.errno == errno.ENOENT: self.log.info("Path to wiki.xml file %s does not exist. Unable " "to import wiki pages from template.", full_path)
def set_password(self, user, password): import re if len(user) < 3: raise TracError("user name must be at least 3 characters long") if not re.match(r"^\w+$", user): raise TracError("user name must consist only of alpha-numeric characters") if user not in self.get_users(): from trac.wiki.model import WikiPage db = self.env.get_db_cnx() page = WikiPage(self.env, user, db=db) # User creation with existing page if page.exists: raise TracError('wiki page "%s" already exists' % user) else: from tractags.api import TagEngine tagspace = TagEngine(self.env).tagspace.wiki tagspace.add_tags(None, user, ["user"]) page.text = """= %(user)s =\n\n[[ListTagged(%(user)s)]]\n\n[[TagIt(user)]]""" % {"user": user} page.save(user, "New user %s registered" % user, None) self.env.log.debug("New user %s registered" % user) HtPasswdStore.set_password(self, user, password)
def set_password(self, user, password): import re if len(user) < 3: raise TracError('user name must be at least 3 characters long') if not re.match(r'^\w+$', user): raise TracError( 'user name must consist only of alpha-numeric characters') if user not in self.get_users(): from trac.wiki.model import WikiPage db = self.env.get_db_cnx() page = WikiPage(self.env, user, db=db) # User creation with existing page if page.exists: raise TracError('wiki page "%s" already exists' % user) else: from tractags.api import TagEngine tagspace = TagEngine(self.env).tagspace.wiki tagspace.add_tags(None, user, ['user']) page.text = '''= %(user)s =\n\n[[ListTagged(%(user)s)]]\n\n[[TagIt(user)]]''' % { 'user': user } page.save(user, 'New user %s registered' % user, None) self.env.log.debug("New user %s registered" % user) HtPasswdStore.set_password(self, user, password)
def initialize_agilo(self, project_name, db_url, svn_repo, demo=False): try: self.do_initenv('%s %s %s %s' % (project_name, db_url, 'svn', svn_repo or 'somewhere')) # Now add agilo and the template path env = Environment(self.envname) ac = AgiloConfig(env) if not svn_repo: # remove the fake from the config ac.change_option('repository_dir', '', 'trac') # sets the restric_owner option ac.change_option('restrict_owner', 'true', 'ticket') # this is also saving the config ac.enable_agilo() # update wiki wiki = WikiPage(env, name='WikiStart') wiki.text = agilo_wiki wiki.save('admin', 'Updated to Agilo', '127.0.0.1') # reset the env self.env_set(envname=self.envname, env=env) # Now initialize Agilo self.do_upgrade('upgrade --no-backup') # Now create the demo if needed if demo: try: from create_demo_data import _create_demo_data _create_demo_data(env) except ImportError, e: env.log.error(exception_to_unicode(e)) except: pass
def main(): options, args = parse_args() names = sorted(name for name in resource_listdir('trac.wiki', 'default-pages') if not name.startswith('.')) if args: args = sorted(set(names) & set(map(os.path.basename, args))) else: args = names if options.download: download_default_pages(args, options.prefix) env = EnvironmentStub() load_components(env) with env.db_transaction: for name in names: wiki = WikiPage(env, name) wiki.text = resource_string('trac.wiki', 'default-pages/' + name).decode('utf-8') if wiki.text: wiki.save('trac', '') else: printout('%s: Skipped empty page' % name) req = Mock(href=Href('/'), abs_href=Href('http://localhost/'), perm=MockPerm()) for name in args: wiki = WikiPage(env, name) if not wiki.exists: continue context = web_context(req, wiki.resource) out = DummyIO() DefaultWikiChecker(env, context, name).format(wiki.text, out)
def add_pages(tc, names): now = datetime.now(utc) for name in names: w = WikiPage(tc.env) w.name = name w.text = "--" w.save("joe", "the page " + name, "::1", now)
def main(): names = sorted(name for name in resource_listdir('trac.wiki', 'default-pages') if not name.startswith('.')) env = EnvironmentStub() load_components(env) with env.db_transaction: for name in names: wiki = WikiPage(env, name) wiki.text = resource_string('trac.wiki', 'default-pages/' + name).decode('utf-8') if wiki.text: wiki.save('trac', '') else: printout('%s: Skipped empty page' % name) req = Mock(href=Href('/'), abs_href=Href('http://trac.edgewall.org/'), perm=MockPerm(), chrome={}) for name in sys.argv[1:]: name = os.path.basename(name) wiki = WikiPage(env, name) if not wiki.exists: continue context = web_context(req, wiki.resource, absurls=True) rst = wiki2rest(env, context, wiki) sys.stdout.write(rst)
def test_delete_page(self): page = WikiPage(self.env) page.name = 'SandBox' page.text = 'Contents for SandBox' page.save('trac', 'create page') mod = WikiModule(self.env) req = MockRequest(self.env, path_info='/wiki/SandBox', method='GET', args={ 'action': 'delete', 'version': '1' }) self.assertTrue(mod.match_request(req)) resp = mod.process_request(req) self.assertEqual(2, len(resp)) self.assertIn('Are you sure you want to completely delete this page?', self._render_template(req, resp[0], resp[1])) req = MockRequest(self.env, path_info='/wiki/SandBox', method='POST', args={'action': 'delete'}) self.assertTrue(mod.match_request(req)) self.assertRaises(RequestDone, mod.process_request, req) self.assertIn('The page SandBox has been deleted.', req.chrome.get('notices')) self.assertEqual(False, WikiPage(self.env, 'SandBox').exists)
def add_pages(tc, names): now = datetime.now(utc) for name in names: w = WikiPage(tc.env) w.name = name w.text = '--' w.save('joe', 'the page ' + name, '::1', now)
def add_pages(tc, names): for name in names: now = datetime_now(utc) w = WikiPage(tc.env) w.name = name w.text = '--' w.save('joe', 'the page ' + name, now)
def do_upgrade_environment(db): for realm in self.SCHEMA: realm_schema = self.SCHEMA[realm] if need_db_create_for_realm(self.env, realm, realm_schema, db): create_db_for_realm(self.env, realm, realm_schema, db) elif need_db_upgrade_for_realm(self.env, realm, realm_schema, db): upgrade_db_for_realm(self.env, 'testmanager.upgrades', realm, realm_schema, db) # Create default values for configuration properties and initialize counters db_insert_or_ignore(self.env, 'testconfig', 'NEXT_CATALOG_ID', '0', db) db_insert_or_ignore(self.env, 'testconfig', 'NEXT_TESTCASE_ID', '0', db) db_insert_or_ignore(self.env, 'testconfig', 'NEXT_PLAN_ID', '0', db) db.commit() # Fix templates with a blank id if self._check_blank_id_templates(db): self._fix_blank_id_templates(db) db.commit() self.env.log.info(_(""" Test Manager templates with blank IDs have been fixed.\n Please go to the Administration panel, in the Test Manager Templates section, and check the associations between templates and Test Cases and Test Catalogs.\n You will have to manually fix any misconfiguration you should find. """)) # Create the basic "TC" Wiki page, used as the root test catalog tc_page = WikiPage(self.env, 'TC') if not tc_page.exists: tc_page.text = ' ' tc_page.save('System', '', '127.0.0.1') db.commit() if self._need_upgrade(db): # Set custom ticket field to hold related test case custom = self.config['ticket-custom'] config_dirty = False if 'testcaseid' not in custom: custom.set('testcaseid', 'text') custom.set('testcaseid.label', _("Test Case")) config_dirty = True if 'planid' not in custom: custom.set('planid', 'text') custom.set('planid.label', _("Test Plan")) config_dirty = True # Set config section for test case outcomes if 'test-outcomes' not in self.config: self.config.set('test-outcomes', 'green.SUCCESSFUL', _("Successful")) self.config.set('test-outcomes', 'yellow.TO_BE_TESTED', _("Untested")) self.config.set('test-outcomes', 'red.FAILED', _("Failed")) self.config.set('test-outcomes', 'default', 'TO_BE_TESTED') config_dirty = True if config_dirty: self.config.save()
def _do_wiki_upgrade(self): """Move all wiki pages starting with Trac prefix to unbranded user guide pages. """ wiki_admin = WikiAdmin(self.env) pages = wiki_admin.get_wiki_list() for old_name in pages: if old_name.startswith('Trac'): new_name = wiki.new_name(old_name) if not new_name: continue if new_name in pages: printout( _( 'Ignoring %(page)s : ' 'The page %(new_page)s already exists', page=old_name, new_page=new_name)) continue try: wiki_admin._do_rename(old_name, new_name) except AdminCommandError, exc: printout( _('Error moving %(page)s : %(message)s', page=old_name, message=unicode(exc))) else: # On success, rename links in other pages self._do_wiki_rename_links(old_name, new_name) # On success, insert redirection page redirection = WikiPage(self.env, old_name) redirection.text = _('See [wiki:"%(name)s"].', name=new_name) comment = 'Bloodhound guide update' redirection.save('bloodhound', comment, '0.0.0.0')
def main(): all_pages = sorted( name for name in resource_listdir('trac.wiki', 'default-pages') if not name.startswith('.')) args = parse_args(all_pages) if args.pages: pages = sorted(args.pages) else: pages = all_pages if args.download: download_default_pages(pages, args.prefix, args.strict) env = EnvironmentStub(disable=['trac.mimeview.pygments.*']) load_components(env) with env.db_transaction: for name in all_pages: wiki = WikiPage(env, name) wiki.text = resource_string('trac.wiki', 'default-pages/' + name).decode('utf-8') if wiki.text: wiki.save('trac', '') else: printout('%s: Skipped empty page' % name) req = Mock(href=Href('/'), abs_href=Href('http://localhost/'), perm=MockPerm()) for name in pages: wiki = WikiPage(env, name) if not wiki.exists: continue context = web_context(req, wiki.resource) out = DummyIO() DefaultWikiChecker(env, context, name).format(wiki.text, out)
def save_wiki_data(self, req): page = WikiPage(self.env, self.name) if not page.exists: self.log.error('Wiki page "%s" doesn\'t exist' % self.name) return None lines = page.text.split('\n') first = -1 last = -1 new_lines = [] for index, line in enumerate(lines): if first < 0: new_lines.append(line) if self.data_start_regexp.match(line): first = index + 1 new_lines.append(self.get_json(False, True)) elif last < 0: if self.data_end_regexp.match(line): last = index - 1 new_lines.append(line) else: new_lines.append(line) if last > 0: page.text = '\n'.join(new_lines) try: page.save(req.authname, 'Kanban board data changed', req.remote_addr) except TracError as e: self.log.error('TracError: "%s"' % e.message)
def add_wiki_page(self, env, name, text): page = WikiPage(env, name) if page.time: self.note(" ** Page %s already exists, not adding it." % name) return page.text = text page.save(author="(System)", comment="Initial page import")
def _do_wiki_upgrade(self): """Move all wiki pages starting with Trac prefix to unbranded user guide pages. """ wiki_admin = WikiAdmin(self.env) pages = wiki_admin.get_wiki_list() for old_name in pages: if old_name.startswith('Trac'): new_name = wiki.new_name(old_name) if not new_name: continue if new_name in pages: printout(_('Ignoring %(page)s : ' 'The page %(new_page)s already exists', page=old_name, new_page=new_name)) continue try: wiki_admin._do_rename(old_name, new_name) except AdminCommandError, exc: printout(_('Error moving %(page)s : %(message)s', page=old_name, message=unicode(exc))) else: # On success, rename links in other pages self._do_wiki_rename_links(old_name, new_name) # On success, insert redirection page redirection = WikiPage(self.env, old_name) redirection.text = _('See [wiki:"%(name)s"].', name=new_name) comment = 'Bloodhound guide update' redirection.save('bloodhound', comment, '0.0.0.0')
def _insert_page(self, name=None): page = WikiPage(self.env) if name is None: name = random_unique_camel() page.name = name page.text = random_paragraph() page.save('user1', 'Page created.') return name
def do_rename(db): page.rename(new_name) if redirect: redirection = WikiPage(self.env, old_name, db=db) redirection.text = _('See [wiki:"%(name)s"].', name=new_name) author = get_reporter_id(req) comment = u'[wiki:"%s@%d" %s] \u2192 [wiki:"%s"].' % ( new_name, old_version, old_name, new_name) redirection.save(author, comment, req.remote_addr)
def _process_page(self, page, author = None, comment = None, ipnr = None): if self.boilerplate_start_re.search( page.text ) != None: # If the audit info isn't available, grab it from the boilerplate page. if author == None or comment == None: page = WikiPage( self.env, page.name ) if author == None: author = page.author if comment == None: comment = page.comment if ipnr == None: ipnr = '127.0.0.1' # I don't know what else to do here. # Extract the boilerplate text and the wanted pages. buf = StringIO() page_list = {} inboilerplate = False for line in page.text.splitlines(): if inboilerplate: if self.boilerplate_end_re.search( line ) != None: inboilerplate = False else: buf.write( line ) buf.write( '\n' ) else: if self.boilerplate_start_re.search( line ) != None: inboilerplate = True else: if line.startswith('||') and line.endswith('||') and line[3] != "'": try: descriptor = ([i.strip() for i in line.strip('||').split('||')]) name = descriptor[0] arguments = descriptor[1:] m = self.extractpagename_re.search( name ) if m != None: name = m.string[m.start(1):m.end(1)] self.env.log.warning("extracted name = " + name ) page_list[ name ] = arguments except Exception, e: self.env.log.warning("Invalid page line: %s (%s)", line, e) # Generate the derived pages as instructed. page_names = page_list.keys() page_names.sort() for name in page_names: text = buf.getvalue() args = page_list[ name ] text = text.replace( '{{0}}', name ) i = 0 for arg in args: text = text.replace('{{%d}}' % (i+1), args[i]) i += 1 newpage = WikiPage( self.env, name ) if newpage.text != text: newpage.text = text newpage.save( author, comment, ipnr )
def upgrade_environment(self, db): # Create or update db for realm in self.SCHEMA: realm_metadata = self.SCHEMA[realm] if need_db_create_for_realm(self.env, realm, realm_metadata, db): create_db_for_realm(self.env, realm, realm_metadata, db) elif need_db_upgrade_for_realm(self.env, realm, realm_metadata, db): upgrade_db_for_realm(self.env, 'testmanager.upgrades', realm, realm_metadata, db) # Create default values for configuration properties and initialize counters db_insert_or_ignore(self.env, 'testconfig', 'NEXT_CATALOG_ID', '0') db_insert_or_ignore(self.env, 'testconfig', 'NEXT_TESTCASE_ID', '0') db_insert_or_ignore(self.env, 'testconfig', 'NEXT_PLAN_ID', '0') # Create the basic "TC" Wiki page, used as the root test catalog tc_page = WikiPage(self.env, 'TC') if not tc_page.exists: tc_page.text = ' ' tc_page.save('System', '', '127.0.0.1') if self._need_upgrade(db): # Set custom ticket field to hold related test case custom = self.config['ticket-custom'] config_dirty = False if 'testcaseid' not in custom: custom.set('testcaseid', 'text') custom.set('testcaseid.label', _("Test Case")) config_dirty = True if 'planid' not in custom: custom.set('planid', 'text') custom.set('planid.label', _("Test Plan")) config_dirty = True # Set config section for test case outcomes if 'test-outcomes' not in self.config: self.config.set('test-outcomes', 'green.SUCCESSFUL', _("Successful")) self.config.set('test-outcomes', 'yellow.TO_BE_TESTED', _("Untested")) self.config.set('test-outcomes', 'red.FAILED', _("Failed")) self.config.set('test-outcomes', 'default', 'TO_BE_TESTED') config_dirty = True # Set config section for default visible columns in tabular view if self.config.get('testmanager', 'testcatalog.visible_description') == '': self.config.set('testmanager', 'testcatalog.visible_description', 'False') config_dirty = True if config_dirty: self.config.save()
def _do_rename(self, req, page): if page.readonly: req.perm(page.resource).require('WIKI_ADMIN') else: req.perm(page.resource).require('WIKI_RENAME') if 'cancel' in req.args: req.redirect(get_resource_url(self.env, page.resource, req.href)) old_name, old_version = page.name, page.version new_name = req.args.get('new_name', '') new_name = re.sub(r'/{2,}', '/', new_name.strip('/')) redirect = req.args.get('redirect') # verify input parameters warn = None if not new_name: warn = _("A new name is mandatory for a rename.") elif not validate_page_name(new_name): warn = _("The new name is invalid (a name which is separated " "with slashes cannot be '.' or '..').") elif new_name == old_name: warn = _("The new name must be different from the old name.") elif WikiPage(self.env, new_name).exists: warn = _("The page %(name)s already exists.", name=new_name) if warn: add_warning(req, warn) return self._render_confirm_rename(req, page, new_name) with self.env.db_transaction as db: page.rename(new_name) if redirect: redirection = WikiPage(self.env, old_name, db=db) redirection.text = _('See [wiki:"%(name)s"].', name=new_name) author = get_reporter_id(req) comment = u'[wiki:"%s@%d" %s] \u2192 [wiki:"%s"].' % ( new_name, old_version, old_name, new_name) redirection.save(author, comment, req.remote_addr) add_notice( req, _("The page %(old_name)s has been renamed to " "%(new_name)s.", old_name=old_name, new_name=new_name)) if redirect: add_notice( req, _( "The page %(old_name)s has been recreated " "with a redirect to %(new_name)s.", old_name=old_name, new_name=new_name)) req.redirect(req.href.wiki(old_name if redirect else new_name))
def setUp(self): ProductResourceTestCase.setUp(self) page = WikiPage(self.global_env) page.name = 'TestPage' page.text = 'Bla bla' t = datetime(2001, 1, 1, 1, 1, 1, 0, utc) page.save('joe', 'Testing global', '::1', t) page.text = 'Bla bla bla' t = datetime(2002, 2, 2, 2, 2, 2, 0, utc) page.save('joe', 'Testing global 2', '::1', t) page = WikiPage(self.env1) page.name = 'TestPage' page.text = 'alb alB' t = datetime(2011, 1, 1, 1, 1, 1, 0, utc) page.save('mary', 'Testing product', '::1', t) page.text = 'Bla bla bla' t = datetime(2012, 2, 2, 2, 2, 2, 0, utc) page.save('mary', 'Testing product 2', '::1', t)
def user_created(self, user, password): req = FakeRequest(self.env, user) resource = Resource('wiki', user) tag_system = TagSystem(self.env) tag_system.add_tags(req, resource, ['user',]) page = WikiPage(self.env, user) page.text = '''= %(user)s =\n\n[[ListTagged(%(user)s)]]\n''' % {'user' : user} page.save(user, 'New user %s registered' % user, None) self.env.log.debug("New user %s registered" % user)
def setUp(self): ProductResourceTestCase.setUp(self) page = WikiPage(self.global_env) page.name = "TestPage" page.text = "Bla bla" t = datetime(2001, 1, 1, 1, 1, 1, 0, utc) page.save("joe", "Testing global", "::1", t) page.text = "Bla bla bla" t = datetime(2002, 2, 2, 2, 2, 2, 0, utc) page.save("joe", "Testing global 2", "::1", t) page = WikiPage(self.env1) page.name = "TestPage" page.text = "alb alB" t = datetime(2011, 1, 1, 1, 1, 1, 0, utc) page.save("mary", "Testing product", "::1", t) page.text = "Bla bla bla" t = datetime(2012, 2, 2, 2, 2, 2, 0, utc) page.save("mary", "Testing product 2", "::1", t)
def setUp(self): self.env = self._create_env() # TODO: remove the following lines in order to discover # all the places were we should use the req.href # instead of env.href self.env.href = self.req.href self.env.abs_href = self.req.abs_href wiki = WikiPage(self.env) wiki.name = 'WikiStart' wiki.text = '--' wiki.save('joe', 'Entry page', '::1', datetime_now(utc)) if self._setup: self._setup(self)
def setUp(self): self.env = EnvironmentStub(enable=[AutoWikify]) self.req = Mock( authname='anonymous', perm=MockPerm(), tz=None, args={}, href=Href('/'), abs_href=Href('http://www.example.com/')) self.autowikify = AutoWikify(self.env) for name in (u'autowikify', u'あいうName', u'Nameあいう', u'かきくけこ'): page = WikiPage(self.env, name) page.text = name page.save('admin', '', '::1') self.context = Context.from_request(self.req, WikiPage(self.env, name))
def test_rename_wiki_page(self): sid = 'subscriber' page = WikiPage(self.env) page.name = name = 'PageInitial' page.text = 'Page content' page.save('actor', 'page created') ws = WatchSubscriber(self.env) ws.set_watch(sid, 1, 'wiki', name) new_name = 'PageRenamed' page.rename(new_name) self.assertFalse(ws.is_watching(sid, 1, 'wiki', name)) self.assertTrue(ws.is_watching(sid, 1, 'wiki', new_name))
def wiki_setup(tc): tc.env = EnvironmentStub(default_data=True, enable=['trac.*', 'tractags.*']) tc.env.path = tempfile.mkdtemp() tc.db_mgr = DatabaseManager(tc.env) tc.db = tc.env.get_db_cnx() cursor = tc.db.cursor() cursor.execute("DROP TABLE IF EXISTS tags") cursor.execute("DROP TABLE IF EXISTS tags_change") cursor.execute("DELETE FROM system WHERE name='tags_version'") cursor.execute("DELETE FROM permission WHERE action %s" % tc.db.like(), ('TAGS_%', )) TagSetup(tc.env).upgrade_environment(tc.db) now = datetime.now(utc) wiki = WikiPage(tc.env) wiki.name = 'TestPage' wiki.text = '--' wiki.save('joe', 'TagsPluginTestPage', '::1', now) cursor = tc.db.cursor() # Populate table with initial test data. cursor.executemany( """ INSERT INTO tags (tagspace, name, tag) VALUES (%s,%s,%s) """, [ ('wiki', 'TestPage', '2ndtag'), ('wiki', 'TestPage', 'a.really?_\wild-thing'), ('wiki', 'TestPage', 'heavily-quoted'), ('wiki', 'TestPage', 'onetag'), ('wiki', 'TestPage', 'tagged'), ('wiki', 'TestPage', "single'quote"), ]) req = Mock(href=Href('/'), abs_href=Href('http://www.example.com/'), authname='anonymous', perm=MockPerm(), tz=utc, args={}, locale=locale_en) tc.env.href = req.href tc.env.abs_href = req.abs_href tc.context = Context.from_request(req) # Enable big diff output. tc.maxDiff = None
def _controller_import(self, req, cat, page, component): """ Performs import. """ # Data to be passed to view data = {'operations': {}} # User selected pages selected_pages = req.args.get('wikiimport_selected_pages') # User has selected some pages if selected_pages: # Choose between preconfigured and raw instance if req.args.get('wikiimport_instance_path'): data['instance_path'] = req.args.get( 'wikiimport_instance_path') source_env = Environment(data['instance_path']) instance_identifier = data['instance_path'] else: data['instance_id'] = req.args.get('wikiimport_instance_id') source_env = self._get_instance_env(data['instance_id']) instance_identifier = data['instance_id'] # Get operations to be performed data['operations'] = self._get_page_operations( source_env, self.env) # This is required in order to display pages list alphabetically data['sorted_pages'] = data['operations'].keys() data['sorted_pages'].sort() # Discard operation for pages that were unchecked on the preview page for page in data['sorted_pages']: if page not in selected_pages: del data['operations'][page] # Update local wiki for page, operation in data['operations'].items(): source_page = WikiPage(source_env, page) local_page = WikiPage(self.env, page) local_page.text = source_page.text local_page.save( get_reporter_id(req, 'author'), 'Importing pages from "%s" using [http://trac-hacks.org/wiki/WikiImportPlugin WikiImport plugin].' % instance_identifier, req.remote_addr) # Add stylesheet to view add_stylesheet(req, 'wikiimport/css/wikiimport.css') return 'admin_wikiimport_import.html', data
def _controller_import(self, req, cat, page, component): """ Performs import. """ # Data to be passed to view data = {'operations': {}} # User selected pages selected_pages = req.args.get('wikiimport_selected_pages') # User has selected some pages if selected_pages: # Choose between preconfigured and raw instance if req.args.get('wikiimport_instance_path'): data['instance_path'] = req.args.get('wikiimport_instance_path') source_env = Environment(data['instance_path']) instance_identifier = data['instance_path'] else: data['instance_id'] = req.args.get('wikiimport_instance_id') source_env = self._get_instance_env(data['instance_id']) instance_identifier = data['instance_id'] # Get operations to be performed data['operations'] = self._get_page_operations(source_env, self.env) # This is required in order to display pages list alphabetically data['sorted_pages'] = data['operations'].keys() data['sorted_pages'].sort() # Discard operation for pages that were unchecked on the preview page for page in data['sorted_pages']: if page not in selected_pages: del data['operations'][page] # Update local wiki for page, operation in data['operations'].items(): source_page = WikiPage(source_env, page) local_page = WikiPage(self.env, page) local_page.text = source_page.text local_page.save( get_reporter_id(req, 'author'), 'Importing pages from "%s" using [http://trac-hacks.org/wiki/WikiImportPlugin WikiImport plugin].' % instance_identifier, req.remote_addr ) # Add stylesheet to view add_stylesheet(req, 'wikiimport/css/wikiimport.css'); return 'admin_wikiimport_import.html', data
def interwiki_setup(tc): tc.env.config.set('interwiki', 'shields', 'https://img.shields.io/') tc.env.config.set('interwiki', 'travis', 'https://travis-ci.org/$1?branch=$2 Travis CI') page = WikiPage(tc.env) page.name = 'InterMapTxt' page.text = """ The InterWikiTxt page ---- {{{ SO http://stackoverflow.com/questions/ # Question $1 in StackOverflow CreoleWiki http://wikicreole.org/wiki/ }}} """ page.save('admin', 'created page')
def process_request(self, req): global page_version repos = RepositoryManager(self.env).repository_dir repdir = repos.split('.git')[0] dirList = os.listdir(repdir + 'wiki') dirList.sort() count_do = 0 count_no = 0 for sFile in dirList: if sFile.find('.txt') == -1: continue try: filename = os.path.splitext(sFile)[0] if filename not in page_version: page_version[filename] = 0 content = read_file(repdir + 'wiki/' + sFile) page = WikiPage(self.env, filename) page.text = content.decode('unicode-escape') if page_version[filename] != page.version: print (filename + ': local page version does not match online version!') print ('Local version: ' + str(page_version[filename]) + ' <-> online version: ' + str(page.version) + '. Overwrite? (y/n)') user_input = raw_input() if user_input == 'y': page.save(author='me', comment='', remote_addr='127.0.0.1') count_do = count_do + 1 print (filename + ' created/modified as wiki page from version ' + str(page_version[filename]) + ' to version ' + str(page.version)) page_version[filename] = page.version else: print 'Page not created/modified' count_no = count_no + 1 continue else: page.save(author='me', comment='', remote_addr='127.0.0.1') count_do = count_do + 1 print (filename + ' created/modified as wiki page from version ' + str(page_version[filename]) + ' to version ' + str(page.version)) page_version[filename] = page.version except: count_no = count_no + 1 print (filename + ' not modified or changed; remained untouched') continue cont = str(count_do) + ' wiki pages created/modified and ' + str(count_no) + ' untouched' req.send_response(200) req.send_header('Content-Type', 'text/plain') req.send_header('Content-Length', len(cont)) req.end_headers() req.write(cont)
def test_upgrade_v1_to_current(self): # The initial db schema from r2963 - 02-Jan-2008 by Alec Thomas. schema = [ Table('votes', key=('resource', 'username', 'vote'))[Column('resource'), Column('username'), Column('vote', 'int'), ] ] self._schema_init(schema) # Populate tables with test data. cursor = self.db.cursor() cursor.executemany( """ INSERT INTO votes (resource,username,vote) VALUES (%s,%s,%s) """, (('ticket/1', 'user', -1), ('ticket/2', 'user', 1), ('wiki/DeletedPage', 'user', -1), ('wiki/ExistingPage', 'user', 1))) # Resources must exist for successful data migration. t = Ticket(self.env, db=self.db) t['summary'] = 'test ticket' t.insert() w = WikiPage(self.env, 'ExistingPage') w.text = 'content' w.save('author', 'comment', '::1') self._verify_schema_unregistered() self.assertEquals(1, self.votes.get_schema_version(self.db)) self.assertTrue(self.votes.environment_needs_upgrade(self.db)) # Data migration and registration of unversioned schema. self.votes.upgrade_environment(self.db) self._verify_curr_schema() cursor.execute('SELECT * FROM votes') votes = cursor.fetchall() t_votes = [ id for realm, id, ver, u, v, t, c in votes if realm == 'ticket' ] w_votes = [ id for realm, id, ver, u, v, t, c in votes if realm == 'wiki' ] self.assertTrue('1' in t_votes) if resource_check: self.assertFalse('2' in t_votes) self.assertFalse('DeletedPage' in w_votes) self.assertTrue('ExistingPage' in w_votes)
def _do_rename(self, req, page): if page.readonly: req.perm(page.resource).require('WIKI_ADMIN') else: req.perm(page.resource).require('WIKI_RENAME') if 'cancel' in req.args: req.redirect(get_resource_url(self.env, page.resource, req.href)) old_name, old_version = page.name, page.version new_name = req.args.get('new_name', '') new_name = re.sub(r'/{2,}', '/', new_name.strip('/')) redirect = req.args.get('redirect') # verify input parameters warn = None if not new_name: warn = _("A new name is mandatory for a rename.") elif not validate_page_name(new_name): warn = _("The new name is invalid (a name which is separated " "with slashes cannot be '.' or '..').") elif new_name == old_name: warn = _("The new name must be different from the old name.") elif WikiPage(self.env, new_name).exists: warn = _("The page %(name)s already exists.", name=new_name) if warn: add_warning(req, warn) return self._render_confirm_rename(req, page, new_name) with self.env.db_transaction as db: page.rename(new_name) if redirect: redirection = WikiPage(self.env, old_name, db=db) redirection.text = _('See [wiki:"%(name)s"].', name=new_name) author = get_reporter_id(req) comment = u'[wiki:"%s@%d" %s] \u2192 [wiki:"%s"].' % ( new_name, old_version, old_name, new_name) redirection.save(author, comment, req.remote_addr) add_notice(req, _("The page %(old_name)s has been renamed to " "%(new_name)s.", old_name=old_name, new_name=new_name)) if redirect: add_notice(req, _("The page %(old_name)s has been recreated " "with a redirect to %(new_name)s.", old_name=old_name, new_name=new_name)) req.redirect(req.href.wiki(old_name if redirect else new_name))
def putPage(self, req, pagename, content, attributes): """ writes the content of the page. """ page = WikiPage(self.env, pagename) if page.readonly: req.perm(page.resource).require("WIKI_ADMIN") elif not page.exists: req.perm(page.resource).require("WIKI_CREATE") else: req.perm(page.resource).require("WIKI_MODIFY") page.text = content if req.perm(page.resource).has_permission("WIKI_ADMIN"): page.readonly = attributes.get("readonly") and 1 or 0 page.save(attributes.get("author", req.authname), attributes.get("comment"), req.remote_addr) return True
def setUp(self): self.env = EnvironmentStub() self.env.path = tempfile.mkdtemp(prefix='trac-tempenv-') self.tmpdir = os.path.join(self.env.path, 'tmp') os.mkdir(self.tmpdir) self.filename = os.path.join(self.tmpdir, 'file.txt') create_file(self.filename, self.page_text) self.admin = WikiAdmin(self.env) with self.env.db_transaction: for name, readonly in (('WritablePage', [0, 1, 0]), ('ReadOnlyPage', [1, 0, 1, 0, 1])): for r in readonly: page = WikiPage(self.env, name) page.text = '[wiki:%s@%d]' % (name, page.version + 1) page.readonly = r page.save('trac', '')
def putPage(self, req, pagename, content, attributes): """ writes the content of the page. """ page = WikiPage(self.env, pagename) if page.readonly: req.perm(page.resource).require('WIKI_ADMIN') elif not page.exists: req.perm(page.resource).require('WIKI_CREATE') else: req.perm(page.resource).require('WIKI_MODIFY') page.text = content if req.perm(page.resource).has_permission('WIKI_ADMIN'): page.readonly = attributes.get('readonly') and 1 or 0 page.save(attributes.get('author', req.authname), attributes.get('comment'), req.remote_addr) return True
def process_request(self, req): pagename = req.args.get('page', '') template = req.args.get('template', '') assert pagename, "Must specify a page name" if pagename.endswith('/'): req.redirect(req.href.newpage(pagename.strip('/'))) page = WikiPage(self.env, pagename) template_page = WikiPage(self.env, WikiModule.PAGE_TEMPLATES_PREFIX + template) fields = self._find_fields(template_page.text) #If page already exists, tell it if page.version != 0: add_warning(req, "Page %s already exists" % pagename) req.perm(page.resource).require('WIKI_MODIFY') else: req.perm.require('WIKI_CREATE') #Add wiki styles css add_stylesheet(req, 'common/css/wiki.css') data = { 'template_page': template_page, 'template': template, 'page': page, 'fields': fields } #Template has no fields? if len(fields) == 0: if page.version == 0 and template: req.redirect( req.href.wiki(page.name, action='edit', template=template)) else: req.redirect(req.href.wiki(page.name)) elif req.method == 'POST': page.text = self._replace_fields(fields, template_page.text, req) page.save(req.authname, 'New page from template %s' % template, req.remote_addr) req.redirect(req.href.wiki(page.name)) else: return 'newpage.html', data, None
def putPage(self, req, pagename, content, attributes): """ writes the content of the page. """ page = WikiPage(self.env, pagename) if page.readonly: req.perm.assert_permission('WIKI_ADMIN') elif not page.exists: req.perm.assert_permission('WIKI_CREATE') else: req.perm.assert_permission('WIKI_MODIFY') page.text = content if req.perm.has_permission('WIKI_ADMIN'): page.readonly = attributes.get('readonly') and 1 or 0 page.save(attributes.get('author', req.authname), attributes.get('comment'), req.remote_addr) return True
def wiki_setup(tc): tc.env = EnvironmentStub(default_data=True, enable=['trac.*', 'tractags.*']) tc.env.path = tempfile.mkdtemp() tc.db_mgr = DatabaseManager(tc.env) tc.db = tc.env.get_db_cnx() cursor = tc.db.cursor() cursor.execute("DROP TABLE IF EXISTS tags") cursor.execute("DROP TABLE IF EXISTS tags_change") cursor.execute("DELETE FROM system WHERE name='tags_version'") cursor.execute("DELETE FROM permission WHERE action %s" % tc.db.like(), ('TAGS_%',)) TagSetup(tc.env).upgrade_environment(tc.db) now = datetime.now(utc) wiki = WikiPage(tc.env) wiki.name = 'TestPage' wiki.text = '--' wiki.save('joe', 'TagsPluginTestPage', '::1', now) cursor = tc.db.cursor() # Populate table with initial test data. cursor.executemany(""" INSERT INTO tags (tagspace, name, tag) VALUES (%s,%s,%s) """, [('wiki', 'TestPage', '2ndtag'), ('wiki', 'TestPage', 'a.really?_\wild-thing'), ('wiki', 'TestPage', 'heavily-quoted'), ('wiki', 'TestPage', 'onetag'), ('wiki', 'TestPage', 'tagged'), ('wiki', 'TestPage', "single'quote"), ]) req = Mock(href=Href('/'), abs_href=Href('http://www.example.com/'), authname='anonymous', perm=MockPerm(), tz=utc, args={}, locale=locale_en) tc.env.href = req.href tc.env.abs_href = req.abs_href tc.context = Context.from_request(req) # Enable big diff output. tc.maxDiff = None
def test_upgrade_v1_to_current(self): # The initial db schema from r2963 - 02-Jan-2008 by Alec Thomas. schema = [ Table('votes', key=('resource', 'username', 'vote'))[ Column('resource'), Column('username'), Column('vote', 'int'), ] ] self._schema_init(schema) # Populate tables with test data. cursor = self.db.cursor() cursor.executemany(""" INSERT INTO votes (resource,username,vote) VALUES (%s,%s,%s) """, (('ticket/1','user',-1), ('ticket/2','user',1), ('wiki/DeletedPage','user',-1), ('wiki/ExistingPage','user',1))) # Resources must exist for successful data migration. t = Ticket(self.env, db=self.db) t['summary'] = 'test ticket' t.insert() w = WikiPage(self.env, 'ExistingPage') w.text = 'content' w.save('author', 'comment', '::1') self._verify_schema_unregistered() self.assertEquals(1, self.votes.get_schema_version(self.db)) self.assertTrue(self.votes.environment_needs_upgrade(self.db)) # Data migration and registration of unversioned schema. self.votes.upgrade_environment(self.db) self._verify_curr_schema() cursor.execute('SELECT * FROM votes') votes = cursor.fetchall() t_votes = [id for realm,id,ver,u,v,t,c in votes if realm == 'ticket'] w_votes = [id for realm,id,ver,u,v,t,c in votes if realm == 'wiki'] self.assertTrue('1' in t_votes) if resource_check: self.assertFalse('2' in t_votes) self.assertFalse('DeletedPage' in w_votes) self.assertTrue('ExistingPage' in w_votes)
def test_wiki_page_path(self): for name in ('WikiStart', 'Page', 'Page/SubPage'): page = WikiPage(self.env) page.name = name page.text = 'Contents for %s\n' % name page.save('trac', 'create page') def get_pagepath(path_info): content = self._render_wiki_page(path_info) match = re.search(r'<div\s+id="pagepath"[^>]*>.*?</div>', content, re.DOTALL) return match and match.group(0) pagepath = get_pagepath('/wiki') self.assertIn(' href="/trac.cgi/wiki">wiki:</a>', pagepath) self.assertIn(' href="/trac.cgi/wiki/WikiStart"', pagepath) pagepath = get_pagepath('/wiki/Page') self.assertIn(' href="/trac.cgi/wiki">wiki:</a>', pagepath) self.assertIn(' href="/trac.cgi/wiki/Page"', pagepath) pagepath = get_pagepath('/wiki/Page/SubPage') self.assertIn(' href="/trac.cgi/wiki">wiki:</a>', pagepath) self.assertIn(' href="/trac.cgi/wiki/Page"', pagepath) self.assertIn(' href="/trac.cgi/wiki/Page/SubPage"', pagepath)
def _render_editor(self, req, page, action='edit', has_collision=False): if has_collision: if action == 'merge': page = WikiPage(self.env, page.name, version=None) req.perm(page.resource).require('WIKI_VIEW') else: action = 'collision' if page.readonly: req.perm(page.resource).require('WIKI_ADMIN') else: req.perm(page.resource).require('WIKI_MODIFY') original_text = page.text if 'text' in req.args: page.text = req.args.get('text') elif 'template' in req.args: template = self.PAGE_TEMPLATES_PREFIX + req.args.get('template') template_page = WikiPage(self.env, template) if template_page and template_page.exists and \ 'WIKI_VIEW' in req.perm(template_page.resource): page.text = template_page.text if action in ('preview', 'diff'): page.readonly = 'readonly' in req.args author = get_reporter_id(req, 'author') comment = req.args.get('comment', '') defaults = {'editrows': 20} prefs = dict((key, req.session.get('wiki_%s' % key, defaults.get(key))) for key in ('editrows', 'sidebyside')) if 'from_editor' in req.args: sidebyside = req.args.get('sidebyside') or None if sidebyside != prefs['sidebyside']: if sidebyside: req.session['wiki_sidebyside'] = '1' else: del req.session['wiki_sidebyside'] else: sidebyside = prefs['sidebyside'] if sidebyside: editrows = max(int(prefs['editrows']), len(page.text.splitlines()) + 1) else: editrows = req.args.get('editrows') if editrows: if editrows != prefs['editrows']: req.session['wiki_editrows'] = editrows else: editrows = prefs['editrows'] data = self._page_data(req, page, action) context = web_context(req, page.resource) data.update({ 'author': author, 'comment': comment, 'edit_rows': editrows, 'sidebyside': sidebyside, 'scroll_bar_pos': req.args.get('scroll_bar_pos', ''), 'diff': None, 'attachments': AttachmentModule(self.env).attachment_data(context), }) if action in ('diff', 'merge'): old_text = original_text.splitlines() if original_text else [] new_text = page.text.splitlines() if page.text else [] diff_data, changes = self._prepare_diff( req, page, old_text, new_text, page.version, '') data.update({'diff': diff_data, 'changes': changes, 'action': 'preview', 'merge': action == 'merge', 'longcol': 'Version', 'shortcol': 'v'}) elif sidebyside and action != 'collision': data['action'] = 'preview' self._wiki_ctxtnav(req, page) Chrome(self.env).add_wiki_toolbars(req) Chrome(self.env).add_auto_preview(req) add_script(req, 'common/js/folding.js') return 'wiki_edit.html', data, None
def read_file(name): text[name] = file("wiki/" + name).read().decode('utf-8') page = WikiPage(env) page.name = name page.text = '--' page.save('', '', '::1', 0)
def wiki_setup(tc): tc.env.config.set('wiki', 'render_unsafe_content', True) # for #9712 now = datetime_now(utc) wiki0 = WikiPage(tc.env) wiki0.name = 'Main/Sub' wiki0.text = '--' wiki0.save('joe', 'subpage', now) wiki1 = WikiPage(tc.env) wiki1.name = 'TestPage' wiki1.text = '--' wiki1.save('joe', 'normal WikiPageNames', now) wiki2 = WikiPage(tc.env) wiki2.name = 'Space 1 23' wiki2.text = '--' wiki2.save('joe', 'not a WikiPageNames', now) wiki3 = WikiPage(tc.env) wiki3.name = u"C'est l'\xe9t\xe9" wiki3.text = '--' wiki3.save('joe', 'unicode WikiPageNames', now) imt = WikiPage(tc.env) imt.name = u"InterMapTxt" imt.text = """ This is the InterMapTxt ---- {{{ MeatBall http://www.usemod.com/cgi-bin/mb.pl? # $1 in MeatBall... tsvn tsvn: complex http://server/$1/page/$2?format=txt # resource $2 in $1 over http://unused/? # Overridden in trac.ini js javascript: javasc javasc }}} ---- {{{ nolink http://noweb }}} """ imt.save('joe', 'test InterWiki links', now) tc.env.config.set('interwiki', 'inter', 'http://inter/$1/page/$2 Resource $2 in $1') tc.env.config.set('interwiki', 'over', 'http://over/$1/page/$2') w = WikiPage(tc.env) w.name = 'FirstLevel' w.text = '--' w.save('joe', 'first level of hierarchy', now) w = WikiPage(tc.env) w.name = 'FirstLevel/SecondLevel' w.text = '--' w.save('joe', 'second level of hierarchy', now) w = WikiPage(tc.env) w.name = 'FirstLevel/SecondLevel/ThirdLevel' w.text = '--' w.save('joe', 'third level of hierarchy', now) w = WikiPage(tc.env) w.name = 'FirstLevel/SecondLevel/OtherThirdLevel' w.text = '--' w.save('joe', 'other third level of hierarchy', now) tc.env.db_transaction("INSERT INTO ticket (id) VALUES ('123')")
def _render_editor(self, req, page, action='edit', has_collision=False): if has_collision: if action == 'merge': page = WikiPage(self.env, page.name) req.perm(page.resource).require('WIKI_VIEW') else: action = 'collision' if not page.exists: req.perm(page.resource).require('WIKI_CREATE') else: req.perm(page.resource).require('WIKI_MODIFY') original_text = page.text comment = req.args.get('comment', '') if 'text' in req.args: page.text = req.args.get('text') elif 'template' in req.args: template = req.args.get('template') template = template[1:] if template.startswith('/') \ else self.PAGE_TEMPLATES_PREFIX + template template_page = WikiPage(self.env, template) if template_page and template_page.exists and \ 'WIKI_VIEW' in req.perm(template_page.resource): page.text = template_page.text elif 'version' in req.args: version = None if req.args.get('version'): # Allow version to be empty version = req.args.as_int('version') if version is not None: old_page = WikiPage(self.env, page.name, version) req.perm(page.resource).require('WIKI_VIEW') page.text = old_page.text comment = _("Reverted to version %(version)s.", version=version) if action in ('preview', 'diff'): page.readonly = 'readonly' in req.args author = get_reporter_id(req, 'author') defaults = {'editrows': str(self.default_edit_area_height)} prefs = {key: req.session.get('wiki_%s' % key, defaults.get(key)) for key in ('editrows', 'sidebyside')} if 'from_editor' in req.args: sidebyside = req.args.get('sidebyside') or None if sidebyside != prefs['sidebyside']: req.session.set('wiki_sidebyside', int(bool(sidebyside)), 0) else: sidebyside = prefs['sidebyside'] if sidebyside: editrows = max(int(prefs['editrows']), len(page.text.splitlines()) + 1) else: editrows = req.args.get('editrows') if editrows: if editrows != prefs['editrows']: req.session.set('wiki_editrows', editrows, defaults['editrows']) else: editrows = prefs['editrows'] data = self._page_data(req, page, action) context = web_context(req, page.resource) data.update({ 'context': context, 'author': author, 'comment': comment, 'edit_rows': editrows, 'sidebyside': sidebyside, 'scroll_bar_pos': req.args.get('scroll_bar_pos', ''), 'diff': None, 'attachments': AttachmentModule(self.env).attachment_data(context) }) if action in ('diff', 'merge'): old_text = original_text.splitlines() if original_text else [] new_text = page.text.splitlines() if page.text else [] diff_data, changes = self._prepare_diff( req, page, old_text, new_text, page.version, '') data.update({'diff': diff_data, 'changes': changes, 'action': 'preview', 'merge': action == 'merge', 'longcol': 'Version', 'shortcol': 'v'}) elif sidebyside and action != 'collision': data['action'] = 'preview' self._wiki_ctxtnav(req, page) Chrome(self.env).add_wiki_toolbars(req) Chrome(self.env).add_auto_preview(req) add_script(req, 'common/js/wiki.js') return 'wiki_edit.html', data
def process_request(self, req): action = req.args.get('action', 'view') pagename = req.args.get('page', self.START_PAGE) version = None if req.args.get('version'): # Allow version to be empty version = req.args.getint('version') old_version = req.args.getint('old_version') if pagename.startswith('/') or pagename.endswith('/') or \ '//' in pagename: pagename = re.sub(r'/{2,}', '/', pagename.strip('/')) req.redirect(req.href.wiki(pagename)) if not validate_page_name(pagename): raise TracError(_("Invalid Wiki page name '%(name)s'", name=pagename)) page = WikiPage(self.env, pagename) versioned_page = WikiPage(self.env, pagename, version) req.perm(versioned_page.resource).require('WIKI_VIEW') if version and versioned_page.version != version: raise ResourceNotFound( _('No version "%(num)s" for Wiki page "%(name)s"', num=version, name=page.name)) add_stylesheet(req, 'common/css/wiki.css') if req.method == 'POST': if action == 'edit': if 'cancel' in req.args: req.redirect(req.href.wiki(page.name)) has_collision = version != page.version for a in ('preview', 'diff', 'merge'): if a in req.args: action = a break versioned_page.text = req.args.get('text') valid = self._validate(req, versioned_page) if action == 'edit' and not has_collision and valid: return self._do_save(req, versioned_page) else: return self._render_editor(req, page, action, has_collision) elif action == 'edit_comment': self._do_edit_comment(req, versioned_page) elif action == 'delete': self._do_delete(req, versioned_page) elif action == 'rename': return self._do_rename(req, page) elif action == 'diff': style, options, diff_data = get_diff_options(req) contextall = diff_data['options']['contextall'] req.redirect(req.href.wiki(versioned_page.name, action='diff', old_version=old_version, version=version, contextall=contextall or None)) else: raise HTTPBadRequest(_("Invalid request arguments.")) elif action == 'delete': return self._render_confirm_delete(req, page) elif action == 'rename': return self._render_confirm_rename(req, page) elif action == 'edit': return self._render_editor(req, page) elif action == 'edit_comment': return self._render_edit_comment(req, versioned_page) elif action == 'diff': return self._render_diff(req, versioned_page) elif action == 'history': return self._render_history(req, versioned_page) else: format = req.args.get('format') if format: Mimeview(self.env).send_converted(req, 'text/x-trac-wiki', versioned_page.text, format, versioned_page.name) return self._render_view(req, versioned_page)