Example #1
0
def create_document_media(dbo, username, linktype, linkid, template, content):
    """
    Creates a new media record for a document for the link given.
    linktype: ANIMAL, PERSON, etc
    linkid: ID for the link
    template: The name of the template used to create the document
    content: The document contents
    """
    mediaid = db.get_id(dbo, "media")
    sql = db.make_insert_sql(
        "media",
        (("ID", db.di(mediaid)), ("MediaName", db.ds("%d.html" % mediaid)),
         ("MediaType", db.di(0)), ("MediaNotes", db.ds(template)),
         ("WebsitePhoto", db.di(0)), ("WebsiteVideo", db.di(0)),
         ("DocPhoto", db.di(0)), ("ExcludeFromPublish", db.di(0)),
         ("NewSinceLastPublish", db.di(1)),
         ("UpdatedSinceLastPublish", db.di(0)), ("LinkID", db.di(linkid)),
         ("LinkTypeID", db.di(linktype)), ("Date", db.nowsql())))
    db.execute(dbo, sql)
    path = ""
    if linktype == ANIMAL:
        path = "/animal"
    elif linktype == PERSON:
        path = "/owner"
    elif linktype == LOSTANIMAL:
        path = "/lostanimal"
    elif linktype == FOUNDANIMAL:
        path = "/foundanimal"
    path += "/" + str(linkid)
    name = str(mediaid) + ".html"
    dbfs.put_string(dbo, name, path, content)
    audit.create(dbo, username, "media",
                 str(mediaid) + ": for " + str(linkid) + "/" + str(linktype))
def save_values_for_link(dbo, post, linkid, linktype="animal"):
    """
    Saves incoming additional field values from a form, clearing any
    existing values first.
    """
    delete_values_for_link(dbo, linkid, linktype)
    af = get_field_definitions(dbo, linktype)
    l = dbo.locale
    for f in af:
        key = "a." + str(f["MANDATORY"]) + "." + str(f["ID"])
        if post.has_key(key):
            val = post[key]
            if f["FIELDTYPE"] == YESNO:
                val = str(post.boolean(key))
            elif f["FIELDTYPE"] == MONEY:
                val = str(post.integer(key))
            elif f["FIELDTYPE"] == DATE:
                if len(val.strip()) > 0 and post.date(key) == None:
                    raise utils.ASMValidationError(
                        _(
                            "Additional date field '{0}' contains an invalid date.",
                            l).format(f["FIELDNAME"]))
                val = python2display(dbo.locale, post.date(key))
            sql = db.make_insert_sql("additional",
                                     (("LinkType", db.di(f["LINKTYPE"])),
                                      ("LinkID", db.di(int(linkid))),
                                      ("AdditionalFieldID", db.di(f["ID"])),
                                      ("Value", db.ds(val))))
            try:
                db.execute(dbo, sql)
            except Exception, err:
                al.error("Failed saving additional field: %s" % str(err),
                         "animal.update_animal_from_form", dbo, sys.exc_info())
Example #3
0
def attach_link_from_form(dbo, username, linktype, linkid, data):
    """
    Attaches a link to a web resource from a form
    """
    existingvid = db.query_int(dbo, "SELECT COUNT(*) FROM media WHERE WebsiteVideo = 1 " \
        "AND LinkID = %d AND LinkTypeID = %d" % ( int(linkid), int(linktype) ))
    defvid = 0
    if existingvid == 0 and utils.df_ki(data,
                                        "linktype") == MEDIATYPE_VIDEO_LINK:
        defvid = 1
    mediaid = db.get_id(dbo, "media")
    url = utils.df_ks(data, "linktarget")
    if url.find("://") == -1:
        url = "http://" + url
    sql = db.make_insert_sql(
        "media",
        (("ID", db.di(mediaid)), ("MediaName", db.ds(url)),
         ("MediaType", utils.df_s(data, "linktype")),
         ("MediaNotes", utils.df_t(data, "comments")),
         ("WebsitePhoto", db.di(0)), ("WebsiteVideo", db.di(defvid)),
         ("DocPhoto", db.di(0)), ("ExcludeFromPublish", db.di(0)),
         ("NewSinceLastPublish", db.di(1)),
         ("UpdatedSinceLastPublish", db.di(0)), ("LinkID", db.di(linkid)),
         ("LinkTypeID", db.di(linktype)), ("Date", db.nowsql())))
    db.execute(dbo, sql)
    audit.create(
        dbo, username, "media",
        str(mediaid) + ": for " + str(linkid) + "/" + str(linktype) +
        ": link to " + utils.df_ks(data, "linktarget"))
Example #4
0
File: users.py Project: magul/asm3
def insert_user_from_form(dbo, username, post):
    """
    Creates a user record from posted form data. Uses
    the roles key (which should be a comma separated list of
    role ids) to create userrole records.
    """
    # Verify the username is unique
    l = dbo.locale
    if 0 != db.query_int(dbo, "SELECT COUNT(*) FROM users WHERE LOWER(UserName) LIKE LOWER(%s)" % post.db_string("username")):
        raise utils.ASMValidationError(i18n._("Username '{0}' already exists", l).format(post["username"]))
    nuserid = db.get_id(dbo, "users")
    sql = db.make_insert_sql("users", ( 
        ( "ID", db.di(nuserid)),
        ( "UserName", post.db_string("username")),
        ( "RealName", post.db_string("realname")),
        ( "EmailAddress", post.db_string("email")),
        ( "Password", db.ds(hash_password(post["password"]))),
        ( "SuperUser", post.db_integer("superuser")),
        ( "RecordVersion", db.di(0)),
        ( "SecurityMap", db.ds("dummy")),
        ( "OwnerID", post.db_integer("person")),
        ( "SiteID", post.db_integer("site")),
        ( "LocationFilter", post.db_string("locationfilter")),
        ( "IPRestriction", post.db_string("iprestriction"))
        ))
    db.execute(dbo, sql)
    audit.create(dbo, username, "users", nuserid, audit.dump_row(dbo, "users", nuserid))
    roles = post["roles"].strip()
    if roles != "":
        for rid in roles.split(","):
            if rid.strip() != "":
                db.execute(dbo, "INSERT INTO userrole VALUES (%d, %d)" % (nuserid, int(rid)))
    return nuserid
Example #5
0
def attach_link_from_form(dbo, username, linktype, linkid, data):
    """
    Attaches a link to a web resource from a form
    """
    existingvid = db.query_int(dbo, "SELECT COUNT(*) FROM media WHERE WebsiteVideo = 1 " \
        "AND LinkID = %d AND LinkTypeID = %d" % ( int(linkid), int(linktype) ))
    defvid = 0
    if existingvid == 0 and utils.df_ki(data, "linktype") == MEDIATYPE_VIDEO_LINK:
        defvid = 1
    mediaid = db.get_id(dbo, "media")
    url = utils.df_ks(data, "linktarget")
    if url.find("://") == -1:
        url = "http://" + url
    sql = db.make_insert_sql("media", (
        ( "ID", db.di(mediaid) ),
        ( "MediaName", db.ds(url) ),
        ( "MediaType", utils.df_s(data, "linktype") ),
        ( "MediaNotes", utils.df_t(data, "comments") ),
        ( "WebsitePhoto", db.di(0) ),
        ( "WebsiteVideo", db.di(defvid) ),
        ( "DocPhoto", db.di(0) ),
        ( "ExcludeFromPublish", db.di(0) ),
        ( "NewSinceLastPublish", db.di(1) ),
        ( "UpdatedSinceLastPublish", db.di(0) ),
        ( "LinkID", db.di(linkid) ),
        ( "LinkTypeID", db.di(linktype) ),
        ( "Date", db.nowsql() )
        ))
    db.execute(dbo, sql)
    audit.create(dbo, username, "media", str(mediaid) + ": for " + str(linkid) + "/" + str(linktype) + ": link to " + utils.df_ks(data, "linktarget"))
