Esempio n. 1
0
    def GET(self):
        input = web.input()
        birth = input.get('birth', '').strip()
        death = input.get('death', '').strip()
        order = input.get('order', '').strip()
        if order not in ('', 'name', 'birth', 'death'):
            order = ''
        html = '''
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title>Merge author</title>
<style>
body { font-family: arial,helvetica,san-serif; }
th { text-align: left; }
</style>
</head>
<body>
'''
        html += '<form method="get">\n'
        html += 'Birth: <input type="text" size="7" name="birth" value="%s">\n' % web.htmlquote(
            birth)
        html += 'Death: <input type="text" size="7" name="death" value="%s">\n' % web.htmlquote(
            death)
        html += '<input type="submit" value="Search">\n</form>'

        if birth or death:
            url = 'http://openlibrary.org/query.json?type=/type/author&birth_date=%s&death_date=%s&name=' % (
                web.urlquote(birth), web.urlquote(death))
            data = get_all(url)
            html += result_table(data, birth, death, order)
        return html + '</body>\n</html>'
Esempio n. 2
0
    def POST(self):
        inp = web.input(close_after=False, item_host=None, item_path=None, item_name=None, content=None, item_user=None)

        model.new_comment(session.user.name, inp.item_host, inp.item_path, inp.item_name, inp.content, inp.item_user)

        page_owner = model.get_user(name=inp.item_user)
        if page_owner.mailmode == "all":
            web.sendmail(
                'Comment on This! <*****@*****.**>',
                page_owner.email,
                '[CoT] New comment on '+get_domain(inp.item_host),
                session.user.name+" posted a comment on "+inp.item_host+inp.item_path+"#"+inp.item_name+":"+
                "\n\n"+inp.content+
                "\n\n    -- The Comment on This Team"
            )

        if inp.close_after:
            return render.comment_thanks()
        else:
            raise web.seeother(
                "/comment"+
                "?item_host="+web.urlquote(inp.item_host)+
                "&item_path="+web.urlquote(inp.item_path)+
                "&item_name="+web.urlquote(inp.item_name)
            )
Esempio n. 3
0
    def GET(
        self,
        domain=None,
    ):
        if domain is None:
            self.cur_domain = None
        else:
            self.cur_domain = str(domain)
            if not iredutils.isDomain(self.cur_domain):
                raise web.seeother('/domains?msg=INVALID_DOMAIN_NAME')

        i = web.input()

        # Get all managed domains.
        connutils = connUtils.Utils()
        qr = connutils.getManagedDomains(
            admin=session.get('username'),
            domainNameOnly=True,
        )

        if qr[0] is True:
            allDomains = qr[1]
        else:
            raise web.seeother('/domains?msg=' + web.urlquote(qr[1]))

        # Set first domain as current domain.
        if self.cur_domain is None:
            if len(allDomains) > 0:
                raise web.seeother('/create/alias/%s' % str(allDomains[0]))
            else:
                raise web.seeother('/domains?msg=NO_DOMAIN_AVAILABLE')

        # Get domain profile.
        domainLib = domainlib.Domain()
        resultOfProfile = domainLib.profile(domain=self.cur_domain)
        if resultOfProfile[0] is True:
            self.profile = resultOfProfile[1]
        else:
            raise web.seeother('/domains?msg=%s' %
                               web.urlquote(resultOfProfile[1]))

        # Cet total number and allocated quota size of existing users under domain.
        self.numberOfExistAccounts = 0

        resultOfCount = domainLib.getCountsOfExistAccountsUnderDomain(
            domain=self.cur_domain,
            accountType='alias',
        )
        if resultOfCount[0] is True:
            self.numberOfExistAccounts = resultOfCount[1]

        return web.render(
            'dbmail_mysql/alias/create.html',
            cur_domain=self.cur_domain,
            allDomains=allDomains,
            profile=self.profile,
            numberOfExistAccounts=self.numberOfExistAccounts,
            numberOfAccounts=2,
            msg=i.get('msg'),
        )
Esempio n. 4
0
def uuap_sso():
    sso_username = web.config.session.get('sso_username')
    #如果有已经登陆则返回用户名,否则跳转到uuap登录页
    if sso_username:
        logging.debug('sso_username: %s' % sso_username)
        return sso_username
    service_url = '%s/zmon/auth?u=%s' % (web.ctx.homedomain, web.urlquote(web.ctx.homepath + web.ctx.fullpath))
    raise web.seeother('%s/login?service=%s' % (SSO_URL, web.urlquote(service_url)))
Esempio n. 5
0
def auth():
    sso_username = web.config.session.get('sso_username')
    if sso_username:
        return sso_username
    service_url = '%s/sso?u=%s' % (
        web.ctx.homedomain, web.urlquote(web.ctx.homepath + web.ctx.fullpath))
    raise web.seeother('%s/login?service=%s' %
                       (SSO_URL, web.urlquote(service_url)))
Esempio n. 6
0
    def GET(self, domain):
        domain = str(domain).lower()

        form = web.input()

        # Get all managed domains.
        _wrap = SQLWrap()
        conn = _wrap.conn

        if session.get('is_global_admin'):
            qr = sql_lib_domain.get_all_domains(conn=conn, name_only=True)
        else:
            qr = sql_lib_admin.get_managed_domains(
                conn=conn,
                admin=session.get('username'),
                domain_name_only=True)

        if qr[0] is True:
            all_domains = qr[1]
        else:
            raise web.seeother('/api?msg=' + web.urlquote(qr[1]))

        # Get domain profile.
        qr_profile = sql_lib_domain.simple_profile(domain=domain, conn=conn)
        if qr_profile[0] is True:
            domain_profile = qr_profile[1]
            domain_settings = sqlutils.account_settings_string_to_dict(
                domain_profile['settings'])
        else:
            raise web.seeother('/api?msg=%s' % web.urlquote(qr_profile[1]))

        # Cet total number and allocated quota size of existing users under domain.
        num_users_under_domain = sql_lib_general.num_users_under_domain(
            domain=domain, conn=conn)

        min_passwd_length = domain_settings.get('min_passwd_length',
                                                settings.min_passwd_length)
        max_passwd_length = domain_settings.get('max_passwd_length',
                                                settings.max_passwd_length)

        return web.render(
            'api/msg/msg.html',
            content_type="application/json",
            msg={
                #"cur_domain":domain,
                #"allDomains":all_domains,
                #"profile":domain_profile,
                #"domain_settings":domain_settings,
                #"min_passwd_length":min_passwd_length,
                #"max_passwd_length":max_passwd_length,
                #"store_password_in_plain_text":settings.STORE_PASSWORD_IN_PLAIN_TEXT,
                #"num_existing_users":num_users_under_domain,
                #"languagemaps":iredutils.get_language_maps(),
                #"password_policies":iredutils.get_password_policies(),
                #"msg":form.get('msg')
                "msg": "Create User API's GET method!"
            })
Esempio n. 7
0
def simple_search(q, offset=0, rows=20, sort=None):
    solr_select = solr_select_url + "?version=2.2&q.op=AND&q=%s&fq=&start=%d&rows=%d&fl=*%%2Cscore&qt=standard&wt=json" % (
        web.urlquote(q), offset, rows)
    if sort:
        solr_select += "&sort=" + web.urlquote(sort)

    stats.begin("solr", url=solr_select)
    json_data = urllib.urlopen(solr_select)
    stats.end()
    return json.load(json_data)
