Esempio n. 1
0
def scale_all_odt(dbo):
    """
    Goes through all odt files attached to records in the database and 
    scales them down (throws away images and objects so only the text remains to save space)
    """
    mo = dbo.query(
        "SELECT ID, MediaName FROM media WHERE MediaMimeType = 'application/vnd.oasis.opendocument.text'"
    )
    total = 0
    for i, m in enumerate(mo):
        name = str(m.MEDIANAME)
        al.debug("scaling %s (%d of %d)" % (name, i, len(mo)),
                 "media.scale_all_odt", dbo)
        odata = dbfs.get_string(dbo, name)
        if odata == "":
            al.error("file %s does not exist" % name, "media.scale_all_odt",
                     dbo)
            continue
        path = dbo.query_string("SELECT Path FROM dbfs WHERE Name = ?", [name])
        ndata = scale_odt(odata)
        if len(ndata) < 512:
            al.error(
                "scaled odt %s came back at %d bytes, abandoning" %
                (name, len(ndata)), "scale_all_odt", dbo)
        else:
            dbfs.put_string(dbo, name, path, ndata)
            dbo.update("media", m.ID, {"MediaSize": len(ndata)})
            total += 1
    al.debug("scaled %d of %d odts" % (total, len(mo)), "media.scale_all_odt",
             dbo)
Esempio n. 2
0
def scale_animal_images(dbo):
    """
    Goes through all animal images in the database and scales
    them to the current incoming media scaling factor.
    """
    mp = db.query(dbo, "SELECT MediaName FROM media WHERE LOWER(MediaName) LIKE '%.jpg' AND LinkTypeID = 0")
    for i, m in enumerate(mp):
        filepath = db.query_string(dbo, "SELECT Path FROM dbfs WHERE Name='%s'" % m["MEDIANAME"])
        name = str(m["MEDIANAME"])
        inputfile = tempfile.NamedTemporaryFile(suffix=".pdf", delete=False)
        outputfile = tempfile.NamedTemporaryFile(suffix=".pdf", delete=False)
        odata = dbfs.get_string(dbo, name)
        inputfile.write(odata)
        inputfile.flush()
        inputfile.close()
        outputfile.close()
        al.debug("scaling %s (%d of %d)" % (name, i, len(mp)), "media.scale_animal_images", dbo)
        scale_image_file(inputfile.name, outputfile.name, configuration.incoming_media_scaling(dbo))
        f = open(outputfile.name, "r")
        data = f.read()
        f.close()
        os.unlink(inputfile.name)
        os.unlink(outputfile.name)
        # Update the image file data
        dbfs.put_string(dbo, name, filepath, data)
    al.debug("scaled %d images" % len(mp), "media.scale_animal_images", dbo)
Esempio n. 3
0
def check_and_scale_pdfs(dbo):
    """
    Goes through all PDFs in the database to see if they have been
    scaled (have a suffix of _scaled.pdf) and scales down any unscaled
    ones.
    """
    if not SCALE_PDF_DURING_BATCH:
        al.warn("SCALE_PDF_DURING_BATCH is disabled, not scaling pdfs",
                "media.check_and_scale_pdfs", dbo)
    if not configuration.scale_pdfs(dbo):
        al.warn(
            "ScalePDFs config option disabled in this database, not scaling pdfs",
            "media.check_and_scale_pdfs", dbo)
    mp = db.query(dbo, \
        "SELECT MediaName FROM media WHERE LOWER(MediaName) LIKE '%.pdf' AND " \
        "LOWER(MediaName) NOT LIKE '%_scaled.pdf'")
    for m in mp:
        filepath = db.query_string(
            dbo, "SELECT Path FROM dbfs WHERE Name='%s'" % m["MEDIANAME"])
        original_name = str(m["MEDIANAME"])
        new_name = str(m["MEDIANAME"])
        new_name = new_name[0:len(new_name) - 4] + "_scaled.pdf"
        odata = dbfs.get_string(dbo, original_name)
        data = scale_pdf(odata)
        # Update the media entry with the new name
        db.execute(dbo, "UPDATE media SET MediaName = '%s' WHERE MediaName = '%s'" % \
            ( new_name, original_name))
        # Update the dbfs entry with the new name
        dbfs.rename_file(dbo, filepath, original_name, new_name)
        # Update the PDF file data
        dbfs.put_string(dbo, new_name, filepath, data)
    al.debug("found and scaled %d pdfs" % len(mp),
             "media.check_and_scale_pdfs", dbo)
Esempio n. 4
0
def scale_all_animal_images(dbo):
    """
    Goes through all animal images in the database and scales
    them to the current incoming media scaling factor.
    """
    mp = dbo.query("SELECT ID, MediaName FROM media WHERE MediaMimeType = 'image/jpeg' AND LinkTypeID = 0")
    for i, m in enumerate(mp):
        filepath = dbo.query_string("SELECT Path FROM dbfs WHERE Name = ?", [m.MEDIANAME])
        name = str(m.MEDIANAME)
        inputfile = tempfile.NamedTemporaryFile(suffix=".jpg", delete=False)
        outputfile = tempfile.NamedTemporaryFile(suffix=".jpg", delete=False)
        odata = dbfs.get_string(dbo, name)
        inputfile.write(odata)
        inputfile.flush()
        inputfile.close()
        outputfile.close()
        al.debug("scaling %s (%d of %d)" % (name, i, len(mp)), "media.scale_all_animal_images", dbo)
        try:
            scale_image_file(inputfile.name, outputfile.name, configuration.incoming_media_scaling(dbo))
        except Exception as err:
            al.error("failed scaling image, doing nothing: %s" % err, "media.scale_all_animal_images", dbo)
            continue
        data = utils.read_binary_file(outputfile.name)
        os.unlink(inputfile.name)
        os.unlink(outputfile.name)
        # Update the image file data
        dbfs.put_string(dbo, name, filepath, data)
        dbo.update("media", m.ID, { "MediaSize": len(data) })
    al.debug("scaled %d images" % len(mp), "media.scale_all_animal_images", dbo)
Esempio n. 5
0
File: media.py Progetto: magul/asm3
def check_and_scale_pdfs(dbo, force = False):
    """
    Goes through all PDFs in the database to see if they have been
    scaled (have a suffix of _scaled.pdf) and scales down any unscaled
    ones.
    If force is set, then all PDFs are checked and scaled again even
    if they've been scaled before.
    """
    if not configuration.scale_pdfs(dbo):
        al.warn("ScalePDFs config option disabled in this database, not scaling pdfs", "media.check_and_scale_pdfs", dbo)
        return
    if force:
        mp = db.query(dbo, \
            "SELECT ID, MediaName FROM media WHERE LOWER(MediaName) LIKE '%.pdf' ORDER BY ID DESC")
    else:
        mp = db.query(dbo, \
            "SELECT ID, MediaName FROM media WHERE LOWER(MediaName) LIKE '%.pdf' AND " \
            "LOWER(MediaName) NOT LIKE '%_scaled.pdf' ORDER BY ID DESC")
    for i, m in enumerate(mp):
        filepath = db.query_string(dbo, "SELECT Path FROM dbfs WHERE Name='%s'" % m["MEDIANAME"])
        original_name = str(m["MEDIANAME"])
        new_name = str(m["ID"]) + "_scaled.pdf"
        odata = dbfs.get_string(dbo, original_name)
        data = scale_pdf(odata)
        al.debug("scaling %s (%d of %d): old size %d, new size %d" % (new_name, i, len(mp), len(odata), len(data)), "check_and_scale_pdfs", dbo)
        # Update the media entry with the new name
        db.execute(dbo, "UPDATE media SET MediaName = '%s' WHERE ID = %d" % ( new_name, m["ID"]))
        # Update the dbfs entry from old name to new name (will be overwritten in a minute but safer than delete)
        dbfs.rename_file(dbo, filepath, original_name, new_name)
        # Store the PDF file data with the new name - if there was a need to change it
        if len(data) < len(odata):
            dbfs.put_string(dbo, new_name, filepath, data)
    al.debug("found and scaled %d pdfs" % len(mp), "media.check_and_scale_pdfs", dbo)
Esempio n. 6
0
def scale_animal_images(dbo):
    """
    Goes through all animal images in the database and scales
    them to the current incoming media scaling factor.
    """
    mp = db.query(
        dbo,
        "SELECT MediaName FROM media WHERE LOWER(MediaName) LIKE '%.jpg' AND LinkTypeID = 0"
    )
    for i, m in enumerate(mp):
        filepath = db.query_string(
            dbo, "SELECT Path FROM dbfs WHERE Name='%s'" % m["MEDIANAME"])
        name = str(m["MEDIANAME"])
        inputfile = tempfile.NamedTemporaryFile(suffix=".pdf", delete=False)
        outputfile = tempfile.NamedTemporaryFile(suffix=".pdf", delete=False)
        odata = dbfs.get_string(dbo, name)
        inputfile.write(odata)
        inputfile.flush()
        inputfile.close()
        outputfile.close()
        al.debug("scaling %s (%d of %d)" % (name, i, len(mp)),
                 "media.scale_animal_images", dbo)
        scale_image_file(inputfile.name, outputfile.name,
                         configuration.incoming_media_scaling(dbo))
        f = open(outputfile.name, "r")
        data = f.read()
        f.close()
        os.unlink(inputfile.name)
        os.unlink(outputfile.name)
        # Update the image file data
        dbfs.put_string(dbo, name, filepath, data)
    al.debug("scaled %d images" % len(mp), "media.scale_animal_images", dbo)
