Пример #1
0
def removeSpawn(spawnID, planets, userID, galaxy):
    markAll = 0
    try:
        conn = dbShared.ghConn()
        cursor = conn.cursor()
    except Exception:
        result = "Error: could not connect to database"

    if (cursor):
        if (planets == "all"):
            markAll = 1
            sqlStr = "UPDATE tResourcePlanet SET unavailable=NOW(), unavailableBy='" + userID + "' WHERE spawnID=" + str(
                spawnID) + ";"
        else:
            # try to look up planet by name if an ID was not provided
            if (planets.isdigit() != True):
                planets = dbShared.getPlanetID(planets)
            sqlStr = "UPDATE tResourcePlanet SET unavailable=NOW(), unavailableBy='" + userID + "' WHERE spawnID=" + str(
                spawnID) + " AND planetID=" + str(planets) + ";"

        # Only allow removal if user has positive reputation
        stats = dbShared.getUserStats(userID, galaxy).split(",")
        cursor.execute(
            "SELECT enteredBy, unavailable FROM tResources WHERE spawnID=%s;",
            [spawnID])
        row = cursor.fetchone()
        if int(
                stats[2]
        ) < ghShared.MIN_REP_VALS['REMOVE_RESOURCE'] and row[0] != userID:
            result = "Error: You must earn a little reputation on the site before you can remove resources.  Try adding or verifying some first. \r\n"
        elif row[1] != None:
            result = "Error: You cannot remove that resource because it is already removed."
        else:
            cursor.execute(sqlStr)

            # add cleanup event
            if not planets.isdigit():
                planets = 0
            dbShared.logEvent(
                "INSERT INTO tResourceEvents (galaxy, spawnID, userID, eventTime, eventType, planetID) VALUES ("
                + str(galaxy) + "," + str(spawnID) + ",'" + userID +
                "',NOW(),'r'," + str(planets) + ");", 'r', userID, galaxy,
                str(spawnID))
            result = "Spawn marked unavailable."
        cursor.close()
    else:
        result = "Error: Could not connect to database"
    conn.close()

    return result
Пример #2
0
percVals = percVals.replace("%","")

if galaxy == "":
	errorStr = "Error: No Galaxy Specified"
else:
	galaxyState = dbShared.galaxyState(galaxy)

if (resGroup != "any" and resGroup != ""):
	joinStr = joinStr + " INNER JOIN (SELECT resourceType FROM tResourceTypeGroup WHERE resourceGroup='" + resGroup + "' GROUP BY resourceType) rtgg ON rt1.resourceType = rtgg.resourceType"
if (resCategory != "any" and resCategory != ""):
	joinStr = joinStr + " INNER JOIN (SELECT resourceType FROM tResourceTypeGroup WHERE resourceGroup='" + resCategory + "' GROUP BY resourceType) rtgc ON rt1.resourceType = rtgc.resourceType"

criteriaStr = "tResources.galaxy=" + galaxy

if (planet == "" and planetName != ""):
	planet = dbShared.getPlanetID(planetName)
if (planet != "any" and planet != ""):
	joinStr = joinStr + " INNER JOIN tResourcePlanet ON tResources.spawnID = tResourcePlanet.spawnID"
	criteriaStr += " AND planetID=" + planet

if (resType != "any" and resType != ""):
	criteriaStr = criteriaStr + " AND tResources.resourceType='" + resType + "'"