Example #6
0
def insert_user_from_form(dbo, username, data):
    """
    Creates a user record from posted form data. Uses
    the roles key (which should be a comma separated list of
    role ids) to create userrole records.
    """
    nuserid = db.get_id(dbo, "users")
    sql = db.make_insert_sql("users", ( 
        ( "ID", db.di(nuserid)),
        ( "UserName", utils.df_t(data, "username")),
        ( "RealName", utils.df_t(data, "realname")),
        ( "EmailAddress", utils.df_t(data, "email")),
        ( "Password", db.ds(hash_password(utils.df_ks(data, "password"), True))),
        ( "SuperUser", utils.df_s(data, "superuser")),
        ( "RecordVersion", db.di(0)),
        ( "SecurityMap", db.ds("dummy")),
        ( "OwnerID", utils.df_s(data, "person")),
        ( "LocationFilter", utils.df_t(data, "locationfilter")),
        ( "IPRestriction", utils.df_t(data, "iprestriction"))
        ))
    db.execute(dbo, sql)
    audit.create(dbo, username, "users", str(nuserid))
    roles = utils.df_ks(data, "roles").strip()
    if roles != "":
        for rid in roles.split(","):
            if rid.strip() != "":
                db.execute(dbo, "INSERT INTO userrole VALUES (%d, %d)" % (nuserid, int(rid)))
    return nuserid
Example #7
0
def insert_user_from_form(dbo, username, data):
    """
    Creates a user record from posted form data. Uses
    the roles key (which should be a comma separated list of
    role ids) to create userrole records.
    """
    nuserid = db.get_id(dbo, "users")
    sql = db.make_insert_sql(
        "users",
        (("ID", db.di(nuserid)), ("UserName", utils.df_t(data, "username")),
         ("RealName", utils.df_t(data, "realname")),
         ("EmailAddress", utils.df_t(data, "email")),
         ("Password", db.ds(hash_password(utils.df_ks(data, "password"),
                                          True))),
         ("SuperUser", utils.df_s(data, "superuser")),
         ("RecordVersion", db.di(0)), ("SecurityMap", db.ds("dummy")),
         ("OwnerID", utils.df_s(data, "person")),
         ("LocationFilter", utils.df_t(data, "locationfilter")),
         ("IPRestriction", utils.df_t(data, "iprestriction"))))
    db.execute(dbo, sql)
    audit.create(dbo, username, "users", str(nuserid))
    roles = utils.df_ks(data, "roles").strip()
    if roles != "":
        for rid in roles.split(","):
            if rid.strip() != "":
                db.execute(
                    dbo, "INSERT INTO userrole VALUES (%d, %d)" %
                    (nuserid, int(rid)))
    return nuserid
Example #8
0
def save_values_for_link(dbo, post, linkid, linktype = "animal"):
    """
    Saves incoming additional field values from a form, clearing any
    existing values first.
    """
    delete_values_for_link(dbo, linkid, linktype)
    af = get_field_definitions(dbo, linktype)
    l = dbo.locale
    for f in af:
        key = "a." + str(f["MANDATORY"]) + "." + str(f["ID"])
        if post.has_key(key):
            val = post[key]
            if f["FIELDTYPE"] == YESNO:
                val = str(post.boolean(key))
            elif f["FIELDTYPE"] == MONEY:
                val = str(post.integer(key))
            elif f["FIELDTYPE"] == DATE:
                if len(val.strip()) > 0 and post.date(key) == None:
                    raise utils.ASMValidationError(_("Additional date field '{0}' contains an invalid date.", l).format(f["FIELDNAME"]))
                val = python2display(dbo.locale, post.date(key))
            sql = db.make_insert_sql("additional", (
                ( "LinkType", db.di(f["LINKTYPE"]) ),
                ( "LinkID", db.di(int(linkid)) ),
                ( "AdditionalFieldID", db.di(f["ID"]) ),
                ( "Value", db.ds(val) ) ))
            try:
                db.execute(dbo, sql)
            except Exception,err:
                al.error("Failed saving additional field: %s" % str(err), "animal.update_animal_from_form", dbo, sys.exc_info())
Example #9
0
File: stock.py Project: magul/asm3
def insert_stocklevel_from_form(dbo, post, username):
    """
    Inserts a stocklevel item from a dialog. The post should include
    the ID of the stocklevel to adjust and a usage record will be
    written so usage data should be sent too.
    """
    l = dbo.locale
    slid = post.integer("id")
    if post["name"] == "":
        raise utils.ASMValidationError(_("Stock level must have a name", l))
    if post["unitname"] == "":
        raise utils.ASMValidationError(_("Stock level must have a unit", l))

    nid = db.get_id(dbo, "stocklevel")
    db.execute(dbo, db.make_insert_sql("stocklevel", (
        ( "ID", db.di(nid) ),
        ( "Name", post.db_string("name") ),
        ( "Description", post.db_string("description") ),
        ( "StockLocationID", post.db_integer("location") ),
        ( "UnitName", post.db_string("unitname") ),
        ( "Total", post.db_floating("total") ),
        ( "Balance", post.db_floating("balance") ),
        ( "Expiry", post.db_date("expiry") ),
        ( "BatchNumber", post.db_string("batchnumber") ),
        ( "Cost", post.db_integer("cost") ),
        ( "UnitPrice", post.db_integer("unitprice") ),
        ( "CreatedDate", db.todaysql() )
    )))
    insert_stockusage(dbo, username, slid, post.floating("balance"), post.date("usagedate"), post.integer("usagetype"), post["comments"])
    audit.create(dbo, username, "stocklevel", nid, audit.dump_row(dbo, "stocklevel", nid))
    return nid
Example #10
0
File: media.py Project: magul/asm3
def attach_link_from_form(dbo, username, linktype, linkid, post):
    """
    Attaches a link to a web resource from a form
    """
    existingvid = db.query_int(dbo, "SELECT COUNT(*) FROM media WHERE WebsiteVideo = 1 " \
        "AND LinkID = %d AND LinkTypeID = %d" % ( int(linkid), int(linktype) ))
    defvid = 0
    if existingvid == 0 and post.integer("linktype") == MEDIATYPE_VIDEO_LINK:
        defvid = 1
    mediaid = db.get_id(dbo, "media")
    url = post["linktarget"]
    if url.find("://") == -1:
        url = "http://" + url
    al.debug("attached link %s" % url, "media.attach_file_from_form")
    sql = db.make_insert_sql("media", (
        ( "ID", db.di(mediaid) ),
        ( "MediaName", db.ds(url) ),
        ( "MediaType", post.db_integer("linktype") ),
        ( "MediaNotes", post.db_string("comments") ),
        ( "WebsitePhoto", db.di(0) ),
        ( "WebsiteVideo", db.di(defvid) ),
        ( "DocPhoto", db.di(0) ),
        ( "ExcludeFromPublish", db.di(0) ),
        # ASM2_COMPATIBILITY
        ( "NewSinceLastPublish", db.di(1) ),
        ( "UpdatedSinceLastPublish", db.di(0) ),
        # ASM2_COMPATIBILITY
        ( "LinkID", db.di(linkid) ),
        ( "LinkTypeID", db.di(linktype) ),
        ( "Date", db.nowsql() )
        ))
    db.execute(dbo, sql)
    audit.create(dbo, username, "media", mediaid, str(mediaid) + ": for " + str(linkid) + "/" + str(linktype) + ": link to " + post["linktarget"])
