Пример #1
0
def send_search_index(environ, start_response, parent_dir=None,
                       env_paths=None, authname='anonymous'):

    req = Request(environ, start_response)
    req.authname = authname;

    loadpaths = []
    if req.environ.get('trac.env_index_template'):
        tmpl_path, template = os.path.split(req.environ['trac.env_index_template'])
        loadpaths.insert(0, tmpl_path)
    else:
        template = 'index.html'
    req.hdf = HDFWrapper(loadpaths)

    tmpl_vars = {}
    if req.environ.get('trac.template_vars'):
        for pair in req.environ['trac.template_vars'].split(','):
            key, val = pair.split('=')
            req.hdf[key] = val

    if parent_dir and not env_paths:
        env_paths = dict([(filename, os.path.join(parent_dir, filename))
                          for filename in os.listdir(parent_dir)])

    chrome = prepare_request(req, environ)

    config = get_allenv(environ, req).config
    need_auth = config.get('tram', 'check_auth') == 'true'
    auth_perm = config.get('tram', 'permission') or 'PROJECT_ACCESS'
    parent_href = get_parent_href(req)
    projects = get_project_list(environ, parent_href, authname=req.authname, require_auth=need_auth, permission=auth_perm)

    data = {}
    data['projects'] = projects
    data["chrome.nav.mainnav.search.active"] = 1
    data["base_url"] = urlsplit(parent_href())[2] + "/"

    # Default to the standard Tram clearsilver first
    templateFileName = "search_index.html"
    fullTemplatePath = os.path.dirname( __file__ ) + "/templates/" + templateFileName

    # Now override, if user has defined a custom one in their environment's templates dir
    customTemplateFile = get_allenv(environ, req).get_templates_dir() + "/" + templateFileName
    if os.path.isfile(customTemplateFile):
        fullTemplatePath = customTemplateFile

    chrome.populate_data(req, data)
    output = chrome.render_template(req, fullTemplatePath, data)
    req.session.save()
    req.send(output, 'text/html')
Пример #2
0
    def dispatch(self, environ, start_response, env_parent_dir, env_paths, req):
        path_info = environ.get('PATH_INFO', '').lstrip('/').split('/')
        env_name = path_info.pop(0)

        #req = Request(environ, start_response)
        req.authname = LoginModule(self.compmgr).authenticate(req);
        # I don't know why this function is called twice.
        req.authname = LoginModule(self.compmgr).authenticate(req);

        # prepare_request function is not working collectly.
        chrome = prepare_request(req, environ)

        config = get_allenv(environ, req).config
        need_auth = config.get('tram', 'check_auth') == 'true'
        auth_perm = config.get('tram', 'permission') or 'PROJECT_ACCESS'
        old_style_index = config.get('tram', 'old_style_index') or 'false'
        if old_style_index == 'false':
            if not env_name:
                env_name = 'all'

        projects = get_project_list(environ, get_parent_href(req), authname=req.authname, require_auth=need_auth, permission=auth_perm)

        try:
            if env_name == '':
                send_project_index_old_style(environ, start_response, env_parent_dir, env_paths, req.authname)
            elif len(path_info) == 0 or (len(path_info) == 1 and path_info[0] == ''):
                #/all/ requested, show project index
                send_project_index(environ, start_response, env_parent_dir, env_paths, req.authname)
            elif path_info[0] == 'query':
                QueryModule().process_request(req, chrome, projects)
            elif path_info[0] == 'browser':
                BrowserModule().process_request(req, chrome, projects)
            elif path_info[0] == 'roadmap':
                RoadmapModule().process_request(req, chrome, projects)
            elif path_info[0] == 'timeline':
                TimelineModule(self.compmgr).process_request(req, chrome, projects)
            elif path_info[0] == 'search':
                send_search_index(environ, start_response, env_parent_dir, env_paths, req.authname)
        finally:
            if req.session:
                req.session.save()