Esempio n. 8
0
    def GET(self, domain):
        domain = str(domain).lower()

        form = web.input()

        # Get all managed domains.
        _wrap = SQLWrap()
        conn = _wrap.conn

        if session.get('is_global_admin'):
            qr = sql_lib_domain.get_all_domains(conn=conn, name_only=True)
        else:
            qr = sql_lib_admin.get_managed_domains(
                conn=conn,
                admin=session.get('username'),
                domain_name_only=True)

        if qr[0] is True:
            all_domains = qr[1]
        else:
            raise web.seeother('/domains?msg=' + web.urlquote(qr[1]))

        # Get domain profile.
        qr_profile = sql_lib_domain.simple_profile(domain=domain, conn=conn)

        if qr_profile[0] is True:
            domain_profile = qr_profile[1]
            domain_settings = sqlutils.account_settings_string_to_dict(
                domain_profile['settings'])
        else:
            raise web.seeother('/domains?msg=%s' % web.urlquote(qr_profile[1]))

        # Cet total number and allocated quota size of existing users under domain.
        num_users_under_domain = sql_lib_general.num_users_under_domain(
            domain=domain, conn=conn)

        min_passwd_length = domain_settings.get('min_passwd_length',
                                                settings.min_passwd_length)
        max_passwd_length = domain_settings.get('max_passwd_length',
                                                settings.max_passwd_length)

        return web.render(
            'sql/user/create.html',
            cur_domain=domain,
            allDomains=all_domains,
            profile=domain_profile,
            domain_settings=domain_settings,
            min_passwd_length=min_passwd_length,
            max_passwd_length=max_passwd_length,
            store_password_in_plain_text=settings.STORE_PASSWORD_IN_PLAIN_TEXT,
            num_existing_users=num_users_under_domain,
            languagemaps=iredutils.get_language_maps(),
            password_policies=iredutils.get_password_policies(),
            msg=form.get('msg'),
        )
Esempio n. 9
0
def run_solr_query(param = {}, rows=100, page=1, sort=None, spellcheck_count=None):
    # called by do_search
    if spellcheck_count == None:
        spellcheck_count = default_spellcheck_count
    offset = rows * (page - 1)

    (q_list, use_dismax) = build_q_list(param)

    fields = ['key', 'author_name', 'author_key', 'title', 'subtitle', 'edition_count', 'ia', 'has_fulltext', 'first_publish_year', 'cover_edition_key', 'public_scan_b', 'lending_edition_s', 'overdrive_s', 'ia_collection_s']
    fl = ','.join(fields)
    if use_dismax:
        q = web.urlquote(' '.join(q_list))
        solr_select = solr_select_url + "?defType=dismax&q.op=AND&q=%s&qf=text+title^5+author_name^5&bf=sqrt(edition_count)^10&start=%d&rows=%d&fl=%s&wt=standard" % (q, offset, rows, fl)
    else:
        q = web.urlquote(' '.join(q_list + ['_val_:"sqrt(edition_count)"^10']))
        solr_select = solr_select_url + "?q.op=AND&q=%s&start=%d&rows=%d&fl=%s&wt=standard" % (q, offset, rows, fl)
    solr_select += '&spellcheck=true&spellcheck.count=%d' % spellcheck_count
    solr_select += "&facet=true&" + '&'.join("facet.field=" + f for f in facet_fields)

    if 'public_scan' in param:
        v = param.pop('public_scan').lower()
        if v in ('true', 'false'):
            if v == 'false':
                # also constrain on print disabled since the index may not be in sync
                param.setdefault('print_disabled', 'false')
            solr_select += '&fq=public_scan_b:%s' % v

    if 'print_disabled' in param:
        v = param.pop('print_disabled').lower()
        if v in ('true', 'false'):
            solr_select += '&fq=%ssubject_key:protected_daisy' % ('-' if v == 'false' else '')

    k = 'has_fulltext'
    if k in param:
        v = param[k].lower()
        if v not in ('true', 'false'):
            del param[k]
        param[k] == v
        solr_select += '&fq=%s:%s' % (k, v)

    for k in facet_list_fields:
        if k == 'author_facet':
            k = 'author_key'
        if k not in param:
            continue
        v = param[k]
        solr_select += ''.join('&fq=%s:"%s"' % (k, url_quote(l)) for l in v if l)
    if sort:
        solr_select += "&sort=" + url_quote(sort)

    stats.begin("solr", url=solr_select)
    reply = urllib.urlopen(solr_select).read()
    stats.end()
    return (reply, solr_select, q_list)
Esempio n. 10
0
def update(mail, profile_type, form, conn=None):
    mail = str(mail).lower()

    # Don't allow to view/update other admins' profile.
    if mail != session.get('username') and not session.get('is_global_admin'):
        return (False, 'PERMISSION_DENIED')

    sql_vars = {'username': mail}

    if not conn:
        _wrap = SQLWrap()
        conn = _wrap.conn

    params = {}
    if profile_type == 'general':
        # Name, preferred language
        params['name'] = form.get('cn', '')
        params['language'] = form_utils.get_language(form)

        # Update account status
        params['active'] = 0
        if 'accountStatus' in form:
            params['active'] = 1
    elif profile_type == 'password':
        newpw = web.safestr(form.get('newpw', ''))
        confirmpw = web.safestr(form.get('confirmpw', ''))

        # Verify new passwords.
        qr = iredpwd.verify_new_password(newpw=newpw, confirmpw=confirmpw)
        if qr[0] is True:
            passwd = iredpwd.generate_password_hash(qr[1])

            params['password'] = passwd
            params['passwordlastchange'] = iredutils.get_gmttime()
        else:
            return qr

    if params:
        try:
            conn.update('admin',
                        vars=sql_vars,
                        where='username=$username',
                        **params)
        except Exception as e:
            log_traceback()
            if 'password' in params:
                raise web.seeother('/profile/admin/password/{}?msg={}'.format(
                    mail, web.urlquote(e)))
            else:
                raise web.seeother('/profile/admin/general/{}?msg={}'.format(
                    mail, web.urlquote(e)))

    return (True, )
Esempio n. 11
0
 def GET(self):
     user_data = web.input(u=None, ticket=None)
     if not user_data.u or not user_data.ticket:
         return render.forbidden('')
     service_url = '%s/zmon/auth?u=%s' % (web.ctx.homedomain, web.urlquote(user_data.u))
     validate_url = '%s/validate?service=%s&ticket=%s' % (SSO_URL, web.urlquote(service_url), web.urlquote(user_data.ticket))
     r = urllib.urlopen(validate_url).readlines()
     if len(r) == 2 and r[0].strip() == 'yes':
         web.config.session.sso_username = r[1].strip()
         raise web.seeother(user_data.u)
     else:
         return render.forbidden('')
Esempio n. 12
0
File: sso.py Progetto: actank/zmon
 def GET(self):
     user_data = web.input(u=None, ticket=None)
     if not user_data.u or not user_data.ticket:
         return render.forbidden(userName)
     service_url = '%s/sso?u=%s' % (web.ctx.homedomain, web.urlquote(user_data.u))
     validate_url = '%s/validate?service=%s&ticket=%s' % (SSO_URL, web.urlquote(service_url), web.urlquote(user_data.ticket))
     r = urllib.urlopen(validate_url).readlines()
     if len(r) == 2 and r[0].strip() == 'yes':
         web.config.session.sso_username = r[1].strip()
         raise web.seeother(user_data.u)
     else:
         return render.forbidden(userName)
Esempio n. 13
0
    def GET(
        self,
        domain=None,
    ):
        if domain is None:
            self.cur_domain = None
        else:
            self.cur_domain = str(domain)
            if not iredutils.is_domain(self.cur_domain):
                raise web.seeother('/domains?msg=INVALID_DOMAIN_NAME')

        i = web.input()

        # Get all managed domains.
        connutils = connUtils.Utils()
        qr = connutils.getManagedDomains(
            admin=session.get('username'),
            domainNameOnly=True,
        )

        if qr[0] is True:
            allDomains = qr[1]
        else:
            raise web.seeother('/domains?msg=%s' % web.urlquote(qr[1]))

        # Set first domain as current domain.
        if self.cur_domain is None:
            if len(allDomains) > 0:
                raise web.seeother('/create/user/%s' % str(allDomains[0]))
            else:
                raise web.seeother('/domains?msg=NO_DOMAIN_AVAILABLE')

        # Get domain profile.
        domainLib = domainlib.Domain()
        resultOfProfile = domainLib.profile(domain=self.cur_domain)
        if resultOfProfile[0] is True:
            self.profile = resultOfProfile[1]
        else:
            raise web.seeother('/domains?msg=%s' %
                               web.urlquote(resultOfProfile[1]))

        return web.render(
            'mysql/user/create.html',
            cur_domain=self.cur_domain,
            allDomains=allDomains,
            profile=self.profile,
            min_passwd_length=settings.min_passwd_length,
            max_passwd_length=settings.max_passwd_length,
            msg=i.get('msg'),
        )
Esempio n. 14
0
def login_hook(handler):
    path_info = web.ctx.env['PATH_INFO']
    if path_info != '/login' and not session.login:
        uri = web.ctx.env['REQUEST_URI']
        web.seeother('/login?return_url=' + web.urlquote(uri))
    else:
        return handler()
Esempio n. 15
0
    def POST(self, domain):
        domain = str(domain).lower()
        form = web.input()

        domain_in_form = form_utils.get_domain_name(form)
        current_admin_managed_domains = sql_lib_admin.get_managed_domains(
            session.get('username'), domain_name_only=True)[1]
        if ((domain != domain_in_form) or
            (domain not in current_admin_managed_domains) or
            (domain_in_form not in current_admin_managed_domains)
            ) and not session.get('is_global_admin'):
            raise web.seeother('/domains?msg=PERMISSION_DENIED')

        # Get username
        username = form_utils.get_single_value(form,
                                               input_name='username',
                                               to_string=True)

        qr = sql_lib_user.add_user_from_form(domain=domain, form=form)

        if qr[0]:
            raise web.seeother(
                '/profile/user/general/{}@{}?msg=CREATED'.format(
                    username, domain))
        else:
            raise web.seeother('/create/user/{}?msg={}'.format(
                domain, web.urlquote(qr[1])))
	def render(self,renderObject):
		if 'frameview' == self.m_renderType or 'view' == self.m_renderType:
			if not self.view():
				self.buildView()
			
			# 在 json 请求中不需要此参数
			self.setVariable('urlPath',self.m_urlPath)
			self.setVariable('url',web.ctx.fullpath)
			self.setVariable('urlquote',web.urlquote( web.ctx.fullpath ) )
			
			if 'frameview' == self.m_renderType:
				return self.view().rootView().render(
					renderObject,
					self.m_variableDict
				)
			else:
				return self.view().render(
					renderObject,
					self.m_variableDict
				)
		elif 'json' == self.m_renderType:
			if self.__status == 'ok':
				self.setVariable('result',True)
			else:
				self.setVariable('result',False)
			return json.dumps(self.m_variableDict)
		else:
			return self.m_renderType
Esempio n. 17
0
    def GET(self, profile_type, domain):
        i = web.input()
        self.domain = web.safestr(domain.split('/', 1)[0])
        self.profile_type = web.safestr(profile_type)

        if not iredutils.is_domain(self.domain):
            raise web.seeother('/domains?msg=EMPTY_DOMAIN')

        domainLib = domainlib.Domain()
        result = domainLib.profile(domain=self.domain)

        if result[0] is False:
            raise web.seeother('/domains?msg=' + web.urlquote(result[1]))

        r = domainLib.listAccounts(attrs=['domainName'])
        if r[0] is True:
            allDomains = r[1]
        else:
            return r

        allAccountSettings = ldaputils.getAccountSettingFromLdapQueryResult(result[1], key='domainName',)

        return web.render(
            'ldap/domain/profile.html',
            cur_domain=self.domain,
            allDomains=allDomains,
            allAccountSettings=allAccountSettings,
            profile=result[1],
            profile_type=self.profile_type,
            msg=i.get('msg', None),
        )
Esempio n. 18
0
    def POST(self):
        # Get username, password.
        i = web.input(_unicode=False)

        username = web.safestr(i.get('username').strip())
        password = str(i.get('password').strip())
        save_pass = web.safestr(i.get('save_pass', 'no').strip())

        auth = core.Auth()
        auth_result = auth.auth(username=username, password=password)

        if auth_result[0] is True:
            # Config session data.
            web.config.session_parameters['cookie_name'] = 'iRedAdmin-Pro'
            # Session expire when client ip was changed.
            web.config.session_parameters['ignore_change_ip'] = False
            # Don't ignore session expiration.
            web.config.session_parameters['ignore_expiry'] = False

            if save_pass == 'yes':
                # Session timeout (in seconds).
                web.config.session_parameters['timeout'] = 86400    # 24 hours
            else:
                # Expire session when browser closed.
                web.config.session_parameters['timeout'] = 600      # 10 minutes

            web.logger(msg="Login success", event='login',)
            raise web.seeother('/dashboard/checknew')
        else:
            session['failedTimes'] += 1
            web.logger(msg="Login failed.", admin=username, event='login', loglevel='error',)
            raise web.seeother('/login?msg=%s' % web.urlquote(auth_result[1]))
Esempio n. 19
0
    def POST(self, domain):
        i = web.input(_unicode=False, mail=[])
        self.domain = web.safestr(domain)
        self.mails = i.get('mail', [])
        self.action = i.get('action', None)

        userLib = user.User()

        if self.action == 'delete':
            result = userLib.delete(domain=self.domain, mails=self.mails,)
            msg = 'DELETED'
        elif self.action == 'disable':
            result = userLib.enableOrDisableAccount(domain=self.domain, mails=self.mails, action='disable',)
            msg = 'DISABLED'
        elif self.action == 'enable':
            result = userLib.enableOrDisableAccount(domain=self.domain, mails=self.mails, action='enable',)
            msg = 'ENABLED'
        else:
            result = (False, 'INVALID_ACTION')
            msg = i.get('msg', None)

        if result[0] is True:
            cur_page = i.get('cur_page', '1')
            raise web.seeother('/users/%s/page/%s?msg=%s' % (self.domain, str(cur_page), msg, ))
        else:
            raise web.seeother('/users/%s?msg=%s' % (self.domain, web.urlquote(result[1])))