Esempio n. 7
0
def get_media_file_data(dbo, mid):
    """
    Gets a piece of media by id
    id: The media id
    Returns a tuple containing the last modified date, media name, 
    mime type and file data
    """
    mm = get_media_by_id(dbo, mid)[0]
    return mm["DATE"], mm["MEDIANAME"], mime_type(mm["MEDIANAME"]), dbfs.get_string(dbo, mm["MEDIANAME"])
Esempio n. 8
0
def get_media_file_data(dbo, mid):
    """
    Gets a piece of media by id
    id: The media id
    Returns a tuple containing the last modified date, media name, 
    mime type and file data
    """
    mm = get_media_by_id(dbo, mid)[0]
    return mm["DATE"], mm["MEDIANAME"], mime_type(
        mm["MEDIANAME"]), dbfs.get_string(dbo, mm["MEDIANAME"])
Esempio n. 9
0
def get_media_file_data(dbo, mid):
    """
    Gets a piece of media by id. Returns None if the media record does not exist.
    id: The media id
    Returns a tuple containing the last modified date, media name, 
    mime type and file data
    """
    mm = get_media_by_id(dbo, mid)
    if len(mm) == 0: return (None, "", "", "")
    mm = mm[0]
    return mm.DATE, mm.MEDIANAME, mm.MEDIAMIMETYPE, dbfs.get_string(dbo, mm.MEDIANAME)
Esempio n. 10
0
def rotate_media(dbo, username, mid, clockwise = True):
    """
    Rotates an image media record 90 degrees if clockwise is true, or 270 degrees if false
    """
    mr = dbo.first_row(dbo.query("SELECT * FROM media WHERE ID=?", [mid]))
    if not mr: raise utils.ASMError("Record does not exist")
    # If it's not a jpg image, we can stop right now
    mn = mr.MEDIANAME
    ext = mn[mn.rfind("."):].lower()
    if ext != ".jpg" and ext != ".jpeg":
        raise utils.ASMError("Image is not a JPEG file, cannot rotate")
    # Load the image data
    path = get_dbfs_path(mr.LINKID, mr.LINKTYPEID)
    imagedata = dbfs.get_string(dbo, mn, path)
    imagedata = rotate_image(imagedata, clockwise)
    # Store it back in the dbfs and add an entry to the audit trail
    dbfs.put_string(dbo, mn, path, imagedata)
    # Update the date stamp on the media record
    dbo.update("media", mid, { "Date": dbo.now(), "MediaSize": len(imagedata) })
    audit.edit(dbo, username, "media", mid, "", "media id %d rotated, clockwise=%s" % (mid, str(clockwise)))
Esempio n. 11
0
def check_and_scale_pdfs(dbo):
    """
    Goes through all PDFs in the database to see if they have been
    scaled (have a suffix of _scaled.pdf) and scales down any unscaled
    ones.
    """
    if not gs_installed():
        al.warn("ghostscript is not installed, can't scale pdfs",
                "media.check_and_scale_pdfs", dbo)
        return
    mp = db.query(dbo, \
        "SELECT MediaName FROM media WHERE LOWER(MediaName) LIKE '%.pdf' AND " \
        "LOWER(MediaName) NOT LIKE '%_scaled.pdf'")
    for m in mp:
        filepath = db.query_string(
            dbo, "SELECT Path FROM dbfs WHERE Name='%s'" % m["MEDIANAME"])
        original_name = str(m["MEDIANAME"])
        new_name = str(m["MEDIANAME"])
        new_name = new_name[0:len(new_name) - 4] + "_scaled.pdf"
        inputfile = tempfile.NamedTemporaryFile(suffix=".pdf", delete=False)
        outputfile = tempfile.NamedTemporaryFile(suffix=".pdf", delete=False)
        odata = dbfs.get_string(dbo, original_name)
        inputfile.write(odata)
        inputfile.flush()
        inputfile.close()
        outputfile.close()
        scale_pdf_file(inputfile.name, outputfile.name)
        f = open(outputfile.name, "r")
        data = f.read()
        f.close()
        os.unlink(inputfile.name)
        os.unlink(outputfile.name)
        # Update the media entry with the new name
        db.execute(dbo, "UPDATE media SET MediaName = '%s' WHERE MediaName = '%s'" % \
            ( new_name, original_name))
        # Update the dbfs entry with the new name
        dbfs.rename_file(dbo, filepath, original_name, new_name)
        # Update the PDF file data
        dbfs.put_string(dbo, new_name, filepath, data)
    al.debug("found and scaled %d pdfs" % len(mp),
             "media.check_and_scale_pdfs", dbo)
Esempio n. 12
0
def rotate_media(dbo, username, mid, clockwise = True):
    """
    Rotates an image media record 90 degrees if clockwise is true, or 270 degrees if false
    """
    mr = db.query(dbo, "SELECT * FROM media WHERE ID=%d" % int(mid))
    if len(mr) == 0: raise utils.ASMError("Record does not exist")
    mr = mr[0]
    mn = mr["MEDIANAME"]
    # If it's not a jpg image, we can stop right now
    ext = mn[mn.rfind("."):].lower()
    if ext != ".jpg" and ext != ".jpeg":
        raise utils.ASMError("Image is not a JPEG file, cannot rotate")
    # Load the image data
    path = get_dbfs_path(mr["LINKID"], mr["LINKTYPEID"])
    imagedata = dbfs.get_string(dbo, mn, path)
    imagedata = rotate_image(imagedata, clockwise)
    # Store it back in the dbfs and add an entry to the audit trail
    dbfs.put_string(dbo, mn, path, imagedata)
    # Update the date stamp on the media record
    db.execute(dbo, "UPDATE media SET Date = %s WHERE ID = %d" % (db.nowsql(), mid))
    audit.edit(dbo, username, "media", "media id %d rotated, clockwise=%s" % (mid, str(clockwise)))
Esempio n. 13
0
def check_and_scale_pdfs(dbo):
    """
    Goes through all PDFs in the database to see if they have been
    scaled (have a suffix of _scaled.pdf) and scales down any unscaled
    ones.
    """
    if not gs_installed(): 
        al.warn("ghostscript is not installed, can't scale pdfs", "media.check_and_scale_pdfs", dbo)
        return
    mp = db.query(dbo, \
        "SELECT MediaName FROM media WHERE LOWER(MediaName) LIKE '%.pdf' AND " \
        "LOWER(MediaName) NOT LIKE '%_scaled.pdf'")
    for m in mp:
        filepath = db.query_string(dbo, "SELECT Path FROM dbfs WHERE Name='%s'" % m["MEDIANAME"])
        original_name = str(m["MEDIANAME"])
        new_name = str(m["MEDIANAME"])
        new_name = new_name[0:len(new_name)-4] + "_scaled.pdf"
        inputfile = tempfile.NamedTemporaryFile(suffix=".pdf", delete=False)
        outputfile = tempfile.NamedTemporaryFile(suffix=".pdf", delete=False)
        odata = dbfs.get_string(dbo, original_name)
        inputfile.write(odata)
        inputfile.flush()
        inputfile.close()
        outputfile.close()
        scale_pdf_file(inputfile.name, outputfile.name)
        f = open(outputfile.name, "r")
        data = f.read()
        f.close()
        os.unlink(inputfile.name)
        os.unlink(outputfile.name)
        # Update the media entry with the new name
        db.execute(dbo, "UPDATE media SET MediaName = '%s' WHERE MediaName = '%s'" % \
            ( new_name, original_name))
        # Update the dbfs entry with the new name
        dbfs.rename_file(dbo, filepath, original_name, new_name)
        # Update the PDF file data
        dbfs.put_string(dbo, new_name, filepath, data)
    al.debug("found and scaled %d pdfs" % len(mp), "media.check_and_scale_pdfs", dbo)
Esempio n. 14
0
File: media.py Progetto: magul/asm3
def scale_all_odt(dbo):
    """
    Goes through all odt files attached to records in the database and 
    scales them down (throws away images and objects so only the text remains to save space)
    """
    mo = db.query(dbo, "SELECT MediaName FROM media WHERE LOWER(MediaName) LIKE '%.odt'")
    for i, m in enumerate(mo):
        name = str(m["MEDIANAME"])
        al.debug("scaling %s (%d of %d)" % (name, i, len(mo)), "media.scale_all_odt", dbo)
        print "%s (%d of %d)" % (name, i, len(mo))
        odata = dbfs.get_string(dbo, name)
        if odata == "":
            al.error("file %s does not exist" % name, "media.scale_all_odt", dbo)
            print "file %s does not exist" % name
            continue
        path = db.query_string(dbo, "SELECT Path FROM dbfs WHERE Name='%s'" % name)
        ndata = scale_odt(odata)
        if len(ndata) < 512:
            al.error("scaled odt %s came back at %d bytes, abandoning" % (name, len(ndata)), "scale_all_odt", dbo)
            print "file too small < 512, doing nothing"
        else:
            print "old size: %d, new size: %d" % (len(odata), len(ndata))
            dbfs.put_string(dbo, name, path, ndata)