if logged_state == 1:
	#for later when nonpublic waypoints in
	#wpCriteria = 'shareLevel=256 OR owner="' + currentUser + '" OR (shareLevel=64 AND owner IN (SELECT f1.friendID FROM tUserFriends f1 INNER JOIN tUserFriends f2 ON f1.userID=f2.friendID WHERE f1.userID="' + currentUser + '")) OR waypointID IN (SELECT uw.waypointID FROM tUserWaypoints uw WHERE unlocked IS NOT NULL AND uw.userID="' + currentUser + '")'
	wpCriteria = 'shareLevel=256'
	if favorite == "on":
		joinStr = joinStr + " INNER JOIN (SELECT itemID, favGroup, despawnAlert FROM tFavorites WHERE userID='" + currentUser + "' AND favType=1) favs ON tResources.spawnID = favs.itemID"
	else:
		joinStr = joinStr + ' LEFT JOIN (SELECT itemID, favGroup, despawnAlert FROM tFavorites WHERE userID="' + currentUser + '" AND favType=1) favs ON tResources.spawnID = favs.itemID'
            markAll = 0
            cursor.execute(
                'SELECT spawnID, resourceType, CR, CD, DR, FL, HR, MA, PE, OQ, SR, UT, ER, unavailable, enteredBy FROM tResources WHERE galaxy='
                + galaxy + ' AND spawnName="' + spawnName + '";')
            row = cursor.fetchone()

            if (row != None):
                spawnID = str(row[0])

            if (planets == "all"):
                markAll = 1
                sqlStr = "UPDATE tResourcePlanet SET unavailable=NOW(), unavailableBy='" + currentUser + "' WHERE spawnID=" + spawnID + ";"
            else:
                # try to look up planet by name if an ID was not provided
                if (planets.isdigit() != True):
                    planets = dbShared.getPlanetID(planets)
                sqlStr = "UPDATE tResourcePlanet SET unavailable=NOW(), unavailableBy='" + currentUser + "' WHERE spawnID=" + spawnID + " AND planetID=" + planets + ";"

            # Only allow removal if user has positive reputation
            stats = dbShared.getUserStats(currentUser, galaxy).split(",")
            if int(stats[2]) < ghShared.MIN_REP_VALS[
                    'REMOVE_RESOURCE'] and row[14] != currentUser:
                result = "Error: You must earn a little reputation on the site before you can remove resources.  Try adding or verifying some first. \r\n"
            elif row[13] != None:
                result = "Error: You cannot remove that resource because it is already removed."
            else:
                cursor.execute(sqlStr)

                # add cleanup event
                if not planets.isdigit():
                    planets = 0
Пример #4
0
if (resCategory != "any" and resCategory != ""):
	joinStr = joinStr + " INNER JOIN (SELECT resourceType FROM tResourceTypeGroup WHERE resourceGroup='" + resCategory + "' GROUP BY resourceType) rtgc ON rt1.resourceType = rtgc.resourceType"

if (unavailableDays != None and unavailableDays.isdigit()):
	if (unavailableDays == "0"):
		criteriaStr = "galaxy=" + galaxy + " AND unavailable IS NULL"
	else:
		if (resType != "any" and resType != "") or (resGroup != "any" and resGroup != ""):
			criteriaStr = "galaxy=" + galaxy + " AND (unavailable IS NULL OR DATEDIFF(NOW(),unavailable) <= " + unavailableDays + ")"
		else:
			errorStr = "You must select a resource type or group when searching for unavailable resources."
else:
	criteriaStr = "galaxy=" + galaxy + " AND unavailable IS NULL"

if (planet == "" and planetName != ""):
	planet = dbShared.getPlanetID(planetName)
if (planet != "any" and planet != ""):
	unPlanetStr = ",'"+planet+"'"
	criteriaStr = criteriaStr + " AND EXISTS (SELECT planetID FROM tResourcePlanet WHERE spawnID = tResources.spawnID AND planetID=" + planet + " AND unavailable IS NULL)"

if (resType != "any" and resType != ""):
	criteriaStr = criteriaStr + " AND tResources.resourceType='" + resType + "'"