Пример #3
0
def send_project_index(environ, start_response, parent_dir=None,
                       env_paths=None, authname='anonymous'):

    req = Request(environ, start_response)
    req.authname = authname;
    if not req.authname:
        req.authname = "anonymous"

    loadpaths = []
    if req.environ.get('trac.env_index_template'):
        tmpl_path, template = os.path.split(req.environ['trac.env_index_template'])
        loadpaths.insert(0, tmpl_path)
    else:
        template = 'index.html'
    req.hdf = HDFWrapper(loadpaths)

    tmpl_vars = {}
    if req.environ.get('trac.template_vars'):
        for pair in req.environ['trac.template_vars'].split(','):
            key, val = pair.split('=')
            req.hdf[key] = val

    if parent_dir and not env_paths:
        env_paths = dict([(filename, os.path.join(parent_dir, filename))
                          for filename in os.listdir(parent_dir)])

    chrome = prepare_request(req, environ)

    config = get_allenv(environ, req).config
    need_auth = config.get('tram', 'check_auth') == 'true'
    auth_perm = config.get('tram', 'permission') or 'PROJECT_ACCESS'
    bar_color = config.get('tram', 'bar_color') or '#0b0'
    expand = config.get('tram', 'expand') or 'true'
    show_tickets_in_project_list = config.get('tram', 'show_tickets_in_project_list') or 'false'
    projects = get_project_list(environ, get_parent_href(req), authname=req.authname, require_auth=need_auth, permission=auth_perm)


    # Very simple method for calculating project activity
    # needs to be more advanced, tickets closed etc and per month not overall
    stop = time.time()
    t = time.localtime()
    start = time.mktime((t[0], t[1] - 1, t[2], t[3], t[4], t[5], t[6], t[7], t[8]))
    stop2 = int(stop)
    start2 = int(start)
    start = datetime(t[0], t[1], t[2], t[3], t[4], t[5], t[6], tzinfo=utc) - timedelta(30)
    stop  = datetime(t[0], t[1], t[2], t[3], t[4], t[5], t[6], tzinfo=utc)

    changes = 0
    changes_month = 0
    max_ticket = 0
    max_ticket_closed = 0
    max_ticket_month = 0
    max_ticket_closed_month = 0
    for project in projects:
        if not project.has_key('env'):
            continue;

        env = project['env']
        revisions = 0
        try:
            repos = env.get_repository(req.authname)
            #change_list = repos.get_changesets(start, stop)

            try:
              for chgset in repos.get_changesets(start, stop):
              #while change_list.next():
                  try:
                    revisions += 1
                  except Exception, e:
                    debug(to_unicode(e))
            except Exception, e:
              debug(to_unicode(e))

            changes_month = max(changes_month, revisions)

            try:
                total_revisions = int(repos.get_youngest_rev())
            except TypeError:
                total_revisions = 0
            changes = max(changes, total_revisions)
        except TracError ,e:
            total_revisions = 0