Esempio n. 15
0
def rotate_media(dbo, username, mid, clockwise=True):
    """
    Rotates an image media record 90 degrees if clockwise is true, or 270 degrees if false
    """
    mr = db.query(dbo, "SELECT * FROM media WHERE ID=%d" % int(mid))
    if len(mr) == 0: raise utils.ASMError("Record does not exist")
    mr = mr[0]
    mn = mr["MEDIANAME"]
    # If it's not a jpg image, we can stop right now
    ext = mn[mn.rfind("."):].lower()
    if ext != ".jpg" and ext != ".jpeg":
        raise utils.ASMError("Image is not a JPEG file, cannot rotate")
    # Load the image data
    path = get_dbfs_path(mr["LINKID"], mr["LINKTYPEID"])
    imagedata = dbfs.get_string(dbo, mn, path)
    imagedata = rotate_image(imagedata, clockwise)
    # Store it back in the dbfs and add an entry to the audit trail
    dbfs.put_string(dbo, mn, path, imagedata)
    # Update the date stamp on the media record
    db.execute(dbo,
               "UPDATE media SET Date = %s WHERE ID = %d" % (db.nowsql(), mid))
    audit.edit(dbo, username, "media",
               "media id %d rotated, clockwise=%s" % (mid, str(clockwise)))
Esempio n. 16
0
 def mrec(mm):
     if justdate:
         return mm[0]["DATE"]
     else:
         return (mm[0]["DATE"], dbfs.get_string(dbo, mm[0]["MEDIANAME"]))
Esempio n. 17
0
def get_image_file_data(dbo, mode, iid, seq=0, justdate=False):
    """
    Gets an image
    mode: animal | media | animalthumb | person | personthumb | dbfs
    iid: The id of the animal for animal/thumb mode or the media record
        or a template path for dbfs mode
    seq: If the mode is animal or person, returns image X for that person/animal
         The first image is always the preferred photo and seq is 1-based.
    if justdate is True, returns the last modified date
    if justdate is False, returns a tuple containing the last modified date and image data
    """
    def nopic():
        NOPIC_DATE = datetime.datetime(2011, 1, 1)
        if justdate: return NOPIC_DATE
        return (NOPIC_DATE, "NOPIC")

    def thumb_nopic():
        NOPIC_DATE = datetime.datetime(2011, 1, 1)
        if justdate: return NOPIC_DATE
        return (NOPIC_DATE, "NOPIC")

    def mrec(mm):
        if len(mm) == 0: return nopic()
        if justdate: return mm[0].DATE
        return (mm[0].DATE, dbfs.get_string(dbo, mm[0].MEDIANAME))

    def thumb_mrec(mm):
        if len(mm) == 0: return thumb_nopic()
        if justdate: return mm[0].DATE
        return (mm[0].DATE,
                scale_thumbnail(dbfs.get_string(dbo, mm[0].MEDIANAME)))

    if mode == "animal":
        if seq == 0:
            return mrec(get_web_preferred(dbo, ANIMAL, int(iid)))
        else:
            return mrec(get_media_by_seq(dbo, ANIMAL, int(iid), seq))

    elif mode == "person":
        if seq == 0:
            return mrec(get_web_preferred(dbo, PERSON, int(iid)))
        else:
            return mrec(get_media_by_seq(dbo, PERSON, int(iid), seq))

    elif mode == "animalthumb":
        return thumb_mrec(get_web_preferred(dbo, ANIMAL, int(iid)))

    elif mode == "personthumb":
        return thumb_mrec(get_web_preferred(dbo, PERSON, int(iid)))

    elif mode == "media":
        return mrec(get_media_by_id(dbo, int(iid)))

    elif mode == "dbfs":
        if justdate:
            return dbo.now()
        else:
            if str(iid).startswith("/"):
                # Complete path was given
                return (dbo.now(), dbfs.get_string_filepath(dbo, str(iid)))
            else:
                # Only name was given
                return (dbo.now(), dbfs.get_string(dbo, str(iid)))

    elif mode == "nopic":
        if dbfs.file_exists(dbo, "nopic.jpg"):
            return (dbo.now(),
                    dbfs.get_string_filepath(dbo, "/reports/nopic.jpg"))
        else:
            return (dbo.now(),
                    utils.read_binary_file(dbo.installpath +
                                           "media/reports/nopic.jpg"))

    else:
        return nopic()
