Пример #1
0
    def executeFormsPage(self):
        """
        Generates and uploads the page of online forms
        """
        self.log("Generating online forms page...")

        thisPageName = "forms.%s" % self.pc.extension
        thisPage = ""

        try:
            forms = onlineform.get_onlineforms(self.dbo)
            thisPage = "<html><head><title>Online Forms</title></head><body>"
            thisPage += "<h2>Online Forms</h2>"
            account = ""
            if smcom.active():
                account = "account=%s&" % self.dbo.database
            for f in forms:
                thisPage += "<p><a target='_blank' href='%s?%smethod=online_form_html&formid=%d'>%s</a></p>" % (
                    SERVICE_URL, account, f["ID"], f["NAME"])
            thisPage += "</body></html>"
        except Exception as err:
            self.setLastError("Error creating forms page: %s" % err)
            self.logError("Error creating forms page: %s" % err,
                          sys.exc_info())
            return

        # Flush and upload the page
        self.log("Saving page to disk: %s (%d bytes)" %
                 (thisPageName, len(thisPage)))
        self.saveFile(os.path.join(self.publishDir, thisPageName), thisPage)
        self.log("Saved page to disk: %s" % thisPageName)
        if self.pc.uploadDirectly:
            self.log("Uploading page: %s" % thisPageName)
            self.upload(thisPageName)
            self.log("Uploaded page: %s" % thisPageName)
Пример #2
0
def switch_storage(dbo):
    """ Goes through all files in dbfs and swaps them into the current storage scheme """
    rows = dbo.query(
        "SELECT ID, Name, Path, URL FROM dbfs WHERE Name LIKE '%.%' ORDER BY ID"
    )
    for i, r in enumerate(rows):
        al.debug(
            "Storage transfer %s/%s (%d of %d)" %
            (r.path, r.name, i, len(rows)), "dbfs.switch_storage", dbo)
        source = DBFSStorage(dbo, r.url)
        target = DBFSStorage(dbo)
        # Don't bother if the file is already stored in the target format
        if source.url_prefix() == target.url_prefix():
            al.debug("source is already %s, skipping" % source.url_prefix(),
                     "dbfs.switch_storage", dbo)
            continue
        try:
            filedata = source.get(r.id, r.url)
            target.put(r.id, r.name, filedata)
            # Update the media size while we're switching in case it wasn't set previously
            dbo.execute("UPDATE media SET MediaSize=? WHERE DBFSID=?",
                        (len(filedata), r.id))
        except Exception as err:
            al.error("Error reading, skipping: %s" % str(err),
                     "dbfs.switch_storage", dbo)
    # smcom only - perform postgresql full vacuum after switching
    if smcom.active(): smcom.vacuum_full(dbo)
Пример #3
0
def page_login(l):
    accountline = ""
    accounttext = _("Database", l)
    if smcom.active(): accounttext = _("SM Account", l)
    if MULTIPLE_DATABASES:
        accountline = "<div data-role='fieldcontain'><label for='database'>%s</label><input type='text' id='database' name='database' /></div>" % accounttext
    return header(l) + """
        <div data-role='page' id='login'>
        <div data-role='header'>
        <h1>%s</h1>
        </div>
        <div data-role='content'>
        <form id="loginform" action="mobile_login" target="_self" method="post">
        <h2>%s</h2>
        %s
        <div data-role="fieldcontain">
            <label for="username">%s</label>
            <input type="text" id="username" name="username" />
        </div>
        <div data-role="fieldcontain">
            <label for="password">%s</label>
            <input type="password" id="password" name="password" />
        </div>
        <button type="submit">%s</button>
        </form>
        </div>
        </div>
        </body>
        </html>
    """ % (_("Login", l), _("Login", l), accountline, _(
        "Username", l), _("Password", l), _("Login", l))