Example #11
0
 def toDB(self):
     """ Writes a lostfoundmatch record from this object """
     sql = db.make_insert_sql("animallostfoundmatch", (
         ( "AnimalLostID", db.di(self.lid) ),
         ( "AnimalFoundID", db.di(self.fid) ),
         ( "AnimalID", db.di(self.fanimalid) ),
         ( "LostContactName", db.ds(self.lcontactname) ),
         ( "LostContactNumber", db.ds(self.lcontactnumber) ),
         ( "LostArea", db.ds(self.larealost) ),
         ( "LostPostcode", db.ds(self.lareapostcode) ),
         ( "LostAgeGroup", db.ds(self.lagegroup) ),
         ( "LostSex", db.di(self.lsexid) ),
         ( "LostSpeciesID", db.di(self.lspeciesid) ),
         ( "LostBreedID", db.di(self.lbreedid) ),
         ( "LostFeatures", db.ds(self.ldistinguishingfeatures) ),
         ( "LostBaseColourID", db.di(self.lbasecolourid) ),
         ( "LostDate", db.dd(self.ldatelost) ),
         ( "FoundContactName", db.ds(self.fcontactname) ),
         ( "FoundContactNumber", db.ds(self.fcontactnumber) ),
         ( "FoundArea", db.ds(self.fareafound) ),
         ( "FoundPostcode", db.ds(self.fareapostcode) ),
         ( "FoundAgeGroup", db.ds(self.fagegroup) ),
         ( "FoundSex", db.di(self.fsexid) ),
         ( "FoundSpeciesID", db.di(self.fspeciesid) ),
         ( "FoundBreedID", db.di(self.fbreedid) ),
         ( "FoundFeatures", db.ds(self.fdistinguishingfeatures) ),
         ( "FoundBaseColourID", db.di(self.fbasecolourid) ),
         ( "FoundDate", db.dd(self.fdatefound) ),
         ( "MatchPoints", db.di(self.matchpoints) ) ))
     db.execute(self.dbo, sql)
Example #12
0
def insert_onlineformincoming_from_form(dbo, post, remoteip):
    """
    Create onlineformincoming records from posted data. We 
    create a row for every key/value pair in the posted data
    with a unique collation ID.
    """
    IGNORE_FIELDS = [ "formname", "flags", "redirect", "account", "filechooser", "method" ]
    collationid = db.query_int(dbo, "SELECT MAX(CollationID) FROM onlineformincoming") + 1
    formname = post["formname"]
    posteddate = i18n.now(dbo.timezone)
    flags = post["flags"]
    for k, v in post.data.iteritems():
        if k not in IGNORE_FIELDS:
            label = ""
            displayindex = 0
            fieldname = k
            # Form fields should have a _ONLINEFORMFIELD.ID suffix we can use to get the
            # original label and display position
            if k.find("_") != -1:
                fid = utils.cint(k[k.rfind("_")+1:])
                fieldname = k[0:k.rfind("_")]
                if fid != 0:
                    fld = db.query(dbo, "SELECT Label, DisplayIndex FROM onlineformfield WHERE ID = %d" % fid)
                    if len(fld) > 0:
                        label = fld[0]["LABEL"]
                        displayindex = fld[0]["DISPLAYINDEX"]

            sql = db.make_insert_sql("onlineformincoming", ( 
                ( "CollationID", db.di(collationid)),
                ( "FormName", db.ds(formname)),
                ( "PostedDate", db.ddt(posteddate)),
                ( "Flags", db.ds(flags)),
                ( "FieldName", db.ds(fieldname)),
                ( "Label", db.ds(label)),
                ( "DisplayIndex", db.di(displayindex)),
                ( "Host", db.ds(remoteip)),
                ( "Value", post.db_string(k))
                ))
            db.execute(dbo, sql)
    # Sort out the preview of the first few fields
    fieldssofar = 0
    preview = []
    for fld in get_onlineformincoming_detail(dbo, collationid):
        if fieldssofar < 3:
            fieldssofar += 1
            preview.append( fld["LABEL"] + ": " + fld["VALUE"] )
    db.execute(dbo, "UPDATE onlineformincoming SET Preview = %s WHERE CollationID = %s" % ( db.ds(", ".join(preview)), db.di(collationid) ))
    # Did the original form specify some email addresses to send 
    # incoming submissions to?
    email = db.query_string(dbo, "SELECT o.EmailAddress FROM onlineform o " \
        "INNER JOIN onlineformincoming oi ON oi.FormName = o.Name " \
        "WHERE oi.CollationID = %d" % int(collationid))
    if email is not None and email.strip() != "":
        utils.send_email(dbo, configuration.email(dbo), email, "", "%s - %s" % (formname, ", ".join(preview)), get_onlineformincoming_plain(dbo, collationid))
    return collationid
Example #13
0
def insert_role_from_form(dbo, username, data):
    """
    Creates a role record from posted form data. 
    """
    nroleid = db.get_id(dbo, "role")
    sql = db.make_insert_sql(
        "role",
        (("ID", db.di(nroleid)), ("Rolename", utils.df_t(data, "rolename")),
         ("SecurityMap", utils.df_t(data, "securitymap"))))
    db.execute(dbo, sql)
    audit.create(dbo, username, "role", str(nroleid))
Example #14
0
def insert_onlineformincoming_from_form(dbo, data, remoteip):
    """
    Create onlineformincoming records from posted data. We 
    create a row for every key/value pair in the posted data
    with a unique collation ID.
    """
    IGNORE_FIELDS = [
        "formname", "flags", "redirect", "account", "filechooser", "method"
    ]
    collationid = db.query_int(
        dbo, "SELECT MAX(CollationID) FROM onlineformincoming") + 1
    formname = utils.df_ks(data, "formname")
    posteddate = i18n.now(dbo.timezone)
    flags = utils.df_ks(data, "flags")
    for k, v in data.iteritems():
        if k not in IGNORE_FIELDS:
            label = ""
            displayindex = 0
            fieldname = k
            # Form fields should have a _ONLINEFORMFIELD.ID suffix we can use to get the
            # original label and display position
            if k.find("_") != -1:
                fid = utils.cint(k[k.rfind("_") + 1:])
                fieldname = k[0:k.rfind("_")]
                if fid != 0:
                    fld = db.query(
                        dbo,
                        "SELECT Label, DisplayIndex FROM onlineformfield WHERE ID = %d"
                        % fid)
                    if len(fld) > 0:
                        label = fld[0]["LABEL"]
                        displayindex = fld[0]["DISPLAYINDEX"]

            sql = db.make_insert_sql(
                "onlineformincoming",
                (("CollationID", db.di(collationid)),
                 ("FormName", db.ds(formname)),
                 ("PostedDate", db.ddt(posteddate)), ("Flags", db.ds(flags)),
                 ("FieldName", db.ds(fieldname)), ("Label", db.ds(label)),
                 ("DisplayIndex", db.di(displayindex)),
                 ("Host", db.ds(remoteip)), ("Value", db.ds(v))))
            db.execute(dbo, sql)
    # Sort out the preview of the first few fields
    fieldssofar = 0
    preview = []
    for fld in get_onlineformincoming_detail(dbo, collationid):
        if fieldssofar < 3:
            fieldssofar += 1
            preview.append(fld["LABEL"] + ": " + fld["VALUE"])
    db.execute(
        dbo,
        "UPDATE onlineformincoming SET Preview = %s WHERE CollationID = %s" %
        (db.ds(", ".join(preview)), db.di(collationid)))
    return collationid
Example #15
0
File: users.py Project: magul/asm3
def insert_role_from_form(dbo, username, post):
    """
    Creates a role record from posted form data. 
    """
    nroleid = db.get_id(dbo, "role")
    sql = db.make_insert_sql("role", ( 
        ( "ID", db.di(nroleid)),
        ( "Rolename", post.db_string("rolename")),
        ( "SecurityMap", post.db_string("securitymap"))
        ))
    db.execute(dbo, sql)
    audit.create(dbo, username, "role", nroleid, audit.dump_row(dbo, "role", nroleid))