Пример #4
0
def dispatch_request(environ, start_response):
    """Main entry point for the Trac web interface.
    
    @param environ: the WSGI environment dict
    @param start_response: the WSGI callback for starting the response
    """
    if 'mod_python.options' in environ:
        options = environ['mod_python.options']
        environ.setdefault('trac.env_path', options.get('TracEnv'))
        environ.setdefault('trac.env_parent_dir', options.get('TracEnvParentDir'))
        environ.setdefault('trac.env_index_template', options.get('TracEnvIndexTemplate'))
        environ.setdefault('trac.template_vars', options.get('TracTemplateVars'))
        environ.setdefault('trac.locale', options.get('TracLocale'))

        if 'TracUriRoot' in options:
            # Special handling of SCRIPT_NAME/PATH_INFO for mod_python, which
            # tends to get confused for whatever reason
            root_uri = options['TracUriRoot'].rstrip('/')
            request_uri = environ['REQUEST_URI'].split('?', 1)[0]
            if not request_uri.startswith(root_uri):
                raise ValueError('TracUriRoot set to %s but request URL '
                                 'is %s' % (root_uri, request_uri))
            environ['SCRIPT_NAME'] = root_uri
            environ['PATH_INFO'] = urllib.unquote(request_uri[len(root_uri):])

    else:
        environ.setdefault('trac.env_path', os.getenv('TRAC_ENV'))
        environ.setdefault('trac.env_parent_dir',
                           os.getenv('TRAC_ENV_PARENT_DIR'))
        environ.setdefault('trac.env_index_template',
                           os.getenv('TRAC_ENV_INDEX_TEMPLATE'))
        environ.setdefault('trac.template_vars',
                           os.getenv('TRAC_TEMPLATE_VARS'))
        environ.setdefault('trac.locale', '')

    locale.setlocale(locale.LC_ALL, environ['trac.locale'])

    env_parent_dir = environ.get('trac.env_parent_dir')
    env_paths = environ.get('trac.env_paths', [])
    import dircache
    paths = dircache.listdir(env_parent_dir)[:]
    dircache.annotate(env_parent_dir, paths)
    env_paths += [os.path.join(env_parent_dir, project) \
                  for project in paths 
                  if project[-1] == '/' and project != '.egg-cache/']


    # Determine the environment
    env_path = environ.get('trac.env_path')
    req = Request(environ, start_response)

    if not env_path:
        if env_parent_dir or env_paths:
            try:
                # The first component of the path is the base name of the
                # environment
                path_info = environ.get('PATH_INFO', '').lstrip('/').split('/')
                env_name = path_info.pop(0)
                if env_name == '':
                    env_name = 'all'
                if env_name == 'all':
                    try:
                        # go on...                       
                        #req = Request(environ, start_response)
                        dispatcher = TramRequestDispatcher(get_allenv(environ, req))
                        dispatcher.dispatch(environ, start_response, env_parent_dir, env_paths, req)
                    except RequestDone, e:
                        return req._response or []
                    #except Exception, e:
                        #raise Exception(e)

                if env_name == 'chrome':
                    env_name = 'all'
                    path_info.insert(0,'chrome')

                # here we send tram chrome, denoted by using the chrome/tram/ parent
                possible_tram_chrome = '/'.join(path_info)
                if (possible_tram_chrome.startswith('chrome/tram/')):
                    file = possible_tram_chrome[12:]
                    path = os.path.dirname(__file__) + "/htdocs/" + file
                    if (os.path.isfile(path)):
                        #req = Request(environ, start_response)
                        try:
                            req.send_file(path, mimeview.get_mimetype(path))
                        except RequestDone, e:
                            return req._response or [];
                    else:
                        raise HTTPNotFound('File %s not found', file)

                if not env_name:
                    # We need to be in the 'all' environment for the auth cookies etc

                    #req = Request(environ, start_response)
                    req.redirect(req.abs_href() + '/all')

            except HTTPException, e:
                #req = Request(environ, start_response)
                prepare_request(req, environ)
                loadpaths = []
                loadpaths.insert(0, os.path.dirname(__file__) + "/templates/")
                data = {
                        'title': e.reason or 'Error',
                        'type': 'TracError',
                        #'message': e.message
                        'message': e.reason or 'Error'
                }
                try:
                    req.send_error(sys.exc_info(), status=e.code, env=Environment(env_path), data=data)
                except RequestDone, e:
                    return []
Пример #5
0
                loadpaths = []
                loadpaths.insert(0, os.path.dirname(__file__) + "/templates/")
                data = {
                        'title': e.reason or 'Error',
                        'type': 'TracError',
                        #'message': e.message
                        'message': e.reason or 'Error'
                }
                try:
                    req.send_error(sys.exc_info(), status=e.code, env=Environment(env_path), data=data)
                except RequestDone, e:
                    return []

            except Exception, e:
                #req = Request(environ, start_response)
                prepare_request(req, environ)
                data = {
                        'title': to_unicode(e) or 'Error',
                        'type': 'internal',
                        'message': to_unicode(e) or 'Error',
                        'traceback': get_last_traceback()
                }
                try:
                    req.send_error(sys.exc_info(), status=500, data=data)
                except RequestDone, e:
                    #debug(to_unicode(e))
                    return []


            # To make the matching patterns of request handlers work, we append
            # the environment name to the `SCRIPT_NAME` variable, and keep only