Пример #4
0
def animals_to_page(dbo,
                    animals,
                    style="",
                    speciesid=0,
                    animaltypeid=0,
                    locationid=0):
    """ Returns a page of animals.
    animals: A resultset containing animal records
    style: The HTML publishing template to use
    speciesid: 0 for all species, or a specific one
    animaltypeid: 0 for all animal types or a specific one
    locationid: 0 for all internal locations or a specific one
    """
    # Get the specified template
    head, body, foot = template.get_html_template(dbo, style)
    if head == "":
        head, body, foot = get_animal_view_template(dbo)
    # Substitute the header and footer tags
    org_tags = wordprocessor.org_tags(dbo, "system")
    head = wordprocessor.substitute_tags(head, org_tags, True, "$$", "$$")
    foot = wordprocessor.substitute_tags(foot, org_tags, True, "$$", "$$")
    # Run through each animal and generate body sections
    bodies = []
    for a in animals:
        if speciesid > 0 and a.SPECIESID != speciesid: continue
        if animaltypeid > 0 and a.ANIMALTYPEID != animaltypeid: continue
        if locationid > 0 and a.SHELTERLOCATION != locationid: continue
        # Translate website media name to the service call for images
        if smcom.active():
            a.WEBSITEMEDIANAME = "%s?account=%s&method=animal_image&animalid=%d" % (
                SERVICE_URL, dbo.database, a.ID)
        else:
            a.WEBSITEMEDIANAME = "%s?method=animal_image&animalid=%d" % (
                SERVICE_URL, a.ID)
        # Generate tags for this row
        tags = wordprocessor.animal_tags_publisher(dbo, a)
        tags = wordprocessor.append_tags(tags, org_tags)
        # Add extra tags for websitemedianame2-4 if they exist
        if a.WEBSITEIMAGECOUNT > 1:
            tags["WEBMEDIAFILENAME2"] = "%s&seq=2" % a.WEBSITEMEDIANAME
        if a.WEBSITEIMAGECOUNT > 2:
            tags["WEBMEDIAFILENAME3"] = "%s&seq=3" % a.WEBSITEMEDIANAME
        if a.WEBSITEIMAGECOUNT > 3:
            tags["WEBMEDIAFILENAME4"] = "%s&seq=4" % a.WEBSITEMEDIANAME
        # Set the description
        if configuration.publisher_use_comments(dbo):
            a.WEBSITEMEDIANOTES = a.ANIMALCOMMENTS
        # Add extra publishing text, preserving the line endings
        notes = utils.nulltostr(a.WEBSITEMEDIANOTES)
        notes += configuration.third_party_publisher_sig(dbo).replace(
            "\n", "<br/>")
        tags["WEBMEDIANOTES"] = notes
        bodies.append(
            wordprocessor.substitute_tags(body, tags, True, "$$", "$$"))
    return "%s\n%s\n%s" % (head, "\n".join(bodies), foot)
Пример #5
0
def publish_hlp(dbo):
    try :

        pc = publish.PublishCriteria(configuration.publisher_presets(dbo))
        publishers = configuration.publishers_enabled(dbo)
        if smcom.active():
            pc.ignoreLock = True

        if publishers.find("hlp") != -1:
            al.info("start helpinglostpets publisher", "cron.publish_hlp", dbo)
            pn = publish.HelpingLostPetsPublisher(dbo, pc)
            pn.run()
            al.info("end helpinglostpets publisher", "cron.publish_hlp", dbo)

    except:
        em = str(sys.exc_info()[0])
        al.error("FAIL: uncaught error running helpinglostpets publisher: %s" % em, "cron.publish_hlp", dbo, sys.exc_info())
Пример #6
0
Файл: cron.py Проект: magul/asm3
def publish_fa(dbo):
    try :

        pc = publish.PublishCriteria(configuration.publisher_presets(dbo))
        publishers = configuration.publishers_enabled(dbo)
        if smcom.active():
            pc.ignoreLock = True

        if publishers.find("fa") != -1:
            al.info("start foundanimals publisher", "cron.publish_fa", dbo)
            ap = publish.FoundAnimalsPublisher(dbo, pc)
            ap.run()
            al.info("end foundanimals publisher", "cron.publish_fa", dbo)

    except:
        em = str(sys.exc_info()[0])
        al.error("FAIL: uncaught error running foundanimals publisher: %s" % em, "cron.publish_fa", dbo, sys.exc_info())