if logged_state == 1:
	#for later when nonpublic waypoints in
	#wpCriteria = 'shareLevel=256 OR owner="' + currentUser + '" OR (shareLevel=64 AND owner IN (SELECT f1.friendID FROM tUserFriends f1 INNER JOIN tUserFriends f2 ON f1.userID=f2.friendID WHERE f1.userID="' + currentUser + '")) OR waypointID IN (SELECT uw.waypointID FROM tUserWaypoints uw WHERE unlocked IS NOT NULL AND uw.userID="' + currentUser + '")'
	wpCriteria = 'shareLevel=256'
	if favorite == "on":
		joinStr = joinStr + " INNER JOIN (SELECT itemID, favGroup FROM tFavorites WHERE userID='" + currentUser + "' AND favType=1) favs ON tResources.spawnID = favs.itemID"
	else:
		joinStr = joinStr + ' LEFT JOIN (SELECT itemID, favGroup FROM tFavorites WHERE userID="' + currentUser + '" AND favType=1) favs ON tResources.spawnID = favs.itemID'
Пример #5
0
def main():
	# Get current url
	try:
		url = os.environ['SCRIPT_NAME']
	except KeyError:
		url = ''

	form = cgi.FieldStorage()
	# Get Cookies
	useCookies = 1
	cookies = Cookie.SimpleCookie()
	try:
		cookies.load(os.environ['HTTP_COOKIE'])
	except KeyError:
		useCookies = 0

	if useCookies:
		try:
			currentUser = cookies['userID'].value
		except KeyError:
			currentUser = ''
		try:
			loginResult = cookies['loginAttempt'].value
		except KeyError:
			loginResult = 'success'
		try:
			sid = cookies['gh_sid'].value
		except KeyError:
			sid = form.getfirst('gh_sid', '')
	else:
		currentUser = ''
		loginResult = 'success'
		sid = form.getfirst('gh_sid', '')

	numRows = form.getfirst("numRows", "")
	# Get form info
	galaxy = form.getfirst("galaxy", "")
	planet = form.getfirst("planet", "")
	spawnID = form.getfirst("resID", "")
	spawnName = form.getfirst("resName", "")
	resType = form.getfirst("resType", "")
	forceOp = form.getfirst("forceOp", "")
	sourceRow = form.getfirst("sourceRow", "")
	CR = form.getfirst("CR", "")
	CD = form.getfirst("CD", "")
	DR = form.getfirst("DR", "")
	FL = form.getfirst("FL", "")
	HR = form.getfirst("HR", "")
	MA = form.getfirst("MA", "")
	PE = form.getfirst("PE", "")
	OQ = form.getfirst("OQ", "")
	SR = form.getfirst("SR", "")
	UT = form.getfirst("UT", "")
	ER = form.getfirst("ER", "")
	# escape input to prevent sql injection
	sid = dbShared.dbInsertSafe(sid)
	numRows = dbShared.dbInsertSafe(numRows)
	galaxy = dbShared.dbInsertSafe(galaxy)
	planet = dbShared.dbInsertSafe(planet)
	spawnID = dbShared.dbInsertSafe(spawnID)
	spawnName = dbShared.dbInsertSafe(spawnName)
	resType = dbShared.dbInsertSafe(resType)
	forceOp = dbShared.dbInsertSafe(forceOp)
	sourceRow = dbShared.dbInsertSafe(sourceRow)
	CR = dbShared.dbInsertSafe(CR)
	CD = dbShared.dbInsertSafe(CD)
	DR = dbShared.dbInsertSafe(DR)
	FL = dbShared.dbInsertSafe(FL)
	HR = dbShared.dbInsertSafe(HR)
	MA = dbShared.dbInsertSafe(MA)
	PE = dbShared.dbInsertSafe(PE)
	OQ = dbShared.dbInsertSafe(OQ)
	SR = dbShared.dbInsertSafe(SR)
	UT = dbShared.dbInsertSafe(UT)
	ER = dbShared.dbInsertSafe(ER)

	spawnName = spawnName.lower()

	# Get a session
	logged_state = 0

	sess = dbSession.getSession(sid)
	if (sess != ''):
		logged_state = 1
		currentUser = sess

	#  Check for errors
	errstr = ""
	if (len(spawnName) < 1 and spawnID == ""):
		errstr = errstr + "Error: no resource name. \r\n"
	if ((resType == "none" or len(resType) < 1) and spawnID == "" and forceOp != "verify"):
		errstr = errstr + "Error: no resource type. \r\n"
	else:
		#  Some automated updaters post reptillian meat as 'reptilian', normalize
		resType = resType.replace("reptilian", "reptillian")

	if spawnID == "":
		if galaxy == "":
			errstr = errstr + "Error: no galaxy selected. \r\n"
		else:
			# try to look up spawnID for editing and verifying
			spawnID = dbShared.getSpawnID(spawnName, galaxy)

	if re.search('\W', spawnName):
		errstr = errstr + "Error: spawn name contains illegal characters."
	if (forceOp != "edit" and planet.isdigit() == False):
		# attempt to lookup planet by name
		if planet != "":
			planet = dbShared.getPlanetID(planet)
		if planet.isdigit() == False:
			errstr = errstr + "Error: planet must be provided to post resource unless editing."

	postBlockedSeconds = dbShared.getUserPostBlockedSecondsRemaining(currentUser, 'r')
	if dbShared.getUserPostBlockedSecondsRemaining(currentUser, 'r') > 0:
		errstr = errstr + "Error: You are currently blocked from adding or updating resources due to recent activity.  Your cooldown ends in less than " + str((postBlockedSeconds / 3600) + 1) + " hours."

	if (errstr == ""):
		result = ""
		galaxyState = dbShared.galaxyState(galaxy)
		if (logged_state > 0 and galaxyState == 1):
			if (spawnName == "" or spawnName == None):
				spawnName = ghNames.getSpawnName(spawnID)

			if (spawnID>-1):
				# spawn already entered
				if (forceOp == "edit"):
					result = "edit: "
					result = result + addResStats(spawnID, resType, CR, CD, DR, FL, HR, MA, PE, OQ, SR, UT, ER, forceOp, currentUser, galaxy)
				else:
					result = addResPlanet(spawnID, planet, spawnName, currentUser, galaxy)
					result = result + '  ' + addResStats(spawnID, resType, CR, CD, DR, FL, HR, MA, PE, OQ, SR, UT, ER, forceOp, currentUser, galaxy)
			else:
				# new spawn
				result = addResource(spawnName, galaxy, resType, CR, CD, DR, FL, HR, MA, PE, OQ, SR, UT, ER, currentUser)
				spawnID = dbShared.getSpawnID(spawnName, galaxy)
				result = addResPlanet(spawnID, planet, spawnName, currentUser, galaxy) + '  ' + result

		else:
			if logged_state > 0:
				result = "Error: You cannot add resource data for an Inactive Galaxy."
			else:
				result = "Error: must be logged in to add resources"
	else:
		result = errstr

	print 'Content-type: text/xml\n'
	doc = minidom.Document()
	eRoot = doc.createElement("result")
	doc.appendChild(eRoot)

	eName = doc.createElement("spawnName")
	tName = doc.createTextNode(spawnName)
	eName.appendChild(tName)
	eRoot.appendChild(eName)
	eText = doc.createElement("resultText")
	tText = doc.createTextNode(result)
	eText.appendChild(tText)
	eRoot.appendChild(eText)
	eSource = doc.createElement("sourceRow")
	tSource = doc.createTextNode(sourceRow)
	eSource.appendChild(tSource)
	eRoot.appendChild(eSource)
	print doc.toxml()

	if (result.find("Error:") > -1):
		sys.exit(500)
	else:
		sys.exit(200)