Esempio n. 20
0
    def POST(self):
        i = web.input(_unicode=False, mail=[])

        self.mails = i.get('mail', [])
        self.action = i.get('action', None)
        msg = i.get('msg', None)

        adminLib = adminlib.Admin()

        if self.action == 'delete':
            result = adminLib.delete(mails=self.mails,)
            msg = 'DELETED'
        elif self.action == 'disable':
            result = adminLib.enableOrDisableAccount(accounts=self.mails, active=False,)
            msg = 'DISABLED'
        elif self.action == 'enable':
            result = adminLib.enableOrDisableAccount(accounts=self.mails, active=True,)
            msg = 'ENABLED'
        else:
            result = (False, 'INVALID_ACTION')

        if result[0] is True:
            raise web.seeother('/admins?msg=%s' % msg)
        else:
            raise web.seeother('/admins?msg=?' + web.urlquote(result[1]))
Esempio n. 21
0
    def get_results(self, q, offset=0, limit=100):
        if config.get('single_core_solr'):            
            valid_fields = ['key', 'name', 'subject_type', 'work_count']
        else:
            valid_fields = ['key', 'name', 'type', 'count']

        q = escape_colon(escape_bracket(q), valid_fields)
        params = {
            "q.op": "AND",
            "q": web.urlquote(q),
            "start": offset,
            "rows": limit,
            "fl": ",".join(valid_fields),
            "qt": "standard",
            "wt": "json"
        }
        if config.get('single_core_solr'):
            params['fq'] = 'type:subject'
            params['sort'] = 'work_count desc'
        else:                
            params['sort'] = 'count desc'

        solr_select = solr_subject_select_url + "?" + urllib.urlencode(params)
        results = run_solr_search(solr_select)
        response = results['response']

        if config.get('single_core_solr'):
            response['docs'] = [self.process_doc(doc) for doc in response['docs']]

        return results
Esempio n. 22
0
    def POST(self, profile_type, domain):
        self.profile_type = web.safestr(profile_type)
        self.domain = web.safestr(domain)

        i = web.input(
            domainAliasName=[],
            enabledService=[],
            domainAdmin=[],
            defaultList=[],
        )

        if self.domain != web.safestr(i.get('domainName', None)).lower():
            raise web.seeother(
                '/profile/domain/%s/%s?msg=DOMAIN_NAME_MISMATCH' %
                (self.profile_type, self.domain))

        domainLib = domainlib.Domain()
        result = domainLib.update(profile_type=self.profile_type,
                                  domain=self.domain,
                                  data=i)
        if result[0] is True:
            raise web.seeother('/profile/domain/%s/%s?msg=UPDATED' %
                               (self.profile_type, self.domain))
        elif result[0] is False:
            raise web.seeother(
                '/profile/domain/%s/%s?msg=%s' %
                (self.profile_type, self.domain, web.urlquote(result[1])))
Esempio n. 23
0
    def POST(self):
        i = web.input(
            domainName=[],
            _unicode=False,
        )
        domainName = i.get('domainName', None)
        self.action = i.get('action')

        domainLib = domainlib.Domain()
        if self.action == 'delete':
            result = domainLib.delete(domains=domainName)
            msg = 'DELETED'
        elif self.action == 'disable':
            result = domainLib.enableOrDisableAccount(
                accounts=domainName,
                active=False,
            )
            msg = 'DISABLED'
        elif self.action == 'enable':
            result = domainLib.enableOrDisableAccount(
                accounts=domainName,
                active=True,
            )
            msg = 'ENABLED'
        else:
            result = (False, 'INVALID_ACTION')
            msg = i.get('msg', None)

        if result[0] is True:
            raise web.seeother('/domains?msg=%s' % msg)
        else:
            raise web.seeother('/domains?msg=' + web.urlquote(result[1]))
Esempio n. 24
0
    def GET(self, cur_page=1):
        i = web.input()
        cur_page = int(cur_page)

        if cur_page == 0:
            cur_page == 1

        adminLib = adminlib.Admin()
        result = adminLib.listAccounts(cur_page=cur_page)
        if result[0] is True:
            (total, records) = (result[1]['total'], result[1]['records'])

            # Get list of global admins.
            allGlobalAdmins = []
            qr = adminLib.get_all_global_admins(mail_only=True)
            if qr[0]:
                allGlobalAdmins = qr[1]

            return web.render(
                'pgsql/admin/list.html',
                cur_page=cur_page,
                total=total,
                admins=records,
                allGlobalAdmins=allGlobalAdmins,
                msg=i.get('msg', None),
            )
        else:
            raise web.seeother('/domains?msg=%s' % web.urlquote(result[1]))
Esempio n. 25
0
 def get_results(q, offset=0, limit=100, snippets=3, fragsize=200, hl_phrase=False):
     m = re_bad_fields.match(q)
     if m:
         return { 'error': m.group(1) + ' search not supported' }
     q = escape_q(q)
     solr_params = [
         ('fl', 'ia,body_length,page_count'),
         ('hl', 'true'),
         ('hl.fl', 'body'),
         ('hl.snippets', snippets),
         ('hl.mergeContiguous', 'true'),
         ('hl.usePhraseHighlighter', 'true' if hl_phrase else 'false'),
         ('hl.simple.pre', '{{{'),
         ('hl.simple.post', '}}}'),
         ('hl.fragsize', fragsize),
         ('q.op', 'AND'),
         ('q', web.urlquote(q)),
         ('start', offset),
         ('rows', limit),
         ('qf', 'body'),
         ('qt', 'standard'),
         ('hl.maxAnalyzedChars', '-1'),
         ('wt', 'json'),
     ]
     solr_select = solr_select_url + '?' + '&'.join("%s=%s" % (k, unicode(v)) for k, v in solr_params)
     stats.begin("solr", url=solr_select)
     json_data = urllib.urlopen(solr_select).read()
     stats.end()
     try:
         return simplejson.loads(json_data)
     except:
         m = re_query_parser_error.search(json_data)
         return { 'error': web.htmlunquote(m.group(1)) }
Esempio n. 26
0
    def POST(self, profile_type, mail):
        i = web.input(
            enabledService=[],
            #mailForwardingAddress=[],
            shadowAddress=[],
            telephoneNumber=[],
            memberOfGroup=[],
            oldMemberOfAlias=[],
            memberOfAlias=[],
            #whitelistSender=[],
            #blacklistSender=[],
            #whitelistRecipient=[],
            #blacklistRecipient=[],
        )
        self.profile_type = web.safestr(profile_type)
        self.mail = str(mail).lower()

        userLib = userlib.User()
        result = userLib.update(
            profile_type=self.profile_type,
            mail=self.mail,
            data=i,
        )

        if result[0] is True:
            raise web.seeother('/profile/user/%s/%s?msg=UPDATED' %
                               (self.profile_type, self.mail))
        else:
            raise web.seeother(
                '/profile/user/%s/%s?msg=%s' %
                (self.profile_type, self.mail, web.urlquote(result[1])))