Example #16
0
def insert_role_from_form(dbo, username, data):
    """
    Creates a role record from posted form data. 
    """
    nroleid = db.get_id(dbo, "role")
    sql = db.make_insert_sql("role", ( 
        ( "ID", db.di(nroleid)),
        ( "Rolename", utils.df_t(data, "rolename")),
        ( "SecurityMap", utils.df_t(data, "securitymap"))
        ))
    db.execute(dbo, sql)
    audit.create(dbo, username, "role", str(nroleid))
Example #17
0
def login(dbo, username):
    """
    Marks the given user as logged in
    """
    logout(dbo, username)
    db.execute(dbo, "DELETE FROM activeuser WHERE UPPER(UserName) LIKE '%s'" % str(username.upper()))
    db.execute(dbo, db.make_insert_sql("activeuser", (
        ( "UserName", db.ds(username)),
        ( "Since", db.ddt(i18n.now())),
        ( "Messages", db.ds("asm3"))
        )))
    al.info("%s logged in" % username, "users.login", dbo)
Example #18
0
def insert_diarytaskhead_from_form(dbo, username, data):
    """
    Creates a diary task header from form data
    """
    nid = db.get_id(dbo, "diarytaskhead")
    sql = db.make_insert_sql("diarytaskhead",
                             (("ID", db.di(nid)),
                              ("Name", utils.df_t(data, "name")),
                              ("RecordType", utils.df_s(data, "type")),
                              ("RecordVersion", db.di(0))))
    db.execute(dbo, sql)
    audit.create(dbo, username, "diarytaskhead", str(nid))
    return nid
Example #19
0
def add_message(dbo, createdby, email, message, forname = "*", priority = 0, expires = add_days(now(), 7), added = now()):
    l = dbo.locale
    db.execute(dbo, db.make_insert_sql("messages", (
        ( "ID", db.di(db.get_id(dbo, "messages"))),
        ( "Added", db.dd(added)),
        ( "Expires", db.dd(expires)),
        ( "CreatedBy", db.ds(createdby)),
        ( "Priority", db.di(priority)),
        ( "ForName", db.ds(forname)),
        ( "Message", db.ds(message)))))
    # If email is set, we email the message to everyone that it would match
    if email == 1:
        utils.send_user_email(dbo, createdby, forname, _("Message from {0}", l).format(createdby), message)
def insert_diarytaskhead_from_form(dbo, username, post):
    """
    Creates a diary task header from form data
    """
    nid = db.get_id(dbo, "diarytaskhead")
    sql = db.make_insert_sql("diarytaskhead",
                             (("ID", db.di(nid)),
                              ("Name", post.db_string("name")),
                              ("RecordType", post.db_integer("type")),
                              ("RecordVersion", db.di(0))))
    db.execute(dbo, sql)
    audit.create(dbo, username, "diarytaskhead", str(nid))
    return nid
Example #21
0
def insert_onlineform_from_form(dbo, username, data):
    """
    Create an onlineform record from posted data
    """
    formid = db.get_id(dbo, "onlineform")
    sql = db.make_insert_sql(
        "onlineform",
        (("ID", db.di(formid)), ("Name", db.ds(utils.df_ks(data, "name"))),
         ("RedirectUrlAfterPOST", db.ds(utils.df_ks(data, "redirect"))),
         ("SetOwnerFlags", db.ds(utils.df_ks(data, "flags"))),
         ("Description", db.ds(utils.df_ks(data, "description")))))
    db.execute(dbo, sql)
    audit.create(dbo, username, "onlineform", str(formid))
    return formid
Example #22
0
File: diary.py Project: magul/asm3
def insert_diarytaskhead_from_form(dbo, username, post):
    """
    Creates a diary task header from form data
    """
    nid = db.get_id(dbo, "diarytaskhead")
    sql = db.make_insert_sql("diarytaskhead", (
        ( "ID", db.di(nid)),
        ( "Name", post.db_string("name")),
        ( "RecordType", post.db_integer("type")),
        ( "RecordVersion", db.di(0))
        ))
    db.execute(dbo, sql)
    audit.create(dbo, username, "diarytaskhead", nid, audit.dump_row(dbo, "diarytaskhead", nid))
    return nid
Example #23
0
def insert_diarytaskhead_from_form(dbo, username, data):
    """
    Creates a diary task header from form data
    """
    nid = db.get_id(dbo, "diarytaskhead")
    sql = db.make_insert_sql("diarytaskhead", (
        ( "ID", db.di(nid)),
        ( "Name", utils.df_t(data, "name")),
        ( "RecordType", utils.df_s(data, "type")),
        ( "RecordVersion", db.di(0))
        ))
    db.execute(dbo, sql)
    audit.create(dbo, username, "diarytaskhead", str(nid))
    return nid
Example #24
0
def login(dbo, username):
    """
    Marks the given user as logged in
    """
    logout(dbo, username)
    db.execute(
        dbo, "DELETE FROM activeuser WHERE UPPER(UserName) LIKE '%s'" %
        str(username.upper()))
    db.execute(
        dbo,
        db.make_insert_sql("activeuser", (("UserName", db.ds(username)),
                                          ("Since", db.ddt(i18n.now())),
                                          ("Messages", db.ds("asm3")))))
    al.info("%s logged in" % username, "users.login", dbo)
Example #25
0
def add_message(dbo, createdby, email, message, forname = "*", priority = 0, expires = add_days(now(), 7), added = now()):
    l = dbo.locale
    mid = db.get_id(dbo, "messages")
    db.execute(dbo, db.make_insert_sql("messages", (
        ( "ID", db.di(mid)),
        ( "Added", db.dd(added)),
        ( "Expires", db.dd(expires)),
        ( "CreatedBy", db.ds(createdby)),
        ( "Priority", db.di(priority)),
        ( "ForName", db.ds(forname)),
        ( "Message", db.ds(message)))))
    # If email is set, we email the message to everyone that it would match
    if email == 1:
        utils.send_user_email(dbo, createdby, forname, _("Message from {0}", l).format(createdby), message)
    return mid
Example #26
0
def create_additional_fields(dbo, row, errors, rowno, csvkey = "ANIMALADDITIONAL", linktype = "animal", linkid = 0):
    # Identify any additional fields that may have been specified with
    # ANIMALADDITIONAL<fieldname>
    for a in additional.get_field_definitions(dbo, linktype):
        v = gks(row, csvkey + str(a["FIELDNAME"]).upper())
        if v != "":
            sql = db.make_insert_sql("additional", (
                ( "LinkType", db.di(a["LINKTYPE"]) ),
                ( "LinkID", db.di(int(linkid)) ),
                ( "AdditionalFieldID", db.di(a["ID"]) ),
                ( "Value", db.ds(v) ) ))
            try:
                db.execute(dbo, sql)
            except Exception,e:
                errors.append( (rowno, str(row), str(e)) )
Example #27
0
def insert_onlineform_from_form(dbo, username, data):
    """
    Create an onlineform record from posted data
    """
    formid = db.get_id(dbo, "onlineform")
    sql = db.make_insert_sql("onlineform", ( 
        ( "ID", db.di(formid)),
        ( "Name", db.ds(utils.df_ks(data, "name"))),
        ( "RedirectUrlAfterPOST", db.ds(utils.df_ks(data, "redirect"))),
        ( "SetOwnerFlags", db.ds(utils.df_ks(data, "flags"))),
        ( "Description", db.ds(utils.df_ks(data, "description")))
        ))
    db.execute(dbo, sql)
    audit.create(dbo, username, "onlineform", str(formid))
    return formid
