Exemple #1
0
def post_handler(req, issue, options):
    db = ibis.IBISDatabase(MAIN_SERVER)
    fs = util.FieldStorage(req, 1)
    #
    req.write(preamble(title="Issue %s" % issue, subtitle=[]))
    req.write('<pre>\n')
    req.write('  disp = [%s]\n' % fs['disp'])
    req.write('  disp_orig = [%s]\n' % fs['disp_orig'])
    nt = stripcr(fs['title'])
    req.write('  new title      = [%s]\n' % html_escape(nt))
    req.write('  new title hash = [%s]\n' % longhash(nt))
    req.write('  old title hash = [%s]\n' % fs['title_hash'])
    req.write('</pre>\n')

    req.write('Processing actions:<br>\n')
    req.write('<hr>\n')
    d = fs['disp']
    if d == "undecided":
        d = ""
    if d != fs['disp_orig']:
        req.write("Set disposition to <b>%s</b>.<br>\n" % d)
        db.mark(issue, 'disposition', d)
    req.write('<hr>\n')
    req.write('<a href="%s?edit=1">[Back to Edit]</a>&nbsp;&nbsp;' % issue)
    req.write('<a href="%s">[View]</a><br>' % issue)
Exemple #2
0
def fup_page(session, req, item, args):
    fup = args['fup']
    db = ibis.IBISDatabase(session.server)
    db.setSession(session)

    if req.method == 'POST':
        fs = util.FieldStorage(req, 1)
        if fup == 'note':
            db.add_note(item, stripcr(fs['title']), stripcr(fs['desc']),
                        'text/plain')
        else:
            db.followup(item, fup, stripcr(fs['title']), stripcr(fs['desc']),
                        None)
        iparent = string.split(item, '.')
        item = iparent[0]
        return do_redirect(session, req,
                           "%s?sid=%s&t=%d" % (item, session.id, time.time()))
    else:
        p = get_processor(req, "fup-specialize")
        z = db.item_details_xml(item)
        r = p.runString(z,
                        topLevelParams={
                            'timestamp': right_now(),
                            'sid': session.id,
                            'user': session.user,
                            'fuptype': fup
                        })
        req.write(r)
        return apache.OK
Exemple #3
0
def notificationLogging(request):
    db = DBConnection()

    form = util.FieldStorage(request)
    event_type = form['Event.1.EventType'].value
    event_time = parseISO(form['Event.1.EventTime'].value)
    hit_type_id = form['Event.1.HITTypeId'].value
    hit_id = form['Event.1.HITId'].value
    assignment_id = None
    if form.has_key('Event.1.AssignmentId'):
        assignment_id = form['Event.1.AssignmentId'].value

    #TODO: check to make sure we never get "event.2.eventtype" etc.
    logging.info("Event notification from MTurk: " + str(event_type) + " " +
                 str(event_time) + " " + str(hit_type_id) + " " + str(hit_id) +
                 " " + str(assignment_id))

    try:
        db.query_and_return_array(
            "INSERT INTO notifications (eventtype, timestamp, hittypeid, hitid, assignmentid) VALUES (%s, %s, %s, %s, %s)"
            "", (event_type, event_time, hit_type_id, hit_id, assignment_id))

        if event_type == "AssignmentReturned":
            db.query_and_return_array(
                """UPDATE `assignments` SET `return` = %s WHERE `assignmentid` = %s;""",
                (event_time, assignment_id))

    except Exception:
        logging.exception("Notification exception")
Exemple #4
0
def annotate_item(session, req, item, args):
    if req.method != "POST":
        raise 'Expected POST method'
    fs = util.FieldStorage(req)
    db = ibis.IBISDatabase(session.server)
    db.add_note(item, stripcr(fs['title']), stripcr(fs['desc']), fs['mime'])
    return redirect_item(session, req, item, args)