Пример #7
0
def publish_pl(dbo):
    try :

        pc = publish.PublishCriteria(configuration.publisher_presets(dbo))
        publishers = configuration.publishers_enabled(dbo)
        if smcom.active():
            pc.ignoreLock = True

        if publishers.find("pl") != -1:
            al.info("start petlink publisher", "cron.publish_pl", dbo)
            pn = publish.PetLinkPublisher(dbo, pc)
            pn.run()
            al.info("end petlink publisher", "cron.publish_pl", dbo)

    except:
        em = str(sys.exc_info()[0])
        al.error("FAIL: uncaught error running petlink publisher: %s" % em, "cron.publish_pl", dbo, sys.exc_info())
Пример #8
0
def publish_rg(dbo):
    try :

        pc = publish.PublishCriteria(configuration.publisher_presets(dbo))
        publishers = configuration.publishers_enabled(dbo)
        if smcom.active():
            pc.ignoreLock = True

        if publishers.find("rg") != -1:
            al.info("start rescuegroups publisher", "cron.publish_rg", dbo)
            rg = publish.RescueGroupsPublisher(dbo, pc)
            rg.run()
            al.info("end rescuegroups publisher", "cron.publish_rg", dbo)

    except:
        em = str(sys.exc_info()[0])
        al.error("FAIL: uncaught error running rescuegroups publisher: %s" % em, "cron.publish_rg", dbo, sys.exc_info())
Пример #9
0
Файл: cron.py Проект: magul/asm3
def publish_veha(dbo):
    try :

        pc = publish.PublishCriteria(configuration.publisher_presets(dbo))
        publishers = configuration.publishers_enabled(dbo)
        if smcom.active():
            pc.ignoreLock = True

        if publishers.find("ve") != -1:
            al.info("start homeagain publisher", "cron.publish_veha", dbo)
            ap = publish.HomeAgainPublisher(dbo, pc)
            ap.run()
            al.info("end homeagain publisher", "cron.publish_veha", dbo)

    except:
        em = str(sys.exc_info()[0])
        al.error("FAIL: uncaught error running homeagain publisher: %s" % em, "cron.publish_veha", dbo, sys.exc_info())
Пример #10
0
Файл: cron.py Проект: magul/asm3
def publish_st(dbo):
    try :

        pc = publish.PublishCriteria(configuration.publisher_presets(dbo))
        publishers = configuration.publishers_enabled(dbo)
        if smcom.active():
            pc.ignoreLock = True

        if publishers.find("st") != -1:
            al.info("start smarttag publisher", "cron.publish_st", dbo)
            ap = publish.SmartTagPublisher(dbo, pc)
            ap.run()
            al.info("end smarttag publisher", "cron.publish_st", dbo)

    except:
        em = str(sys.exc_info()[0])
        al.error("FAIL: uncaught error running smarttag publisher: %s" % em, "cron.publish_st", dbo, sys.exc_info())
Пример #11
0
Файл: cron.py Проект: magul/asm3
def publish_ptuk(dbo):
    try :

        pc = publish.PublishCriteria(configuration.publisher_presets(dbo))
        publishers = configuration.publishers_enabled(dbo)
        if smcom.active():
            pc.ignoreLock = True

        if publishers.find("pt") != -1:
            al.info("start pettrac uk publisher", "cron.publish_ptuk", dbo)
            pn = publish.PETtracUKPublisher(dbo, pc)
            pn.run()
            al.info("end pettrac uk publisher", "cron.publish_ptuk", dbo)

    except:
        em = str(sys.exc_info()[0])
        al.error("FAIL: uncaught error running pettrac uk publisher: %s" % em, "cron.publish_ptuk", dbo, sys.exc_info())
Пример #12
0
Файл: cron.py Проект: magul/asm3
def publish_rg(dbo):
    try :

        pc = publish.PublishCriteria(configuration.publisher_presets(dbo))
        publishers = configuration.publishers_enabled(dbo)
        if smcom.active():
            pc.ignoreLock = True

        if publishers.find("rg") != -1:
            al.info("start rescuegroups publisher", "cron.publish_rg", dbo)
            rg = publish.RescueGroupsPublisher(dbo, pc)
            rg.run()
            al.info("end rescuegroups publisher", "cron.publish_rg", dbo)

    except:
        em = str(sys.exc_info()[0])
        al.error("FAIL: uncaught error running rescuegroups publisher: %s" % em, "cron.publish_rg", dbo, sys.exc_info())
Пример #13
0
Файл: cron.py Проект: magul/asm3
def publish_hlp(dbo):
    try :

        pc = publish.PublishCriteria(configuration.publisher_presets(dbo))
        publishers = configuration.publishers_enabled(dbo)
        if smcom.active():
            pc.ignoreLock = True

        if publishers.find("hlp") != -1:
            al.info("start helpinglostpets publisher", "cron.publish_hlp", dbo)
            pn = publish.HelpingLostPetsPublisher(dbo, pc)
            pn.run()
            al.info("end helpinglostpets publisher", "cron.publish_hlp", dbo)

    except:
        em = str(sys.exc_info()[0])
        al.error("FAIL: uncaught error running helpinglostpets publisher: %s" % em, "cron.publish_hlp", dbo, sys.exc_info())
Пример #14
0
Файл: cron.py Проект: magul/asm3
def publish_mp(dbo):
    try :

        pc = publish.PublishCriteria(configuration.publisher_presets(dbo))
        publishers = configuration.publishers_enabled(dbo)
        if smcom.active():
            pc.ignoreLock = True

        if publishers.find("mp") != -1:
            al.info("start meetapet publisher", "cron.publish_mp", dbo)
            mp = publish.MeetAPetPublisher(dbo, pc)
            mp.run()
            al.info("end meetapet publisher", "cron.publish_mp", dbo)

    except:
        em = str(sys.exc_info()[0])
        al.error("FAIL: uncaught error running meetapet publisher: %s" % em, "cron.publish_mp", dbo, sys.exc_info())
Пример #15
0
def publish_ap(dbo):
    try :

        pc = publish.PublishCriteria(configuration.publisher_presets(dbo))
        publishers = configuration.publishers_enabled(dbo)
        if smcom.active():
            pc.ignoreLock = True

        if publishers.find("ap") != -1:
            al.info("start adoptapet publisher", "cron.publish_ap", dbo)
            ap = publish.AdoptAPetPublisher(dbo, pc)
            ap.run()
            al.info("end adoptapet publisher", "cron.publish_ap", dbo)

    except:
        em = str(sys.exc_info()[0])
        al.error("FAIL: uncaught error running adoptapet publisher: %s" % em, "cron.publish_ap", dbo, sys.exc_info())
Пример #16
0
def publish_st(dbo):
    try :

        pc = publish.PublishCriteria(configuration.publisher_presets(dbo))
        publishers = configuration.publishers_enabled(dbo)
        if smcom.active():
            pc.ignoreLock = True

        if publishers.find("st") != -1:
            al.info("start smarttag publisher", "cron.publish_st", dbo)
            ap = publish.SmartTagPublisher(dbo, pc)
            ap.run()
            al.info("end smarttag publisher", "cron.publish_st", dbo)

    except:
        em = str(sys.exc_info()[0])
        al.error("FAIL: uncaught error running smarttag publisher: %s" % em, "cron.publish_st", dbo, sys.exc_info())
Пример #17
0
def publish_veha(dbo):
    try:

        pc = publish.PublishCriteria(configuration.publisher_presets(dbo))
        publishers = configuration.publishers_enabled(dbo)
        if smcom.active():
            pc.ignoreLock = True

        if publishers.find("ve") != -1:
            al.info("start homeagain publisher", "cron.publish_veha", dbo)
            ap = publish.HomeAgainPublisher(dbo, pc)
            ap.run()
            al.info("end homeagain publisher", "cron.publish_veha", dbo)

    except:
        em = str(sys.exc_info()[0])
        al.error("FAIL: uncaught error running homeagain publisher: %s" % em,
                 "cron.publish_veha", dbo, sys.exc_info())