def insert_diarytaskdetail_from_form(dbo, username, post):
    """
    Creates a diary task detail from form data
    """
    nid = db.get_id(dbo, "diarytaskdetail")
    sql = db.make_insert_sql(
        "diarytaskdetail",
        (("ID", db.di(nid)), ("DiaryTaskHeadID", post.db_integer("taskid")),
         ("DayPivot", post.db_integer("pivot")),
         ("WhoFor", post.db_string("for")),
         ("Subject", post.db_string("subject")),
         ("Note", post.db_string("note")), ("RecordVersion", db.di(0))))
    db.execute(dbo, sql)
    audit.create(dbo, username, "diarytaskdetail", str(nid))
    return nid
Example #29
0
def insert_onlineformincoming_from_form(dbo, data, remoteip):
    """
    Create onlineformincoming records from posted data. We 
    create a row for every key/value pair in the posted data
    with a unique collation ID.
    """
    IGNORE_FIELDS = [ "formname", "flags", "redirect", "account", "filechooser", "method" ]
    collationid = db.query_int(dbo, "SELECT MAX(CollationID) FROM onlineformincoming") + 1
    formname = utils.df_ks(data, "formname")
    posteddate = i18n.now(dbo.timezone)
    flags = utils.df_ks(data, "flags")
    for k, v in data.iteritems():
        if k not in IGNORE_FIELDS:
            label = ""
            displayindex = 0
            fieldname = k
            # Form fields should have a _ONLINEFORMFIELD.ID suffix we can use to get the
            # original label and display position
            if k.find("_") != -1:
                fid = utils.cint(k[k.rfind("_")+1:])
                fieldname = k[0:k.rfind("_")]
                if fid != 0:
                    fld = db.query(dbo, "SELECT Label, DisplayIndex FROM onlineformfield WHERE ID = %d" % fid)
                    if len(fld) > 0:
                        label = fld[0]["LABEL"]
                        displayindex = fld[0]["DISPLAYINDEX"]

            sql = db.make_insert_sql("onlineformincoming", ( 
                ( "CollationID", db.di(collationid)),
                ( "FormName", db.ds(formname)),
                ( "PostedDate", db.ddt(posteddate)),
                ( "Flags", db.ds(flags)),
                ( "FieldName", db.ds(fieldname)),
                ( "Label", db.ds(label)),
                ( "DisplayIndex", db.di(displayindex)),
                ( "Host", db.ds(remoteip)),
                ( "Value", db.ds(v))
                ))
            db.execute(dbo, sql)
    # Sort out the preview of the first few fields
    fieldssofar = 0
    preview = []
    for fld in get_onlineformincoming_detail(dbo, collationid):
        if fieldssofar < 3:
            fieldssofar += 1
            preview.append( fld["LABEL"] + ": " + fld["VALUE"] )
    db.execute(dbo, "UPDATE onlineformincoming SET Preview = %s WHERE CollationID = %s" % ( db.ds(", ".join(preview)), db.di(collationid) ))
    return collationid
Example #30
0
def action(dbo, action, username, tablename, description):
    """
    Adds an audit record
    """
    # Truncate description field to 16k if it's very long
    if len(description) > 16384:
        description = description[0:16384]

    sql = db.make_insert_sql("audittrail", (
        ( "Action", db.ds(action) ),
        ( "AuditDate", db.ddt(i18n.now(dbo.timezone)) ),
        ( "UserName", db.ds(username) ),
        ( "TableName", db.ds(tablename) ),
        ( "Description", db.ds(description) )
        ))
    db.execute(dbo, sql)
Example #31
0
def insert_diarytaskdetail_from_form(dbo, username, data):
    """
    Creates a diary task detail from form data
    """
    nid = db.get_id(dbo, "diarytaskdetail")
    sql = db.make_insert_sql("diarytaskdetail", (
        ( "ID", db.di(nid)),
        ( "DiaryTaskHeadID", utils.df_s(data, "taskid")),
        ( "DayPivot", utils.df_s(data, "pivot")),
        ( "WhoFor", utils.df_t(data, "for")),
        ( "Subject", utils.df_t(data, "subject")),
        ( "Note", utils.df_t(data, "note")),
        ( "RecordVersion", db.di(0))
        ))
    db.execute(dbo, sql)
    audit.create(dbo, username, "diarytaskdetail", str(nid))
    return nid
Example #32
0
File: diary.py Project: magul/asm3
def insert_diarytaskdetail_from_form(dbo, username, post):
    """
    Creates a diary task detail from form data
    """
    nid = db.get_id(dbo, "diarytaskdetail")
    sql = db.make_insert_sql("diarytaskdetail", (
        ( "ID", db.di(nid)),
        ( "DiaryTaskHeadID", post.db_integer("taskid")),
        ( "DayPivot", post.db_integer("pivot")),
        ( "WhoFor", post.db_string("for")),
        ( "Subject", post.db_string("subject")),
        ( "Note", post.db_string("note")),
        ( "RecordVersion", db.di(0))
        ))
    db.execute(dbo, sql)
    audit.create(dbo, username, "diarytaskdetail", nid, audit.dump_row(dbo, "diarytaskdetail", nid))
    return nid
Example #33
0
def insert_field_from_form(dbo, username, post):
    """
    Creates an additional field
    """
    nid = db.get_id(dbo, "additionalfield")
    sql = db.make_insert_sql(
        "additionalfield",
        (("ID", db.di(nid)), ("FieldName", post.db_string("name")),
         ("FieldLabel", post.db_string("label")),
         ("ToolTip", post.db_string("tooltip")),
         ("LookupValues", post.db_string("lookupvalues")),
         ("Mandatory", post.db_boolean("mandatory")),
         ("FieldType", post.db_integer("type")),
         ("LinkType", post.db_integer("link")),
         ("DisplayIndex", post.db_integer("displayindex"))))
    db.execute(dbo, sql)
    audit.create(dbo, username, "additionalfield", post["name"])
Example #34
0
def insert_onlineform_from_form(dbo, username, post):
    """
    Create an onlineform record from posted data
    """
    formid = db.get_id(dbo, "onlineform")
    sql = db.make_insert_sql("onlineform", ( 
        ( "ID", db.di(formid)),
        ( "Name", post.db_string("name")),
        ( "RedirectUrlAfterPOST", post.db_string("redirect")),
        ( "SetOwnerFlags", post.db_string("flags")),
        ( "EmailAddress", post.db_string("email")),
        ( "Header", post.db_string("header")),
        ( "Footer", post.db_string("footer")),
        ( "Description", post.db_string("description"))
        ))
    db.execute(dbo, sql)
    audit.create(dbo, username, "onlineform", str(formid))
    return formid
Example #35
0
def insert_onlineformfield_from_form(dbo, username, data):
    """
    Create an onlineformfield record from posted data
    """
    formfieldid = db.get_id(dbo, "onlineformfield")
    sql = db.make_insert_sql("onlineformfield", ( 
        ( "ID", db.di(formfieldid)),
        ( "OnlineFormID", db.di(utils.df_ki(data, "formid"))),
        ( "FieldName", db.ds(utils.df_ks(data, "fieldname"))),
        ( "FieldType", db.di(utils.df_ki(data, "fieldtype"))),
        ( "Label", db.ds(utils.df_ks(data, "label"))),
        ( "DisplayIndex", db.di(utils.df_ki(data, "displayindex"))),
        ( "Lookups", db.ds(utils.df_ks(data, "lookups"))),
        ( "Tooltip", db.ds(utils.df_ks(data, "tooltip")))
        ))
    db.execute(dbo, sql)
    audit.create(dbo, username, "onlineformfield", str(formfieldid))
    return formfieldid