Esempio n. 27
0
    def GET(self, domain, cur_page=1):
        self.domain = web.safestr(domain).split('/', 1)[0]
        cur_page = int(cur_page)

        if not iredutils.is_domain(self.domain):
            raise web.seeother('/domains?msg=INVALID_DOMAIN_NAME')

        if cur_page == 0:
            cur_page = 1

        userLib = userlib.User()
        result = userLib.listAccounts(domain=self.domain, cur_page=cur_page,)
        if result[0] is True:
            (total, records) = (result[1], result[2])

            return web.render(
                'pgsql/user/list.html',
                cur_domain=self.domain,
                cur_page=cur_page,
                total=total,
                users=records,
                msg=web.input().get('msg', None),
            )
        else:
            raise web.seeother('/domains?msg=%s' % web.urlquote(result[1]))
Esempio n. 28
0
    def POST(self, profile_type, mail):
        self.profile_type = web.safestr(profile_type)
        self.mail = web.safestr(mail)
        i = web.input(domainName=[], )

        if session.get('domainGlobalAdmin'
                       ) is not True and session.get('username') != self.mail:
            # Don't allow to view/update others' profile.
            raise web.seeother(
                '/profile/admin/general/%s?msg=PERMISSION_DENIED' %
                session.get('username'))

        adminLib = adminlib.Admin()
        result = adminLib.update(
            profile_type=self.profile_type,
            mail=self.mail,
            data=i,
        )

        if result[0] is True:
            raise web.seeother('/profile/admin/%s/%s?msg=UPDATED' %
                               (self.profile_type, self.mail))
        else:
            raise web.seeother('/profile/admin/%s/%s?msg=%s' % (
                self.profile_type,
                self.mail,
                web.urlquote(result[1]),
            ))
Esempio n. 29
0
    def POST(self, profile_type, domain):
        self.profile_type = str(profile_type)
        self.domain = str(domain)

        i = web.input(
            domainAliasName=[],
            domainAdmin=[],
            defaultList=[],
        )

        domainLib = domainlib.Domain()
        result = domainLib.update(
            profile_type=self.profile_type,
            domain=self.domain,
            data=i,
        )

        if result[0] is True:
            raise web.seeother('/profile/domain/%s/%s?msg=UPDATED' %
                               (self.profile_type, self.domain))
        else:
            raise web.seeother('/profile/domain/%s/%s?msg=%s' % (
                self.profile_type,
                self.domain,
                web.urlquote(result[1]),
            ))
Esempio n. 30
0
    def POST(self):
        form = web.input(domainName=[], _unicode=False)

        domains = form.get('domainName', [])
        action = form.get('action', None)

        if not domains:
            raise web.seeother('/domains?msg=INVALID_DOMAIN_NAME')

        if action == 'delete':
            keep_mailbox_days = form_utils.get_single_value(
                form=form,
                input_name='keep_mailbox_days',
                default_value=0,
                is_integer=True)

            result = ldap_lib_domain.delete_domains(
                domains=domains, keep_mailbox_days=keep_mailbox_days)
            msg = 'DELETED'
        elif action == 'disable':
            result = ldap_lib_domain.enable_disable_domains(domains=domains,
                                                            action='disable')
            msg = 'DISABLED'
        elif action == 'enable':
            result = ldap_lib_domain.enable_disable_domains(domains=domains,
                                                            action='enable')
            msg = 'ENABLED'
        else:
            result = (False, 'INVALID_ACTION')
            msg = form.get('msg', None)

        if result[0] is True:
            raise web.seeother('/domains?msg=%s' % msg)
        else:
            raise web.seeother('/domains?msg=' + web.urlquote(result[1]))
Esempio n. 31
0
    def GET(self, profile_type, domain):
        i = web.input()
        self.domain = web.safestr(domain.split('/', 1)[0])
        self.profile_type = web.safestr(profile_type)

        if not iredutils.is_domain(self.domain):
            raise web.seeother('/domains?msg=EMPTY_DOMAIN')

        domainLib = domainlib.Domain()
        result = domainLib.profile(domain=self.domain)

        if result[0] is False:
            raise web.seeother('/domains?msg=' + web.urlquote(result[1]))

        r = domainLib.listAccounts(attrs=['domainName'])
        if r[0] is True:
            allDomains = r[1]
        else:
            return r

        allAccountSettings = ldaputils.getAccountSettingFromLdapQueryResult(
            result[1],
            key='domainName',
        )

        return web.render(
            'ldap/domain/profile.html',
            cur_domain=self.domain,
            allDomains=allDomains,
            allAccountSettings=allAccountSettings,
            profile=result[1],
            profile_type=self.profile_type,
            msg=i.get('msg', None),
        )
Esempio n. 32
0
    def GET(self, profile_type, mail):
        i = web.input()
        self.mail = str(mail).lower()
        self.cur_domain = self.mail.split('@', 1)[-1]
        self.profile_type = str(profile_type)

        if self.mail.startswith('@') and iredutils.is_domain(self.cur_domain):
            # Catchall account.
            raise web.seeother('/profile/domain/catchall/%s' % self.cur_domain)

        if not iredutils.is_email(self.mail):
            raise web.seeother('/domains?msg=INVALID_USER')

        if not iredutils.is_domain(self.cur_domain):
            raise web.seeother('/domains?msg=INVALID_DOMAIN_NAME')

        userLib = userlib.User()
        qr = userLib.profile(domain=self.cur_domain, mail=self.mail)
        if qr[0] is True:
            self.profile = qr[1]
        else:
            raise web.seeother('/users/%s?msg=%s' % (self.cur_domain, web.urlquote(qr[1])))

        return web.render(
            'pgsql/user/profile.html',
            cur_domain=self.cur_domain,
            mail=self.mail,
            profile_type=self.profile_type,
            profile=self.profile,
            languagemaps=get_language_maps(),
            msg=i.get('msg'),
        )
Esempio n. 33
0
    def POST(self, domain):
        i = web.input(_unicode=False, mail=[])

        self.domain = str(domain)

        if not iredutils.is_domain(self.domain):
            raise web.seeother('/domains?msg=INVALID_DOMAIN_NAME')

        self.mails = [str(v)
                      for v in i.get('mail', [])
                      if iredutils.is_email(v)
                      and str(v).endswith('@' + self.domain)
                     ]

        action = i.get('action', '')
        msg = i.get('msg', None)

        userLib = userlib.User()

        if action == 'delete':
            result = userLib.delete(domain=self.domain, mails=self.mails,)
            msg = 'DELETED'
        elif action == 'disable':
            result = userLib.enableOrDisableAccount(domain=self.domain, accounts=self.mails, active=False)
            msg = 'DISABLED'
        elif action == 'enable':
            result = userLib.enableOrDisableAccount(domain=self.domain, accounts=self.mails, active=True)
            msg = 'ENABLED'
        else:
            result = (False, 'INVALID_ACTION')

        if result[0] is True:
            raise web.seeother('/users/%s?msg=%s' % (self.domain, msg,))
        else:
            raise web.seeother('/users/%s?msg=%s' % (self.domain, web.urlquote(result[1]),))
Esempio n. 34
0
    def POST(self):
        i = web.input(domainName=[], _unicode=False,)

        self.domainName = i.get('domainName', [])
        self.action = i.get('action', None)

        domainLib = domainlib.Domain()

        if self.action == 'delete':
            result = domainLib.delete(domains=self.domainName)
            msg = 'DELETED'
        elif self.action == 'disable':
            result = domainLib.enableOrDisableAccount(domains=self.domainName, action='disable',)
            msg = 'DISABLED'
        elif self.action == 'enable':
            result = domainLib.enableOrDisableAccount(domains=self.domainName, action='enable',)
            msg = 'ENABLED'
        else:
            result = (False, 'INVALID_ACTION')
            msg = i.get('msg', None)

        if result[0] is True:
            raise web.seeother('/domains?msg=%s' % msg)
        else:
            raise web.seeother('/domains?msg=' + web.urlquote(result[1]))
Esempio n. 35
0
    def GET(self, cur_page=1):
        i = web.input()
        cur_page = int(cur_page)

        if cur_page == 0:
            cur_page == 1

        adminLib = adminlib.Admin()
        result = adminLib.listAccounts(cur_page=cur_page)
        if result[0] is True:
            (total, records) = (result[1], result[2])

            # Get list of global admins.
            allGlobalAdmins = []
            connutils = connUtils.Utils()
            qr = connutils.getAllGlobalAdmins()
            if qr[0] is True:
                allGlobalAdmins = qr[1]

            return web.render(
                'dbmail_mysql/admin/list.html',
                cur_page=cur_page,
                total=total,
                admins=records,
                allGlobalAdmins=allGlobalAdmins,
                msg=i.get('msg', None),
            )
        else:
            raise web.seeother('/domains?msg=%s' % web.urlquote(result[1]))
Esempio n. 36
0
    def POST(self):
        form = web.input(_unicode=False, mail=[])

        accounts = form.get('mail', [])
        action = form.get('action', None)
        msg = form.get('msg', None)

        _wrap = SQLWrap()
        conn = _wrap.conn

        if action == 'delete':
            result = sql_lib_admin.delete_admins(
                mails=accounts,
                revoke_admin_privilege_from_user=True,
                conn=conn)
            msg = 'DELETED'
        elif action == 'disable':
            result = sql_lib_utils.set_account_status(conn=conn,
                                                      accounts=accounts,
                                                      account_type='admin',
                                                      enable_account=False)
            msg = 'DISABLED'
        elif action == 'enable':
            result = sql_lib_utils.set_account_status(conn=conn,
                                                      accounts=accounts,
                                                      account_type='admin',
                                                      enable_account=True)
            msg = 'ENABLED'
        else:
            result = (False, 'INVALID_ACTION')

        if result[0] is True:
            raise web.seeother('/admins?msg=%s' % msg)
        else:
            raise web.seeother('/admins?msg=' + web.urlquote(result[1]))
Esempio n. 37
0
    def POST(self):
        i = web.input(_unicode=False, mail=[])

        self.mails = i.get('mail', [])
        self.action = i.get('action', None)
        msg = i.get('msg', None)

        adminLib = adminlib.Admin()

        if self.action == 'delete':
            result = adminLib.delete(mails=self.mails, )
            msg = 'DELETED'
        elif self.action == 'disable':
            result = adminLib.enableOrDisableAccount(
                accounts=self.mails,
                active=False,
            )
            msg = 'DISABLED'
        elif self.action == 'enable':
            result = adminLib.enableOrDisableAccount(
                accounts=self.mails,
                active=True,
            )
            msg = 'ENABLED'
        else:
            result = (False, 'INVALID_ACTION')

        if result[0] is True:
            raise web.seeother('/admins?msg=%s' % msg)
        else:
            raise web.seeother('/admins?msg=?' + web.urlquote(result[1]))
Esempio n. 38
0
    def GET(self, cur_page=1):
        form = web.input()
        cur_page = int(cur_page)

        if cur_page == 0:
            cur_page = 1

        _wrap = SQLWrap()
        conn = _wrap.conn

        result = sql_lib_admin.get_paged_admins(conn=conn, cur_page=cur_page)

        if result[0] is True:
            (total, records) = (result[1]['total'], result[1]['records'])

            # Get list of global admins.
            all_global_admins = []
            qr = sql_lib_admin.get_all_global_admins(conn=conn)
            if qr[0]:
                all_global_admins = qr[1]

            return web.render(
                'sql/admin/list.html',
                cur_page=cur_page,
                total=total,
                admins=records,
                allGlobalAdmins=all_global_admins,
                msg=form.get('msg', None),
            )
        else:
            raise web.seeother('/domains?msg=%s' % web.urlquote(result[1]))
Esempio n. 39
0
    def POST(self, profile_type, mail):
        mail = str(mail).lower()
        form = web.input(domainName=[], managed_domains=[])

        if not (session.get('is_global_admin')
                or session.get('username') == mail):
            # Don't allow to view/update others' profile.
            raise web.seeother(
                '/profile/admin/general/%s?msg=PERMISSION_DENIED' %
                session.get('username'))

        _wrap = SQLWrap()
        conn = _wrap.conn

        result = sql_lib_admin.update(mail=mail,
                                      profile_type=profile_type,
                                      form=form,
                                      conn=conn)

        if result[0]:
            raise web.seeother('/profile/admin/{}/{}?msg=UPDATED'.format(
                profile_type, mail))
        else:
            raise web.seeother('/profile/admin/{}/{}?msg={}'.format(
                profile_type, mail, web.urlquote(result[1])))
Esempio n. 40
0
    def POST(self):
        i = web.input(domainName=[], _unicode=False,)
        domainName = i.get('domainName', None)
        action = i.get('action')

        domainLib = domainlib.Domain()
        if action == 'delete':
            keep_mailbox_days = form_utils.get_single_value(form=i,
                                                            input_name='keep_mailbox_days',
                                                            default_value=0,
                                                            is_integer=True)

            result = domainLib.delete(domains=domainName, keep_mailbox_days=keep_mailbox_days)
            msg = 'DELETED'
        elif action == 'disable':
            result = domainLib.enableOrDisableAccount(accounts=domainName, active=False,)
            msg = 'DISABLED'
        elif action == 'enable':
            result = domainLib.enableOrDisableAccount(accounts=domainName, active=True,)
            msg = 'ENABLED'
        else:
            result = (False, 'INVALID_ACTION')
            msg = i.get('msg', None)

        if result[0] is True:
            raise web.seeother('/domains?msg=%s' % msg)
        else:
            raise web.seeother('/domains?msg=' + web.urlquote(result[1]))
Esempio n. 41
0
    def POST(self, profile_type, domain):
        profile_type = web.safestr(profile_type)
        domain = str(domain).lower()

        form = web.input(
            enabledService=[],
            domainAdmin=[],
            defaultList=[],
        )

        if domain != web.safestr(form.get('domainName', None)).lower():
            raise web.seeother(
                '/profile/domain/{}/{}?msg=DOMAIN_NAME_MISMATCH'.format(
                    profile_type, domain))

        qr = ldap_lib_domain.update(domain=domain,
                                    profile_type=profile_type,
                                    form=form,
                                    conn=None)

        if qr[0] is True:
            raise web.seeother('/profile/domain/{}/{}?msg=UPDATED'.format(
                profile_type, domain))
        else:
            raise web.seeother('/profile/domain/{}/{}?msg={}'.format(
                profile_type, domain, web.urlquote(qr[1])))