Esempio n. 18
0
    # Generate the body of the post from our facebook template
    tags = wordprocessor.animal_tags(dbo, a)
    template = configuration.facebook_template(dbo)
    posttext = wordprocessor.substitute_tags(template, tags, False, "$$", "$$")

    # Post on the wall
    try:

        l = dbo.locale
        fb_url = "https://graph.facebook.com/%s/photos?access_token=%s" % (
            post_to, access_token)
        al.debug(
            "FB posting photo and text '%s' to '%s' at %s" %
            (posttext, page_name, fb_url), "social.post_animal_facebook", dbo)
        imagedata = dbfs.get_string(dbo, a["WEBSITEMEDIANAME"])
        req, hdr, response = utils.post_multipart(
            fb_url,
            (("message", utils.decode_html(posttext).encode("utf-8")), ),
            (("source", "pic.jpg", imagedata), ))
        al.debug("FB response: %s" % response, "social.post_animal_facebook",
                 dbo)

        # If the option is on and all was ok, make a note in the log
        if configuration.facebook_log(dbo):
            al.debug(
                "FB writing entry to animal log: %s %s" %
                (a["SHELTERCODE"], a["ANIMALNAME"]),
                "social.post_animal_facebook", dbo)
            log.add_log(
                dbo, user, log.ANIMAL, utils.cint(oauth_state[1:]),
Esempio n. 19
0
 def test_get_string(self):
     assert len(dbfs.get_string(base.get_dbo(), "nopic.jpg",
                                "/reports")) > 0
Esempio n. 20
0
def handler(post, path, remoteip, referer, querystring):
    """ Handles the various service method types.
    post:        The GET/POST parameters
    path:        The current system path/code.PATH
    remoteip:    The IP of the caller
    referer:     The referer HTTP header
    querystring: The complete querystring
    return value is a tuple containing MIME type, max-age, content
    """
    # Get service parameters
    account = post["account"]
    username = post["username"]
    password = post["password"]
    method = post["method"]
    animalid = post.integer("animalid")
    formid = post.integer("formid")
    seq = post.integer("seq")
    title = post["title"]
    strip_personal = post.integer("sensitive") == 0

    cache_key = querystring.replace(" ", "")

    # Do we have a cached response for these parameters?
    cached_response = get_cached_response(cache_key)
    if cached_response is not None:
        al.debug("cache hit for %s" % (cache_key), "service.handler")
        return cached_response

    # Are we dealing with multiple databases, but no account was specified?
    if account == "" and MULTIPLE_DATABASES:
        return ("text/plain", 0, 0, "ERROR: No database/alias specified")

    dbo = db.get_database(account)

    if dbo.database in ("FAIL", "DISABLED", "WRONGSERVER"):
        al.error(
            "auth failed - invalid smaccount %s from %s (%s)" %
            (account, remoteip, dbo.database), "service.handler", dbo)
        return ("text/plain", 0, 0,
                "ERROR: Invalid database (%s)" % dbo.database)

    # If the database has disabled the service API, stop now
    if not configuration.service_enabled(dbo):
        al.error("Service API is disabled (%s)" % method, "service.handler",
                 dbo)
        return ("text/plain", 0, 0, "ERROR: Service API is disabled")

    # Do any database updates need doing in this db?
    dbo.installpath = path
    if dbupdate.check_for_updates(dbo):
        dbupdate.perform_updates(dbo)

    # Does the method require us to authenticate? If so, do it.
    user = None
    securitymap = ""
    if method in AUTH_METHODS:
        # If the database has authenticated service methods disabled, stop now
        if not configuration.service_auth_enabled(dbo):
            al.error("Service API for auth methods is disabled (%s)" % method,
                     "service.handler", dbo)
            return ("text/plain", 0, 0,
                    "ERROR: Service API for authenticated methods is disabled")
        user = users.authenticate(dbo, username, password)
        if user is None:
            al.error(
                "auth failed - %s/%s is not a valid username/password from %s"
                % (username, password, remoteip), "service.handler", dbo)
            return ("text/plain", 0, 0, "ERROR: Invalid username and password")
        securitymap = users.get_security_map(dbo, user["USERNAME"])

    # Get the preferred locale and timezone for the site
    l = configuration.locale(dbo)
    dbo.locale = l
    dbo.timezone = configuration.timezone(dbo)
    al.info("call %s->%s [%s %s]" % (username, method, str(animalid), title),
            "service.handler", dbo)

    if method == "animal_image":
        hotlink_protect("animal_image", referer)
        if utils.cint(animalid) == 0:
            al.error(
                "animal_image failed, %s is not an animalid" % str(animalid),
                "service.handler", dbo)
            return ("text/plain", 0, 0, "ERROR: Invalid animalid")
        else:
            mediadate, data = media.get_image_file_data(
                dbo, "animal", utils.cint(animalid), seq)
            if data == "NOPIC":
                mediadate, data = media.get_image_file_data(dbo, "nopic", 0)
            return set_cached_response(cache_key, "image/jpeg", 86400, 3600,
                                       data)

    elif method == "animal_thumbnail":
        if utils.cint(animalid) == 0:
            al.error(
                "animal_thumbnail failed, %s is not an animalid" %
                str(animalid), "service.handler", dbo)
            return ("text/plain", 0, 0, "ERROR: Invalid animalid")
        else:
            mediadate, data = media.get_image_file_data(
                dbo, "animalthumb", utils.cint(animalid), seq)
            if data == "NOPIC":
                mediadate, data = media.get_image_file_data(dbo, "nopic", 0)
            return set_cached_response(cache_key, "image/jpeg", 86400, 86400,
                                       data)

    elif method == "animal_view":
        if utils.cint(animalid) == 0:
            al.error(
                "animal_view failed, %s is not an animalid" % str(animalid),
                "service.handler", dbo)
            return ("text/plain", 0, 0, "ERROR: Invalid animalid")
        else:
            return set_cached_response(
                cache_key, "text/html", 86400, 120,
                publishers.html.get_animal_view(dbo, utils.cint(animalid)))

    elif method == "animal_view_adoptable_js":
        return set_cached_response(
            cache_key, "application/javascript", 10800, 600,
            publishers.html.get_animal_view_adoptable_js(dbo))

    elif method == "animal_view_adoptable_html":
        return set_cached_response(
            cache_key, "text/html", 86400, 120,
            publishers.html.get_animal_view_adoptable_html(dbo))

    elif method == "dbfs_image":
        hotlink_protect("dbfs_image", referer)
        return set_cached_response(
            cache_key, "image/jpeg", 86400, 86400,
            utils.iif(title.startswith("/"),
                      dbfs.get_string_filepath(dbo, title),
                      dbfs.get_string(dbo, title)))

    elif method == "extra_image":
        hotlink_protect("extra_image", referer)
        return set_cached_response(cache_key, "image/jpeg", 86400, 86400,
                                   dbfs.get_string(dbo, title, "/reports"))

    elif method == "json_adoptable_animal":
        if utils.cint(animalid) == 0:
            al.error(
                "json_adoptable_animal failed, %s is not an animalid" %
                str(animalid), "service.handler", dbo)
            return ("text/plain", 0, 0, "ERROR: Invalid animalid")
        else:
            users.check_permission_map(l, user["SUPERUSER"], securitymap,
                                       users.VIEW_ANIMAL)
            rs = publishers.base.get_animal_data(
                dbo,
                None,
                utils.cint(animalid),
                include_additional_fields=True)
            return set_cached_response(cache_key, "application/json", 3600,
                                       3600, utils.json(rs))

    elif method == "html_adoptable_animals":
        return set_cached_response(cache_key, "text/html", 10800, 1800, \
            publishers.html.get_adoptable_animals(dbo, style=post["template"], \
                speciesid=post.integer("speciesid"), animaltypeid=post.integer("animaltypeid"), locationid=post.integer("locationid")))

    elif method == "html_adopted_animals":
        return set_cached_response(cache_key, "text/html", 10800, 1800, \
            publishers.html.get_adopted_animals(dbo, daysadopted=post.integer("days"), style=post["template"], \
                speciesid=post.integer("speciesid"), animaltypeid=post.integer("animaltypeid")))

    elif method == "html_deceased_animals":
        return set_cached_response(cache_key, "text/html", 10800, 1800, \
            publishers.html.get_deceased_animals(dbo, daysdeceased=post.integer("days"), style=post["template"], \
                speciesid=post.integer("speciesid"), animaltypeid=post.integer("animaltypeid")))

    elif method == "html_held_animals":
        return set_cached_response(cache_key, "text/html", 10800, 1800, \
            publishers.html.get_held_animals(dbo, style=post["template"], \
                speciesid=post.integer("speciesid"), animaltypeid=post.integer("animaltypeid")))

    elif method == "json_adoptable_animals":
        users.check_permission_map(l, user["SUPERUSER"], securitymap,
                                   users.VIEW_ANIMAL)
        rs = publishers.base.get_animal_data(dbo,
                                             None,
                                             include_additional_fields=True)
        if strip_personal: rs = strip_personal_data(rs)
        return set_cached_response(cache_key, "application/json", 3600, 3600,
                                   utils.json(rs))

    elif method == "jsonp_adoptable_animals":
        users.check_permission_map(l, user["SUPERUSER"], securitymap,
                                   users.VIEW_ANIMAL)
        rs = publishers.base.get_animal_data(dbo,
                                             None,
                                             include_additional_fields=True)
        if strip_personal: rs = strip_personal_data(rs)
        return ("application/javascript", 0, 0,
                "%s(%s);" % (post["callback"], utils.json(rs)))

    elif method == "xml_adoptable_animal":
        if utils.cint(animalid) == 0:
            al.error(
                "xml_adoptable_animal failed, %s is not an animalid" %
                str(animalid), "service.handler", dbo)
            return ("text/plain", 0, 0, "ERROR: Invalid animalid")
        else:
            users.check_permission_map(l, user["SUPERUSER"], securitymap,
                                       users.VIEW_ANIMAL)
            rs = publishers.base.get_animal_data(
                dbo,
                None,
                utils.cint(animalid),
                include_additional_fields=True)
            return set_cached_response(cache_key, "application/xml", 3600,
                                       3600, html.xml(rs))

    elif method == "xml_adoptable_animals":
        users.check_permission_map(l, user["SUPERUSER"], securitymap,
                                   users.VIEW_ANIMAL)
        rs = publishers.base.get_animal_data(dbo,
                                             None,
                                             include_additional_fields=True)
        if strip_personal: rs = strip_personal_data(rs)
        return set_cached_response(cache_key, "application/xml", 3600, 3600,
                                   html.xml(rs))

    elif method == "json_found_animals":
        users.check_permission_map(l, user["SUPERUSER"], securitymap,
                                   users.VIEW_FOUND_ANIMAL)
        rs = lostfound.get_foundanimal_last_days(dbo)
        return set_cached_response(cache_key, "application/json", 3600, 3600,
                                   utils.json(rs))

    elif method == "jsonp_found_animals":
        users.check_permission_map(l, user["SUPERUSER"], securitymap,
                                   users.VIEW_FOUND_ANIMAL)
        rs = lostfound.get_foundanimal_last_days(dbo)
        return ("application/javascript", 0, 0,
                "%s(%s);" % (post["callback"], utils.json(rs)))

    elif method == "xml_found_animals":
        users.check_permission_map(l, user["SUPERUSER"], securitymap,
                                   users.VIEW_FOUND_ANIMAL)
        rs = lostfound.get_foundanimal_last_days(dbo)
        return set_cached_response(cache_key, "application/json", 3600, 3600,
                                   html.xml(rs))

    elif method == "json_lost_animals":
        users.check_permission_map(l, user["SUPERUSER"], securitymap,
                                   users.VIEW_LOST_ANIMAL)
        rs = lostfound.get_lostanimal_last_days(dbo)
        return set_cached_response(cache_key, "application/json", 3600, 3600,
                                   utils.json(rs))

    elif method == "jsonp_lost_animals":
        users.check_permission_map(l, user["SUPERUSER"], securitymap,
                                   users.VIEW_LOST_ANIMAL)
        rs = lostfound.get_lostanimal_last_days(dbo)
        return ("application/javascript", 0, 0,
                "%s(%s);" % (post["callback"], utils.json(rs)))

    elif method == "xml_lost_animals":
        users.check_permission_map(l, user["SUPERUSER"], securitymap,
                                   users.VIEW_LOST_ANIMAL)
        rs = lostfound.get_lostanimal_last_days(dbo)
        return set_cached_response(cache_key, "application/json", 3600, 3600,
                                   html.xml(rs))

    elif method == "json_recent_adoptions":
        users.check_permission_map(l, user["SUPERUSER"], securitymap,
                                   users.VIEW_ANIMAL)
        rs = movement.get_recent_adoptions(dbo)
        return set_cached_response(cache_key, "application/json", 3600, 3600,
                                   utils.json(rs))

    elif method == "jsonp_recent_adoptions":
        users.check_permission_map(l, user["SUPERUSER"], securitymap,
                                   users.VIEW_ANIMAL)
        rs = movement.get_recent_adoptions(dbo)
        return ("application/javascript", 0, 0,
                "%s(%s);" % (post["callback"], utils.json(rs)))

    elif method == "xml_recent_adoptions":
        users.check_permission_map(l, user["SUPERUSER"], securitymap,
                                   users.VIEW_ANIMAL)
        rs = movement.get_recent_adoptions(dbo)
        return set_cached_response(cache_key, "application/xml", 3600, 3600,
                                   html.xml(rs))

    elif method == "html_report":
        users.check_permission_map(l, user["SUPERUSER"], securitymap,
                                   users.VIEW_REPORT)
        crid = reports.get_id(dbo, title)
        p = reports.get_criteria_params(dbo, crid, post)
        rhtml = reports.execute(dbo, crid, username, p)
        return set_cached_response(cache_key, "text/html", 600, 600, rhtml)

    elif method == "csv_mail" or method == "csv_report":
        users.check_permission_map(l, user["SUPERUSER"], securitymap,
                                   users.VIEW_REPORT)
        crid = reports.get_id(dbo, title)
        p = reports.get_criteria_params(dbo, crid, post)
        rows, cols = reports.execute_query(dbo, crid, username, p)
        mcsv = utils.csv(l, rows, cols, True)
        return set_cached_response(cache_key, "text/csv", 600, 600, mcsv)

    elif method == "jsonp_recent_changes":
        users.check_permission_map(l, user["SUPERUSER"], securitymap,
                                   users.VIEW_ANIMAL)
        sa = animal.get_recent_changes(dbo)
        return ("application/javascript", 0, 0,
                "%s(%s);" % (post["callback"], utils.json(sa)))

    elif method == "json_recent_changes":
        users.check_permission_map(l, user["SUPERUSER"], securitymap,
                                   users.VIEW_ANIMAL)
        sa = animal.get_recent_changes(dbo)
        return set_cached_response(cache_key, "application/json", 3600, 3600,
                                   utils.json(sa))

    elif method == "xml_recent_changes":
        users.check_permission_map(l, user["SUPERUSER"], securitymap,
                                   users.VIEW_ANIMAL)
        sa = animal.get_recent_changes(dbo)
        return set_cached_response(cache_key, "application/xml", 3600, 3600,
                                   html.xml(sa))

    elif method == "jsonp_shelter_animals":
        users.check_permission_map(l, user["SUPERUSER"], securitymap,
                                   users.VIEW_ANIMAL)
        sa = animal.get_shelter_animals(dbo)
        if strip_personal: sa = strip_personal_data(sa)
        return ("application/javascript", 0, 0,
                "%s(%s);" % (post["callback"], utils.json(sa)))

    elif method == "json_shelter_animals":
        users.check_permission_map(l, user["SUPERUSER"], securitymap,
                                   users.VIEW_ANIMAL)
        sa = animal.get_shelter_animals(dbo)
        if strip_personal: sa = strip_personal_data(sa)
        return set_cached_response(cache_key, "application/json", 3600, 3600,
                                   utils.json(sa))

    elif method == "xml_shelter_animals":
        users.check_permission_map(l, user["SUPERUSER"], securitymap,
                                   users.VIEW_ANIMAL)
        sa = animal.get_shelter_animals(dbo)
        if strip_personal: sa = strip_personal_data(sa)
        return set_cached_response(cache_key, "application/xml", 3600, 3600,
                                   html.xml(sa))

    elif method == "rss_timeline":
        users.check_permission_map(l, user["SUPERUSER"], securitymap,
                                   users.VIEW_ANIMAL)
        return set_cached_response(cache_key, "application/rss+xml", 3600,
                                   3600, html.timeline_rss(dbo))

    elif method == "upload_animal_image":
        users.check_permission_map(l, user["SUPERUSER"], securitymap,
                                   users.ADD_MEDIA)
        media.attach_file_from_form(dbo, username, media.ANIMAL, int(animalid),
                                    post)
        return ("text/plain", 0, 0, "OK")

    elif method == "online_form_html":
        if formid == 0:
            raise utils.ASMError(
                "method online_form_html requires a valid formid")
        return set_cached_response(cache_key, "text/html; charset=utf-8", 120,
                                   120,
                                   onlineform.get_onlineform_html(dbo, formid))

    elif method == "online_form_json":
        if formid == 0:
            raise utils.ASMError(
                "method online_form_json requires a valid formid")
        return set_cached_response(cache_key,
                                   "application/json; charset=utf-8", 30, 30,
                                   onlineform.get_onlineform_json(dbo, formid))

    elif method == "online_form_post":
        flood_protect("online_form_post", remoteip, 15)
        onlineform.insert_onlineformincoming_from_form(dbo, post, remoteip)
        redirect = post["redirect"]
        if redirect == "":
            redirect = BASE_URL + "/static/pages/form_submitted.html"
        return ("redirect", 0, 0, redirect)

    elif method == "sign_document":
        if formid == 0:
            raise utils.ASMError(
                "method sign_document requires a valid formid")
        if post["sig"] == "":
            return set_cached_response(cache_key, "text/html", 2, 2,
                                       sign_document_page(dbo, formid))
        else:
            media.sign_document(dbo, "service", formid, post["sig"],
                                post["signdate"])
            media.create_log(dbo, "service", formid, "ES02",
                             _("Document signed", l))
            return ("text/plain", 0, 0, "OK")

    else:
        al.error("invalid method '%s'" % method, "service.handler", dbo)
        raise utils.ASMError("Invalid method '%s'" % method)
Esempio n. 21
0
def handler(data, remoteip, referer):
    """
    Handles the various service method types.
    data: The GET/POST parameters 
    return value is a tuple containing MIME type, max-age, content
    """
    # Database info
    dbo = db.DatabaseInfo()

    # Get service parameters
    account = utils.df_ks(data, "account")
    username = utils.df_ks(data, "username")
    password = utils.df_ks(data, "password")
    method = utils.df_ks(data, "method")
    animalid = utils.df_ki(data, "animalid")
    formid = utils.df_ki(data, "formid")
    title = utils.df_ks(data, "title")
    cache_key = "a" + account + "u" + username + "p" + password + "m" + method + "a" + str(
        animalid) + "f" + str(formid) + "t" + title

    # cache keys aren't allowed spaces
    cache_key = cache_key.replace(" ", "")

    # Do we have a cached response for these parameters?
    cached_response = get_cached_response(cache_key)
    if cached_response is not None:
        al.debug(
            "cache hit for %s/%s/%s/%s" % (account, method, animalid, title),
            "service.handler")
        return cached_response

    # Are we dealing with multiple databases, but no account was specified?
    if account == "" and MULTIPLE_DATABASES:
        return ("text/plan", 0, "ERROR: No database/alias specified")

    # Are we dealing with multiple databases and an account was specified?
    if account != "":
        if MULTIPLE_DATABASES:
            if MULTIPLE_DATABASES_TYPE == "smcom":
                # Is this sheltermanager.com? If so, we need to get the
                # database connection info (dbo) before we can login.
                dbo = smcom.get_database_info(account)
            else:
                # Look up the database info from our map
                dbo = db.get_multiple_database_info(account)
            if dbo.database == "FAIL" or dbo.database == "DISABLED":
                al.error(
                    "auth failed - invalid smaccount %s from %s" %
                    (account, remoteip), "service.handler", dbo)
                return ("text/plain", 0, "ERROR: Invalid database")

    # Does the method require us to authenticate? If so, do it.
    user = None
    if method in AUTH_METHODS:
        user = users.authenticate(dbo, username, password)
        if user is None:
            al.error(
                "auth failed - %s/%s is not a valid username/password from %s"
                % (username, password, remoteip), "service.handler", dbo)
            return ("text/plain", 0, "ERROR: Invalid username and password")

    # Get the preferred locale for the site
    dbo.locale = configuration.locale(dbo)
    al.info("call %s->%s [%s %s]" % (username, method, str(animalid), title),
            "service.handler", dbo)

    if method == "animal_image":
        # If we have a hotlinking restriction, enforce it
        if referer != "" and IMAGE_HOTLINKING_ONLY_FROM_DOMAIN != "" and referer.find(
                IMAGE_HOTLINKING_ONLY_FROM_DOMAIN) == -1:
            raise utils.ASMPermissionError("Image hotlinking is forbidden.")
        if animalid == "" or utils.cint(animalid) == 0:
            al.error(
                "animal_image failed, %s is not an animalid" % str(animalid),
                "service.handler", dbo)
            return ("text/plain", 0, "ERROR: Invalid animalid")
        # If the option is on, forbid hotlinking
        else:
            seq = utils.df_ki(data, "seq")
            if seq == 0: seq = 1
            mm = media.get_media_by_seq(dbo, media.ANIMAL,
                                        utils.cint(animalid), seq)
            if len(mm) == 0:
                return ("image/jpeg", 86400,
                        dbfs.get_string(dbo, "nopic.jpg", "/reports"))
            else:
                return ("image/jpeg", 86400,
                        dbfs.get_string(dbo, mm[0]["MEDIANAME"]))

    elif method == "extra_image":
        return ("image/jpeg", 86400, dbfs.get_string(dbo, title, "/reports"))

    elif method == "json_adoptable_animals":
        pc = publish.PublishCriteria(configuration.publisher_presets(dbo))
        rs = publish.get_animal_data(dbo, pc, True)
        return set_cached_response(cache_key, "application/json", 3600,
                                   html.json(rs))

    elif method == "xml_adoptable_animals":
        pc = publish.PublishCriteria(configuration.publisher_presets(dbo))
        rs = publish.get_animal_data(dbo, pc, True)
        return set_cached_response(cache_key, "application/xml", 3600,
                                   html.xml(rs))

    elif method == "json_recent_adoptions":
        rs = movement.get_recent_adoptions(dbo)
        return set_cached_response(cache_key, "application/json", 3600,
                                   html.json(rs))

    elif method == "xml_recent_adoptions":
        rs = movement.get_recent_adoptions(dbo)
        return set_cached_response(cache_key, "application/xml", 3600,
                                   html.xml(rs))

    elif method == "html_report":
        crid = reports.get_id(dbo, title)
        p = reports.get_criteria_params(dbo, crid, data)
        rhtml = reports.execute(dbo, crid, username, p)
        return set_cached_response(cache_key, "text/html", 3600, rhtml)

    elif method == "jsonp_shelter_animals":
        sa = animal.get_animal_find_simple(dbo, "", "shelter")
        return set_cached_response(
            cache_key, "application/javascript", 3600,
            str(utils.df_ks(data, "callback")) + "(" + html.json(sa) + ")")

    elif method == "json_shelter_animals":
        sa = animal.get_animal_find_simple(dbo, "", "shelter")
        return set_cached_response(cache_key, "application/json", 3600,
                                   html.json(sa))

    elif method == "xml_shelter_animals":
        sa = animal.get_animal_find_simple(dbo, "", "shelter")
        return set_cached_response(cache_key, "application/xml", 3600,
                                   html.json(sa))

    elif method == "upload_animal_image":
        media.attach_file_from_form(dbo, username, media.ANIMAL, int(animalid),
                                    data)
        return ("text/plain", 0, "OK")

    elif method == "online_form_html":
        if formid == 0:
            raise utils.ASMError(
                "method online_form_html requires a valid formid")
        return set_cached_response(cache_key, "text/html", 120,
                                   onlineform.get_onlineform_html(dbo, formid))

    elif method == "online_form_post":
        onlineform.insert_onlineformincoming_from_form(dbo, data, remoteip)
        redirect = utils.df_ks(data, "redirect")
        if redirect == "":
            redirect = BASE_URL + "/static/pages/form_submitted.html"
        return ("redirect", 0, redirect)

    else:
        al.error("invalid method '%s'" % method, "service.handler", dbo)
        raise utils.ASMError("Invalid method '%s'" % method)
Esempio n. 22
0
def handler(data, remoteip, referer):
    """
    Handles the various service method types.
    data: The GET/POST parameters 
    return value is a tuple containing MIME type, max-age, content
    """
    # Database info
    dbo = db.DatabaseInfo()

    # Get service parameters
    account = utils.df_ks(data, "account")
    username = utils.df_ks(data, "username")
    password = utils.df_ks(data, "password")
    method = utils.df_ks(data, "method")
    animalid = utils.df_ki(data, "animalid")
    formid = utils.df_ki(data, "formid")
    title = utils.df_ks(data, "title")
    cache_key = "a" + account + "u" + username + "p" + password + "m" + method + "a" + str(animalid) + "f" + str(formid) + "t" + title
    
    # cache keys aren't allowed spaces
    cache_key = cache_key.replace(" ", "")

    # Do we have a cached response for these parameters?
    cached_response = get_cached_response(cache_key)
    if cached_response is not None:
        al.debug("cache hit for %s/%s/%s/%s" % (account, method, animalid, title), "service.handler")
        return cached_response

    # Are we dealing with multiple databases, but no account was specified?
    if account == "" and MULTIPLE_DATABASES:
        return ("text/plan", 0, "ERROR: No database/alias specified")

    # Are we dealing with multiple databases and an account was specified?
    if account != "":
        if MULTIPLE_DATABASES:
            if MULTIPLE_DATABASES_TYPE == "smcom":
                # Is this sheltermanager.com? If so, we need to get the 
                # database connection info (dbo) before we can login.
                dbo = smcom.get_database_info(account)
            else:
                # Look up the database info from our map
                dbo  = db.get_multiple_database_info(account)
            if dbo.database == "FAIL" or dbo.database == "DISABLED": 
                al.error("auth failed - invalid smaccount %s from %s" % (account, remoteip), "service.handler", dbo)
                return ("text/plain", 0, "ERROR: Invalid database")

    # Does the method require us to authenticate? If so, do it.
    user = None
    if method in AUTH_METHODS:
        user = users.authenticate(dbo, username, password)
        if user is None:
            al.error("auth failed - %s/%s is not a valid username/password from %s" % (username, password, remoteip), "service.handler", dbo)
            return ("text/plain", 0, "ERROR: Invalid username and password")

    # Get the preferred locale for the site
    dbo.locale = configuration.locale(dbo)
    al.info("call %s->%s [%s %s]" % (username, method, str(animalid), title), "service.handler", dbo)

    if method =="animal_image":
        # If we have a hotlinking restriction, enforce it
        if referer != "" and IMAGE_HOTLINKING_ONLY_FROM_DOMAIN != "" and referer.find(IMAGE_HOTLINKING_ONLY_FROM_DOMAIN) == -1:
            raise utils.ASMPermissionError("Image hotlinking is forbidden.")
        if animalid == "" or utils.cint(animalid) == 0:
            al.error("animal_image failed, %s is not an animalid" % str(animalid), "service.handler", dbo)
            return ("text/plain", 0, "ERROR: Invalid animalid")
        # If the option is on, forbid hotlinking
        else:
            seq = utils.df_ki(data, "seq")
            if seq == 0: seq = 1
            mm = media.get_media_by_seq(dbo, media.ANIMAL, utils.cint(animalid), seq)
            if len(mm) == 0:
                return ("image/jpeg", 86400, dbfs.get_string(dbo, "nopic.jpg", "/reports"))
            else:
                return ("image/jpeg", 86400, dbfs.get_string(dbo, mm[0]["MEDIANAME"]))

    elif method =="extra_image":
        return ("image/jpeg", 86400, dbfs.get_string(dbo, title, "/reports"))

    elif method == "json_adoptable_animals":
        pc = publish.PublishCriteria(configuration.publisher_presets(dbo))
        rs = publish.get_animal_data(dbo, pc, True)
        return set_cached_response(cache_key, "application/json", 3600, html.json(rs))

    elif method == "xml_adoptable_animals":
        pc = publish.PublishCriteria(configuration.publisher_presets(dbo))
        rs = publish.get_animal_data(dbo, pc, True)
        return set_cached_response(cache_key, "application/xml", 3600, html.xml(rs))

    elif method == "json_recent_adoptions":
        rs = movement.get_recent_adoptions(dbo)
        return set_cached_response(cache_key, "application/json", 3600, html.json(rs))

    elif method == "xml_recent_adoptions":
        rs = movement.get_recent_adoptions(dbo)
        return set_cached_response(cache_key, "application/xml", 3600, html.xml(rs))

    elif method == "html_report":
        crid = reports.get_id(dbo, title)
        p = reports.get_criteria_params(dbo, crid, data)
        rhtml = reports.execute(dbo, crid, username, p)
        return set_cached_response(cache_key, "text/html", 3600, rhtml)

    elif method == "jsonp_shelter_animals":
        sa = animal.get_animal_find_simple(dbo, "", "shelter")
        return set_cached_response(cache_key, "application/javascript", 3600, str(utils.df_ks(data, "callback")) + "(" + html.json(sa) + ")")

    elif method == "json_shelter_animals":
        sa = animal.get_animal_find_simple(dbo, "", "shelter")
        return set_cached_response(cache_key, "application/json", 3600, html.json(sa))

    elif method == "xml_shelter_animals":
        sa = animal.get_animal_find_simple(dbo, "", "shelter")
        return set_cached_response(cache_key, "application/xml", 3600, html.json(sa))

    elif method == "upload_animal_image":
        media.attach_file_from_form(dbo, username, media.ANIMAL, int(animalid), data)
        return ("text/plain", 0, "OK")

    elif method == "online_form_html":
        if formid == 0:
            raise utils.ASMError("method online_form_html requires a valid formid")
        return set_cached_response(cache_key, "text/html", 120, onlineform.get_onlineform_html(dbo, formid))

    elif method == "online_form_post":
        onlineform.insert_onlineformincoming_from_form(dbo, data, remoteip)
        redirect = utils.df_ks(data, "redirect")
        if redirect == "":
            redirect = BASE_URL + "/static/pages/form_submitted.html"
        return ("redirect", 0, redirect)

    else:
        al.error("invalid method '%s'" % method, "service.handler", dbo)
        raise utils.ASMError("Invalid method '%s'" % method)
Esempio n. 23
0
 def mrec(mm):
     if len(mm) == 0: return nopic()
     if justdate: return mm[0].DATE
     return (mm[0].DATE, dbfs.get_string(dbo, mm[0].MEDIANAME))
Esempio n. 24
0
 def thumb_mrec(mm):
     if justdate:
         return mm[0]["DATE"]
     else:
         return (mm[0]["DATE"], scale_thumbnail(dbfs.get_string(dbo, mm[0]["MEDIANAME"])))
Esempio n. 25
0
def handler(post, remoteip, referer):
    """
    Handles the various service method types.
    data: The GET/POST parameters 
    return value is a tuple containing MIME type, max-age, content
    """
    # Database info
    dbo = db.DatabaseInfo()

    # Get service parameters
    account = post["account"]
    username = post["username"]
    password = post["password"]
    method = post["method"]
    animalid = post.integer("animalid")
    formid = post.integer("formid")
    seq = post.integer("seq")
    title = post["title"]
    cache_key = "a" + account + "u" + username + "p" + password + "m" + method + \
        "i" + str(animalid) + "s" + str(seq) + "f" + str(formid) + "t" + title
    
    # cache keys aren't allowed spaces
    cache_key = cache_key.replace(" ", "")

    # Do we have a cached response for these parameters?
    cached_response = get_cached_response(cache_key)
    if cached_response is not None:
        al.debug("cache hit for %s/%s/%s/%s" % (account, method, animalid, title), "service.handler")
        return cached_response

    # Are we dealing with multiple databases, but no account was specified?
    if account == "" and MULTIPLE_DATABASES:
        return ("text/plan", 0, "ERROR: No database/alias specified")

    # Are we dealing with multiple databases and an account was specified?
    if account != "":
        if MULTIPLE_DATABASES:
            if MULTIPLE_DATABASES_TYPE == "smcom":
                # Is this sheltermanager.com? If so, we need to get the 
                # database connection info (dbo) before we can login.
                dbo = smcom.get_database_info(account)
            else:
                # Look up the database info from our map
                dbo  = db.get_multiple_database_info(account)
            if dbo.database == "FAIL" or dbo.database == "DISABLED": 
                al.error("auth failed - invalid smaccount %s from %s" % (account, remoteip), "service.handler", dbo)
                return ("text/plain", 0, "ERROR: Invalid database")

    # If the database has disabled the service API, stop now
    if not configuration.service_enabled(dbo):
        al.error("Service API is disabled (%s)" % method, "service.handler", dbo)
        return ("text/plain", 0, "ERROR: Service API is disabled")

    # Do any database updates need doing in this db?
    if dbupdate.check_for_updates(dbo):
        dbupdate.perform_updates(dbo)

    # Does the method require us to authenticate? If so, do it.
    user = None
    securitymap = ""
    if method in AUTH_METHODS:
        # If the database has authenticated service methods disabled, stop now
        if not configuration.service_auth_enabled(dbo):
            al.error("Service API for auth methods is disabled (%s)" % method, "service.handler", dbo)
            return ("text/plain", 0, "ERROR: Service API for authenticated methods is disabled")
        user = users.authenticate(dbo, username, password)
        if user is None:
            al.error("auth failed - %s/%s is not a valid username/password from %s" % (username, password, remoteip), "service.handler", dbo)
            return ("text/plain", 0, "ERROR: Invalid username and password")
        securitymap = users.get_security_map(dbo, user["USERNAME"])

    # Get the preferred locale and timezone for the site
    l = configuration.locale(dbo)
    dbo.locale = l
    dbo.timezone = configuration.timezone(dbo)
    al.info("call %s->%s [%s %s]" % (username, method, str(animalid), title), "service.handler", dbo)

    if method =="animal_image":
        hotlink_protect("animal_image", referer)
        if animalid == "" or utils.cint(animalid) == 0:
            al.error("animal_image failed, %s is not an animalid" % str(animalid), "service.handler", dbo)
            return ("text/plain", 0, "ERROR: Invalid animalid")
        else:
            if seq == 0: seq = 1
            mm = media.get_media_by_seq(dbo, media.ANIMAL, utils.cint(animalid), seq)
            if len(mm) == 0:
                return set_cached_response(cache_key, "image/jpeg", 86400, 120, dbfs.get_string(dbo, "nopic.jpg", "/reports"))
            else:
                return set_cached_response(cache_key, "image/jpeg", 86400, 120, dbfs.get_string(dbo, mm[0]["MEDIANAME"]))

    elif method == "animal_view":
        if animalid == "" or utils.cint(animalid) == 0:
            al.error("animal_view failed, %s is not an animalid" % str(animalid), "service.handler", dbo)
            return ("text/plain", 0, "ERROR: Invalid animalid")
        else:
            return set_cached_response(cache_key, "text/html", 120, 120, publish.get_animal_view(dbo, int(animalid)))

    elif method =="dbfs_image":
        hotlink_protect("dbfs_image", referer)
        return set_cached_response(cache_key, "image/jpeg", 86400, 120, dbfs.get_string_filepath(dbo, title))

    elif method =="extra_image":
        hotlink_protect("extra_image", referer)
        return set_cached_response(cache_key, "image/jpeg", 86400, 120, dbfs.get_string(dbo, title, "/reports"))

    elif method == "json_adoptable_animals":
        users.check_permission_map(l, user["SUPERUSER"], securitymap, users.VIEW_ANIMAL)
        pc = publish.PublishCriteria(configuration.publisher_presets(dbo))
        rs = publish.get_animal_data(dbo, pc, True)
        return set_cached_response(cache_key, "application/json", 3600, 3600, html.json(rs))

    elif method == "jsonp_adoptable_animals":
        users.check_permission_map(l, user["SUPERUSER"], securitymap, users.VIEW_ANIMAL)
        pc = publish.PublishCriteria(configuration.publisher_presets(dbo))
        rs = publish.get_animal_data(dbo, pc, True)
        return ("application/javascript", 0, "%s(%s);" % (post["callback"], html.json(rs)))

    elif method == "xml_adoptable_animals":
        users.check_permission_map(l, user["SUPERUSER"], securitymap, users.VIEW_ANIMAL)
        pc = publish.PublishCriteria(configuration.publisher_presets(dbo))
        rs = publish.get_animal_data(dbo, pc, True)
        return set_cached_response(cache_key, "application/xml", 3600, 3600, html.xml(rs))

    elif method == "json_recent_adoptions":
        users.check_permission_map(l, user["SUPERUSER"], securitymap, users.VIEW_ANIMAL)
        rs = movement.get_recent_adoptions(dbo)
        return set_cached_response(cache_key, "application/json", 3600, 3600, html.json(rs))

    elif method == "jsonp_recent_adoptions":
        users.check_permission_map(l, user["SUPERUSER"], securitymap, users.VIEW_ANIMAL)
        rs = movement.get_recent_adoptions(dbo)
        return ("application/javascript", 0, "%s(%s);" % (post["callback"], html.json(rs)))

    elif method == "xml_recent_adoptions":
        users.check_permission_map(l, user["SUPERUSER"], securitymap, users.VIEW_ANIMAL)
        rs = movement.get_recent_adoptions(dbo)
        return set_cached_response(cache_key, "application/xml", 3600, 3600, html.xml(rs))

    elif method == "html_report":
        users.check_permission_map(l, user["SUPERUSER"], securitymap, users.VIEW_REPORT)
        crid = reports.get_id(dbo, title)
        p = reports.get_criteria_params(dbo, crid, post)
        rhtml = reports.execute(dbo, crid, username, p)
        return set_cached_response(cache_key, "text/html", 3600, 3600, rhtml)

    elif method == "csv_mail" or method == "csv_report":
        users.check_permission_map(l, user["SUPERUSER"], securitymap, users.VIEW_REPORT)
        crid = reports.get_id(dbo, title)
        p = reports.get_criteria_params(dbo, crid, post)
        rows, cols = reports.execute_query(dbo, crid, username, p)
        mcsv = utils.csv(l, rows, cols, True)
        return set_cached_response(cache_key, "text/csv", 3600, 3600, mcsv)

    elif method == "jsonp_shelter_animals":
        users.check_permission_map(l, user["SUPERUSER"], securitymap, users.VIEW_ANIMAL)
        sa = animal.get_animal_find_simple(dbo, "", "shelter")
        return ("application/javascript", 0, "%s(%s);" % (post["callback"], html.json(sa)))

    elif method == "json_shelter_animals":
        users.check_permission_map(l, user["SUPERUSER"], securitymap, users.VIEW_ANIMAL)
        sa = animal.get_animal_find_simple(dbo, "", "shelter")
        return set_cached_response(cache_key, "application/json", 3600, 3600, html.json(sa))

    elif method == "xml_shelter_animals":
        users.check_permission_map(l, user["SUPERUSER"], securitymap, users.VIEW_ANIMAL)
        sa = animal.get_animal_find_simple(dbo, "", "shelter")
        return set_cached_response(cache_key, "application/xml", 3600, 3600, html.xml(sa))

    elif method == "rss_timeline":
        users.check_permission_map(l, user["SUPERUSER"], securitymap, users.VIEW_ANIMAL)
        return set_cached_response(cache_key, "application/rss+xml", 3600, 3600, html.timeline_rss(dbo))

    elif method == "upload_animal_image":
        users.check_permission_map(l, user["SUPERUSER"], securitymap, users.ADD_MEDIA)
        media.attach_file_from_form(dbo, username, media.ANIMAL, int(animalid), post)
        return ("text/plain", 0, "OK")

    elif method == "online_form_html":
        if formid == 0:
            raise utils.ASMError("method online_form_html requires a valid formid")
        return set_cached_response(cache_key, "text/html; charset=utf-8", 120, 120, onlineform.get_onlineform_html(dbo, formid))

    elif method == "online_form_json":
        if formid == 0:
            raise utils.ASMError("method online_form_json requires a valid formid")
        return set_cached_response(cache_key, "text/json; charset=utf-8", 30, 30, onlineform.get_onlineform_json(dbo, formid))

    elif method == "online_form_post":
        flood_protect("online_form_post", remoteip, 15)
        onlineform.insert_onlineformincoming_from_form(dbo, post, remoteip)
        redirect = post["redirect"]
        if redirect == "":
            redirect = BASE_URL + "/static/pages/form_submitted.html"
        return ("redirect", 0, redirect)

    elif method == "sign_document":
        if formid == 0:
            raise utils.ASMError("method sign_document requires a valid formid")
        if post["sig"] == "":
            return set_cached_response(cache_key, "text/html", 2, 2, sign_document_page(dbo, formid))
        else:
            media.sign_document(dbo, "service", formid, post["sig"], post["signdate"])
            return ("text/plain", 0, "OK")

    else:
        al.error("invalid method '%s'" % method, "service.handler", dbo)
        raise utils.ASMError("Invalid method '%s'" % method)
Esempio n. 26
0
 def thumb_mrec(mm):
     if len(mm) == 0: return thumb_nopic()
     if justdate: return mm[0].DATE
     return (mm[0].DATE,
             scale_thumbnail(dbfs.get_string(dbo, mm[0].MEDIANAME)))
Esempio n. 27
0
 def thumb_mrec(mm):
     if justdate:
         return mm[0]["DATE"]
     else:
         return (mm[0]["DATE"],
                 scale_thumbnail(dbfs.get_string(dbo, mm[0]["MEDIANAME"])))
Esempio n. 28
0
 def test_get_string(self):
     assert len(dbfs.get_string(base.get_dbo(), "nopic.jpg", "/reports")) > 0
Esempio n. 29
0
def create_animal(dbo, username, wlid):
    """
    Creates an animal record from a waiting list entry with the id given
    """
    l = dbo.locale
    a = dbo.first_row(
        dbo.query("SELECT * FROM animalwaitinglist WHERE ID = ?", [wlid]))

    data = {
        "animalname": _("Waiting List {0}", l).format(wlid),
        "markings": str(a["ANIMALDESCRIPTION"]),
        "reasonforentry": str(a["REASONFORWANTINGTOPART"]),
        "species": str(a["SPECIESID"]),
        "hiddenanimaldetails": str(a["COMMENTS"]),
        "broughtinby": str(a["OWNERID"]),
        "originalowner": str(a["OWNERID"]),
        "animaltype": configuration.default_type(dbo),
        "breed1": configuration.default_breed(dbo),
        "breed2": configuration.default_breed(dbo),
        "basecolour": configuration.default_colour(dbo),
        "size": configuration.default_size(dbo),
        "internallocation": configuration.default_location(dbo),
        "dateofbirth": python2display(l, subtract_years(now(dbo.timezone))),
        "estimateddob": "1"
    }
    # If we aren't showing the time brought in, set it to midnight
    if not configuration.add_animals_show_time_brought_in(dbo):
        data["timebroughtin"] = "00:00:00"

    # If we're creating shelter codes manually, we need to put something unique
    # in there for now. Use the id
    if configuration.manual_codes(dbo):
        data["sheltercode"] = "WL" + str(wlid)
        data["shortcode"] = "WL" + str(wlid)
    nextid, code = animal.insert_animal_from_form(dbo,
                                                  utils.PostedData(data, l),
                                                  username)

    # Now that we've created our animal, we should remove this entry from the waiting list
    dbo.update(
        "animalwaitinglist", wlid, {
            "DateRemovedFromList": dbo.today(),
            "ReasonForRemoval": _("Moved to animal record {0}", l).format(code)
        }, username)

    # If there were any logs and media entries on the waiting list, create them on the animal

    # Media
    for me in dbo.query(
            "SELECT * FROM media WHERE LinkTypeID = ? AND LinkID = ?",
        (media.WAITINGLIST, wlid)):
        ext = me.medianame
        ext = ext[ext.rfind("."):].lower()
        mediaid = dbo.get_id("media")
        medianame = "%d%s" % (mediaid, ext)
        dbo.insert(
            "media",
            {
                "ID": mediaid,
                "DBFSID": 0,
                "MediaSize": 0,
                "MediaName": medianame,
                "MediaMimeType": media.mime_type(medianame),
                "MediaType": me.mediatype,
                "MediaNotes": me.medianotes,
                "WebsitePhoto": me.websitephoto,
                "WebsiteVideo": me.websitevideo,
                "DocPhoto": me.docphoto,
                "ExcludeFromPublish": me.excludefrompublish,
                # ASM2_COMPATIBILITY
                "NewSinceLastPublish": 1,
                "UpdatedSinceLastPublish": 0,
                # ASM2_COMPATIBILITY
                "LinkID": nextid,
                "LinkTypeID": media.ANIMAL,
                "Date": me.date,
                "RetainUntil": me.retainuntil
            },
            generateID=False)

        # Now clone the dbfs item pointed to by this media item if it's a file
        if me.mediatype == media.MEDIATYPE_FILE:
            filedata = dbfs.get_string(dbo, me.medianame)
            dbfsid = dbfs.put_string(dbo, medianame, "/animal/%d" % nextid,
                                     filedata)
            dbo.execute(
                "UPDATE media SET DBFSID = ?, MediaSize = ? WHERE ID = ?",
                (dbfsid, len(filedata), mediaid))

    # Logs
    for lo in dbo.query("SELECT * FROM log WHERE LinkType = ? AND LinkID = ?",
                        (log.WAITINGLIST, wlid)):
        dbo.insert(
            "log", {
                "LinkID": nextid,
                "LinkType": log.ANIMAL,
                "LogTypeID": lo.LOGTYPEID,
                "Date": lo.DATE,
                "Comments": lo.COMMENTS
            }, username)

    return nextid
Esempio n. 30
0
 def mrec(mm):
     if justdate:
         return mm[0]["DATE"]
     else:
         return (mm[0]["DATE"], dbfs.get_string(dbo, mm[0]["MEDIANAME"]))
Esempio n. 31
0
    # Bail out if we have a problem
    if a is None: 
        raise utils.ASMValidationError("Facebook response did not contain a valid animal ID (got %s)" % oauth_state[1:])

    # Generate the body of the post from our facebook template
    tags = wordprocessor.animal_tags(dbo, a)
    template = configuration.facebook_template(dbo)
    posttext = wordprocessor.substitute_tags(template, tags, False, "$$", "$$")

    # Post on the wall
    try:

        l = dbo.locale
        fb_url = "https://graph.facebook.com/%s/photos?access_token=%s" % (post_to, access_token)
        al.debug("FB posting photo and text '%s' to '%s' at %s" % (posttext, page_name, fb_url), "social.post_animal_facebook", dbo)
        imagedata = dbfs.get_string(dbo, a["WEBSITEMEDIANAME"])
        req, hdr, response = utils.post_multipart(fb_url, ( ("message", utils.decode_html(posttext).encode("utf-8")),), ( ("source", "pic.jpg", imagedata), ))
        al.debug("FB response: %s" % response, "social.post_animal_facebook", dbo)

        # If the option is on and all was ok, make a note in the log
        if configuration.facebook_log(dbo):
            al.debug("FB writing entry to animal log: %s %s" % (a["SHELTERCODE"], a["ANIMALNAME"]), "social.post_animal_facebook", dbo)
            log.add_log(dbo, user, log.ANIMAL, utils.cint(oauth_state[1:]), configuration.facebook_log_type(dbo),
                _("{0} {1}: posted to Facebook page {2} by {3}", l).format(a["SHELTERCODE"], a["ANIMALNAME"], page_name, 
                user))

    except urllib2.HTTPError,herr:
        em = str(herr.read())
        al.error("Failed posting photo to facebook: %s" % em, "social.post_animal_facebook", dbo, sys.exc_info())
        raise utils.ASMValidationError("Failed posting photo and details to Facebook (http).")
    except Exception,err: