def _process_changes(self, req, protos, scm_type): scm_protos = dav_protos = set([]) allowed_scm_schemes = protos.allowed_protocols(scm_type) allowed_dav_schemes = protos.allowed_protocols('dav') if 'scm_proto' in req.args: scm_protos = set(self._to_list(req.args['scm_proto'])) if 'dav_proto' in req.args: dav_protos = set(self._to_list(req.args['dav_proto'])) if not self._validate(scm_protos, dav_protos): msg = 'Changes not stored, make sure that at least one protocol for each ' \ 'section is selected. If you want to disable any section, configure ' \ 'the appropriate permissions in the "Groups" page' add_warning(req, msg) return try: # Change scm protocols protos.disallow_protocols(allowed_scm_schemes - scm_protos, scm_type) protos.allow_protocols(scm_protos - allowed_scm_schemes, scm_type) # Change dav protocols protos.disallow_protocols(allowed_dav_schemes - dav_protos, 'dav') protos.allow_protocols(dav_protos - allowed_dav_schemes, 'dav') except: raise TracError("Server error. Try again later.") add_notice(req, "Changes saved")
def _select_login_action(self, req, remote_user): """ Select login action based on user status. - If user is expired, error msg is shown - If user is active, user will be logged in - If user is inactive, legal process is started - Otherwise user has no way of logging in (is banned or disabled) """ user_store = get_userstore() user = user_store.getUser(remote_user) if not user: # This may happen if authentication method is case-insensitive add_notice(req, _("Incorrect username or password - please try again")) return self._show_login(req) # Check if expired if user.expires and user.expires <= datetime.utcnow(): author = user_store.get_user_author(user) if author: add_warning(req, _('Account expired. Contact {0} for extension'.format(author.getDisplayName()))) else: add_warning(req, _('Account expired. Contact service support for extension')) return self._show_login(req) # User is authentic but can not log in before knowing he is not banned or disabled or activation required if user.status == user.STATUS_INACTIVE and self.env.config.getbool('multiproject', 'login_requires_agreed_terms'): return self._request_legal_approval(req, remote_user) if user.status in (user.STATUS_ACTIVE, user.STATUS_INACTIVE): return self._login_success(req, remote_user) add_warning(req, _("User status is '%s'. Can not log in." % user_store.USER_STATUS_LABELS[user.status])) return self._show_login(req)
def pre_process_request(self, req, handler): if req.path_info.startswith('/admin/ticket/components/'): if req.method == "POST" and 'renamechildren' in req.args: if req.args.get('renamechildren') != 'on': return handler # Let trac handle this update # First process the parent component. parentcomponentname = req.path_info[25:] parentcomponent = model.Component(self.env, parentcomponentname) parentcomponent.name = req.args.get('name') parentcomponent.owner = req.args.get('owner') parentcomponent.description = req.args.get('description') try: parentcomponent.update() except self.env.db_exc.IntegrityError: raise TracError(_('The component "%(name)s" already ' 'exists.', name=parentcomponentname)) # Now update the child components childcomponents = self._get_component_children(parentcomponentname) for component in childcomponents: component.name = component.name.replace(parentcomponentname, req.args.get('name'), 1) component.update() add_notice(req, _('Your changes have been saved.')) req.redirect(req.href.admin('ticket', 'components')) return handler
def _process_delete(self, req, ticket): reminder_id = req.args.get('reminder') redirect_url = get_resource_url(self.env, ticket.resource, req.href) with self.env.db_transaction as db: for reminder in db(""" SELECT id, time, author, origin, description FROM ticketreminder WHERE id=%s """, (reminder_id,)): break else: add_warning(req, "Could not find reminder to delete.") req.redirect(redirect_url) if req.method == "POST": db(""" DELETE FROM ticketreminder WHERE id=%s """, (reminder_id,)) if req.method == "POST": add_notice(req, "Reminder has been deleted.") req.redirect(redirect_url + "#reminders") kwargs = {'delete_button': False} data = { 'ticket': ticket, 'formatted_reminder': self._format_reminder(req, ticket, *reminder, **kwargs), } return "ticket_reminder_delete.html", data, None
def _add_ldap_group(self, req, group_store): req.perm.require("PERMISSION_GRANT") group_name = req.args.get("group") ldap_group_name = req.args.get("ldap_group", "").strip() ldap_group_name = ldap_group_name.upper() if re.search(r"[^\_A-Z0-9]", ldap_group_name): # allowed characters add_warning(req, "LDAP group name can contain only alphanumeric characters and underline.") return if not ldap_group_name: add_warning( req, _( "You are trying to add an LDAP group to a user group, " "but you have not specified all the required parameters." ), ) return group_store.add_ldapgroup_to_group(ldap_group_name, group_name) add_notice( req, _("LDAP group %(who)s has been added to group %(where)s.", who=ldap_group_name, where=group_name) )
def _do_save(self, req, user): """ Save ssh key into database """ if not req.args.get('ssh_key'): add_warning(req, _('Failed to add SSH key: Key is required')) return user ssh_key = req.args.get('ssh_key') ssh_key = SshKey.remove_comment_from_key_string(ssh_key) if not SshKey.validate_key_string(ssh_key): add_warning(req, _('Failed to add SSH key: invalid SSH key, key must be in open ssh format')) return user description = req.args.get('description') if len(description) > 200: add_warning(req, _('Failed to add SSH key: Too long description')) return user key_store = CQDESshKeyStore.instance() user_id = user.id if key_store.add_ssh_key(user_id, ssh_key, description): add_notice(req, _('New SSH key added (please allow 5 minutes for replication)')) return user add_warning(req, _('Failed to add SSH key: Server error')) return user
def save(self, req, id, fields=None, redirect=True): req.perm.require('CLOUD_MODIFY') self.log.debug('Saving data bag item %s/%s..' % (self.name,id)) item = self.chefapi.resource(self.crud_resource, id, self.name) # prepare modify data self.cloudapi.modify_rds_instance(id, allocated_storage = req.args.get('allocated_storage'), instance_class = req.args.get('instance_class'), multi_az = req.args.get('multi_az'), apply_immediately = req.args.get('cmd_apply_now')) # prepare fields; remove command fields if fields is None: fields = self.fields.get_list('crud_edit', filter=r"cmd_.*") for field in fields: field.set(item, req) item['multi_az'] = item['multi_az'] in ('1','true') item.save() self.log.info('Saved data bag item %s/%s' % (self.name,id)) if redirect: # show the view add_notice(req, _('%(label)s %(id)s has been saved.', label=self.label, id=id)) req.redirect(req.href.cloud(self.name, id))
def post_new_artifact(request, dbp, obj, resource): require_permission(request.req, resource, dbp.env, operation="CREATE") assert(obj is Instance or isinstance(obj, Entity)) # otherwise, we're trying to instantiate something that is not an artifact spec_name = request.req.args['spec'] if spec_name: try: dbp.load_spec(spec_name) spec = dbp.pool.get_item(spec_name) except ValueError: add_warning(request.req, "Spec '%s' not found, assumed an empty spec instead." % spec_name) spec = Instance else: spec = Instance values, str_attr = _group_artifact_values(request.req) brand_new_inst = spec(str_attr=str_attr, values=values) dbp.pool.add(brand_new_inst) dbp.save(get_reporter_id(request.req), 'comment', request.req.remote_addr) if request.get_format() == 'page': add_notice(request.req, 'Your changes have been saved.') url = request.req.href.customartifacts('artifact/%d' % (brand_new_inst.get_id(),), action='view', format=request.get_format()) request.req.redirect(url) else: import json url = request.req.href.customartifacts('artifact/%d' % (brand_new_inst.get_id(),), action='view') msg = json.dumps([{'result': 'success', 'resource_id': brand_new_inst.get_id(), 'resource_url': url}]) request.req.send_response(200) request.req.send_header('Content-Type', 'application/json') request.req.send_header('Content-Length', len(msg)) request.req.end_headers() request.req.write(msg)
def _do_account(self, req): assert(req.authname and req.authname != 'anonymous') action = req.args.get('action') delete_enabled = self.acctmgr.supports('delete_user') and \ self.acctmgr.allow_delete_account data = {'delete_enabled': delete_enabled, 'delete_msg_confirm': _( "Are you sure you want to delete your account?"), } force_change_password = req.session.get('force_change_passwd', False) if req.method == 'POST': if action == 'save': data.update(self._do_change_password(req)) if force_change_password: del(req.session['force_change_passwd']) req.session.save() chrome.add_notice(req, Markup(tag.span(tag_( "Thank you for taking the time to update your password." )))) force_change_password = False elif action == 'delete' and delete_enabled: data.update(self._do_delete(req)) else: data.update({'error': 'Invalid action'}) if force_change_password: chrome.add_warning(req, Markup(tag.span(_( "You are required to change password because of a recent " "password change request. "), tag.b(_("Please change your password now."))))) return data
def render_admin_panel(self, req, cat, page, version): self.log.debug("cat: %s page: %s", cat, page) req.perm.require('TRAC_ADMIN') options = ( 'api_base_url', 'api_token', 'room_id', 'only_owner_changed', 'notify_symbol', 'api_token_field_name') self.log.debug("method: %s", req.method) if req.method == 'POST': for option in options: self.config.set(SECTION_NAME, option, req.args.get(option)) try: self.config.save() self.log.debug('config saved.') add_notice(req, 'Your changes have been saved.') except Exception, e: self.log.error("Error writing to trac.ini: %s", exception_to_unicode(e)) add_warning(req, 'Error writing to trac.ini.') req.redirect(req.href.admin(cat, page))
def render_admin_panel(self, req, cat, page, svnhooks_name): req.perm.require('REPOSITORY_ADMIN') data = {} obj = SVNHooksModel(self.env) if req.method == 'POST': if req.args.get('add') : hook = req.args.get('hook').strip() path = req.args.get('path').strip() validate_path=obj.validate(path,hook) if validate_path > 0: add_warning(req,_('Already exists')) else: obj.insert( path, hook) add_notice(req, _('Added SVN hook "%s" for path :%s successfully' %(self._hooks_info()[hook], path))) elif req.args.get('remove'): sel = req.args.get('sel') if not sel: raise TracError(_('No hook selected')) if not isinstance(sel, list): sel = [sel] for id in sel: path, hook = obj.get_by_id(id) obj.delete(id) add_notice(req, _('Hooks "%s" for path :%s deleted successfully' %(self._hooks_info()[hook], path))) req.redirect(req.href.admin(cat, page)) add_stylesheet(req, 'svnhooks/css/svnhooks.css') add_javascript(req, 'svnhooks/js/svnhooks.js') data['svnhooks'] = obj.getall() data['svnhook_names'] = self._hooks_info(type='name') data['svnhook_descriptions'] = self._hooks_info(type='description') return 'admin-svnhooks.html', data
def save(self, req, id): req.perm.require('CLOUD_MODIFY') self.log.debug('Saving data bag item %s/%s..' % (self.name,id)) item = self.chefapi.resource(self.crud_resource, id, self.name) # check to attach and/or detach volume to/from instance(s) new_instance_id = req.args.get('instance_id','') if 'instance_id' not in item or item['instance_id'] != new_instance_id: # check if attaching or detaching if 'instance_id' in item and item['instance_id']: # detach req.args['status'] = self.cloudapi.detach_ebs_volume(id, item['instance_id'], item['device']) if new_instance_id: # attach req.args['status'] = self.cloudapi.attach_ebs_volume(id, new_instance_id, req.args.get('device','')) else: req.args['device'] = '' # prepare fields; remove command fields fields = self.fields.get_list('crud_edit', filter=r"cmd_.*") for field in fields: field.set(item, req) item.save() self.log.info('Saved data bag item %s/%s' % (self.name,id)) # show the view add_notice(req, _('%(label)s %(id)s has been saved.', label=self.label, id=id)) req.redirect(req.href.cloud(self.name, id))
def render_admin_panel(self, req, cat, page, path_info): wikipages = urllib.unquote_plus(req.args.get('wikipages','')); parts = wikipages.splitlines(); data = { 'find': urllib.unquote_plus(req.args.get('find','')), 'replace': urllib.unquote_plus(req.args.get('replace','')), 'wikipages': parts, 'redir': req.args.get('redirect','') == '1', } if req.method == 'POST': # Check that required fields are filled in. if not data['find']: add_warning(req, 'The Find field was empty. Nothing was changed.') if not data['wikipages'] or not data['wikipages'][0]: add_warning(req, 'The Wiki pages field was empty. Nothing was changed.') # Replace the text if the find and wikipages fields have been input. if data['find'] and data['wikipages'] and data['wikipages'][0]: add_notice(req, 'Replaced "%s" with "%s". See the timeline for modified pages.' % (data['find'], data['replace'])) wiki_text_replace(self.env, data['find'], data['replace'], data['wikipages'], req.authname, req.remote_addr, debug=self.log.debug) # Reset for the next display data['find'] = '' data['replace'] = '' data['wikipages'] = '' return 'admin_wikireplace.html', data
def _render_editor(self, req, milestone): # Suggest a default due time of 18:00 in the user's timezone now = datetime.now(req.tz) default_due = datetime(now.year, now.month, now.day, 18) if now.hour > 18: default_due += timedelta(days=1) default_due = to_datetime(default_due, req.tz) data = { 'milestone': milestone, 'datetime_hint': get_datetime_format_hint(req.lc_time), 'default_due': default_due, 'milestone_groups': [], } if milestone.exists: req.perm(milestone.resource).require('MILESTONE_MODIFY') milestones = [m for m in Milestone.select(self.env) if m.name != milestone.name and 'MILESTONE_VIEW' in req.perm(m.resource)] data['milestone_groups'] = group_milestones(milestones, 'TICKET_ADMIN' in req.perm) else: req.perm(milestone.resource).require('MILESTONE_CREATE') if milestone.name: add_notice(req, _("Milestone %(name)s does not exist. You can" " create it here.", name=milestone.name)) chrome = Chrome(self.env) chrome.add_jquery_ui(req) chrome.add_wiki_toolbars(req) return 'milestone_edit.html', data, None
def _do_config(self, req, category, page): parentpath = self.config.get('svnadmin', 'parent_path') client = self.config.get('svnadmin', 'svn_client_location') admin = self.config.get('svnadmin', 'svnadmin_location') hookspath = self.config.get('svnadmin', 'hooks_path') if req.method == 'POST' and req.args.get('save_settings'): parentpath = req.args.get('parentpath') client = req.args.get('client') admin = req.args.get('admin') hookspath = req.args.get('hookspath') self.config.set('svnadmin', 'parent_path', parentpath) self.config.set('svnadmin', 'svn_client_location', client) self.config.set('svnadmin', 'svnadmin_location', admin) self.config.set('svnadmin', 'hooks_path', hookspath) self.config.save() add_notice(req, _('The settings have been saved.')) data = { 'parentpath': parentpath, 'client': client, 'admin': admin, 'hookspath': hookspath } add_stylesheet(req, 'svnadmin/css/svnadmin.css') return 'config.html', data
def _do_save(self, req, user): """ Update user information into database """ userstore = get_userstore() if not req.args.get('mail'): add_warning(req, _('User should have an e-mail address')) return user user.mail = req.args.get('mail') if not req.args.get('lastName'): add_warning(req, _('Last name required')) return user # NOTE: Values are escaped in userstore update user.lastName = req.args.get('lastName') user.givenName = req.args.get('givenName') user.mobile = req.args.get('mobile') if userstore.updateUser(user): user = userstore.getUser(user.username) add_notice(req, _('Updated user settings')) if req.args.get('approve') == 'on' and user.status == user.STATUS_INACTIVE: user.activate() add_notice(req, _("Your account is now activated.")) return user add_warning(req, _('Failed to update user')) return user
def changePassword(self, req): userstore = get_userstore() user = userstore.getUser(req.authname) oldpw = req.args.get('oldpassword') newpw = req.args.get('newpassword') if not oldpw or not userstore.userExists(req.authname, oldpw): add_warning(req, _('Old password is invalid')) return user if not newpw or len(newpw) < 7: add_warning(req, _('New password should be at least 7 characters long')) return user if newpw != req.args.get('confirmpw'): add_warning(req, _('Passwords do not match')) return user if not userstore.updatePassword(user, newpw): add_warning(req, _('Failed to change the password')) return user add_notice(req, _('Password changed')) return user
def post_process_request(self, req, template, data, content_type): if template is None or not req.session.authenticated: # Don't start the email verification procedure on anonymous users. return template, data, content_type email = req.session.get('email') # Only send verification if the user entered an email address. if self.verify_email and self.email_enabled is True and email and \ email != req.session.get('email_verification_sent_to') and \ 'ACCTMGR_ADMIN' not in req.perm: req.session['email_verification_token'] = self._gen_token() req.session['email_verification_sent_to'] = email try: AccountManager(self.env)._notify( 'email_verification_requested', req.authname, req.session['email_verification_token'] ) except NotificationError, e: chrome.add_warning(req, _( "Error raised while sending a change notification." ) + _("You should report that issue to a Trac admin.")) self.log.error('Unable to send registration notification: %s', exception_to_unicode(e, traceback=True)) else: # TRANSLATOR: An email has been sent to <%(email)s> # with a token to ... (the link label for following message) link = tag.a(_("verify your new email address"), href=req.href.verify_email()) # TRANSLATOR: ... verify your new email address chrome.add_notice(req, tag_( "An email has been sent to <%(email)s> with a token to " "%(link)s.", email=tag(email), link=link))
def process_request(self, req): if not req.session.authenticated: chrome.add_warning(req, tag_( "Please log in to finish email verification procedure.")) req.redirect(req.href.login()) if 'email_verification_token' not in req.session: chrome.add_notice(req, _("Your email is already verified.")) elif req.method == 'POST' and 'resend' in req.args: try: AccountManager(self.env)._notify( 'email_verification_requested', req.authname, req.session['email_verification_token'] ) except NotificationError, e: chrome.add_warning(req, _("Error raised while sending a " "change notification.") + _( "You should " "report that issue to a Trac admin.")) self.log.error('Unable to send verification notification: %s', exception_to_unicode(e, traceback=True)) else: chrome.add_notice(req, _("A notification email has been " "resent to <%s>."), req.session.get('email'))
def post_process_request(self, req, template, data, content_type): if not req.session.authenticated: # Don't start the email verification procedure on anonymous users. return template, data, content_type email = req.session.get('email') # Only send verification if the user entered an email address. if self.verify_email and self.email_enabled is True and email and \ email != req.session.get('email_verification_sent_to') and \ not req.perm.has_permission('ACCTMGR_ADMIN'): req.session['email_verification_token'] = self._gen_token() req.session['email_verification_sent_to'] = email AccountManager(self.env)._notify( 'email_verification_requested', req.authname, req.session['email_verification_token'] ) # TRANSLATOR: An email has been sent to <%(email)s> # with a token to ... (the link label for following message) link = tag.a(_("verify your new email address"), href=req.href.verify_email() ) # TRANSLATOR: ... verify your new email address chrome.add_notice(req, Markup(tag.span(Markup(_( """An email has been sent to <%(email)s> with a token to %(link)s.""", email=email, link=link)))) ) return template, data, content_type
def render_module(self, req, cat, page, path_info): global db_conn testaction = test_action.TestAction(self.env, db_conn, req=req) templates = 'iTest_NewTest.html' if gl.gl_b_submittest in req.args \ or gl.gl_b_saveandstarttest in req.args: testtype = req.args.get(gl.gl_test_type_mode) if testtype == gl.gl_HSIT: testtype = gl.gl_psit name = req.args.get(gl.gl_name, '') name = utils.name_filter_dirty_symbol(self.env, str(name)) if testtype == gl.gl_rdit: rditPlatform = req.args.get('rditPlatform') pre_name = name if rditPlatform == 'T2W1' \ or rditPlatform == 'T2(9810)W1':#两个单子 #1-- 'W1' name = pre_name + '_' + 'W1' name += '_' + utils._get_current_time_str() ret = testaction.B_Save2start(req, testtype=testtype, name=name, rditPlatform=rditPlatform) #2-- 'W1' if rditPlatform == 'T2W1': name = pre_name + '_' + 'T2' name += '_' + utils._get_current_time_str() ret = testaction.B_Save2start(req, testtype=testtype, name=name, rditPlatform=rditPlatform) elif rditPlatform == 'T2(9810)W1': name = pre_name + '_' + 'T2_9810' name += '_' + utils._get_current_time_str() ret = testaction.B_Save2start(req, testtype=testtype, name=name, rditPlatform=rditPlatform) else:#单个 if rditPlatform == gl.gl_T2_9810: name += '_T2_9810' elif rditPlatform == gl.gl_T2_8810: name += '_T2_8810' elif rditPlatform == gl.gl_T2_8501c: name += '_T2_8501c' else: name += '_' + rditPlatform name += '_' + utils._get_current_time_str() ret = testaction.B_Save2start(req, testtype=testtype, name=name, rditPlatform=rditPlatform) else: time_string = utils.curtime_string() time_string = re.sub('[\D]', '', time_string) self.log.debug('NewTest: time_string,%s', time_string) name += '_' + time_string ret = testaction.B_Save2start(req, testtype=testtype, name=name) if ret == True: templates = 'iTest_Server_Manager.html' data = itest_mmi_data.iTest_Server_Manager(self.env, req) else: add_notice(req, "Error, Plz Check.") data = test_action.iTest_NewTest(self.env,req) elif gl.gl_b_uploadcaselist_txt in req.args: txt_file = test_action.iTest_UploadCaselist(self.env, req) data = test_action.iTest_NewTest(self.env, req, txt_file_name=txt_file) else: data = test_action.iTest_NewTest(self.env,req) return templates, data
def _do_change_password(self, req): username = req.authname old_password = req.args.get('old_password') if not self.acctmgr.check_password(username, old_password): if old_password: add_warning(req, _("Old password is incorrect.")) else: add_warning(req, _("Old password cannot be empty.")) return password = req.args.get('password') if not password: add_warning(req, _("Password cannot be empty.")) elif password != req.args.get('password_confirm'): add_warning(req, _("The passwords must match.")) elif password == old_password: add_warning(req, _("Password must not match old password.")) else: _set_password(self.env, req, username, password, old_password) if req.session.get('password') is not None: # Fetch all session_attributes in case new user password is in # SessionStore, preventing overwrite by session.save(). req.session.get_session(req.authname, authenticated=True) add_notice(req, _("Password updated successfully.")) return True
def _do_account(self, req): if not req.authname or req.authname == 'anonymous': req.redirect(req.href.wiki()) action = req.args.get('action') delete_enabled = AccountManager(self.env).supports('delete_user') data = {'delete_enabled': delete_enabled} force_change_password = req.session.get('force_change_passwd', False) if req.method == 'POST': if action == 'save': data.update(self._do_change_password(req)) if force_change_password: del(req.session['force_change_passwd']) req.session.save() chrome.add_notice(req, Markup(tag( "Thank you for taking the time to update your password." ))) force_change_password = False elif action == 'delete' and delete_enabled: data.update(self._do_delete(req)) else: data.update({'error': 'Invalid action'}) if force_change_password: chrome.add_warning(req, Markup(tag( "You are required to change password because of a recent " "password change request. ", tag.b("Please change your password now.")))) return data
def render_voter(self, req): resource = self.normalise_resource(req.path_info) vote = self.get_vote(req, resource) up = tag.img(src=req.href.chrome('vote/' + self.image_map[vote][0]), alt='Up-vote') down = tag.img(src=req.href.chrome('vote/' + self.image_map[vote][1]), alt='Down-vote') if 'VOTE_MODIFY' in req.perm and get_reporter_id(req) != 'anonymous': down = tag.a(down, id='downvote', href=req.href.vote('down', resource), title='Down-vote') up = tag.a(up, id='upvote', href=req.href.vote('up', resource), title='Up-vote') add_script(req, 'vote/js/tracvote.js') shown = req.session.get('shown_vote_message') if not shown: add_notice(req, 'You can vote for resources on this Trac ' 'install by clicking the up-vote/down-vote arrows ' 'in the context navigation bar.') req.session['shown_vote_message'] = '1' body, title = self.format_votes(resource) votes = tag.span(body, id='votes') add_stylesheet(req, 'vote/css/tracvote.css') elm = tag.span(up, votes, down, id='vote', title=title) req.chrome.setdefault('ctxtnav', []).insert(0, elm)
def post_process_request(self, req, template, data, content_type): if 'BLOG_VIEW' not in req.perm: return (template, data, content_type) if '_blog_watch_message_' in req.session: add_notice(req, req.session['_blog_watch_message_']) del req.session['_blog_watch_message_'] if req.authname == "anonymous": return (template, data, content_type) # FullBlogPlugin sets the blog_path arg in pre_process_request name = req.args.get('blog_path') if not name: return (template, data, content_type) klass = self.__class__.__name__ attrs = SubscriptionAttribute.find_by_sid_class_and_target( self.env, req.session.sid, req.session.authenticated, klass, name) if attrs: add_ctxtnav(req, tag.a(_('Unwatch This'), href=req.href.blog_watch(name))) else: add_ctxtnav(req, tag.a(_('Watch This'), href=req.href.blog_watch(name))) return (template, data, content_type)
def post_new_spec(request, dbp, obj, resource): require_permission(request.req, resource, dbp.env, operation="CREATE") if obj is Entity: # instantiating Entity (i.e., creating a spec) pass elif obj is Instance or isinstance(obj, Entity): # instantiating an existing spec return post_new_artifact(request.req, dbp, obj, resource) else: raise Exception("Trying to instantiate something that can't be instantiated '%s'" % (obj,)) name = request.req.args.get('name') parent_name = request.req.args.get('parent') attributes = [Attribute(n,m,t) for n,t,m in _group_spec_attributes(request.req)] if parent_name: dbp.load_spec(parent_name) bases = (dbp.pool.get_item(parent_name),) else: bases = tuple() brand_new_inst = Entity(name=name, attributes=attributes, bases=bases) dbp.pool.add(brand_new_inst) dbp.save(get_reporter_id(request.req), 'comment', request.req.remote_addr) add_notice(request.req, 'Your changes have been saved.') url = request.req.href.customartifacts('spec', brand_new_inst.get_name(), action='view') request.req.redirect(url)
def edit_category(self, req): req.perm.require('TRAC_ADMIN') category_id = req.args.get('edited_category_id', '') if category_id.isdigit(): category = self.categorystore.get_category_by_id(category_id) if not category_id or not category: add_warning(req, _('Invalid category id provided.')) return category_name = req.args.get('edited_category_name', '') category_description = req.args.get('edited_category_description', '') if len(category_description.split("#")) == 2: category_name = category_name + "#" + category_description.split("#")[1] if not category_name or not category_description: add_warning(req, _('Category name and description cannot be empty. "%s" "%s"'%(category_name, category_description))) return if category.name == category_name and category.description == category_description: add_warning(req, _('Category name and description are already as requested.')) return try: self.categorystore.edit_category(category.category_id, category_name, category_description) add_notice(req, _('Category has been edited.')) except Exception as e: add_warning(req, _('Category was not edited. ') + _(str(e)))
def _add_organization(self, req, group_store): req.perm.require("PERMISSION_GRANT") group_name = req.args.get("group") organization = req.args.get("organization") try: group_store.add_organization_to_group(organization, group_name) add_notice( req, _( "Organization %(organization)s added to group %(group)s", group=group_name, organization=organization, ), ) except ValueError: add_warning( req, _( "Organization %(organization)s already exists in group %(group)s", group=group_name, organization=organization, ), )
def _process_add(self, req, ticket): if req.method == "POST" and self._validate_add(req): if req.args.get('reminder_type') == 'interval': time = clear_time(to_datetime(None)) delta = _time_intervals[req.args.get('unit')](req.args.get('interval')) time += delta time = to_utimestamp(time) else: time = to_utimestamp(parse_date(req.args.get('date'))) origin = to_utimestamp(to_datetime(None)) self.env.db_transaction(""" INSERT INTO ticketreminder (ticket, time, author, origin, reminded, description) VALUES (%s, %s, %s, %s, 0, %s) """, (ticket.id, time, get_reporter_id(req, 'author'), origin, req.args.get('description'))) add_notice(req, "Reminder has been added.") req.redirect(get_resource_url(self.env, ticket.resource, req.href) + "#reminders") add_script(req, 'ticketreminder/js/ticketreminder.js') data = { 'ticket': ticket, 'date_hint': get_date_format_hint(), } return ("ticket_reminder_add.html", data, None)
def _do_delete(self, req, milestone): req.perm(milestone.resource).require('MILESTONE_DELETE') retarget_to = req.args.get('target') or None # Don't translate ticket comment (comment:40:ticket:5658) retargeted_tickets = \ milestone.move_tickets(retarget_to, req.authname, "Ticket retargeted after milestone deleted") milestone.delete(author=req.authname) add_notice(req, _('The milestone "%(name)s" has been deleted.', name=milestone.name)) if retargeted_tickets: add_notice(req, _('The tickets associated with milestone ' '"%(name)s" have been retargeted to milestone ' '"%(retarget)s".', name=milestone.name, retarget=retarget_to)) new_values = {'milestone': retarget_to} comment = _("Tickets retargeted after milestone deleted") tn = BatchTicketNotifyEmail(self.env) try: tn.notify(retargeted_tickets, new_values, comment, None, req.authname) except Exception, e: self.log.error("Failure sending notification on ticket batch " "change: %s", exception_to_unicode(e)) add_warning(req, tag_("The changes have been saved, but an " "error occurred while sending " "notifications: %(message)s", message=to_unicode(e)))
def remove_user(self, req): """ Show removal form and handle POST as remove action """ username = req.args.get('username') # Check method and permissions if not req.method.upper() == 'POST' or not username: raise PermissionError() # Load user userstore = get_userstore() user = userstore.getUser(req.authname) account = userstore.getUser(username) if not account: add_warning(req, "Could not find user '{0}' from service".format(account.username)) return req.redirect(req.href('admin/users/manage')) # Check permissions req.perm.require('USER_AUTHOR', Resource('user', id=account.id)) # If removable user is project author, change the ownership to person who deletes the user papi = projects.Projects() for project in papi.get_authored_projects(account): project.author = user project.save() # Check if user has TRAC_ADMIN rights for the new project, if not, try setting if not req.perm.has_permission('TRAC_ADMIN', Resource('project', id=project.id)): groupstore = CQDEUserGroupStore(project.trac_environment_key) # Iterate existing project groups and put user into group with TRAC_ADMIN rights for gname, pname in groupstore.get_all_group_permissions(): if pname == 'TRAC_ADMIN': groupstore.add_user_to_group(project.author.username, gname) self.log.info('Added TRAC_ADMIN permissions to {0} at {0}'.format(project.author, project)) self.log.info('Changed ownership of project {0} from {0} to {0}'.format(project, project.author, user)) add_notice(req, tag(_("Changed ownership of the project to you: "), tag.a(project.project_name, href=req.href('..', project.env_name)))) if userstore.deleteUser(account): add_notice(req, "Removed user '{0}' successfully from local store".format(account.username)) else: add_warning(req, "Failed to remove user '{0}' from local store".format(account.username)) # Redirect to user listing return req.redirect(req.href('admin/users/manage'))
def _render_settings(self, req, cat, page, component): req.perm.assert_permission('TRAC_ADMIN') data = {} try: if req.method == 'POST': default_days_back = req.args.get('default_days_back', '90') default_interval = req.args.get('default_interval', '7') testplan_sortby = req.args.get('testplan_sortby', 'name') open_new_window = req.args.get('open_new_window', 'False') testcatalog_default_view = req.args.get('testcatalog_default_view', 'tree') testplan_default_view = req.args.get('testplan_default_view', 'tree') self.env.config.set('testmanager', 'default_days_back', default_days_back) self.env.config.set('testmanager', 'default_interval', default_interval) self.env.config.set('testmanager', 'testplan.sortby', testplan_sortby) self.env.config.set('testmanager', 'testcase.open_new_window', ('False', 'True')[open_new_window == 'on']) self.env.config.set('testmanager', 'testcatalog.default_view', testcatalog_default_view) self.env.config.set('testmanager', 'testplan.default_view', testplan_default_view) _set_columns_visible(self.env, 'testcatalog', req.args, self.env.config) _set_columns_visible(self.env, 'testplan', req.args, self.env.config) _set_columns_total_operation(self.env, 'testcatalog', req.args, self.env.config) _set_columns_total_operation(self.env, 'testplan', req.args, self.env.config) self.env.config.save() add_notice(req, _("Settings saved")) except: self.env.log.error(formatExceptionInfo()) add_warning(req, _("Error saving the settings")) data['default_days_back'] = self.env.config.get('testmanager', 'default_days_back', '90') data['default_interval'] = self.env.config.get('testmanager', 'default_interval', '7') data['testplan_sortby'] = self.env.config.get('testmanager', 'testplan.sortby', 'name') data['open_new_window'] = self.env.config.get('testmanager', 'testcase.open_new_window', 'False') data['testcatalog_default_view'] = self.env.config.get('testmanager', 'testcatalog.default_view', 'tree') data['testplan_default_view'] = self.env.config.get('testmanager', 'testplan.default_view', 'tree') testcatalog_columns, foo, bar = get_all_table_columns_for_object(self.env, 'testcatalog', self.env.config) testplan_columns, foo, bar = get_all_table_columns_for_object(self.env, 'testplan', self.env.config) data['testcatalog_columns'] = testcatalog_columns data['testplan_columns'] = testplan_columns return 'admin_settings.html', data
def install_workflow_controller(self, req): """Set MultipleWorkflowPlugin as the current workflow controller in trac.ini. Note that the current setting will be replaced and saved using the key 'workflow_mwf_install'. If you want to use several workflow controllers at the same time you have to create a list on your own. A notice will be shown to the user on success. """ save_key = 'workflow_mwf_install' # key in section [ticket] to keep the previous setting prev_controller = self.config.get('ticket', 'workflow', '') self.config.set('ticket', 'workflow', 'MultipleWorkflowPlugin') self.config.set('ticket', save_key, prev_controller) self.config.save() add_notice(req, Markup(_(u'Workflow controller installed by setting <em>workflow=MultipleWorkflowPlugin</em> ' u'in section <em>[ticket]</em>.'))) add_notice(req, Markup(_(u'Previous workflow controller was saved as ' u'<em>%s=%s</em> in section <em>[ticket]</em>.') % (save_key, prev_controller)))
def _save_config(config, req, log, notices=None): """Try to save the config, and display either a success notice or a failure warning. """ try: config.save() if notices is None: notices = [_("Your changes have been saved.")] for notice in notices: add_notice(req, notice) except Exception as e: log.error("Error writing to trac.ini: %s", exception_to_unicode(e)) add_warning( req, _("Error writing to trac.ini, make sure it is " "writable by the web server. Your changes have " "not been saved."))
def _do_save(self, req): for field in self._form_fields: val = req.args.get(field, '').strip() if val: if field == 'tz' and 'tz' in req.session and \ val not in all_timezones: del req.session['tz'] elif field == 'newsid': req.session.change_sid(val) elif field == 'accesskeys': req.session[field] = '1' else: req.session[field] = val elif field in req.session and (field in req.args or field + '_cb' in req.args): del req.session[field] add_notice(req, _('Your preferences have been saved.'))
def post_edit_artifact(request, dbp, obj, resource): require_permission(request.req, resource, dbp.env, operation="MODIFY") assert ( isinstance(obj, Instance) ) # otherwise, we're trying to edit something that is not an artifact spec_name = request.req.args['spec'] if spec_name: try: dbp.load_spec(spec_name) spec = dbp.pool.get_item(spec_name) except ValueError: add_warning( request.req, "Type '%s' not found, assumed an empty type instead." % spec_name) spec = Instance else: spec = Instance obj.__class__ = spec values, str_attr = _group_artifact_values(request.req) obj.replace_values(values) obj.str_attr = str_attr if not str_attr is None else 'id' dbp.save(get_reporter_id(request.req), 'comment', request.req.remote_addr) url = request.req.href.customartifacts('artifact/%s' % (obj.get_id(), ), action='view') if request.get_format() == 'page': add_notice(request.req, 'Your changes have been saved.') request.req.redirect(url) else: import json msg = json.dumps([{ 'result': 'success', 'resource_id': obj.get_id(), 'resource_url': url }]) request.req.send_response(200) request.req.send_header('Content-Type', 'application/json') request.req.send_header('Content-Length', len(msg)) request.req.end_headers() request.req.write(msg)
def _do_create(self, req): req.perm.require('REPORT_CREATE') if 'cancel' in req.args: req.redirect(req.href.report()) title = req.args.get('title', '') query = req.args.get('query', '') description = req.args.get('description', '') with self.env.db_transaction as db: cursor = db.cursor() cursor.execute(""" INSERT INTO report (title,query,description) VALUES (%s,%s,%s) """, (title, query, description)) report_id = db.get_last_id(cursor, 'report') add_notice(req, _("The report has been created.")) req.redirect(req.href.report(report_id))
def _do_edit_comment(self, req, page): req.perm(page.resource).require('WIKI_ADMIN') if 'cancel' in req.args: req.redirect(req.href.wiki(page.name, action='history')) new_comment = req.args.get('new_comment') page.edit_comment(new_comment) add_notice( req, _( "The comment of version %(version)s of the page " "%(name)s has been updated.", version=page.version, name=page.name)) req.redirect(req.href.wiki(page.name, action='history'))
def _render_editor(self, req, milestone): # Suggest a default due time of 18:00 in the user's timezone now = datetime.now(req.tz) default_due = datetime(now.year, now.month, now.day, 18) if now.hour > 18: default_due += timedelta(days=1) default_due = to_datetime(default_due, req.tz) data = { 'milestone': milestone, 'datetime_hint': get_datetime_format_hint(req.lc_time), 'default_due': default_due, 'milestone_groups': [], } if milestone.exists: req.perm(milestone.resource).require('MILESTONE_MODIFY') milestones = [ m for m in Milestone.select(self.env) if m.name != milestone.name and 'MILESTONE_VIEW' in req.perm(m.resource) ] num_tickets = self.env.db_query( """ SELECT COUNT(*) FROM ticket WHERE milestone=%s""", (milestone.name, ))[0][0] data['milestone_groups'] = group_milestones( milestones, 'TICKET_ADMIN' in req.perm) data['num_tickets'] = num_tickets data['retarget_to'] = self.default_retarget_to else: req.perm(milestone.resource).require('MILESTONE_CREATE') if milestone.name: add_notice( req, _( "Milestone %(name)s does not exist. You can" " create it here.", name=milestone.name)) chrome = Chrome(self.env) chrome.add_jquery_ui(req) chrome.add_wiki_toolbars(req) add_stylesheet(req, 'common/css/roadmap.css') return 'milestone_edit.html', data, None
def _do_rename(self, req, page): 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) 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) 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 render_preference_panel(self, req, panel): styles = list(get_all_styles()) if req.method == 'POST': style = req.args.get('style') if style and style in styles: req.session['pygments_style'] = style add_notice(req, _("Your preferences have been saved.")) req.redirect(req.href.prefs(panel or None)) for style in sorted(styles): add_stylesheet(req, '/pygments/%s.css' % style, title=style.title()) output = self._generate('html', self.EXAMPLE) return 'prefs_pygments.html', { 'output': output, 'selection': req.session.get('pygments_style', self.default_style), 'styles': styles }
def pre_process_request(self, req, handler): from trac.wiki.web_ui import WikiModule if isinstance(handler, WikiModule): path = req.path_info args = req.args if not (req.method == 'GET'): self.env.log.debug('Hacks: no notice: no GET request') elif not (path.startswith('/wiki/') or path == '/wiki'): self.env.log.debug('Hacks: no notice: not a wiki path') elif not args.has_key('hack'): self.env.log.debug('Hacks: no notice: hack= missing') elif args['hack'] != 'created': self.env.log.debug('Hacks: no notice: hack=%s' % args['hack']) else: self.env.log.debug('Hacks: notice added') add_notice(req, 'Your hack has been created successfully.') return handler
def _find_or_create_session(self, req, id_token): """ Find or create authenticated session for subject. """ userdb = self.userdb authname = userdb.find_session(id_token) if not authname: # There is no authenticated session for the user, # create a new one # XXX: should it be configurable whether this happens? authname = userdb.create_session(id_token) add_notice( req, _( "Hello! You appear to be new here. " "A new authenticated session with " "username '%(authname)s' has been created for you.", authname=authname)) return authname
def _do_deletes(self, req, user): """ Delete ssh key from database """ key_store = CQDESshKeyStore.instance() user_id = user.id key_ids = req.args.get('deletelist') key_ids = isinstance(key_ids, list) and key_ids or [key_ids] for key_id in key_ids: if key_id: if key_store.remove_ssh_key(user_id, key_id): add_notice(req, _('SSH key deleted')) else: add_warning(req, _('Failed to delete SSH key: Server error.')) return user
def merge_to_category(self, req): req.perm.require('TRAC_ADMIN') # possible params involved in req: target_category_name, target_category_id target_category = self._translate_req_to_category(req, 'target') # possible params involved in req: merged_category_id, merged_category_name merged_category = self._translate_req_to_category(req, 'merged') if not target_category or not merged_category: add_warning(req, _('Invalid merge category parameters: No corresponding category found.')) return try: self.categorystore.merge_category_to_category(merged_category.category_id, target_category.category_id) add_notice(req, _('Category %(merged)s has been merged to %(target)s.', merged = merged_category.name, target = target_category.name)) except Exception as e: add_warning(req, _('Category %(what)s was not merged. ', what=merged_category.name) + _(str(e)))
def _add_organization(self, req, group_store): req.perm.require('PERMISSION_GRANT') group_name = req.args.get('group') organization = req.args.get('organization') try: group_store.add_organization_to_group(organization, group_name) add_notice( req, _('Organization %(organization)s added to group %(group)s', group=group_name, organization=organization)) except ValueError: add_warning( req, _('Organization %(organization)s already exists in group %(group)s', group=group_name, organization=organization))
def _do_save(self, req, id): """Save report changes to the database""" req.perm.require('REPORT_MODIFY') if 'cancel' not in req.args: title = req.args.get('title', '') query = req.args.get('query', '') description = req.args.get('description', '') @self.env.with_transaction() def do_save(db): cursor = db.cursor() cursor.execute( "UPDATE report " "SET title=%s,query=%s,description=%s " "WHERE id=%s", (title, query, description, id)) add_notice(req, _('Your changes have been saved.')) req.redirect(req.href.report(id))
def _reset_password(self, req, username, email): acctmgr = self.acctmgr new_password = self._random_password try: self.store.set_password(username, new_password) acctmgr._notify('password_reset', username, email, new_password) # No message, if method has been called from user admin panel. if not req.path_info.startswith('/admin'): add_notice( req, _("A new password has been sent to you at " "<%(email)s>.", email=email)) except Exception, e: add_warning( req, _("Cannot reset password: %(error)s", error=', '.join(map(to_unicode, e.args)))) return
def _upload_request(self, req, handler): self.log.debug('Handling file upload for "%s"', req.authname) # Retrieve uploaded file upload_file = req.args['bsop_upload_file'] # Retrieve filename, normalize, use to check a file was uploaded # Filename checks adapted from trac/attachment.py filename = getattr(upload_file, 'filename', '') filename = unicodedata.normalize('NFC', unicode(filename, 'utf-8')) filename = filename.replace('\\', '/').replace(':', '/') filename = posixpath.basename(filename) if not filename: raise TracError('No file uploaded') # Check size of uploaded file, accepting 0 to max_upload_size bytes file_data = upload_file.value # Alternatively .file for file object file_size = len(file_data) if self.max_upload_size > 0 and file_size > self.max_upload_size: raise TracError('Uploaded file is too large, ' 'maximum upload size: %s' % pretty_size(self.max_upload_size)) self.log.debug('Received file %s with %i bytes', filename, file_size) commit_msg = req.args.get('bsop_upload_commit') self.log.debug('Opening repository for file upload') reponame, repos, path = _get_repository(self.env, req) try: repos_path = repos.normalize_path('/'.join([path, filename])) self.log.debug('Writing file %s to %s in %s', filename, repos_path, reponame) svn_writer = SubversionWriter(self.env, repos, req.authname) rev = svn_writer.put_content(repos_path, file_data, commit_msg) add_notice( req, _("Uploaded %s, creating revision %s.") % (filename, rev)) except Exception, e: self.log.exception("Failed when uploading file %s" % filename) add_warning(req, _("Failed to upload file: %s") % e)
def _do_delete(self, req, milestone): req.perm(milestone.resource).require('MILESTONE_DELETE') retarget_to = req.args.get('target') or None # Don't translate ticket comment (comment:40:ticket:5658) retargeted_tickets = \ milestone.move_tickets(retarget_to, req.authname, "Ticket retargeted after milestone deleted") milestone.delete() add_notice( req, _('The milestone "%(name)s" has been deleted.', name=milestone.name)) if retargeted_tickets: add_notice( req, _( 'The tickets associated with milestone ' '"%(name)s" have been retargeted to milestone ' '"%(retarget)s".', name=milestone.name, retarget=retarget_to)) new_values = {'milestone': retarget_to} comment = _("Tickets retargeted after milestone deleted") event = BatchTicketChangeEvent(retargeted_tickets, None, req.authname, comment, new_values, None) try: NotificationSystem(self.env).notify(event) except Exception as e: self.log.error( "Failure sending notification on ticket batch " "change: %s", exception_to_unicode(e)) add_warning( req, tag_( "The changes have been saved, but an " "error occurred while sending " "notifications: %(message)s", message=to_unicode(e))) req.redirect(req.href.roadmap())
def _save_config(self, req, notices=None): """Try to save the config, and display either a success notice or a failure warning. """ try: self.cronconf.save() if notices is None: notices = [_('Your changes have been saved.')] for notice in notices: add_notice(req, notice) except Exception, e: self.env.log.error('Error writing to trac.ini: %s', exception_to_unicode(e)) add_warning( req, _('Error writing to trac.ini, make sure it is ' 'writable by the web server. Your changes have ' 'not been saved.'))
def _do_edit_comment(self, req, page): req.perm(page.resource).require('WIKI_ADMIN') redirect_to = req.args.get('redirect_to') version = old_version = None if redirect_to == 'diff': version = page.version old_version = version - 1 redirect_href = req.href.wiki(page.name, action=redirect_to, version=version, old_version=old_version) if 'cancel' in req.args: req.redirect(redirect_href) new_comment = req.args.get('new_comment') page.edit_comment(new_comment) add_notice(req, _("The comment of version %(version)s of the page " "%(name)s has been updated.", version=page.version, name=page.name)) req.redirect(redirect_href)
def render_admin_panel(self, req, cat, page, path_info): wikipages = urllib.unquote_plus(req.args.get('wikipages', '')) parts = wikipages.splitlines() data = { 'find': urllib.unquote_plus(req.args.get('find', '')), 'replace': urllib.unquote_plus(req.args.get('replace', '')), 'wikipages': parts, 'redir': req.args.get('redirect', '') == '1', } if req.method == 'POST': # Check that required fields are filled in. if not data['find']: add_warning(req, 'The Find field was empty. Nothing was changed.') if not data['wikipages'] or not data['wikipages'][0]: add_warning( req, 'The Wiki pages field was empty. Nothing was changed.') # Replace the text if the find and wikipages fields have been input. if data['find'] and data['wikipages'] and data['wikipages'][0]: add_notice( req, 'Replaced "%s" with "%s". See the timeline for modified pages.' % (data['find'], data['replace'])) wiki_text_replace(self.env, data['find'], data['replace'], data['wikipages'], req.authname, req.remote_addr, debug=self.log.debug) # Reset for the next display data['find'] = '' data['replace'] = '' data['wikipages'] = '' return 'admin_wikireplace.html', data
def _process_remove_request(self, req, data): """Remove an existing repository.""" repo = self._get_checked_repository(req, req.args.get('reponame')) open_ticket = None with self.env.db_transaction as db: tickets = db("""SELECT ticket FROM ( SELECT src.ticket, src.value as srcrepo, dst.value as dstrepo FROM ticket_custom AS src JOIN ticket_custom AS dst ON (src.ticket = dst.ticket) WHERE src.name = 'pr_srcrepo' AND dst.name = 'pr_dstrepo') WHERE srcrepo = %d OR dstrepo = %d """ % (repo.id, repo.id)) for values in tickets: (id,) = values ticket = Ticket(self.env, id) if ticket['status'] != 'closed': open_ticket = id break if open_ticket: link = tag.a(_("pull request"), href=req.href.ticket(open_ticket)) add_warning(req, tag_('The repository "%(name)s can not be ' 'removed as it is referenced by an open ' '%(link)s.', name=repo.reponame, link=link)) LoginModule(self.env)._redirect_back(req) if req.args.get('confirm'): RepositoryManager(self.env).remove(repo, req.args.get('delete')) add_notice(req, _('The repository "%(name)s" has been removed.', name=repo.reponame)) req.redirect(req.href.repository()) elif req.args.get('cancel'): LoginModule(self.env)._redirect_back(req) data.update({'title': _("Remove Repository"), 'repository': repo})
def _do_account(self, req): if not req.authname or req.authname == 'anonymous': # DEVEL: Shouldn't this be a more generic URL? req.redirect(req.href.wiki()) action = req.args.get('action') delete_enabled = self.acctmgr.supports('delete_user') and \ self.acctmgr.allow_delete_account data = { 'delete_enabled': delete_enabled, 'delete_msg_confirm': _("Are you sure you want to delete your account?"), } force_change_password = req.session.get('force_change_passwd', False) if req.method == 'POST': if action == 'save': data.update(self._do_change_password(req)) if force_change_password: del (req.session['force_change_passwd']) req.session.save() chrome.add_notice( req, Markup( tag.span( tag_( "Thank you for taking the time to update your password." )))) force_change_password = False elif action == 'delete' and delete_enabled: data.update(self._do_delete(req)) else: data.update({'error': 'Invalid action'}) if force_change_password: chrome.add_warning( req, Markup( tag.span( _("You are required to change password because of a recent " "password change request. "), tag.b(_("Please change your password now."))))) return data
def _check_quickjump(self, req, noquickjump, kwd): """Look for search shortcuts""" # Source quickjump FIXME: delegate to ISearchSource.search_quickjump quickjump_href = None if kwd[0] == '/': quickjump_href = req.href.browser(kwd) name = kwd description = _('Browse repository path %(path)s', path=kwd) else: context = web_context(req, 'search') link = find_element(extract_link(self.env, context, kwd), 'href') if link is not None: quickjump_href = link.attrib.get('href') name = link.children description = link.attrib.get('title', '') if quickjump_href: # Only automatically redirect to local quickjump links if not quickjump_href.startswith(req.base_path or '/'): noquickjump = True if noquickjump: return { 'href': quickjump_href, 'name': tag.em(name), 'description': description } else: help_url = req.href.wiki('TracSearch') + '#Quicksearches' search_url = req.href.search(q=kwd, noquickjump=1) # FIXME: use tag_ add_notice( req, Markup( _( 'You arrived here through the <a href="%(help_url)s">' 'quick-jump</a> search feature. To instead search for the ' 'term <strong>%(term)s</strong>, click <a ' 'href="%(search_url)s">here</a>.', help_url=escape(help_url), term=escape(kwd), search_url=escape(search_url)))) req.redirect(quickjump_href)
def _do_save(self, req, page): if not page.exists: req.perm(page.resource).require('WIKI_CREATE') else: req.perm(page.resource).require('WIKI_MODIFY') if 'WIKI_ADMIN' in req.perm(page.resource): # Modify the read-only flag if it has been changed and the user is # WIKI_ADMIN page.readonly = int('readonly' in req.args) try: page.save(get_reporter_id(req, 'author'), req.args.get('comment'), req.remote_addr) add_notice(req, _("Your changes have been saved in version " "%(version)s.", version=page.version)) req.redirect(get_resource_url(self.env, page.resource, req.href, version=None)) except TracError: add_warning(req, _("Page not modified, showing latest version.")) return self._render_view(req, page)
def _do_create(self, req): req.perm.require('REPORT_CREATE') if 'cancel' in req.args: req.redirect(req.href.report()) title = req.args.get('title', '') query = req.args.get('query', '') description = req.args.get('description', '') report_id = [None] @self.env.with_transaction() def do_create(db): cursor = db.cursor() cursor.execute( "INSERT INTO report (title,query,description) " "VALUES (%s,%s,%s)", (title, query, description)) report_id[0] = db.get_last_id(cursor, 'report') add_notice(req, _('The report has been created.')) req.redirect(req.href.report(report_id[0]))
def _do_delete(self, req, page): req.perm(page.resource).require('WIKI_DELETE') if 'cancel' in req.args: req.redirect(get_resource_url(self.env, page.resource, req.href)) version = req.args.getint('version') old_version = req.args.getint('old_version', version) with self.env.db_transaction: if version and old_version and version > old_version: # delete from `old_version` exclusive to `version` inclusive: for v in xrange(old_version, version): page.delete(v + 1) else: # only delete that `version`, or the whole page if `None` page.delete(version) if not page.exists: add_notice(req, _("The page %(name)s has been deleted.", name=page.name)) req.redirect(req.href.wiki()) else: if version and old_version and version > old_version + 1: add_notice(req, _("The versions %(from_)d to %(to)d of the " "page %(name)s have been deleted.", from_=old_version + 1, to=version, name=page.name)) else: add_notice(req, _("The version %(version)d of the page " "%(name)s has been deleted.", version=version, name=page.name)) req.redirect(req.href.wiki(page.name))
def process_request(self, req): if not req.session.authenticated: chrome.add_warning( req, Markup( tag.span( tag_( "Please log in to finish email verification procedure." )))) req.redirect(req.href.login()) if 'email_verification_token' not in req.session: chrome.add_notice(req, _("Your email is already verified.")) elif req.method == 'POST' and 'resend' in req.args: AccountManager(self.env)._notify( 'email_verification_requested', req.authname, req.session['email_verification_token']) chrome.add_notice( req, _("A notification email has been resent to <%s>."), req.session.get('email')) elif 'verify' in req.args: # allow via POST or GET (the latter for email links) if req.args['token'] == req.session['email_verification_token']: del req.session['email_verification_token'] chrome.add_notice( req, _("Thank you for verifying your email address.")) req.redirect(req.href.prefs()) else: chrome.add_warning(req, _("Invalid verification token")) data = {'_dgettext': dgettext} if 'token' in req.args: data['token'] = req.args['token'] if 'email_verification_token' not in req.session: data['button_state'] = {'disabled': 'disabled'} return 'verify_email.html', data, None