Example #36
0
def insert_onlineformfield_from_form(dbo, username, data):
    """
    Create an onlineformfield record from posted data
    """
    formfieldid = db.get_id(dbo, "onlineformfield")
    sql = db.make_insert_sql(
        "onlineformfield",
        (("ID", db.di(formfieldid)),
         ("OnlineFormID", db.di(utils.df_ki(data, "formid"))),
         ("FieldName", db.ds(utils.df_ks(data, "fieldname"))),
         ("FieldType", db.di(utils.df_ki(data, "fieldtype"))),
         ("Label", db.ds(utils.df_ks(data, "label"))),
         ("DisplayIndex", db.di(utils.df_ki(data, "displayindex"))),
         ("Lookups", db.ds(utils.df_ks(data, "lookups"))),
         ("Tooltip", db.ds(utils.df_ks(data, "tooltip")))))
    db.execute(dbo, sql)
    audit.create(dbo, username, "onlineformfield", str(formfieldid))
    return formfieldid
Example #37
0
def insert_onlineformfield_from_form(dbo, username, post):
    """
    Create an onlineformfield record from posted data
    """
    formfieldid = db.get_id(dbo, "onlineformfield")
    sql = db.make_insert_sql("onlineformfield", ( 
        ( "ID", db.di(formfieldid)),
        ( "OnlineFormID", post.db_integer("formid")),
        ( "FieldName", post.db_string("fieldname")),
        ( "FieldType", post.db_integer("fieldtype")),
        ( "Label", post.db_string("label")),
        ( "DisplayIndex", post.db_integer("displayindex")),
        ( "Mandatory", post.db_boolean("mandatory")),
        ( "Lookups", post.db_string("lookups")),
        ( "Tooltip", post.db_string("tooltip"))
        ))
    db.execute(dbo, sql)
    audit.create(dbo, username, "onlineformfield", str(formfieldid))
    return formfieldid
Example #38
0
def create_blank_document_media(dbo, username, linktype, linkid):
    """
    Creates a new media record for a blank document for the link given.
    linktype: ANIMAL, PERSON, etc
    linkid: ID for the link
    returns the new media id
    """
    mediaid = db.get_id(dbo, "media")
    sql = db.make_insert_sql(
        "media",
        (
            ("ID", db.di(mediaid)),
            ("MediaName", db.ds("%d.html" % mediaid)),
            ("MediaType", db.di(0)),
            ("MediaNotes", db.ds("New document")),
            ("WebsitePhoto", db.di(0)),
            ("WebsiteVideo", db.di(0)),
            ("DocPhoto", db.di(0)),
            ("ExcludeFromPublish", db.di(0)),
            # ASM2_COMPATIBILITY
            ("NewSinceLastPublish", db.di(1)),
            ("UpdatedSinceLastPublish", db.di(0)),
            # ASM2_COMPATIBILITY
            ("LinkID", db.di(linkid)),
            ("LinkTypeID", db.di(linktype)),
            ("Date", db.nowsql())))
    db.execute(dbo, sql)
    path = ""
    if linktype == ANIMAL:
        path = "/animal"
    elif linktype == PERSON:
        path = "/owner"
    elif linktype == LOSTANIMAL:
        path = "/lostanimal"
    elif linktype == FOUNDANIMAL:
        path = "/foundanimal"
    path += "/" + str(linkid)
    name = str(mediaid) + ".html"
    dbfs.put_string(dbo, name, path, "")
    audit.create(dbo, username, "media",
                 str(mediaid) + ": for " + str(linkid) + "/" + str(linktype))
    return mediaid
Example #39
0
def create_additional_fields(dbo,
                             row,
                             errors,
                             rowno,
                             csvkey="ANIMALADDITIONAL",
                             linktype="animal",
                             linkid=0):
    # Identify any additional fields that may have been specified with
    # ANIMALADDITIONAL<fieldname>
    for a in additional.get_field_definitions(dbo, linktype):
        v = gks(row, csvkey + str(a["FIELDNAME"]).upper())
        if v != "":
            sql = db.make_insert_sql("additional",
                                     (("LinkType", db.di(a["LINKTYPE"])),
                                      ("LinkID", db.di(int(linkid))),
                                      ("AdditionalFieldID", db.di(a["ID"])),
                                      ("Value", db.ds(v))))
            try:
                db.execute(dbo, sql)
            except Exception, e:
                errors.append((rowno, str(row), str(e)))
Example #40
0
def insert_field_from_form(dbo, username, post):
    """
    Creates an additional field
    """
    nid = db.get_id(dbo, "additionalfield")
    sql = db.make_insert_sql("additionalfield", ( 
        ( "ID", db.di(nid)),
        ( "FieldName", post.db_string("name")),
        ( "FieldLabel", post.db_string("label")),
        ( "ToolTip", post.db_string("tooltip")),
        ( "LookupValues", post.db_string("lookupvalues")),
        ( "DefaultValue", post.db_string("defaultvalue")),
        ( "Mandatory", post.db_boolean("mandatory")),
        ( "Searchable", post.db_boolean("searchable")),
        ( "FieldType", post.db_integer("type")),
        ( "LinkType", post.db_integer("link")),
        ( "DisplayIndex", post.db_integer("displayindex"))
        ))
    db.execute(dbo, sql)
    audit.create(dbo, username, "additionalfield", nid, audit.dump_row(dbo, "additionalfield", nid))
    return nid
Example #41
0
File: media.py Project: magul/asm3
def create_document_media(dbo, username, linktype, linkid, template, content):
    """
    Creates a new media record for a document for the link given.
    linktype: ANIMAL, PERSON, etc
    linkid: ID for the link
    template: The name of the template used to create the document
    content: The document contents
    """
    mediaid = db.get_id(dbo, "media")
    sql = db.make_insert_sql("media", (
        ( "ID", db.di(mediaid) ),
        ( "MediaName", db.ds("%d.html" % mediaid) ),
        ( "MediaType", db.di(0)),
        ( "MediaNotes", db.ds(template) ),
        ( "WebsitePhoto", db.di(0) ),
        ( "WebsiteVideo", db.di(0) ),
        ( "DocPhoto", db.di(0) ),
        ( "ExcludeFromPublish", db.di(0) ),
        # ASM2_COMPATIBILITY
        ( "NewSinceLastPublish", db.di(1) ),
        ( "UpdatedSinceLastPublish", db.di(0) ),
        # ASM2_COMPATIBILITY
        ( "LinkID", db.di(linkid) ),
        ( "LinkTypeID", db.di(linktype) ),
        ( "Date", db.nowsql() )
        ))
    db.execute(dbo, sql)
    path = ""
    if linktype == ANIMAL:
        path = "/animal"
    elif linktype == PERSON:
        path = "/owner"
    elif linktype == LOSTANIMAL:
        path = "/lostanimal"
    elif linktype == FOUNDANIMAL:
        path = "/foundanimal"
    path += "/" + str(linkid)
    name = str(mediaid) + ".html"
    dbfs.put_string(dbo, name, path, content)
    audit.create(dbo, username, "media", mediaid, str(mediaid) + ": for " + str(linkid) + "/" + str(linktype))
Example #42
0
def create_blank_document_media(dbo, username, linktype, linkid):
    """
    Creates a new media record for a blank document for the link given.
    linktype: ANIMAL, PERSON, etc
    linkid: ID for the link
    returns the new media id
    """
    mediaid = db.get_id(dbo, "media")
    sql = db.make_insert_sql("media", (
        ( "ID", db.di(mediaid) ),
        ( "MediaName", db.ds("%d.html" % mediaid) ),
        ( "MediaType", db.di(0)),
        ( "MediaNotes", db.ds("New document") ),
        ( "WebsitePhoto", db.di(0) ),
        ( "WebsiteVideo", db.di(0) ),
        ( "DocPhoto", db.di(0) ),
        ( "ExcludeFromPublish", db.di(0) ),
        ( "NewSinceLastPublish", db.di(1) ),
        ( "UpdatedSinceLastPublish", db.di(0) ),
        ( "LinkID", db.di(linkid) ),
        ( "LinkTypeID", db.di(linktype) ),
        ( "Date", db.nowsql() )
        ))
    db.execute(dbo, sql)
    path = ""
    if linktype == ANIMAL:
        path = "/animal"
    elif linktype == PERSON:
        path = "/owner"
    elif linktype == LOSTANIMAL:
        path = "/lostanimal"
    elif linktype == FOUNDANIMAL:
        path = "/foundanimal"
    path += "/" + str(linkid)
    name = str(mediaid) + ".html"
    dbfs.put_string(dbo, name, path, "")
    audit.create(dbo, username, "media", str(mediaid) + ": for " + str(linkid) + "/" + str(linktype))
    return mediaid
Example #43
0
def attach_link_from_form(dbo, username, linktype, linkid, post):
    """
    Attaches a link to a web resource from a form
    """
    existingvid = db.query_int(dbo, "SELECT COUNT(*) FROM media WHERE WebsiteVideo = 1 " \
        "AND LinkID = %d AND LinkTypeID = %d" % ( int(linkid), int(linktype) ))
    defvid = 0
    if existingvid == 0 and post.integer("linktype") == MEDIATYPE_VIDEO_LINK:
        defvid = 1
    mediaid = db.get_id(dbo, "media")
    url = post["linktarget"]
    if url.find("://") == -1:
        url = "http://" + url
    al.debug("attached link %s" % url, "media.attach_file_from_form")
    sql = db.make_insert_sql(
        "media",
        (
            ("ID", db.di(mediaid)),
            ("MediaName", db.ds(url)),
            ("MediaType", post.db_integer("linktype")),
            ("MediaNotes", post.db_string("comments")),
            ("WebsitePhoto", db.di(0)),
            ("WebsiteVideo", db.di(defvid)),
            ("DocPhoto", db.di(0)),
            ("ExcludeFromPublish", db.di(0)),
            # ASM2_COMPATIBILITY
            ("NewSinceLastPublish", db.di(1)),
            ("UpdatedSinceLastPublish", db.di(0)),
            # ASM2_COMPATIBILITY
            ("LinkID", db.di(linkid)),
            ("LinkTypeID", db.di(linktype)),
            ("Date", db.nowsql())))
    db.execute(dbo, sql)
    audit.create(
        dbo, username, "media",
        str(mediaid) + ": for " + str(linkid) + "/" + str(linktype) +
        ": link to " + post["linktarget"])
Example #44
0
def attach_file_from_form(dbo, username, linktype, linkid, post):
    """
    Attaches a media file from the posted form
    data is the web.py data object and should contain
    comments, the filechooser object, with filename and value 
    props - OR a parameter called base64image containing a base64
    encoded jpg image.
    """
    ext = ""
    base64data = ""
    base64image = post["base64image"]
    if base64image != "":
        ext = ".jpg"
        # If an HTML5 data url was used, strip the prefix so we just have base64 data
        if base64image.find("data:") != -1:
            base64data = base64image[base64image.find(",") + 1:]
            # Browser escaping turns base64 pluses back into spaces, so switch back
            base64data = base64data.replace(" ", "+")
        else:
            base64data = base64image
        al.debug(
            "received HTML5 base64 image data (%d bytes)" % (len(base64image)),
            "media.attach_file_from_form", dbo)
    else:
        ext = post.filename()
        ext = ext[ext.rfind("."):].lower()
    mediaid = db.get_id(dbo, "media")
    medianame = "%d%s" % (mediaid, ext)
    ispicture = ext == ".jpg" or ext == ".jpeg"
    ispdf = ext == ".pdf"

    # Does this link have anything with web/doc set? If not, set the
    # web/doc flags
    web = 0
    doc = 0
    existing_web = db.query_int(dbo, "SELECT COUNT(*) FROM media WHERE WebsitePhoto = 1 " \
        "AND LinkID = %d AND LinkTypeID = %d" % ( int(linkid), int(linktype) ))
    existing_doc = db.query_int(dbo, "SELECT COUNT(*) FROM media WHERE DocPhoto = 1 " \
        "AND LinkID = %d AND LinkTypeID = %d" % ( int(linkid), int(linktype) ))
    if existing_web == 0 and ispicture:
        web = 1
    if existing_doc == 0 and ispicture:
        doc = 1

    if base64image != "":
        filedata = base64.b64decode(base64data)
    else:
        filedata = post.filedata()
        al.debug(
            "received POST file data '%s' (%d bytes)" %
            (post.filename(), len(filedata)), "media.attach_file_from_form",
            dbo)

    # Is it a picture?
    if ispicture:
        # Autorotate it to match the EXIF orientation
        filedata = auto_rotate_image(dbo, filedata)
        # Scale it down to the system set size
        scalespec = configuration.incoming_media_scaling(dbo)
        if scalespec != "None":
            filedata = scale_image(filedata, scalespec)
            al.debug(
                "scaled image to %s (%d bytes)" % (scalespec, len(filedata)),
                "media.attach_file_from_form", dbo)

    # Is it a PDF? If so, compress it if we can and the option is on
    if ispdf and SCALE_PDF_DURING_ATTACH and configuration.scale_pdfs(dbo):
        filedata = scale_pdf(filedata)
        medianame = "%d_scaled.pdf" % mediaid
        al.debug("compressed PDF (%d bytes)" % (len(filedata)),
                 "media.attach_file_from_form", dbo)

    # Attach the file in the dbfs
    path = get_dbfs_path(linkid, linktype)
    dbfs.put_string(dbo, medianame, path, filedata)

    # Are the notes for an image blank and we're defaulting them from animal comments?
    comments = post["comments"]
    if comments == "" and ispicture and linktype == ANIMAL and configuration.auto_media_notes(
            dbo):
        comments = animal.get_comments(dbo, int(linkid))
        # Are the notes blank and we're defaulting them from the filename?
    elif comments == "" and configuration.default_media_notes_from_file(
            dbo) and base64image == "":
        comments = utils.filename_only(post.filename())

    # Create the media record
    sql = db.make_insert_sql(
        "media",
        (
            ("ID", db.di(mediaid)),
            ("MediaName", db.ds(medianame)),
            ("MediaType", db.di(0)),
            ("MediaNotes", db.ds(comments)),
            ("WebsitePhoto", db.di(web)),
            ("WebsiteVideo", db.di(0)),
            ("DocPhoto", db.di(doc)),
            ("ExcludeFromPublish", db.di(0)),
            # ASM2_COMPATIBILITY
            ("NewSinceLastPublish", db.di(1)),
            ("UpdatedSinceLastPublish", db.di(0)),
            # ASM2_COMPATIBILITY
            ("LinkID", db.di(linkid)),
            ("LinkTypeID", db.di(linktype)),
            ("Date", db.dd(i18n.now(dbo.timezone)))))
    db.execute(dbo, sql)
    audit.create(dbo, username, "media",
                 str(mediaid) + ": for " + str(linkid) + "/" + str(linktype))
Example #45
0
def attach_file_from_form(dbo, username, linktype, linkid, data):
    """
    Attaches a media file from the posted form
    data is the web.py data object and should contain
    comments, the filechooser object, with filename and value 
    props - OR a parameter called base64image containing a base64
    encoded jpg image.
    """
    ext = ""
    base64data = ""
    base64image = utils.df_ks(data, "base64image")
    if base64image != "":
        ext = ".jpg"
        # If an HTML5 data url was used, strip the prefix so we just have base64 data
        if base64image.find("data:") != -1:
            base64data = base64image[base64image.find(",")+1:]
            # Browser escaping turns base64 pluses back into spaces, so switch back
            base64data = base64data.replace(" ", "+")
        else:
            base64data = base64image
    else:
        ext = data.filechooser.filename
        ext = ext[ext.rfind("."):].lower()
    mediaid = db.get_id(dbo, "media")
    medianame = "%d%s" % ( mediaid, ext )
    ispicture = ext == ".jpg" or ext == ".jpeg"
    ispdf = ext == ".pdf"

    # Does this link have anything with web/doc set? If not, set the
    # web/doc flags
    web = 0
    doc = 0
    existing_web = db.query_int(dbo, "SELECT COUNT(*) FROM media WHERE WebsitePhoto = 1 " \
        "AND LinkID = %d AND LinkTypeID = %d" % ( int(linkid), int(linktype) ))
    existing_doc = db.query_int(dbo, "SELECT COUNT(*) FROM media WHERE DocPhoto = 1 " \
        "AND LinkID = %d AND LinkTypeID = %d" % ( int(linkid), int(linktype) ))
    if existing_web == 0 and ispicture:
        web = 1
    if existing_doc == 0 and ispicture:
        doc = 1

    if base64image != "":
        filedata = base64.b64decode(base64data)
    else:
        filedata = data.filechooser.value

    # Is it a picture?
    if ispicture:
        # Autorotate it to match the EXIF orientation
        filedata = auto_rotate_image(filedata)
        # Scale it down to the system set size
        scalespec = configuration.incoming_media_scaling(dbo)
        if scalespec != "None":
            filedata = scale_image(filedata, scalespec)

    # Is it a PDF? If so, compress it if we can and the option is on
    if ispdf and gs_installed() and SCALE_PDF:
        filedata = scale_pdf(filedata)
        medianame = "%d_scaled.pdf" % mediaid

    # Attach the file in the dbfs
    path = get_dbfs_path(linkid, linktype)
    dbfs.put_string(dbo, medianame, path, filedata)

    # Are the notes for an image blank and we're defaulting them from animal comments?
    comments = utils.df_ks(data, "comments")
    if comments == "" and ispicture and linktype == ANIMAL and configuration.auto_media_notes(dbo):
        comments = animal.get_comments(dbo, int(linkid))
        # Are the notes blank and we're defaulting them from the filename?
    elif comments == "" and configuration.default_media_notes_from_file(dbo) and base64image == "":
        comments = utils.filename_only(data.filechooser.filename)
    
    # Create the media record
    sql = db.make_insert_sql("media", (
        ( "ID", db.di(mediaid) ),
        ( "MediaName", db.ds(medianame) ),
        ( "MediaType", db.di(0) ),
        ( "MediaNotes", db.ds(comments) ),
        ( "WebsitePhoto", db.di(web) ),
        ( "WebsiteVideo", db.di(0) ),
        ( "DocPhoto", db.di(doc) ),
        ( "ExcludeFromPublish", db.di(0) ),
        ( "NewSinceLastPublish", db.di(1) ),
        ( "UpdatedSinceLastPublish", db.di(0) ),
        ( "LinkID", db.di(linkid) ),
        ( "LinkTypeID", db.di(linktype) ),
        ( "Date", db.nowsql() )
        ))
    db.execute(dbo, sql)
    audit.create(dbo, username, "media", str(mediaid) + ": for " + str(linkid) + "/" + str(linktype))
Example #46
0
File: media.py Project: magul/asm3
def attach_file_from_form(dbo, username, linktype, linkid, post):
    """
    Attaches a media file from the posted form
    data is the web.py data object and should contain
    comments and either the filechooser object, with filename and value 
    OR filedata, filetype and filename parameters (filetype is the MIME type, filedata is base64 encoded contents)
    """
    ext = ""
    filedata = post["filedata"]
    filename = post["filename"]
    comments = post["comments"]
    checkpref = True
    if filedata != "":
        checkpref = False
        filetype = post["filetype"]
        if filetype.startswith("image"): ext = ".jpg"
        elif filetype.find("pdf") != -1: ext = ".pdf"
        elif filetype.find("html") != -1: ext = ".html"
        # Strip the data:mime prefix so we just have base64 data
        if filedata.startswith("data:"):
            filedata = filedata[filedata.find(",")+1:]
            # Browser escaping turns base64 pluses back into spaces, so switch back
            filedata = filedata.replace(" ", "+")
        filedata = base64.b64decode(filedata)
        al.debug("received HTML5 file data '%s' (%d bytes)" % (filename, len(filedata)), "media.attach_file_from_form", dbo)
    else:
        # It's a traditional form post with a filechooser, we should make
        # it the default web/doc picture after posting if none is available.
        checkpref = True
        ext = post.filename()
        ext = ext[ext.rfind("."):].lower()
        filedata = post.filedata()
        filename = post.filename()
        al.debug("received POST file data '%s' (%d bytes)" % (filename, len(filedata)), "media.attach_file_from_form", dbo)

    mediaid = db.get_id(dbo, "media")
    medianame = "%d%s" % ( mediaid, ext )
    ispicture = ext == ".jpg" or ext == ".jpeg"
    ispdf = ext == ".pdf"

    # Is it a picture?
    if ispicture:
        # Autorotate it to match the EXIF orientation
        filedata = auto_rotate_image(dbo, filedata)
        # Scale it down to the system set size
        scalespec = configuration.incoming_media_scaling(dbo)
        if scalespec != "None":
            filedata = scale_image(filedata, scalespec)
            al.debug("scaled image to %s (%d bytes)" % (scalespec, len(filedata)), "media.attach_file_from_form", dbo)

    # Is it a PDF? If so, compress it if we can and the option is on
    if ispdf and SCALE_PDF_DURING_ATTACH and configuration.scale_pdfs(dbo):
        filedata = scale_pdf(filedata)
        medianame = "%d_scaled.pdf" % mediaid
        al.debug("compressed PDF (%d bytes)" % (len(filedata)), "media.attach_file_from_form", dbo)

    # Attach the file in the dbfs
    path = get_dbfs_path(linkid, linktype)
    dbfs.put_string(dbo, medianame, path, filedata)

    # Are the notes for an image blank and we're defaulting them from animal comments?
    if comments == "" and ispicture and linktype == ANIMAL and configuration.auto_media_notes(dbo):
        comments = animal.get_comments(dbo, int(linkid))
        # Are the notes blank and we're defaulting them from the filename?
    elif comments == "" and configuration.default_media_notes_from_file(dbo):
        comments = utils.filename_only(filename)
    
    # Create the media record
    sql = db.make_insert_sql("media", (
        ( "ID", db.di(mediaid) ),
        ( "MediaName", db.ds(medianame) ),
        ( "MediaType", db.di(0) ),
        ( "MediaNotes", db.ds(comments) ),
        ( "WebsitePhoto", db.di(0) ),
        ( "WebsiteVideo", db.di(0) ),
        ( "DocPhoto", db.di(0) ),
        ( "ExcludeFromPublish", db.di(0) ),
        # ASM2_COMPATIBILITY
        ( "NewSinceLastPublish", db.di(1) ),
        ( "UpdatedSinceLastPublish", db.di(0) ),
        # ASM2_COMPATIBILITY
        ( "LinkID", db.di(linkid) ),
        ( "LinkTypeID", db.di(linktype) ),
        ( "Date", db.dd(i18n.now(dbo.timezone)))
        ))
    db.execute(dbo, sql)
    audit.create(dbo, username, "media", mediaid, str(mediaid) + ": for " + str(linkid) + "/" + str(linktype))

    if ispicture and checkpref:
        check_default_web_doc_pic(dbo, mediaid, linkid, linktype)