Esempio n. 42
0
def simple_search(q, offset=0, rows=20, sort=None):
    solr_select = solr_select_url + "?version=2.2&q.op=AND&q=%s&fq=&start=%d&rows=%d&fl=*%%2Cscore&qt=standard&wt=json" % (web.urlquote(q), offset, rows)
    if sort:
        solr_select += "&sort=" + web.urlquote(sort)

    stats.begin("solr", url=solr_select)
    json_data = urllib.urlopen(solr_select)
    stats.end()
    return json.load(json_data)
Esempio n. 43
0
 def POST(self):
     i = web.input()
     self.domain = web.safestr(i.get('domainName')).strip().lower()
     domainLib = domainlib.Domain()
     result = domainLib.add(data=i)
     if result[0] is True:
         raise web.seeother('/profile/domain/general/%s?msg=CREATED' % self.domain)
     else:
         raise web.seeother('/create/domain?msg=%s' % web.urlquote(result[1]))
Esempio n. 44
0
	def GET(self):
		login_error = '登录失败,可能是服务器与新浪oauth服务交互出现问题,请稍候重试,<a href="/">返回</a>'

		i = web.input()
		if i.get('act') == 'auth':
			try:
				token, secret = login_auth.get_weibo_token()
			except:
				web.header('Content-Type', 'text/html; charset=utf-8')
				traceback.print_exc()
				return login_error
			session.token = token
			session.secret = secret
			if web.ctx.env['SERVER_PORT'] == '9527':
				oauth_callback = web.urlquote('http://localhost:9527/login?act=callback')
			else:
				oauth_callback = web.urlquote('http://gaoding.me/login?act=callback')

			raise web.seeother('http://api.t.sina.com.cn/oauth/authorize?oauth_token=%(token)s&oauth_callback=%(oauth_callback)s' % locals())
		elif i.get('act') == 'callback':
			'''
			http://localhost:8080/login?act=callback&oauth_token=e43e721b87c0b1c5fc9ad0746fcd1c0f&oauth_verifier=186264
			'''
			token = i.get('oauth_token')
			secret = session.get('secret')
			oauth_verifier = i.get('oauth_verifier')
			
			try:
				token, secret, user_id = login_auth.get_weibo_access_token(token, secret, oauth_verifier)
				user_info = login_auth.get_weibo_info(token, secret)
			except:
				traceback.print_exc()
				web.header('Content-Type', 'text/html; charset=utf-8')
				return login_error

			user_info = simplejson.loads(user_info)
			
			user = User()
			user.login('weibo', user_info)

			raise web.seeother('/')

		return 'Access denied'
Esempio n. 45
0
    def GET(self, domain=None,):
        if domain is None:
            self.cur_domain = None
        else:
            self.cur_domain = str(domain)
            if not iredutils.is_domain(self.cur_domain):
                raise web.seeother('/domains?msg=INVALID_DOMAIN_NAME')

        i = web.input()

        # Get all managed domains.
        connutils = connUtils.Utils()
        qr = connutils.getManagedDomains(admin=session.get('username'), domainNameOnly=True,)

        if qr[0] is True:
            allDomains = qr[1]
        else:
            raise web.seeother('/domains?msg=' % web.urlquote(qr[1]))

        # Set first domain as current domain.
        if self.cur_domain is None:
            if len(allDomains) > 0:
                raise web.seeother('/create/user/%s' % str(allDomains[0]))
            else:
                raise web.seeother('/domains?msg=NO_DOMAIN_AVAILABLE')

        # Get domain profile.
        domainLib = domainlib.Domain()
        resultOfProfile = domainLib.profile(domain=self.cur_domain)
        if resultOfProfile[0] is True:
            self.profile = resultOfProfile[1]
        else:
            raise web.seeother('/domains?msg=%s' % web.urlquote(resultOfProfile[1]))

        return web.render(
            'pgsql/user/create.html',
            cur_domain=self.cur_domain,
            allDomains=allDomains,
            profile=self.profile,
            min_passwd_length=settings.min_passwd_length,
            max_passwd_length=settings.max_passwd_length,
            msg=i.get('msg'),
        )
	def process(self):
		i = web.input()
		
		if 'redirect' in i:
			redirect = i['redirect']
		else:
			redirect = '/'
		
		self.setVariable('redirect',redirect)
		self.setVariable('redirect_quote',web.urlquote( redirect ) )
Esempio n. 47
0
    def GET(self, domainName=None):
        i = web.input()

        if domainName is None:
            self.cur_domain = ''
        else:
            self.cur_domain = web.safestr(domainName)

        domainLib = domainlib.Domain()
        result = domainLib.listAccounts(attrs=['domainName', 'accountSetting', 'domainCurrentQuotaSize', ])
        if result[0] is True:
            allDomains = result[1]

            if len(allDomains) == 0:
                raise web.seeother('/domains?msg=NO_DOMAIN_AVAILABLE')
            else:
                # Redirect to create new user under first domain, so that we
                # can get per-domain account settings, such as number of
                # account limit, password length control, etc.
                if self.cur_domain == '':
                    raise web.seeother('/create/user/' + str(allDomains[0][1]['domainName'][0]))

            # Get accountSetting of current domain.
            allAccountSettings = ldaputils.getAccountSettingFromLdapQueryResult(allDomains, key='domainName')
            domainAccountSetting = allAccountSettings.get(self.cur_domain, {})
            defaultUserQuota = domainLib.getDomainDefaultUserQuota(self.cur_domain, domainAccountSetting)
        else:
            raise web.seeother('/domains?msg=' % web.urlquote(result[1]))

        # Get number of account limit.
        connutils = connUtils.Utils()
        result = connutils.getNumberOfCurrentAccountsUnderDomain(self.cur_domain, accountType='user', )
        if result[0] is True:
            numberOfCurrentAccounts = result[1]
        else:
            numberOfCurrentAccounts = 0

        # Get current domain quota size.
        result = connutils.getDomainCurrentQuotaSizeFromLDAP(domain=self.cur_domain)
        if result[0] is True:
            domainCurrentQuotaSize = result[1]
        else:
            # -1 means temporary error. Don't allow to create new user.
            domainCurrentQuotaSize = -1

        return web.render('ldap/user/create.html',
                          cur_domain=self.cur_domain,
                          allDomains=allDomains,
                          defaultUserQuota=defaultUserQuota,
                          domainAccountSetting=domainAccountSetting,
                          numberOfCurrentAccounts=numberOfCurrentAccounts,
                          domainCurrentQuotaSize=domainCurrentQuotaSize,
                          msg=i.get('msg'),
                         )
Esempio n. 48
0
def search_inside_result_count(q):
    q = escape_q(q)
    solr_select = solr_select_url + "?fl=ia&q.op=AND&wt=json&q=" + web.urlquote(q)
    stats.begin("solr", url=solr_select)
    json_data = urllib.urlopen(solr_select).read()
    stats.end()
    try:
        results = simplejson.loads(json_data)
    except:
        return None
    return results['response']['numFound']
Esempio n. 49
0
def search_inside_result_count(q):
    q = escape_q(q)
    params = {
        'fl': 'ia',
        'q.op': 'AND',
        'q': web.urlquote(q)
    }
    results = inside_solr_select(params)
    if 'error' in results:
        return None

    return results['response']['numFound']
Esempio n. 50
0
    def POST(self):
        i = web.input()
        self.mail = web.safestr(i.get('mail'))

        adminLib = adminlib.Admin()
        result = adminLib.add(data=i)

        if result[0] is True:
            # Redirect to assign domains.
            raise web.seeother('/profile/admin/general/%s?msg=CREATED' % self.mail)
        else:
            raise web.seeother('/create/admin?msg=' + web.urlquote(result[1]))
Esempio n. 51
0
    def POST(self, domain):
        i = web.input()

        # Get domain name, username, cn.
        self.username = web.safestr(i.get('username', ''))
        self.cur_domain = web.safestr(i.get('domainName', ''))

        userLib = userlib.User()
        result = userLib.add(domain=self.cur_domain, data=i)
        if result[0] is True:
            raise web.seeother('/profile/user/general/%s@%s?msg=CREATED' % (self.username, self.cur_domain))
        else:
            raise web.seeother('/create/user/%s?msg=%s' % (self.cur_domain, web.urlquote(result[1])))
Esempio n. 52
0
        def get_results(q, offset=0, limit=100, snippets=3, fragsize=200, hl_phrase=False):
            m = re_bad_fields.match(q)
            if m:
                return { 'error': m.group(1) + ' search not supported' }
            q = escape_q(q)
            solr_params = [
                ('fl', 'ia,body_length,page_count'),
                ('hl', 'true'),
                ('hl.fl', 'body'),
                ('hl.snippets', snippets),
                ('hl.mergeContiguous', 'true'),
                ('hl.usePhraseHighlighter', 'true' if hl_phrase else 'false'),
                ('hl.simple.pre', '{{{'),
                ('hl.simple.post', '}}}'),
                ('hl.fragsize', fragsize),
                ('q.op', 'AND'),
                ('q', web.urlquote(q)),
                ('start', offset),
                ('rows', limit),
                ('qf', 'body'),
                ('qt', 'standard'),
                ('hl.maxAnalyzedChars', '-1'),
                ('wt', 'json'),
            ]
            solr_select = solr_select_url + '?' + '&'.join("%s=%s" % (k, unicode(v)) for k, v in solr_params)
            stats.begin("solr", url=solr_select)
            json_data = urllib.urlopen(solr_select).read()
            stats.end()
           
            try:
                results = simplejson.loads(json_data)
            except:
                m = re_query_parser_error.search(json_data)
                return { 'error': web.htmlunquote(m.group(1)) }

            ekey_doc = {}
            for doc in results['response']['docs']:
                ia = doc['ia']
                q = {'type': '/type/edition', 'ocaid': ia}
                ekeys = web.ctx.site.things(q)
                if not ekeys:
                    del q['ocaid']
                    q['source_records'] = 'ia:' + ia
                    ekeys = web.ctx.site.things(q)
                if ekeys:
                    ekey_doc[ekeys[0]] = doc

            editions = web.ctx.site.get_many(ekey_doc.keys())
            for e in editions:
                ekey_doc[e['key']]['edition'] = e
            return results
Esempio n. 53
0
def result_table(data, birth, death, order):
    html = ' %d results' % len(data)
    l = []
    def clean(i, default, field):
        if field not in i:
            return default
        if i[field] is None:
            return ''
        m = re_year.match(i[field])
        return m.group(1) if m else i[field]

    data = [
        {
            'key': i['key'],
            'name': i['name'],
            'birth': clean(i, birth, 'birth_date'),
            'death': clean(i, death, 'death_date'),
        } for i in data]

    base_url = web.htmlquote("?birth=%s&death=%s&order=" % (web.urlquote(birth), web.urlquote(death)))
    html += '<tr>'
    html += '<th><a href="' + base_url + 'name">Name</a></th>'
    if birth:
        html += '<th>birth</th>'
    else:
        html += '<th><a href="' + base_url + 'birth">birth</a></th>'
    if death:
        html += '<th>death</th>'
    else:
        html += '<th><a href="' + base_url + 'death">death</a></th>'
    html += '</tr>'
    if order:
        data = sorted(data, key=lambda i:i[order])
    for i in data:
        html += '<tr><td><a href="http://openlibrary.org%s">%s</td><td>%s</td><td>%s</td><tr>' % (i['key'], web.htmlquote(i['name']), i['birth'], i['death'])
    return '<table>' + html + '</table>'
Esempio n. 54
0
def get_all_ia():
    print 'c'
    q = {'source_records~': 'ia:*', 'type': '/type/edition'}
    limit = 10
    q['limit'] = limit
    q['offset'] = 0

    while True:
        url = base_url() + "/api/things?query=" + web.urlquote(json.dumps(q))
        ret = jsonload(url)['result']
        for i in ret:
            yield i
        if not ret:
            return
        q['offset'] += limit
Esempio n. 55
0
 def GET(self, tags = None):
     if tags:
         tags = [tag.lower() for tag in tags.split('/')]
     else: 
         tags = []
         
     add_tag = web.input(addtag = None)['addtag']
     remove_tag = web.input(removetag = None)['removetag']
     page = int(web.input(page = 1)['page'])
     category = web.input(category = '')['category']
     
     if add_tag in tags  or len(tags)>= MAX_NUMBER_OF_TAGS_FILTERS:
         add_tag = None
     
     if add_tag:
         tags = tags + [tag.lower() for tag in add_tag.split()]
         if category:
             return web.redirect('/tag/%s?category=%s' % (web.urlquote('/'.join(tags)), category))
         else:
             return web.redirect('/tag/%s' % web.urlquote('/'.join(tags)))
     if remove_tag:
         tags.remove(remove_tag.lower())
         if category:
             return web.redirect('/tag/%s?category=%s' % (web.urlquote('/'.join(tags)), category))
         else:
             return web.redirect('/tag/%s' % web.urlquote('/'.join(tags)))
     
     posts_count = models.Post.get_posts_count(tags_filter = tags, category_filter= category)
     posts = models.Post.get_posts(page, limit = POSTS_PER_PAGE, offset = POSTS_PER_PAGE * (page - 1), tags_filter = tags, category_filter= category)
     
     return render_template(render.index(posts, 
                                         tags, 
                                         category, 
                                         pagination = utils.Pagination(posts_count, page, POSTS_PER_PAGE),
                                         is_user_admin = users.is_current_user_admin()),
                                         title = 'Home')
Esempio n. 56
-1
def grab_screenshot(screenshot_url):
    try:
        data = utils.dnl(screenshot_url)
        guid = utils.get_guid() + "." + utils.get_extension_from_url(screenshot_url)
        image.save(data, "public/img/screenshot/" + guid)

    except:
        raise 'Ooops! Submission has failed &#8211; <a href="%s">' % web.urlquote(
            screenshot
        ) + " the screenshot</a> in your XML could not be found, was broken, or had the wrong dimensions" + " (should be above 30x20 and below 460x420)."

    return guid