Пример #18
0
def get_animal_view(dbo, animalid):
    """ Constructs the animal view page to the template. """
    a = dbo.first_row(
        get_animal_data(dbo,
                        animalid=animalid,
                        include_additional_fields=True,
                        strip_personal_data=True))
    # If the animal is not adoptable, bail out
    if a is None:
        raise utils.ASMPermissionError("animal is not adoptable (None)")
    if not is_animal_adoptable(dbo, a):
        raise utils.ASMPermissionError("animal is not adoptable (False)")
    # If the option is on, use animal comments as the notes
    if configuration.publisher_use_comments(dbo):
        a.WEBSITEMEDIANOTES = a.ANIMALCOMMENTS
    head, body, foot = get_animal_view_template(dbo)
    if head == "":
        head = "<!DOCTYPE html>\n<html>\n<head>\n<title>$$SHELTERCODE$$ - $$ANIMALNAME$$</title></head>\n<body>"
        body = "<h2>$$SHELTERCODE$$ - $$ANIMALNAME$$</h2><p><img src='$$WEBMEDIAFILENAME$$'/></p><p>$$WEBMEDIANOTES$$</p>"
        foot = "</body>\n</html>"
    if smcom.active():
        a.WEBSITEMEDIANAME = "%s?account=%s&method=animal_image&animalid=%d" % (
            SERVICE_URL, dbo.database, animalid)
    else:
        a.WEBSITEMEDIANAME = "%s?method=animal_image&animalid=%d" % (
            SERVICE_URL, animalid)
    s = head + body + foot
    tags = wordprocessor.animal_tags_publisher(dbo, a)
    tags = wordprocessor.append_tags(tags,
                                     wordprocessor.org_tags(dbo, "system"))
    # Add extra tags for websitemedianame2-10 if they exist
    for x in range(2, 11):
        if a.WEBSITEIMAGECOUNT > x - 1:
            tags["WEBMEDIAFILENAME%d" %
                 x] = "%s&seq=%d" % (a.WEBSITEMEDIANAME, x)
    # Add extra publishing text, preserving the line endings
    notes = utils.nulltostr(a.WEBSITEMEDIANOTES)
    notes += configuration.third_party_publisher_sig(dbo)
    notes = notes.replace("\n", "**le**")
    tags["WEBMEDIANOTES"] = notes
    tags["WEBSITEMEDIANOTES"] = notes
    s = wordprocessor.substitute_tags(s, tags, True, "$$", "$$")
    s = s.replace("**le**", "<br />")
    return s
Пример #19
0
def route(dbo, when, caller, post):
    """ 
    routes any extension calls. 
    when:    "before" or "after"
    method:  the calling method name - eg: insert_animal_from_form
    post:    any posted values sent to the caller so they can be
             passed to the plugin method.
    return value: True to continue or False to cancel whatever the 
             default behaviour is (only applies to before) -or 
             raise an exception.
    """
    target = when + "_" + caller
    method = globals().get(target)
    if method:
        return method(dbo, post)
    if smcom.active():
        return smcom.route_customer_extension(dbo, when, caller, post)
    else:
        return True
Пример #20
0
def page_login(l):
    accountline = ""
    accounttext = _("Database", l)
    if smcom.active():
        accounttext = _("SM Account", l)
    if MULTIPLE_DATABASES:
        accountline = (
            "<div data-role='fieldcontain'><label for='database'>%s</label><input type='text' id='database' name='database' /></div>"
            % accounttext
        )
    return (
        header(l)
        + """
        <div data-role='page' id='login'>
        <div data-role='header'>
        <h1>%s</h1>
        </div>
        <div data-role='content'>
        <form id="loginform" action="mobile_login" target="_self" method="post">
        <h2>%s</h2>
        %s
        <div data-role="fieldcontain">
            <label for="username">%s</label>
            <input type="text" id="username" name="username" />
        </div>
        <div data-role="fieldcontain">
            <label for="password">%s</label>
            <input type="password" id="password" name="password" />
        </div>
        <button type="submit">%s</button>
        </form>
        </div>
        </div>
        </body>
        </html>
    """
        % (_("Login", l), _("Login", l), accountline, _("Username", l), _("Password", l), _("Login", l))
    )