def main():
    # Get current url
    try:
        url = os.environ['SCRIPT_NAME']
    except KeyError:
        url = ''

    form = cgi.FieldStorage()
    # Get Cookies
    useCookies = 1
    cookies = Cookie.SimpleCookie()
    try:
        cookies.load(os.environ['HTTP_COOKIE'])
    except KeyError:
        useCookies = 0

    if useCookies:
        try:
            currentUser = cookies['userID'].value
        except KeyError:
            currentUser = ''
        try:
            loginResult = cookies['loginAttempt'].value
        except KeyError:
            loginResult = 'success'
        try:
            sid = cookies['gh_sid'].value
        except KeyError:
            sid = form.getfirst('gh_sid', '')
    else:
        currentUser = ''
        loginResult = 'success'
        sid = form.getfirst('gh_sid', '')

    errstr = ''

    if not form.has_key("reportFile"):
        errstr = "No report file sent."
    else:
        rpt_data = form["reportFile"]
        if not rpt_data.file: errstr = "report data is not a file."

    src_url = form.getfirst('src_url', '/surveyList.py')
    galaxyID = form.getfirst('reportGalaxy', '')
    dataAction = form.getfirst('dataAction', '')
    # escape input to prevent sql injection
    sid = dbShared.dbInsertSafe(sid)
    galaxyID = dbShared.dbInsertSafe(galaxyID)

    # Get a session
    logged_state = 0
    linkappend = ''

    sess = dbSession.getSession(sid)
    if (sess != ''):
        logged_state = 1
        currentUser = sess
        if (useCookies == 0):
            linkappend = 'gh_sid=' + sid

    #  Check for errors
    if not galaxyID.isdigit():
        errstr = errstr + "Galaxy ID must be a valid number. \r\n"
    if errstr == '':
        rptName = rpt_data.filename
    if (logged_state == 0):
        errstr = errstr + "You must be logged in to post resources. \r\n"

    if (errstr != ''):
        result = "Your report could not be posted because of the following errors:\r\n" + errstr
    else:
        result = ''
        isNGE = False

        # process file
        thisSpawn = ghObjects.resourceSpawn()
        resourcesFound = []
        planetID = 0
        classID = ''
        headerMatch = None
        planetMatch = None
        classMatch = None
        resourceStart = None
        typeMatch = None
        nameMatch = None
        statMatch = None
        conn = dbShared.ghConn()
        cursor = conn.cursor()
        if (cursor):
            cursor.execute(
                'SELECT galaxyNGE FROM tGalaxy WHERE galaxyID={0};'.format(
                    str(galaxyID)))
            row = cursor.fetchone()
            if (row != None) and (row[0] > 0):
                isNGE = True
            cursor.close()
        # NGE version of droid report has different format with more indent and group levels
        if isNGE:
            typePattern = ' +([a-zA-Z][a-zA-Z0-9\- ]+)'
            namePattern = ' +\\\#pcontrast1 (\w+)\\\#'
        else:
            typePattern = '\t([a-zA-Z0-9\- ]+)'
            namePattern = '\t\t\\\#pcontrast1 (\w+)\\\#'

        while 1:
            line = rpt_data.file.readline()
            if not line: break
            if headerMatch == None and (planetMatch == None
                                        or classMatch == None):
                headerMatch = re.match("Interplanetary Survey: (\w+) - (\w+)",
                                       line)
                planetMatch = re.match(
                    "\\\#pcontrast\d\sPlanet: \\\#pcontrast\d\s(.+)", line)
                classMatch = re.match(
                    "\\\#pcontrast\d\sResource Class: \\\#pcontrast\d\s(.+)",
                    line)
            else:
                if resourceStart == None:
                    resourceStart = re.match(
                        "\\\#pcontrast\d\sResources located.*", line)
                else:
                    typeMatch = re.match(typePattern, line)
                    nameMatch = re.match(namePattern, line)
                    if typeMatch:
                        thisType = dbShared.getResourceTypeID(
                            conn, typeMatch.group(1))
                        thisTypeName = typeMatch.group(1)
                    if nameMatch:
                        if thisSpawn.spawnName != '':
                            resourcesFound.append(thisSpawn)
                        thisName = nameMatch.group(1)
                        thisSpawn = ghObjects.resourceSpawn()
                        thisSpawn.spawnName = thisName.lower()
                        thisSpawn.resourceType = thisType
                        thisSpawn.resourceTypeName = thisTypeName
                    # Check for resource stats from enhanced droid reports
                    statMatch = re.match(
                        "\t\t\t(ER|CR|CD|DR|FL|HR|MA|PE|OQ|SR|UT): (\d+)",
                        line)
                    if statMatch:
                        setattr(thisSpawn.stats, statMatch.group(1),
                                int(statMatch.group(2)))

        conn.close()

        if thisSpawn.spawnName != '':
            resourcesFound.append(thisSpawn)

        # Update planet data if valid results
        if headerMatch:
            planetID = dbShared.getPlanetID(headerMatch.group(1))
            classID = headerMatch.group(2).lower()
        elif planetMatch:
            planetID = dbShared.getPlanetID(planetMatch.group(1))
        else:
            result = "Error: No planet found in file header."
        if classMatch:
            classID = classMatch.group(1).lower()

        if planetID > 0:
            if dataAction == 'returnJSON':
                result = getSpawnsJSON(
                    planetID,
                    resourcesFound, "{0} spawns loaded from report".format(
                        len(resourcesFound)))
            else:
                result = updatePlanetSpawns(planetID, classID, resourcesFound,
                                            galaxyID, currentUser)
        else:
            result = "Error: Could not determine planet from file header."

    if dataAction == 'returnJSON':
        # add resources page uses json data to populate grid
        print "Content-Type: text/json\n"
        print result
    else:
        # survey list page will load result message from cookie after redirect
        if useCookies:
            cookies['surveyReportAttempt'] = result
            cookies['surveyReportAttempt']['max-age'] = 60
            print cookies
        else:
            linkappend = linkappend + '&surveyReportAttempt=' + urllib.quote(
                result)

        print "Content-Type: text/html\n"
        if src_url != None:
            print '<html><head><script type=text/javascript>document.location.href="' + src_url + linkappend + '"</script></head><body></body></html>'
        else:
            print result

    if result.find("Error:") > -1:
        sys.exit(500)
    else:
        sys.exit(200)
Пример #7
0
	if (cursor):
		if (dbShared.galaxyState(galaxy) == 1):
			markAll = 0
			cursor.execute('SELECT spawnID, resourceType, CR, CD, DR, FL, HR, MA, PE, OQ, SR, UT, ER FROM tResources WHERE galaxy=' + galaxy + ' AND spawnName="' + spawnName + '";')
			row = cursor.fetchone()

			if (row != None):
				spawnID = str(row[0])
		
			if (planets == "all"):
				markAll = 1
				sqlStr = "UPDATE tResourcePlanet SET unavailable=NOW(), unavailableBy='" + currentUser + "' WHERE spawnID=" + spawnID + ";"
			else:
				# try to look up planet by name if an ID was not provided
				if (planets.isdigit() != True):
					planets = dbShared.getPlanetID(planets)
				sqlStr = "UPDATE tResourcePlanet SET unavailable=NOW(), unavailableBy='" + currentUser + "' WHERE spawnID=" + spawnID + " AND planetID=" + planets + ";"
			cursor.execute(sqlStr)
			# check if any planets still available
			cursor.execute("SELECT enteredBy FROM tResourcePlanet WHERE spawnID=" + str(spawnID) + " AND unavailable IS NULL;")
			row = cursor.fetchone()
			if (row == None):
				markAll = 1

			# update main table when all planets unavailable
			if (markAll == 1):
				sqlStr = "UPDATE tResources SET unavailable=NOW(), unavailableBy='" + currentUser + "' WHERE spawnID=" + str(spawnID) + ";"
				cursor.execute(sqlStr)

			# add cleanup event
			if not planets.isdigit():