Exemple #5
0
    def content(self):
        """
		Create response
		"""
        global svg_stylesheet
        global defs_stylesheet

        ns = etree.FunctionNamespace("http://www.praterm.com.pl/ISL/pxslt")
        ns.prefix = 'pxslt'
        ns['isl_vu'] = self.isl_vu

        fc = util.FieldStorage(self.req)
        req_type = fc.getfirst('type')
        if req_type == 'defs':
            stylesheet = XSLT(defs_stylesheet)
        else:
            stylesheet = XSLT(svg_stylesheet)

        # this should be set in Apache configuration file using
        # PythonOption directive, for example:
        #   PythonOption szarp.paramd.uri "http://localhost:8081/"
        paramd_uri = self.req.get_options()['szarp.paramd.uri']

        fname = 'file:///etc/szarp/default/config' + self.req.parsed_uri[
            apache.URI_PATH]

        doc = etree.parse(fname, parser)

        r = 'test'
        try:
            r = stylesheet(doc, uri="'" + paramd_uri + "'")
        except Exception, e:
            self.req.log_error('content: stylesheet failed %s' % str(e),
                               apache.APLOG_ERR)
            r = stylesheet.error_log
Exemple #6
0
def getText(request):
    request.content_type = "application/json"

    db = MySQLdb.connect(host=settings.DB_HOST,
                         passwd=settings.DB_PASSWORD,
                         user=settings.DB_USER,
                         db=settings.DB_DATABASE,
                         use_unicode=True)
    cur = db.cursor(MySQLdb.cursors.DictCursor)

    form = util.FieldStorage(request)
    id = int(form['textid'].value)

    cur.execute("""SELECT html FROM texts WHERE pk = %s""", (id, ))

    text = cur.fetchone()
    paragraph = text['html']

    result = dict()
    result['pk'] = id
    result['text'] = paragraph

    request.write(json.dumps(result))

    cur.close()
    db.close()
Exemple #7
0
def modPythonHandler(apacheReq, service):
    from mod_python import apache, util
    try:
        if apacheReq.headers_in.has_key("X-Forwarded-Host"):
            host = "http://" + apacheReq.headers_in["X-Forwarded-Host"]
        else:
            host = "http://" + apacheReq.headers_in["Host"]
        host += apacheReq.uri[:-len(apacheReq.path_info)]
        format, image = service.dispatchRequest(util.FieldStorage(apacheReq),
                                                apacheReq.path_info,
                                                apacheReq.method, host)
        apacheReq.content_type = format
        apacheReq.status = apache.HTTP_OK
        if format.startswith("image/"):
            if service.cache.sendfile:
                apacheReq.headers_out['X-SendFile'] = image
            if service.cache.expire:
                apacheReq.headers_out['Expires'] = email.Utils.formatdate(
                    time.time() + service.cache.expire, False, True)

        apacheReq.set_content_length(len(image))
        apacheReq.send_http_header()
        if format.startswith("image/") and service.cache.sendfile:
            apacheReq.write("")
        else:
            apacheReq.write(image)
    except TileCacheException, E:
        apacheReq.content_type = "text/plain"
        apacheReq.status = apache.HTTP_NOT_FOUND
        apacheReq.send_http_header()
        apacheReq.write("An error occurred: %s\n" % (str(E)))
Exemple #8
0
def index(req):
    form = util.FieldStorage(req)
    act = req.form.getfirst('act')
    if act == 'login':
        if not login(req): printHtmlWithAlert(req)
    else:
        printHtml(req)
Exemple #9
0
 def __init__(self, aRequest):
     
     self.OK = apache.OK
     self.HTTP_NOT_ACCEPTABLE = apache.HTTP_NOT_ACCEPTABLE
     
     # Set response hook to equal the Request object.
     self.response = aRequest
     self.load_params(aRequest)
     
     # Set uri data from Request object.
     if aRequest.protocol.count('HTTPS') > 0: self.protocol = 'https'
     rawIP, self.port = aRequest.connection.local_addr
     self.hostname = aRequest.hostname
     atoms = aRequest.uri.split("/")
     self.script = atoms.pop()
     self.path = "/".join(atoms)
     
     self.user = aRequest.user
     
     # Retrieve the submitted parameters from Apache/mod_python.
     # ONLY CALL ONCE per request.
     newData = util.FieldStorage(aRequest, 1).list
     self.requestParams.flush()
     if newData is not None:
         for eachParam in newData:
             self.requestParams.add_param(str(eachParam.name),
                                          str(eachParam.value))