Пример #21
0
def web_login(post, session, remoteip, path):
    """
    Performs a login and sets up the user's session.
    Returns the username on successful login, or:
        FAIL        - problem with user/pass/account/ip
        DISABLED    - The database is disabled
        WRONGSERVER - The database is not on this server
    """
    dbo = db.DatabaseInfo()
    database = post["database"]
    username = post["username"]
    password = post["password"]
    mobileapp = post["mobile"] == "true"
    nologconnection = post["nologconnection"]
    if len(username) > 100:
        username = username[0:100]
    # Do we have multiple databases?
    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.
            # If a database hasn't been supplied, let's bail out now
            # since we can't do anything
            if str(database).strip() == "":
                return "FAIL"
            else:
                dbo = smcom.get_database_info(database)
                # Bail out if there was a problem with the database
                if dbo.database in ("FAIL", "DISABLED", "WRONGSERVER"):
                    return dbo.database
        else:
            # Look up the database info from our map
            dbo  = db.get_multiple_database_info(database)
            if dbo.database == "FAIL":
                return dbo.database
    # Connect to the database and authenticate the username and password
    user = authenticate(dbo, username, password)
    if user is not None and not authenticate_ip(user, remoteip):
        al.error("user %s with ip %s failed ip restriction check '%s'" % (username, remoteip, user["IPRESTRICTION"]), "users.web_login", dbo)
        return "FAIL"
    if user is not None:
        al.info("%s successfully authenticated from %s" % (username, remoteip), "users.web_login", dbo)
        try:
            dbo.locked = configuration.smdb_locked(dbo)
            dbo.timezone = configuration.timezone(dbo)
            dbo.installpath = path
            session.locale = configuration.locale(dbo)
            dbo.locale = session.locale
            session.dbo = dbo
            session.user = user["USERNAME"]
            session.superuser = user["SUPERUSER"]
            session.passchange = (password == "password")
            session.mobileapp = mobileapp
            update_session(session)
        except:
            al.error("failed setting up session: %s" % str(sys.exc_info()[0]), "users.web_login", dbo, sys.exc_info())
            return "FAIL"
        try:
            session.securitymap = get_security_map(dbo, user["USERNAME"])
        except:
            # This is a pre-3002 login where the securitymap is with 
            # the user (the error occurs because there's no role table)
            al.debug("role table does not exist, using securitymap from user", "users.web_login", dbo)
            session.securitymap = user["SECURITYMAP"]
        try:
            ur = get_users(dbo, user["USERNAME"])[0]
            session.roles = ur["ROLES"]
            session.roleids = ur["ROLEIDS"]
            session.siteid = utils.cint(user["SITEID"])
            session.locationfilter = utils.nulltostr(user["LOCATIONFILTER"])
        except:
            # Users coming from v2 won't have the
            # IPRestriction or EmailAddress fields necessary for get_users - we can't
            # help them right now so just give them an empty set of
            # roles and locationfilter until they login again after the db update
            session.roles = ""
            session.roleids = ""
            session.locationfilter = ""
            session.siteid = 0
        try:
            # If it's a sheltermanager.com database, try and update the
            # last time the user connected to today
            if smcom.active() and database != "" and nologconnection == "":
                smcom.set_last_connected(dbo)
        except:
            pass
        try:
            # Mark the user logged in
            audit.login(dbo, username)
            # Check to see if any updates need performing on this database
            if dbupdate.check_for_updates(dbo):
                dbupdate.perform_updates(dbo)
                # We did some updates, better reload just in case config/reports/etc changed
                update_session(session)
            # Check to see if our views and sequences are out of date and need reloading
            if dbupdate.check_for_view_seq_changes(dbo):
                dbupdate.install_db_views(dbo)
                dbupdate.install_db_sequences(dbo)
        except:
            al.error("failed updating database: %s" % str(sys.exc_info()[0]), "users.web_login", dbo, sys.exc_info())
        try:
            al.info("%s logged in" % user["USERNAME"], "users.login", dbo)
            update_user_activity(dbo, user["USERNAME"])
        except:
            al.error("failed updating user activity: %s" % str(sys.exc_info()[0]), "users.web_login", dbo, sys.exc_info())
            return "FAIL"
    else:
        al.error("database:%s username:%s password:%s failed authentication from %s" % (database, username, password, remoteip), "users.web_login", dbo)
        return "FAIL"

    return user["USERNAME"]
Пример #22
0
def web_login(post, session, remoteip, path):
    """
    Performs a login and sets up the user's session.
    Returns the username on successful login, or:
        FAIL     - problem with user/pass/account/ip
        DISABLED - The database is disabled
    """
    dbo = db.DatabaseInfo()
    database = post["database"]
    username = post["username"]
    password = post["password"]
    nologconnection = post["nologconnection"]
    # Do we have multiple databases?
    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.
            # If a database hasn't been supplied, let's bail out now
            # since we can't do anything
            if str(database).strip() == "":
                return "FAIL"
            else:
                dbo = smcom.get_database_info(database)
                # Bail out if there was a problem with the database
                if dbo.database == "FAIL" or dbo.database == "DISABLED":
                    return dbo.database
        else:
            # Look up the database info from our map
            dbo = db.get_multiple_database_info(database)
            if dbo.database == "FAIL":
                return dbo.database
    # Connect to the database and authenticate the username and password
    user = authenticate(dbo, username, password)
    if user is not None and not authenticate_ip(user, remoteip):
        al.error(
            "user %s with ip %s failed ip restriction check '%s'" %
            (username, remoteip, user["IPRESTRICTION"]), "users.web_login",
            dbo)
        return "FAIL"
    if user is not None:
        al.info("%s successfully authenticated from %s" % (username, remoteip),
                "users.web_login", dbo)
        try:
            dbo.locked = configuration.smdb_locked(dbo)
            dbo.timezone = configuration.timezone(dbo)
            dbo.installpath = path
            session.locale = configuration.locale(dbo)
            dbo.locale = session.locale
            session.dbo = dbo
            session.user = user["USERNAME"]
            session.superuser = user["SUPERUSER"]
            session.passchange = (password == "password")
            update_session(session)
        except:
            al.error("failed setting up session: %s" % str(sys.exc_info()[0]),
                     "users.web_login", dbo, sys.exc_info())
            return "FAIL"
        try:
            session.securitymap = get_security_map(dbo, user["USERNAME"])
        except:
            # This is a pre-3002 login where the securitymap is with
            # the user (the error occurs because there's no role table)
            al.debug("role table does not exist, using securitymap from user",
                     "users.web_login", dbo)
            session.securitymap = user["SECURITYMAP"]
        try:
            ur = get_users(dbo, user["USERNAME"])[0]
            session.roles = ur["ROLES"]
            session.roleids = ur["ROLEIDS"]
            session.locationfilter = utils.nulltostr(user["LOCATIONFILTER"])
        except:
            # Users coming from v2 won't have the
            # IPRestriction or EmailAddress fields necessary for get_users - we can't
            # help them right now so just give them an empty set of
            # roles and locationfilter until they login again after the db update
            session.roles = ""
            session.roleids = ""
            session.locationfilter = ""
        try:
            # If it's a sheltermanager.com database, try and update the
            # last time the user connected to today
            if smcom.active() and database != "" and nologconnection == "":
                smcom.set_last_connected(dbo)
        except:
            pass
        try:
            # Check to see if any updates need performing on this database
            if dbupdate.check_for_updates(dbo):
                dbupdate.perform_updates(dbo)
                # We did some updates, better reload just in case config/reports/etc changed
                update_session(session)
            # Check to see if our views and sequences are out of date and need reloading
            if dbupdate.check_for_view_seq_changes(dbo):
                dbupdate.install_db_views(dbo)
                dbupdate.install_db_sequences(dbo)
        except:
            al.error("failed updating database: %s" % str(sys.exc_info()[0]),
                     "users.web_login", dbo, sys.exc_info())
        try:
            # Log out any old users that have been hanging around
            auto_logout(dbo)
            # Let this user through
            login(dbo, user["USERNAME"])
        except:
            al.error(
                "failed updating activeuser table: %s" %
                str(sys.exc_info()[0]), "users.web_login", dbo, sys.exc_info())
            return "FAIL"
    else:
        al.error(
            "database:%s username:%s password:%s failed authentication from %s"
            % (database, username, password, remoteip), "users.web_login", dbo)
        return "FAIL"

    return user["USERNAME"]