Exemple #10
0
def index(req):

    req.content_type = 'text/html; charset=utf-8'
    form = req.form or util.FieldStorage(req)

    p = form.get('p', None)  # page
    q = form.get('q', None)  # query
    d = form.get('d', None)  # dir
    s = form.get('s', None)  # search
    x = form.get('x', None)  # extra
    j = form.get('j', None)  # json

    if j:
        xurl.init(logfile='vod-load-json.log')
        j = getUnparsedURL(req) or j
        req.write(xurl.load(j))

    elif p:
        xurl.init(logfile='vod-page.log')
        p = getUnparsedURL(req) or p
        req.write(page.getPageJSON(p))

    elif q:
        xurl.init(logfile='vod-page-search.log')
        req.write(page.getSearchJSON(q, s, x))

    elif d:
        req.write(page.getDIRJSON(d))

    return
Exemple #11
0
def index(req):
    #pobranie parametru GET[url]
    form = util.FieldStorage(req, keep_blank_values=1)
    url = form.getfirst("url")

    try:
        url = urllib.url2pathname(url)
        #wyciaganie domeny z url
        domain = urlparse(url).netloc
        #pobranie tresci strony
        page = get_content(url)
        #zdeponowanie w utf8
        page = page.decode('utf-8')
        #jesli dolaczone media nie maja byc keszowane
        if (CACHE == False):
            #dopisanie do tresci strony obrazka w formie base64
            page = get_images_base64(page, url)
        #keszowanie zawartosci
        else:
            #zapisanie obrazka w keszu i podlaczenie pod strone
            page = get_images_cache(page, url)
        page = redirect_ahref(page, url)
    #pojawil sie blad w polaczeniu lub nie podano url
    except:
        #pusta strona startowa
        page = "<html><head></head><body>  </body></html>"
        #podlaczenie paska z polem do wpisania url
        page = add_bar(page)
    return page
Exemple #12
0
 def _setup_form(self):
     self.form = {}
     if self.reallympy:
         from mod_python import util
         pg_fields = util.FieldStorage(self.mpyreq, 1).list
         for field in pg_fields:
             self.form[field.name] = field.value
Exemple #13
0
    def add(self, path=None, req=None):

        if not self.isvalidrequest(path, req):
            return (self.patherror, None, 'application/json')

        try:
            thefile = util.FieldStorage(
                req
            )['file']  #TODO get the correct param name for the field holding the file
            newName = thefile.filename

            with open(newName, 'rb') as f:
                f.write(thefile.value)

        except:

            result = {
                'Path': path,
                'Name': newName,
                'Error': file_currenterror
            }

        else:
            result = {
                'Path': path,
                'Name': newName,
                'Error': 'No file was uploaded.'
            }

        req.content_type('text/html')
        req.write(('<textarea>' + encode_json(result) + '</textarea>'))
Exemple #14
0
def log(request):
    db = DBConnection()

    form = util.FieldStorage(request)

    event = form['event'].value
    detail = form['detail'].value  # e.g., word number
    assignment = form['assignmentid'].value
    worker = form['workerid'].value
    hit = form['hitid'].value
    ip = request.connection.remote_ip
    useragent = request.headers_in['User-Agent']
    time = parseISO(form['time'].value)
    servertime = unixtime(datetime.now())

    #logging.debug("Logging assignment %s event %s" % (assignment, event))

    try:
        db.query_and_return_array(
            """INSERT INTO logging (event, detail, assignmentid, time, servertime, ip, useragent) VALUES (%s, %s, %s, %s, %s, %s, %s)""",
            (event, detail, assignment, time, servertime, ip, useragent))

        # if it's an accept event, we start logging information about it in our assignments table
        if event == "accept":
            db.query_and_return_array(
                """INSERT INTO assignments (assignmentid, workerid, hitid, accept) VALUES (%s, %s, %s, %s) ON DUPLICATE KEY UPDATE workerid = %s, `accept` = %s, `show` = NULL, `go` = NULL, `first` = NULL, `submit` = NULL, `videoid` = NULL""",
                (assignment, worker, hit, time, worker, time))
    except:
        logging.exception("Logging exception:")
Exemple #15
0
def handler(req):
    try:
        if req.session["kirjautunut"] == "ok":
            return apache.OK
    except:
        f = urllib.urlopen(
            "http://users.jyu.fi/~helireki/wsovellukset15/demo4/kirjaudu.html")
        pohja = f.read()
        dom1 = parseString(pohja)
        form = util.FieldStorage(req)
        tunnus = form.getfirst("tunnus")
        salasana = form.getfirst("salasana")
        if tunnus == "*****@*****.**" and salasana == "salasana":
            req.session["kirjautunut"] = "ok"
            req.session.save()
            return apache.OK
        req.content_type = "text/html ;charset=utf-8"

        bodi = dom1.getElementsByTagName("body")[0]
        viesti = ""
        if form.getfirst("kirjaudu") == "Kirjaudu":
            if tunnus != "*****@*****.**":
                viesti = "Käyttäjätunnusta ei löytynyt. "
            elif salasana != "salasana":
                viesti += "Käyttäjätunnus oli oikea, mutta salasana väärä. "
            p = dom1.createElement("p")
            viesti += "Syötä tunnus ja salasana uudelleen."
            p.appendChild(dom1.createTextNode(viesti.decode("UTF-8")))
            bodi.appendChild(p)
        req.write(dom1.toxml("UTF-8"))

    return apache.DONE
Exemple #16
0
def setAgreement(request):
    form = util.FieldStorage(request)
    worker_id = form['workerid'].value
    
    db=DBConnection()
    
    result = db.query_and_return_array("""UPDATE workers SET read_instructions = TRUE WHERE workerid = %s""", (worker_id, ))
Exemple #17
0
def disableVideo(request):
    db = DBConnection()
    form = util.FieldStorage(request)
    videoid = form['videoid'].value

    db.query_and_return_array("""DELETE FROM pictures WHERE videoid = %s""", (videoid, ))
    db.query_and_return_array("""UPDATE videos SET enabled = FALSE WHERE pk = %s""", (videoid, ))
Exemple #18
0
def handler(req):
    req.send_http_header()
    req.content_type = 'text/html;charset=UTF-8'
    session = Session.Session(req, timeout=3600)
    session.load()
    session = session_init(session)
    oauth_manager = oauthmanager.OAuth_manager(session)
    calender_api = calenderapi.Calender_api(oauth_manager)
    #request parameter
    formValueList = util.FieldStorage(req)
    #URL에서 파일명 추출
    real_file_name = req.filename[req.filename.rfind('/') + 1:]
    if real_file_name == 'index.html':
        #등록된 accessToken이 있는지 판단
        if oauth_manager.check_access_token():
            template = file(config.index_file).read()
            search_date = formValueList.get(
                'date',
                '%s-%s' % (time.localtime().tm_year, time.localtime().tm_mon))
            try:
                content = createcalender.Create_calender(
                    int(search_date.split('-')[0]),
                    int(search_date.split('-')[1]), calender_api)
            except ValueError, error:
                #data 형식이 잘못 되었을 경우
                req.write("ValueError -> %s" % error)
            else:
                req.write(template % content)
        else:
            #등록된 accessToken이 없다면 인증페이지로
            util.redirect(req, 'oauth.py')
Exemple #19
0
    def __init__(self, req, fields):
        htmllib.html.__init__(self)

        self.enable_request_timeout()

        req.content_type = "text/html; charset=UTF-8"
        req.header_sent = False

        # All URIs end in .py. We strip away the .py and get the
        # name of the page.
        self.myfile = req.uri.split("/")[-1][:-3]

        self.req = req
        if fields:
            self.fields = fields
        else:
            self.fields = util.FieldStorage(self.req, keep_blank_values = 1)
        self.read_get_vars()
        self.read_cookies()

        # Disable caching for all our pages as they are mostly dynamically generated,
        # user related and are required to be up-to-date on every refresh
        self.set_http_header("Cache-Control", "no-cache")

        self.init_mobile()
        self.set_output_format(self.var("output_format", "html"))
Exemple #20
0
def modPythonHandler(apacheReq, service):
    from mod_python import apache, util
    try:
        if "X-Forwarded-Host" in apacheReq.headers_in:
            host = "http://" + apacheReq.headers_in["X-Forwarded-Host"]
        else:
            host = "http://" + apacheReq.headers_in["Host"]
        host += apacheReq.uri[:-len(apacheReq.path_info)]
        fmt, image = service.dispatchRequest(util.FieldStorage(apacheReq),
                                             apacheReq.path_info,
                                             apacheReq.method,
                                             host)
        apacheReq.content_type = fmt
        apacheReq.status = apache.HTTP_OK
        if format.startswith("image/"):
            if service.cache.sendfile:
                apacheReq.headers_out['X-SendFile'] = image
            if service.cache.expire:
                apacheReq.headers_out['Expires'] = email.Utils.formatdate(
                    time.time() + service.cache.expire, False, True)

        apacheReq.set_content_length(len(image))
        apacheReq.send_http_header()
        if format.startswith("image/") and service.cache.sendfile:
            apacheReq.write("")
        else:
            apacheReq.write(image)
    except IOError, E:
        pass
def handler(req):
    req.content_type = "text/html"
    if req.header_only:
        # Don't supply the body
        return apache.OK

    req.write("""<HTML>
<HEAD>
<TITLE>mod_python Escape Example</TITLE></HEAD><BODY>""")

    form = util.FieldStorage(req)

    if form.getfirst('data') == None:
        req.write("No submitted data.<P>\n")
    else:
        req.write("Submitted data:<P>\n")
        req.write('<A HREF="%s?data=%s"><TT>%s</TT></A><P>' % \
                  (req.uri,
                   urllib.quote_plus(form.getfirst('data')),
                   escape(form.getfirst('data'))))

    req.write("""<FORM METHOD="GET" ACTION="%s">
    Supply some data: 
    <INPUT TYPE="text" NAME="data" WIDTH="40">
    <INPUT TYPE="submit" NAME="submit" VALUE="Submit">
    </FORM>
    </BODY></HTML>\n""" % req.uri)

    return apache.OK
Exemple #22
0
def is_ready(request):
    request.content_type = "application/json"
    db = DBConnection(autocommit=False)

    form = util.FieldStorage(request)
    assignmentid = form['assignmentid'].value
    workerid = form['workerid'].value

    if form.has_key('videoid'):
        videoid = int(form['videoid'].value)
    else:
        is_slow = form.has_key('slow') and form['slow'] == "1"
        result = unlabeledVideos(db, is_slow)
        logging.debug(result)

        if is_slow:
            # have I already labeled this video?
            result = filter(lambda x: not haveCompleted(x['pk'], workerid, db),
                            result)

        if len(result) == 0:
            request.write(json.dumps({'is_ready': False}))
            return
        else:
            # grab the most recent video upload
            logging.debug("Videos needing labels: " + str(result))
            videoid = result[0]['pk']

    video = getAndAssignVideo(assignmentid, videoid)
    db.commit()
    request.write(json.dumps(video, cls=location_ping.DecimalEncoder))
Exemple #23
0
def verify_core(req):
    """This is the first phase of the OpenID login. We check the
	provided identifier, try to work out who we should ask about it,
	and redirect the user to the provider's site for their login
	process."""
    # Set up the OpenID library
    session = Session.Session(req, timeout=60)
    global store
    if store is None:
        Logger.log.debug("Creating new store")
        server_options = req.get_options()
        store_path = os.path.join(server_options['wor.root_path'], "oid_store")
        store = filestore.FileOpenIDStore(store_path)
    oid_consumer = consumer.Consumer(session, store)

    # Get the user's account details that they provided
    if getattr(req, "form", None) is None:
        req.form = util.FieldStorage(req, True)
    account = req.form.getfirst("openid_identifier")

    # Look up the OAuth provider for this account
    try:
        request = oid_consumer.begin(account)
    except consumer.DiscoveryFailure, ex:
        raise
Exemple #24
0
def headerparserhandler(req):
    options = req.get_options()

    realm = None
    if options.has_key('Realm'):
        realm = options['Realm']
    else:
        apache.log_error('no realm specified')
        return apache.DECLINED

    # if the token is in the URL, extract it and send it to the login page
    token = None
    if req.args != None:
        try:
            dict = util.FieldStorage(req)
            if dict.has_key('token'):
                token = dict['token']
        except:
            pass

    sess = Session.Session(req, lock=0)
    sess.lock()
    sess.set_timeout(SESSION_TIMEOUT)

    username = session_user(sess, realm)

    if None == username and realm == 'Reports':
        username = session_user(sess, 'Administrator')

    if None == username and realm == 'SetupWizard':
        username = session_user(sess, 'Administrator')

    if None == username and realm == 'SetupWizard' and not is_wizard_complete():
        username = '******'
        save_session_user(sess, realm, username)

    if None == username and is_local_process_uid_authorized(req):
        username = '******'
        log_login(req, username, True, True, None)
        save_session_user(sess, realm, username)

    #if sess.has_key('apache_realms'):
    #    apache.log_error('DEBUG apache_realms: %s' % sess['apache_realms'])
    #    if sess['apache_realms'].has_key(realm):
    #        apache.log_error('DEBUG apache_realms[%s]: %s' % (realm, sess['apache_realms'][realm]))
    #else:
    #    apache.log_error('DEBUG apache_realms: %s' % None)

    sess.save()
    sess.unlock()

    if username != None:
        pw = base64.encodestring('%s' % username).strip()
        req.headers_in['Authorization'] = "BASIC % s" % pw
        req.notes['authorized'] = 'true'
        return apache.OK

    apache.log_error('Auth failure [Username not specified]. Redirecting to auth page. (realm: %s)' % realm)
    login_redirect(req, realm, token)
Exemple #25
0
	def _parseArgs(self):
		fields = util.FieldStorage(self._req)
		self._user = str(fields.getfirst('user', ''))
		self._stamp = str(fields.getfirst('stamp', ''))
		try:
			self._stampTime = int(self._stamp)
		except Exception, e:
			self._stampTime = 0
Exemple #26
0
def changePassword(req):
    form = util.FieldStorage(req, keep_blank_values=1)
    api = form.getfirst("api")
    param = json.loads( form.getfirst("param") )
    req.content_type = appjson

    msg = { 'done':True }
    req.write( json.dumps(msg) )
Exemple #27
0
def enableVideo(request):
    # request.content_type = "application/json"
    db = DBConnection()

    form = util.FieldStorage(request)
    videoid = form['videoid'].value

    db.query_and_return_array("""UPDATE videos SET enabled = TRUE WHERE pk = %s""", (videoid, ))
Exemple #28
0
def index(req):

    argv = util.FieldStorage(req)
    text = argv["text"].value
    name = argv["name"].value
    index = int(argv["index"].value)

    return html_form % (text, name, index)
Exemple #29
0
def fileupload(req):
    from mod_python import util
    import md5
    fields = util.FieldStorage(req)
    f = fields.getfirst('testfile')

    req.write(md5.new(f.file.read()).hexdigest())
    return apache.OK
Exemple #30
0
def logout(req):
    form = util.FieldStorage(req, keep_blank_values=1)
    api = form.getfirst("api")
    param = json.loads( form.getfirst("param") )
    sid = param['sid']
    
    req.content_type = appjson
    msg = { 'done':True }
    req.write( json.dumps(msg) )