示例#1
0
def addResPlanet(spawn, planet, spawnName):
	# Add resource to a planet
	returnStr = ""
	conn = dbShared.ghConn()
	cursor = conn.cursor()
	cursor.execute("SELECT trp.enteredBy, trp.unavailable, tr.unavailable AS tru, trp.planetID, tr.enteredBy, trp.verified, trp.verifiedBy FROM tResources tr LEFT JOIN (SELECT * FROM tResourcePlanet WHERE tResourcePlanet.spawnID=" + str(spawn) + " AND tResourcePlanet.planetID=" + str(planet) + ") trp ON tr.spawnID = trp.spawnID WHERE tr.spawnID=" + str(spawn) + ";")
	row = cursor.fetchone()
	if row[3] == None:
		# insert spawn planet record
		tempSQL = "INSERT INTO tResourcePlanet (spawnID, planetID, entered, enteredBy) VALUES (" + str(spawn) + "," + str(planet) + ",NOW(),'" + currentUser + "');"
		cursor.execute(tempSQL)
		result = cursor.rowcount
		if (result < 1):
			returnStr = "Error: Could not add resource to planet."
		else:
			returnStr = spawnName + " added to " + str(ghNames.getPlanetName(planet))
		# add resource planet add event
		dbShared.logEvent("INSERT INTO tResourceEvents (spawnID, userID, eventTime, eventType, planetID) VALUES (" + str(spawn) + ",'" + currentUser + "',NOW(),'p'," + str(planet) + ");",'p',currentUser, galaxy, spawn)
		if row[2] != None:
			# update main resource table when becoming re-available
			tempSQL = "UPDATE tResources SET unavailable=NULL WHERE spawnID = " + str(spawn) + ";"
			cursor.execute(tempSQL)
			returnStr += " and marked re-available"
	else:
		if (row[1] == None and row[2] == None):
			if ((row[0] == None) or (row[0].lower() != currentUser.lower() and row[4].lower() != currentUser.lower())):
				if (row[6] == None or row[6].lower() != currentUser.lower()):
					tempSQL = "UPDATE tResourcePlanet SET verified=NOW(), verifiedBy='" + currentUser + "' WHERE spawnID=" + str(spawn) + " AND planetID=" + str(planet) + ";"
					result = cursor.execute(tempSQL)
					if (result < 1):
						returnStr = "Error: Resource " + spawnName + " was marked available on " + str(ghNames.getPlanetName(planet)) + " by " + row[0] + " and there was an error entering your verification."
					else:
						returnStr = "Resource " + spawnName + " has been verified by you.  It was marked available on " + str(ghNames.getPlanetName(planet)) + " by " + row[0] + "."
						# add event for verification
						dbShared.logEvent("INSERT INTO tResourceEvents (spawnID, userID, eventTime, eventType, planetID) VALUES (" + str(spawn) + ",'" + currentUser + "',NOW(),'v'," + str(planet) + ");",'v',currentUser,galaxy,spawn)
						# update main resource table when verifying
						tempSQL = "UPDATE tResources SET verified=NOW(), verifiedBy='" + currentUser + "' WHERE spawnID = " + str(spawn) + ";"
						cursor.execute(tempSQL)
				else:
					returnStr = "You already verified " + spawnName + " on " + str(row[5]) + "."
			else:
				returnStr = "You already entered resource " + spawnName
		else:
			# update resource status available for planet
			tempSQL = "UPDATE tResourcePlanet SET unavailable = NULL WHERE spawnID=" + str(spawn) + " AND planetID=" + str(planet) + ";"
			cursor.execute(tempSQL)
			result = cursor.rowcount

			# update main resource table when becoming re-available
			tempSQL = "UPDATE tResources SET unavailable=NULL WHERE spawnID = " + str(spawn) + ";"
			cursor.execute(tempSQL)
			returnStr = spawnName + " marked re-available on " + ghNames.getPlanetName(planet)
    
	cursor.close()
	conn.close()
	return returnStr
示例#2
0
def verifySessionDB():
	conn = dbShared.ghConn()
	cursor = conn.cursor()
	cursor.execute("show tables like 'tSessions';")
	row = cursor.fetchone()
	if row == None:
		tablesql = "CREATE TABLE tSessions (sid VARCHAR(40) NOT NULL PRIMARY KEY, userID VARCHAR(32) NOT NULL, expires FLOAT);"
		cursor.execute(tablesql)
	cursor.close()
	conn.close()
示例#3
0
def getItemName(sqlStr):
    result = ""
    conn = dbShared.ghConn()
    cursor = conn.cursor()
    if (cursor):
        cursor.execute(sqlStr)
        row = cursor.fetchone()
        if (row != None):
            result = row[1]
	cursor.close()
    conn.close()
    return result
示例#4
0
def getSpawnID(resName, galaxy):
	conn = dbShared.ghConn()
	cursor = conn.cursor()
	cursor.execute("SELECT spawnID FROM tResources WHERE galaxy=" + galaxy + " AND spawnName='" + resName + "';")
	row = cursor.fetchone()
	if row == None:
		newid = -1
	else:
		newid = row[0]

	cursor.close()
	conn.close()
	return newid
示例#5
0
def findName(nameString):
    conn = dbShared.ghConn()
    cursor = conn.cursor()
    cursor.execute("SELECT userID FROM tUsers WHERE userID='" + nameString + "'")
    row = cursor.fetchone()
    if row == None:
        userid = ""
    else:
        userid = row[0]

    cursor.close()
    conn.close()
    return userid
def getUnavailableTypes(resGroup):
	retTypes = ''
	conn = dbShared.ghConn()
	cursor = conn.cursor()
	if (cursor):
		sqlStr1 = 'SELECT tResourceType.resourceType, resourceTypeName, ur.maxent FROM tResourceType LEFT JOIN (SELECT tResources.resourceType AS resType, Max(entered) AS maxent FROM tResources INNER JOIN tResourceType rt ON tResources.resourceType = rt.resourceType WHERE unavailable IS NULL AND rt.resourceGroup="' + resGroup + '" GROUP BY tResources.resourceType) ur ON tResourceType.resourceType = ur.resType WHERE enterable = 1 AND resourceGroup="' + resGroup + '";'
		cursor.execute(sqlStr1)
		row = cursor.fetchone()
		while (row != None):
			if (row[2] == None):
				retTypes = retTypes + row[1] + '- '
			row = cursor.fetchone()

	return retTypes.rstrip('- ')
def getTypeGroups(resType):
	retGroups = ['resources|Resources','','','','','','']
	conn = dbShared.ghConn()
	cursor = conn.cursor()
	if (cursor):
		sqlStr1 = 'SELECT groupLevel, groupName, tResourceTypeGroup.resourceGroup FROM tResourceTypeGroup INNER JOIN tResourceGroup ON tResourceTypeGroup.resourceGroup = tResourceGroup.resourceGroup WHERE tResourceTypeGroup.resourceType="' + resType + '";'
		cursor.execute(sqlStr1)
		row = cursor.fetchone()
		while (row != None):
			if (row[0] != None):
				retGroups[row[0]-1] = row[2] + '|' + row[1]
			row = cursor.fetchone()

	return retGroups
示例#8
0
def updateWaypoint(waypointID, spawnID, planetID, price, concentration, lattitude, longitude, wpName, shareLevel):
	# Update waypoint information
	returnStr = ""
	conn = dbShared.ghConn()
	cursor = conn.cursor()
	tempSQL = "UPDATE tWaypoint SET spawnID=" + str(spawnID) + ", planetID=" + str(planetID) + ", price=" + price + ", concentration=" + str(concentration) + ", lattitude=" + str(lattitude) + ", longitude=" + str(longitude) + ", waypointName='" + wpName + "', shareLevel=" + str(shareLevel) + " WHERE waypointID=" + str(waypointID) + ";"
	cursor.execute(tempSQL)
	result = cursor.rowcount
	if (result < 1):
		returnStr = "Error: waypoint not updated."
	else:
		returnStr = " waypoint updated."

	cursor.close()
	conn.close()
	return returnStr
示例#9
0
def addResStats(spawn, resType, CR, CD, DR, FL, HR, MA, PE, OQ, SR, UT, ER, forceOp):
	# Update stats for a spawn
	returnStr = ""
	needStat = 0
	hasStats = 0
	resStats = [CR,CD,DR,FL,HR,MA,PE,OQ,SR,UT,ER]

	conn = dbShared.ghConn()
	cursor = conn.cursor()
	cursor.execute("SELECT CR, CD, DR, FL, HR, MA, PE, OQ, SR, UT, ER, CRmax, CDmax, DRmax, FLmax, HRmax, MAmax, PEmax, OQmax, SRmax, UTmax, ERmax, tResources.resourceType FROM tResources INNER JOIN tResourceType ON tResources.resourceType=tResourceType.resourceType WHERE spawnID=" + str(spawn) + ";")
	row = cursor.fetchone()
	if row != None:
		for i in range(11):
			if row[i+11] > 0 and row[i] == None:
				needStat = 1
			if (resStats[i]>0 and resStats[i] != "" and resStats[i] != None):
				hasStats = 1
		# override normal behavior of only updating
		# when there are no stats if forceOp is set to edit
		if ( (not needStat) and forceOp != "edit"):
			returnStr = "Resource stats already entered."
		else:
			# update resource stats
			if hasStats:
				tempSQL = "UPDATE tResources SET enteredBy='" + currentUser + "', CR=" + n2n(CR) + ", CD=" + n2n(CD) + ", DR=" + n2n(DR) + ", FL=" + n2n(FL) + ", HR=" + n2n(HR) + ", MA=" + n2n(MA) + ", PE=" + n2n(PE) + ", OQ=" + n2n(OQ) + ", SR=" + n2n(SR) + ", UT=" + n2n(UT) + ", ER=" + n2n(ER) + " WHERE spawnID=" + str(spawn) + ";"
				#sys.stderr.write("sql: " + tempSQL + "\n")
				cursor.execute(tempSQL)
				result = cursor.rowcount
				returnStr = str(spawnName) + " stats updated"
				# add resource edit event
				if needStat:
					dbShared.logEvent("INSERT INTO tResourceEvents (spawnID, userID, eventTime, eventType) VALUES (" + str(spawn) + ",'" + currentUser + "',NOW(),'a');",'a',currentUser,galaxy,spawn)
				else:
					dbShared.logEvent("INSERT INTO tResourceEvents (spawnID, userID, eventTime, eventType) VALUES (" + str(spawn) + ",'" + currentUser + "',NOW(),'e');",'e',currentUser,galaxy,spawn)

		if (row[22] != resType and len(resType)>0):
			tempSQL = "UPDATE tResources SET resourceType='" + resType + "' WHERE spawnID=" + str(spawn) + ";"
			cursor.execute(tempSQL)
			returnStr = returnStr + " type updated"

	else:
		returnStr = "Error: could not find that resource " + str(spawnName) + "."
    
	cursor.close()
	conn.close()
	return returnStr
示例#10
0
def getOptionList(sqlStr):
	result = ""
	conn = dbShared.ghConn()
	cursor = conn.cursor()
	if (cursor):
		cursor.execute(sqlStr)
		row = cursor.fetchone()
		while (row != None):
			if len(row)>2:
				result = result + '  <option value="' + str(row[0]) + '" group="' + str(row[2]) + '">' + row[1] + '</option>'
			elif len(row)>1:
				result = result + '  <option value="' + str(row[0]) + '">' + row[1] + '</option>'
			else:
				result = result + '  <option>' + row[0] + '</option>'
			row = cursor.fetchone()
		cursor.close()
	conn.close()
	return result
示例#11
0
def addWaypoint(spawnID, planetID, price, concentration, lattitude, longitude, wpName, shareLevel):
	# Add new waypoint
	returnStr = ""
	conn = dbShared.ghConn()
	cursor = conn.cursor()
	tempSQL = "INSERT INTO tWaypoint (spawnID, planetID, owner, price, concentration, lattitude, longitude, waypointType, waypointName, shareLevel, entered) VALUES (" + str(spawnID) + "," + str(planetID) + ",'" + currentUser + "'," + price + "," + str(concentration) + "," + str(lattitude) + "," + str(longitude) + ",'u','" + wpName + "'," + str(shareLevel) + ",NOW());"
	try:
		cursor.execute(tempSQL)
		returnStr = "Waypoint added."
		waypointID = cursor.lastrowid
	except:
		returnStr = 'Error: Add Failed.'

	if str(waypointID).isdigit():
		dbShared.logEvent("INSERT INTO tResourceEvents (spawnID, userID, eventTime, eventType, planetID) VALUES (" + str(spawnID) + ",'" + currentUser + "',NOW(),'w'," + str(planetID) + ");","w",currentUser, galaxy, str(spawnID))

	cursor.close()
	conn.close()
	return returnStr
示例#12
0
def getSession(sid, duration):
	conn = dbShared.ghConn()
	cursor = conn.cursor()
	cursor.execute("SELECT userID, expires FROM tSessions WHERE sid='" + sid + "'")
	row = cursor.fetchone()
	if row == None:
		# no record
		result = ""
	else:
		if time.time() > row[1]:
			# session is expired, delete it
			result = ""
			tempSQL = "DELETE FROM tSessions WHERE sid='" + sid + "'"
			cursor.execute(tempSQL)
		else:
			# good session, return userid
			result = row[0]

	cursor.close()
	conn.close()
	return result
示例#13
0
def addResource(resName, galaxy, resType, CR, CD, DR, FL, HR, MA, PE, OQ, SR, UT, ER):
	# Add new resource
	returnStr = ""
	conn = dbShared.ghConn()
	cursor = conn.cursor()
	# clear invalid stat values incase type was switched in the UI
	tempSQL = "SELECT CRmin, CRMax, CDmin, CDmax, DRmin, DRmax, FLmin, FLmax, HRmin, HRmax, MAmin, MAmax, PEmin, PEmax, OQmin, OQmax, SRmin, SRmax, UTmin, UTmax, ERmin, ERmax FROM tResourceType WHERE resourceType='" + resType + "';"
	cursor.execute(tempSQL)
	row = cursor.fetchone()
	if row != None:
		if row[0] == 0: CR = ''
		if row[2] == 0: CD = ''
		if row[4] == 0: DR = ''
		if row[6] == 0: FL = ''
		if row[8] == 0: HR = ''
		if row[10] == 0: MA = ''
		if row[12] == 0: PE = ''
		if row[14] == 0: OQ = ''
		if row[16] == 0: SR = ''
		if row[18] == 0: UT = ''
		if row[20] == 0: ER = ''
			

	tempSQL = "INSERT INTO tResources (spawnName, galaxy, entered, enteredBy, resourceType, CR, CD, DR, FL, HR, MA, PE, OQ, SR, UT, ER) VALUES ('" + resName + "'," + n2n(galaxy) + ",NOW(),'" + currentUser + "','" + resType + "'," + n2n(CR) + "," + n2n(CD) + "," + n2n(DR) + "," + n2n(FL) + "," + n2n(HR) + "," + n2n(MA) + "," + n2n(PE) + "," + n2n(OQ) + "," + n2n(SR) + "," + n2n(UT) + "," + n2n(ER) + ");"
	cursor.execute(tempSQL)
	result = cursor.rowcount
	if (result < 1):
		returnStr = "Error: resource not added."
	else:
		returnStr = "1st entry."
	# add event for add if stats included
	if OQ.isdigit():
		spawnID = dbShared.getSpawnID(resName,galaxy)
		dbShared.logEvent("INSERT INTO tResourceEvents (spawnID, userID, eventTime, eventType) VALUES (" + str(spawnID) + ",'" + currentUser + "',NOW(),'a');","a",currentUser, galaxy,spawnID)

	cursor.close()
	conn.close()
	return returnStr
示例#14
0
def getResourceTree():
	errorstr = ''
	currentLevel = 1
	levelCounter = 0
	currentLevelNodes = ['','','','','','','']
	tmpLeft = 0
	tmpTop = 0
	treeHTML = ''

	try:
		conn = dbShared.ghConn()
		cursor = conn.cursor()
	except Exception:
		errorstr = 'Error: could not connect to database'
	
	if errorstr == '':
		cursor.execute('SELECT resourceGroup, groupName, groupLevel, groupOrder from tResourceGroup ORDER BY groupOrder;');
		row = cursor.fetchone()
		while (row != None):
			if currentLevel < row[2]:
				levelCounter += 1
			currentLevel = row[2]
			tmpLeft = ((row[3]-levelCounter-1) * 26) - 30
			tmpTop = ((7 - currentLevel) * 110) + 260

			currentLevelNodes[row[2]-1] = currentLevelNodes[row[2]-1] + '<a href="' + ghShared.BASE_SCRIPT_URL + 'resourceType.py/' + row[0] + '"><div class="inlineBlock resTreeItem" style="left:' + str(tmpLeft) + 'px;top:' + str(tmpTop) + 'px;">' + row[1] + '</div></a>'
			row = cursor.fetchone()

		cursor.close()

	conn.close()

	currentLevelNodes = currentLevelNodes[1:]
	for level in currentLevelNodes:
		treeHTML = '<div>' + level + '</div>' + treeHTML

	return '<div id="resourceTree">' + treeHTML + '</div>'
示例#15
0
def main():
	# Get current url
	try:
		url = os.environ['SCRIPT_NAME']
	except KeyError:
		url = ''

	form = cgi.FieldStorage()
	uiTheme = ''
	# 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', '')
		try:
			uiTheme = cookies['uiTheme'].value
		except KeyError:
			uiTheme = ''
		try:
			galaxy = cookies['galaxy'].value
		except KeyError:
			galaxy = "8"
	else:
		currentUser = ''
		loginResult = form.getfirst('loginAttempt', '')
		sid = form.getfirst('gh_sid', '')

	# escape input to prevent sql injection
	sid = dbShared.dbInsertSafe(sid)

	# Get a session
	logged_state = 0
	linkappend = ''
	disableStr = ''
	if loginResult == None:
		loginResult = 'success'

	sess = dbSession.getSession(sid, 2592000)
	if (sess != ''):
		logged_state = 1
		currentUser = sess
		if (uiTheme == ''):
			uiTheme = dbShared.getUserAttr(currentUser, 'themeName')
		if (useCookies == 0):
			linkappend = 'gh_sid=' + sid
	else:
		disableStr = ' disabled="disabled"'
		if (uiTheme == ''):
			uiTheme = 'crafter'

	# Get recipe id from path
	path = []
	if os.environ.has_key('PATH_INFO'):
		path = os.environ['PATH_INFO'].split('/')[1:]
		path = [p for p in path if p != '']
	recipeHTML = ''
	slotHTML = ''
	schematicSummaryHTML = ''
	schematicDetailsHTML = ''
	ingTypes = ''
	ingGroups = ''
	pageType = 'recipe'
	if len(path) > 0:
		recipeID = dbShared.dbInsertSafe(path[0])
		url = url + '/' + recipeID
		if logged_state == 1:
			# Look up recipe info
			try:
				conn = dbShared.ghConn()
				cursor = conn.cursor()
			except Exception:
				recipeHTML = "Error: could not connect to database"
			if (cursor and recipeID.isdigit()):
				cursor.execute('SELECT recipeID, userID, tRecipe.schematicID, recipeName, (SELECT imageName FROM tSchematicImages si WHERE si.schematicID=tRecipe.schematicID AND si.imageType=1) AS schemImage, schematicName, complexity FROM tRecipe INNER JOIN tSchematic ON tRecipe.schematicID = tSchematic.schematicID WHERE recipeID=' + recipeID + ';')
				row = cursor.fetchone()

				if (row != None):
					if row[1] == currentUser:
						# main recipe data
						if (row[4] != None):
							schemImageName = row[4]
						else:
							schemImageName = 'none.jpg'
						schematicSummaryHTML = '<img src="/images/schematics/' + schemImageName + '" class="schematics" />'
						r = ghObjectRecipe.schematicRecipe()
						r.recipeID = row[0]
						r.schematicID = row[2]
						r.recipeName = row[3]
						r.schematicImage = schemImageName
						recipeHTML = '<div><a href="" id="nameLink" onclick="$(this).hide();$(\'#nameEditor\').show();$(\'#recipeName\').focus();return false;" title="Click to edit name." class="nameLink">' + r.recipeName + '</a></div><div id="nameEditor" style="display:none;"><input type="text" id="recipeName" size="30" maxlength="255" value="' + r.recipeName + '" onblur="$(\'#nameLink\').html(this.value).show();$(\'#nameEditor\').hide();" onkeyup="if(event.keyCode == 13){$(\'#nameLink\').html(this.value).show();$(\'#nameEditor\').hide();}"/></div><div style="float:right;"><button type=button value="Save" class="ghButton" onclick="saveRecipe(' + recipeID + ',$(\'#recipeName\').val());">Save</button> <button type=button value="Delete" class="ghButton" onclick="deleteRecipe(\'recipe\',' + str(r.recipeID) + ');">Delete</button></div>'
						recipeHTML += '<div class="footer"/><div id="factoryCalc" style="text-align:left">Calculate Factory Run: <input type="text" id="factoryAmount" size="6" maxlength="4"/> units.  <button type="button" value="Calculate" class="ghButton" onclick="getFactoryList(parseInt($(\'#factoryAmount\').val()))">Calculate</button><div id="factoryResults"></div></div>'

						# schematic quality data
						schematicDetailsHTML = '<div><a href="' + ghShared.BASE_SCRIPT_URL + 'schematics.py/' + row[2] + '" title="Go to schematic page.">' + row[5] + '</a></div>'
						schematicDetailsHTML += '<div>Complexity: ' + str(row[6]) + '</div>'
						expGroup = ''
						expProp = ''
						schematicDetailsHTML += '<td valign="top"><h3>Qualities</h3><ul id="qualitiesList" style="margin-top:6px;">'
						expCursor = conn.cursor()
						expCursor.execute('SELECT tSchematicQualities.expQualityID, expProperty, expGroup, statName, statWeight, weightTotal FROM tSchematicQualities INNER JOIN tSchematicResWeights ON tSchematicQualities.expQualityID = tSchematicResWeights.expQualityID WHERE schematicID="' + r.schematicID + '" ORDER BY expGroup, expProperty, statName;')
						expRow = expCursor.fetchone()
						while (expRow != None):
							if (expGroup != expRow[2]):
								tmpName = expRow[2].replace('_',' ')
								schematicDetailsHTML = schematicDetailsHTML + '<li class="groupText">' + tmpName + '</li>'
								expGroup = expRow[2]
							if (expProp != expRow[1]):
								tmpName = expRow[1].replace('_',' ')
								schematicDetailsHTML = schematicDetailsHTML + '<li class="schemQualityProperty altText">' + tmpName + '</li>'
								expProp = expRow[1]
						
							schematicDetailsHTML += '<li class="schemQualityItem" tag="' + expRow[3] + ':' + str((expRow[4]*1.0/expRow[5])*100) + '"><span class="inlineBlock" style="width:100px;">' + ghNames.getStatName(expRow[3]) + (': </span><span>%.0f' % ((expRow[4]*1.0/expRow[5])*100)) + '%</span></li>'

							expRow = expCursor.fetchone()

						expCursor.close()
						# Look up ingredient data
						ri = None
						sqlStr = 'SELECT si.ingredientName, ingredientResource, ingredientObject, ingredientQuantity, ingredientContribution, rt.containerType tcontainer, rg.containerType gcontainer, rt.resourceTypeName, rg.groupName, ingredientQuality FROM tSchematicIngredients si LEFT JOIN (SELECT ingredientName, ingredientResource, ingredientQuality FROM tRecipeIngredients WHERE recipeID=' + str(r.recipeID) + ') ri ON si.ingredientName = ri.ingredientName LEFT JOIN tResourceType rt ON si.ingredientObject = rt.resourceType LEFT JOIN tResourceGroup rg ON si.ingredientObject = rg.resourceGroup WHERE schematicID="' + r.schematicID + '" ORDER BY ingredientQuantity DESC, si.ingredientName'
						ingCursor = conn.cursor()
						ingCursor.execute(sqlStr)
						ingRow = ingCursor.fetchone()
						while (ingRow != None):
							if ingRow[5] == None:
								if ingRow[6] == None:
									container = 'default'
									objectName = ingRow[2].rpartition('/')[2].replace('_',' ')
									if objectName[-4:] == '.iff':
										objectName = objectName[:-4]
								else:
									ingGroups += '"' + ingRow[2] + '",'
									container = ingRow[6]
									objectName = ingRow[8]
							else:
								ingTypes += '"' + ingRow[2] + '",'
								container = ingRow[5]
								objectName = ingRow[7]

							# get details of ingredient resource for schematic
							resDetails = ''
							if ingRow[1] != None and (ingRow[5] != None or ingRow[6] != None):
								spawn = resource.getResource(conn, logged_state, currentUser, ingRow[1], None, None)
								resDetails = 'Loaded with: ' + spawn.spawnName + ', ' + spawn.resourceTypeName + '<br />' + spawn.getStatList()
							r.recipeIngredients.append(ghObjectRecipe.recipeIngredient(ingRow[2], ingRow[1], ingRow[0], ingRow[3], container, objectName, ingRow[9], resDetails))
							ingRow = ingCursor.fetchone()

						ingCursor.close()
						if ingTypes != '':
							ingTypes = ingTypes[:-1]
						if ingGroups != '':
							ingGroups = ingGroups[:-1]
						slotHTML = r.getIngredientSlots()
					else:
						recipeHTML = "That is not your recipe."
				else:
					recipeHTML = "The recipe ID given could not be found."
				cursor.close()
			else:
				# Render recipe home if any non number in sub path
				pageType = 'home'
				recipeHTML = 'Home<div style="float:right;"><button type=button value="New Recipe" class="ghButton" onclick="addRecipe();">New Recipe</button></div>'

			conn.close()
		else:
			recipeHTML = "You must be logged in to manage recipes."
	else:
		recipeHTML = 'You have not specified a recipe to edit, would you like to create a new one?<div style="float:right;"><button type=button value="New Recipe" class="ghButton" onclick="addRecipe();">New Recipe</button></div>'

	pictureName = dbShared.getUserAttr(currentUser, 'pictureName')
	print 'Content-type: text/html\n'
	env = Environment(loader=FileSystemLoader('templates'))
	env.globals['BASE_SCRIPT_URL'] = ghShared.BASE_SCRIPT_URL
	template = env.get_template('recipe.html')
	print template.render(uiTheme=uiTheme, loggedin=logged_state, currentUser=currentUser, loginResult=loginResult, linkappend=linkappend, url=url, pictureName=pictureName, imgNum=ghShared.imgNum, planetList=ghLists.getPlanetList(), galaxyList=ghLists.getGalaxyList(), professionList=ghLists.getProfessionList(), recipeHTML=recipeHTML, slotHTML=slotHTML, schematicSummaryHTML=schematicSummaryHTML, schematicDetailsHTML=schematicDetailsHTML, ingTypes=ingTypes, ingGroups=ingGroups, pageType=pageType)
示例#16
0
def main():
    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:
            sid = cookies['gh_sid'].value
        except KeyError:
            sid = form.getfirst('gh_sid', '')
    else:
        currentUser = ''
        sid = form.getfirst('gh_sid', '')

    listFormat = form.getfirst('listFormat', '')
    listType = form.getfirst('listType', '')
    galaxy = form.getfirst('galaxy', '')
    profession = form.getfirst('profession', '')

    # Get a session
    logged_state = 0

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

    # Main program
    errstr = ''
    tmpStr = ''

    if not galaxy.isdigit():
        errstr = 'Error: You must provide a valid galaxy id.'
    if profession != '' and not profession.isdigit():
        errstr = 'Error: That is not a valid profession id.'
    if logged_state != 1:
        errstr = 'Error: You must be logged in to get your recipe list.'

    conn = dbShared.ghConn()
    cursor = conn.cursor()
    if (cursor and errstr == ''):
        headStr = '<table width="100%">'
        if listType == 'suggest':
            rl = getSuggestedRecipes(conn, currentUser, galaxy, profession)
            if len(rl) > 0:
                for r in rl:
                    tmpStr += r.getRow(listType)
            else:
                tmpStr = '<tr><td>No suggestions at this time.  Try adding more to your inventory.</td></tr>'
        else:
            sqlStr = 'SELECT recipeID, userID, schematicID, recipeName, (SELECT imageName FROM tSchematicImages img WHERE img.schematicID=tRecipe.schematicID AND img.imageType=1) AS schemImage FROM tRecipe WHERE userID="' + currentUser + '" AND (galaxy=' + str(
                galaxy) + ' OR galaxy IS NULL) ORDER BY recipeName;'
            cursor.execute(sqlStr)
            row = cursor.fetchone()

            while (row != None):
                if (row[4] != None):
                    schemImageName = row[4]
                else:
                    schemImageName = 'none.jpg'
                r = ghObjectRecipe.schematicRecipe()
                r.recipeID = row[0]
                r.schematicID = row[2]
                r.recipeName = row[3]
                r.schematicImage = schemImageName
                sqlStr = 'SELECT si.ingredientName, ingredientResource, ingredientObject, ingredientContribution, ingredientQuality FROM tSchematicIngredients si LEFT JOIN (SELECT ingredientName, ingredientResource, ingredientQuality FROM tRecipeIngredients WHERE recipeID=' + str(
                    r.recipeID
                ) + ') ri ON si.ingredientName = ri.ingredientName WHERE schematicID="' + r.schematicID + '" and ingredientType = 0 ORDER BY ingredientQuantity DESC, si.ingredientName;'
                ingCursor = conn.cursor()
                ingCursor.execute(sqlStr)
                ingRow = ingCursor.fetchone()
                while (ingRow != None):
                    ri = ghObjectRecipe.recipeIngredient()
                    ri.ingredientObject = ingRow[2]
                    ri.ingredientResource = ingRow[1]
                    ri.ingredientName = ingRow[0]
                    ri.ingredientAmount = ingRow[3]
                    ri.resourceQuality = ingRow[4]
                    r.recipeIngredients.append(ri)
                    ingRow = ingCursor.fetchone()

                ingCursor.close()
                tmpStr += r.getRow('normal', sid)

                row = cursor.fetchone()

        tmpStr = headStr + tmpStr + '</table>'

        cursor.close()
    conn.close()

    print 'Content-type: text/html\n'
    print tmpStr
示例#17
0
def main():
    resHTML = '<h2>That resource type does not exist</h2>'
    resHistory = ''
    useCookies = 1
    linkappend = ''
    logged_state = 0
    currentUser = ''
    typeGroup = 'type'
    typeID = ''
    typeName = ''
    uiTheme = ''
    # Get current url
    try:
        url = os.environ['SCRIPT_NAME']
    except KeyError:
        url = ''

    form = cgi.FieldStorage()
    # Get Cookies

    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', '')
        try:
            uiTheme = cookies['uiTheme'].value
        except KeyError:
            uiTheme = ''
        try:
            galaxy = cookies['galaxy'].value
        except KeyError:
            galaxy = form.getfirst('galaxy', ghShared.DEFAULT_GALAXY)
    else:
        loginResult = form.getfirst('loginAttempt', '')
        sid = form.getfirst('gh_sid', '')
        galaxy = form.getfirst('galaxy', ghShared.DEFAULT_GALAXY)

    # escape input to prevent sql injection
    sid = dbShared.dbInsertSafe(sid)

    # Get a session

    if loginResult == None:
        loginResult = 'success'

    sess = dbSession.getSession(sid)
    if (sess != ''):
        logged_state = 1
        currentUser = sess
        if (uiTheme == ''):
            uiTheme = dbShared.getUserAttr(currentUser, 'themeName')
        if (useCookies == 0):
            linkappend = 'gh_sid=' + sid
    else:
        if (uiTheme == ''):
            uiTheme = 'crafter'

    path = ['']
    if os.environ.has_key('PATH_INFO'):
        path = os.environ['PATH_INFO'].split('/')[1:]
        path = [p for p in path if p != '']

    try:
        conn = dbShared.ghConn()
    except Exception:
        errorstr = "Error: could not connect to database"

    if path[0] != '':
        typeID = dbShared.dbInsertSafe(path[0])
        cursor = conn.cursor()
        if (cursor):
            cursor.execute(
                'SELECT resourceTypeName, rg1.groupName, rg2.groupName, rt.containerType, CRmin, CRmax, CDmin, CDmax, DRmin, DRmax, FLmin, FLmax, HRmin, HRmax, MAmin, MAmax, PEmin, PEmax, OQmin, OQmax, SRmin, SRmax, UTmin, UTmax, ERmin, ERmax, rt.resourceCategory, rt.resourceGroup FROM tResourceType rt INNER JOIN tResourceGroup rg1 ON rt.resourceCategory = rg1.resourceGroup INNER JOIN tResourceGroup rg2 ON rt.resourceGroup = rg2.resourceGroup WHERE resourceType="'
                + typeID + '";')
            row = cursor.fetchone()
            if (row != None):
                typeName = row[0]
            else:
                # look up group info if not found as a type
                typeGroup = 'group'
                cursor.execute(
                    'SELECT groupName, (SELECT rg.groupName FROM tResourceGroupCategory rgc INNER JOIN tResourceGroup rg ON rgc.resourceCategory = rg.resourceGroup WHERE rgc.resourceGroup=tResourceGroup.resourceGroup AND rg.groupLevel = tResourceGroup.groupLevel -1) AS resCat, "" AS resourceGroup, Max(tResourceType.containerType) AS contType, Min(CRmin), Max(CRmax), Min(CDmin), Max(CDmax), Min(DRmin), Max(DRmax), Min(FLmin), Max(FLmax), Min(HRmin), Max(HRmax), Min(MAmin), Max(MAmax), Min(PEmin), Max(PEmax), Min(OQmin), Max(OQmax), Min(SRmin), Max(SRmax), Min(UTmin), Max(UTmax), Min(ERmin), Max(ERmax), (SELECT rgc.resourceCategory FROM tResourceGroupCategory rgc INNER JOIN tResourceGroup rg ON rgc.resourceCategory = rg.resourceGroup WHERE rgc.resourceGroup=tResourceGroup.resourceGroup AND rg.groupLevel = tResourceGroup.groupLevel -1) AS catID FROM tResourceGroup, tResourceType WHERE tResourceGroup.resourceGroup="'
                    + typeID +
                    '" AND tResourceType.resourceType IN (SELECT resourceType FROM tResourceTypeGroup WHERE resourceGroup="'
                    + typeID + '" GROUP BY resourceType);')
                row = cursor.fetchone()
                if (row != None):
                    typeName = row[0]
                else:
                    typeGroup = ''

            favHTML = ''
            if logged_state > 0:
                favCursor = conn.cursor()
                favSQL = ''.join((
                    'SELECT itemID FROM tFavorites WHERE favType=2 AND userID="',
                    currentUser, '" AND favGroup="', typeID, '" AND galaxy=',
                    galaxy))
                favCursor.execute(favSQL)
                favRow = favCursor.fetchone()
                if favRow != None:
                    favHTML = '  <div class="inlineBlock" style="width:3%;float:left;"><a alt="Favorite" title="Favorite" style="cursor: pointer;" onclick="toggleFavorite(this, 2, \'' + typeID + '\', $(\'#galaxySel\').val());"><img src="/images/favorite16On.png" /></a></div>'
                else:
                    favHTML = '  <div class="inlineBlock" style="width:3%;float:left;"><a alt="Favorite" title="Favorite" style="cursor: pointer;" onclick="toggleFavorite(this, 2, \'' + typeID + '\', $(\'#galaxySel\').val());"><img src="/images/favorite16Off.png" /></a></div>'
                favCursor.close()

            if typeName != '' and typeName != None:
                resHTML = '<div style="font-size:16px;font-weight:bold;">' + favHTML + typeName

                if row != None and row[3] != None:
                    if row[1] != typeName:
                        resHTML += '<div style="float:right;"><img src="/images/resources/' + row[
                            3] + '.png" /></div></div>'
                    else:
                        resHTML += '</div>'
                    # breadcrumb to resource type if not top level category
                    if row[1] != typeName:
                        resHTML += '<h3 style="margin-bottom:12px;">'
                        if row[26] != 'resource':
                            resHTML += '<a href="' + ghShared.BASE_SCRIPT_URL + 'resourceType.py/' + str(
                                row[26]) + '">' + str(row[1]) + '</a>'
                        else:
                            resHTML += row[1]
                        if typeGroup == 'type':
                            resHTML += ' > <a href="' + ghShared.BASE_SCRIPT_URL + 'resourceType.py/' + row[
                                27] + '">' + row[2] + '</a>'
                        resHTML += ' > ' + typeName + '</h3>'
                    # min/max stats table
                    resHTML += '<table class="resAttr resourceStats"><tr>'
                    resHTML += '<td><td class="header"><span>CR</span></td><td class="header"><span>CD</span></td><td class="header"><span>DR</span></td><td class="header"><span>FL</span></td><td class="header"><span>HR</span></td><td class="header"><span>MA</span></td><td class="header"><span>PE</span></td><td class="header"><span>OQ</span></td><td class="header"><span>SR</span></td><td class="header"><span>UT</span></td><td class="header"><span>ER</span></td></tr>'
                    resHTML += '<tr><td class="header">Min</td><td>' + z2b(
                        row[4]
                    ) + '</td><td>' + z2b(row[6]) + '</td><td>' + z2b(
                        row[8]
                    ) + '</td><td>' + z2b(row[10]) + '</td><td>' + z2b(
                        row[12]) + '</td><td>' + z2b(
                            row[14]) + '</td><td>' + z2b(
                                row[16]) + '</td><td>' + z2b(
                                    row[18]) + '</td><td>' + z2b(
                                        row[20]) + '</td><td>' + z2b(
                                            row[22]) + '</td><td>' + z2b(
                                                row[24]) + '</td></tr>'
                    resHTML += '<tr><td class="header">Max</td><td>' + z2b(
                        row[5]
                    ) + '</td><td>' + z2b(row[7]) + '</td><td>' + z2b(
                        row[9]
                    ) + '</td><td>' + z2b(row[11]) + '</td><td>' + z2b(
                        row[13]) + '</td><td>' + z2b(
                            row[15]) + '</td><td>' + z2b(
                                row[17]) + '</td><td>' + z2b(
                                    row[19]) + '</td><td>' + z2b(
                                        row[21]) + '</td><td>' + z2b(
                                            row[23]) + '</td><td>' + z2b(
                                                row[25]) + '</td></tr>'
                    resHTML += '</table>'
                else:
                    resHTML += '</div>'

        cursor.close()
    else:
        resHTML = '<h1>Resource Type Groups</h1>'
        resHTML += '<div id="resTypeInfo">You have reached the resource type page.  From here, you can browse to any resource type and view things like: best spawns, schematics, creatures, and min/max stats.</div>'

    creature = max([
        typeID.find('bone_'),
        typeID.find('hide_'),
        typeID.find('meat_'),
        typeID.find('milk_')
    ])
    if typeID == '':
        # Print the plain group list for pre-IE9 because it does not support rotate css
        tmpAgent = os.environ.get("HTTP_USER_AGENT", "unknown")
        if tmpAgent == 'unknown' or (tmpAgent.find("IE") > -1
                                     and tmpAgent.find("MSIE 9.0") == -1):
            resTree = getResourceGroupsPlain()
        else:
            resTree = getResourceTree()
    else:
        resTree = ''
    pictureName = dbShared.getUserAttr(currentUser, 'pictureName')
    # Get reputation to determine editing abilities
    stats = dbShared.getUserStats(currentUser, galaxy).split(",")
    userReputation = int(stats[2])
    admin = dbShared.getUserAdmin(conn, currentUser, galaxy)
    conn.close()
    print 'Content-type: text/html\n'
    env = Environment(loader=FileSystemLoader('templates'))
    env.globals['BASE_SCRIPT_URL'] = ghShared.BASE_SCRIPT_URL
    env.globals['MOBILE_PLATFORM'] = ghShared.getMobilePlatform(
        os.environ['HTTP_USER_AGENT'])
    template = env.get_template('resourcetype.html')
    print template.render(
        uiTheme=uiTheme,
        loggedin=logged_state,
        currentUser=currentUser,
        loginResult=loginResult,
        linkappend=linkappend,
        url=url,
        pictureName=pictureName,
        imgNum=ghShared.imgNum,
        galaxyList=ghLists.getGalaxyList(),
        typeGroup=typeGroup,
        typeID=typeID,
        resHTML=resHTML,
        creature=creature,
        resTree=resTree,
        editCreatures=(userReputation >= ghShared.MIN_REP_VALS['ADD_CREATURE']
                       or admin),
        resourceType=typeID)
示例#18
0
def getChartURL(chartType, chartSize, dataType, resType, available, groupType, galaxy):

	chartStr = "http://chart.apis.google.com/chart?cht=" + chartType + "&chs=" + chartSize
	chartData = "&chd=t:"
	chartLabels = ""
	chartMax = 0
	if chartType == 'bhs':
		# just display y axis and data values for bar chart
		chartAxes = '&chxt=y&chm=N,000000,0,-1,11'
	else:
		chartAxes = '&chxt=x,y'
	galaxyCriteria = ''
	if galaxy != None and galaxy <> '':
		galaxyCriteria = ' AND mt.galaxy=' + galaxy

	conn = dbShared.ghConn()
	cursor = conn.cursor()
	if (cursor):
		if groupType == 'user':
			# group by userID charts
			if resType == 'all':
				sqlStr = 'SELECT userID, ' + dataType + ' FROM tUserStats mt WHERE 1=1' + galaxyCriteria + ' ORDER BY ' + dataType + ' DESC LIMIT 5;'
			else:
				sqlStr = 'SELECT userID, Count(eventTime) AS numActions FROM tResourceEvents mt INNER JOIN tResources ON mt.spawnID = tResources.spawnID INNER JOIN tResourceTypeGroup ON tResources.resourceType = tResourceTypeGroup.resourceType WHERE resourceGroup = \'' + resType + '\'' + galaxyCriteria
				if available != 0:
					sqlStr += ' AND unavailable IS NULL'
				sqlStr += ' AND eventType=\'' + dataType + '\' GROUP BY userID ORDER BY Count(eventTime) DESC LIMIT 5;'
		else:
			# group by time period charts
			if groupType == 'day':
				dateSelect = 'DAY(eventTime)'
				dateGroup = 'YEAR(eventTime), MONTH(eventTime), DAY(eventTime)'
			elif groupType == 'week':
				dateSelect = 'WEEK(eventTime)'
				dateGroup = 'YEAR(eventTime), WEEK(eventTime)'
			else:
				dateSelect = 'YEAR(eventTime)'
				dateGroup = 'YEAR(eventTime)'

			sqlStr = 'SELECT ' + dateSelect + ' AS eDate, Count(eventTime) AS numActions FROM tResourceEvents mt INNER JOIN tResources ON mt.spawnID = tResources.spawnID INNER JOIN tResourceTypeGroup ON tResources.resourceType = tResourceTypeGroup.resourceType WHERE resourceGroup = \'' + resType + '\'' + galaxyCriteria + ' AND eventType=\'' + dataType + '\' AND eventTime > DATE_SUB(CURDATE(),INTERVAL ' + str(available) + ' DAY) GROUP BY ' + dateGroup + ' ORDER BY ' + dateGroup + ';'
		cursor.execute(sqlStr)
		row = cursor.fetchone()

		while (row != None):
			# keep track of maximum data value for scale
			if row[1] > chartMax:
				chartMax = row[1]
			# build chart data and label strings (dont know why labels need to be opposite order for bar charts)
			chartData = chartData + str(row[1]) + ','
			chartLabels = '|' + str(row[0]) + chartLabels
			row = cursor.fetchone()

		cursor.close()
		# strip trailing comma
		if len(chartData) > 1:
			chartData = chartData[:-1]

	conn.close()
	# add proper value scaling to y axis on line chart
	if chartType == 'lc':
		chartAxes = chartAxes + '&chxr=1,0,' + str(chartMax)

	return chartStr + chartData + '&chco=e8d43d&chds=0,' + str(int(chartMax*1.03)) + chartAxes + '&chxl=0:' + chartLabels
示例#19
0
if (itemID != "0" and suggestion == ""):
    try:
        int(voteValue)
    except ValueError:
        errstr = errstr + "That is not a valid vote value. \r\n"
    except TypeError:
        errstr = errstr + "That is not a valid vote value. \r\n"

if (logged_state == 0):
    errstr = errstr + "You must be logged in to add or update feedback. \r\n"

if re.search("[><&]", suggestion):
    errstr = errstr + "There are illegal characters in your suggestion.  No HTML allowed."

if (len(errstr) < 5):
    cconn = dbShared.ghConn()
    if (suggestion == ""):
        cursor = cconn.cursor()
        cursor.execute("SELECT vote FROM tFeedbackVotes WHERE feedbackID=" +
                       str(itemID) + " AND userID='" + currentUser + "';")
        row = cursor.fetchone()
        ccursor = cconn.cursor()
        if row != None:
            if (str(row[0]) != voteValue):
                ccursor.execute("UPDATE tFeedbackVotes SET vote=" +
                                str(voteValue) +
                                ", entered=NOW() WHERE feedbackID=" +
                                str(itemID) + " AND userID='" + currentUser +
                                "';")
                resultRows = ccursor.rowcount
            else:
示例#20
0
def addResPlanet(spawn, planet, spawnName, userID, galaxy):
    # Add resource to a planet
    returnStr = ""
    detailCol = ""
    detailVal = ""
    conn = dbShared.ghConn()
    cursor = conn.cursor()
    cursor.execute(
        "SELECT trp.enteredBy, trp.unavailable, tr.unavailable AS tru, trp.planetID, tr.enteredBy, trp.verified, trp.verifiedBy, tr.verified, tr.verifiedBy FROM tResources tr LEFT JOIN (SELECT * FROM tResourcePlanet WHERE tResourcePlanet.spawnID="
        + str(spawn) + " AND tResourcePlanet.planetID=" + str(planet) +
        ") trp ON tr.spawnID = trp.spawnID WHERE tr.spawnID=" + str(spawn) +
        ";")
    row = cursor.fetchone()
    if row[3] == None:
        # insert spawn planet record
        tempSQL = "INSERT INTO tResourcePlanet (spawnID, planetID, entered, enteredBy) VALUES (" + str(
            spawn) + "," + str(planet) + ",NOW(),'" + userID + "');"
        cursor.execute(tempSQL)
        result = cursor.rowcount
        if (result < 1):
            returnStr = "Error: Could not add resource to planet."
        else:
            returnStr = spawnName + " added to " + str(
                ghNames.getPlanetName(planet))

        if row[2] != None:
            # update main resource table when becoming re-available
            tempSQL = "UPDATE tResources SET unavailable=NULL WHERE spawnID = " + str(
                spawn) + ";"
            cursor.execute(tempSQL)
            returnStr += " and marked re-available"
            detailCol = ", eventDetail"
            detailVal = ", 'previously unavailable'"

        # add resource planet add event
        dbShared.logEvent(
            "INSERT INTO tResourceEvents (galaxy, spawnID, userID, eventTime, eventType, planetID"
            + detailCol + ") VALUES (" + str(galaxy) + "," + str(spawn) +
            ",'" + userID + "',NOW(),'p'," + str(planet) + detailVal + ");",
            'p', userID, galaxy, spawn)
    else:
        if (row[1] == None and row[2] == None):
            if ((row[0] == None) or (row[0].lower() != userID.lower()
                                     and row[4].lower() != userID.lower())):
                if (row[6] == None or row[6].lower() != userID.lower()):
                    tempSQL = "UPDATE tResourcePlanet SET verified=NOW(), verifiedBy='" + userID + "' WHERE spawnID=" + str(
                        spawn) + " AND planetID=" + str(planet) + ";"
                    result = cursor.execute(tempSQL)
                    if (result < 1):
                        returnStr = "Error: Resource " + spawnName + " was marked available on " + str(
                            ghNames.getPlanetName(planet)
                        ) + " by " + row[
                            0] + " and there was an error entering your verification."
                    else:
                        returnStr = "Resource " + spawnName + " has been verified by you.  It was marked available on " + str(
                            ghNames.getPlanetName(
                                planet)) + " by " + row[0] + "."
                        # add event for verification
                        if row[7] != None:
                            detailCol = ", eventDetail"
                            detailVal = ", 'previously verified by " + row[
                                8] + " on " + str(row[7]) + "'"
                        dbShared.logEvent(
                            "INSERT INTO tResourceEvents (galaxy, spawnID, userID, eventTime, eventType, planetID"
                            + detailCol + ") VALUES (" + str(galaxy) + "," +
                            str(spawn) + ",'" + userID + "',NOW(),'v'," +
                            str(planet) + detailVal + ");", 'v', userID,
                            galaxy, spawn)
                        # update main resource table when verifying
                        tempSQL = "UPDATE tResources SET verified=NOW(), verifiedBy='" + userID + "' WHERE spawnID = " + str(
                            spawn) + ";"
                        cursor.execute(tempSQL)
                else:
                    returnStr = "You already verified " + spawnName + " on " + str(
                        row[5]) + "."
            else:
                returnStr = "You already entered resource " + spawnName
        else:
            # update resource status available for planet
            tempSQL = "UPDATE tResourcePlanet SET unavailable = NULL WHERE spawnID=" + str(
                spawn) + " AND planetID=" + str(planet) + ";"
            cursor.execute(tempSQL)
            result = cursor.rowcount
            # update main resource table when becoming re-available
            tempSQL = "UPDATE tResources SET unavailable=NULL WHERE spawnID = " + str(
                spawn) + ";"
            cursor.execute(tempSQL)
            returnStr = spawnName + " marked re-available on " + ghNames.getPlanetName(
                planet)
            detailCol = ", eventDetail"
            detailVal = ", 'previously unavailable'"
            # add resource planet add event
            dbShared.logEvent(
                "INSERT INTO tResourceEvents (galaxy, spawnID, userID, eventTime, eventType, planetID"
                + detailCol + ") VALUES (" + str(galaxy) + "," + str(spawn) +
                ",'" + userID + "',NOW(),'p'," + str(planet) + detailVal +
                ");", 'p', userID, galaxy, spawn)

    cursor.close()
    conn.close()
    return returnStr
示例#21
0
def renderFeed(path):
    newest = dbShared.getLastResourceChange()
    resTitles = [
        'CR', 'CD', 'DR', 'FL', 'HR', 'MA', 'PE', 'OQ', 'SR', 'UT', 'ER'
    ]
    rfc822time = "%a, %d %b %Y %H:%M:%S -0800"
    print "Content-Type: text/xml; charset=iso-8859-15\n"
    print "<?xml version=\"1.0\" encoding=\"iso-8859-15\"?>"
    print "<rss version=\"2.0\""
    print "xmlns:content=\"http://purl.org/rss/1.0/modules/content/\""
    print ">"
    print "<channel>"
    resGroup = ""
    if len(path) >= 1:
        if (path[0] == "creature"):
            resGroup = "creature_resources"
        elif (path[0] == "flora"):
            resGroup = "flora_resources"
        elif (path[0] == "chemical"):
            resGroup = "chemical"
        elif (path[0] == "water"):
            resGroup = "water"
        elif (path[0] == "mineral"):
            resGroup = "mineral"
        elif (path[0] == "gas"):
            resGroup = "gas"
        elif (path[0] == "energy"):
            resGroup = "energy_renewable"
    if resGroup != "":
        print "<title>Galaxy Harvester Resource Activity: " + resGroup + "</title>"
    else:
        print "<title>Galaxy Harvester Resource Activity</title>"
    print "<link>http://galaxyharvester.net</link>"
    print "<description>Latest additions to Galaxy Harvester resource listing</description>"
    print "<pubDate>" + newest.strftime(rfc822time) + "</pubDate>"
    print "<lastBuildDate>" + newest.strftime(rfc822time) + "</lastBuildDate>"
    print "<generator>http://galaxyharvester.net/resourceList.py</generator>"
    print "<language>en</language>"

    # print resources
    conn = dbShared.ghConn()
    cursor = conn.cursor()
    criteriaStr = " WHERE unavailable IS NULL"
    if (cursor):
        if (resGroup != "any" and resGroup != ""):
            criteriaStr = criteriaStr + " AND tResourceType.resourceType IN (SELECT resourceType FROM tResourceTypeGroup WHERE resourceGroup='" + resGroup + "' GROUP BY resourceType)"
        sqlStr1 = 'SELECT spawnID, spawnName, galaxy, entered, enteredBy, tResources.resourceType, resourceTypeName, resourceGroup,'
        sqlStr1 += ' CR, CD, DR, FL, HR, MA, PE, OQ, SR, UT, ER,'
        sqlStr1 += ' CASE WHEN CRmax > 0 THEN ((CR-CRmin) / (CRmax-CRmin))*100 ELSE 0 END AS CRperc, CASE WHEN CDmax > 0 THEN ((CD-CDmin) / (CDmax-CDmin))*100 ELSE 0 END AS CDperc, CASE WHEN DRmax > 0 THEN ((DR-DRmin) / (DRmax-DRmin))*100 ELSE 0 END AS DRperc, CASE WHEN FLmax > 0 THEN ((FL-FLmin) / (FLmax-FLmin))*100 ELSE 0 END AS FLperc, CASE WHEN HRmax > 0 THEN ((HR-HRmin) / (HRmax-HRmin))*100 ELSE 0 END AS HRperc, CASE WHEN MAmax > 0 THEN ((MA-MAmin) / (MAmax-MAmin))*100 ELSE 0 END AS MAperc, CASE WHEN PEmax > 0 THEN ((PE-PEmin) / (PEmax-PEmin))*100 ELSE 0 END AS PEperc, CASE WHEN OQmax > 0 THEN ((OQ-OQmin) / (OQmax-OQmin))*100 ELSE 0 END AS OQperc, CASE WHEN SRmax > 0 THEN ((SR-SRmin) / (SRmax-SRmin))*100 ELSE 0 END AS SRperc, CASE WHEN UTmax > 0 THEN ((UT-UTmin) / (UTmax-UTmin))*100 ELSE 0 END AS UTperc, CASE WHEN ERmax > 0 THEN ((ER-ERmin) / (ERmax-ERmin))*100 ELSE 0 END AS ERperc,'
        sqlStr1 += ' galaxyName FROM tResources INNER JOIN tResourceType ON tResources.resourceType = tResourceType.resourceType INNER JOIN tGalaxy ON tResources.galaxy = tGalaxy.galaxyID'
        sqlStr1 = sqlStr1 + criteriaStr + ' ORDER BY entered DESC LIMIT 25;'
        cursor.execute(sqlStr1)
        row = cursor.fetchone()
        while (row != None):
            print "<item>"
            print "<title>" + row[1] + " Added by " + row[4] + " on " + row[
                30] + "</title>"
            print "<link>http://galaxyharvester.net/resource.py/" + str(
                row[2]) + "/" + row[1] + "</link>"
            print "<pubDate>" + row[3].strftime(rfc822time) + "</pubDate>"
            print "<guid isPermalink=\"true\">http://galaxyharvester.net/resource.py/" + str(
                row[2]) + "/" + row[1] + "</guid>"
            print "<description><![CDATA[ " + row[6] + " ]]></description>"
            print "<content:encoded><![CDATA["
            print "<br />" + row[6] + "<br />"
            for i in range(11):
                if (row[i + 8] != None and row[i + 19] != None):
                    print resTitles[i] + ": " + str(row[i + 8]) + " (" + (
                        "%.0f" % float(row[i + 19])) + "%)<br />",
            print "]]></content:encoded>"
            print "</item>"
            row = cursor.fetchone()

    print "</channel>"
    print "</rss>"
示例#22
0
def getChartURL(chartType, chartSize, dataType, resType, available, groupType, galaxy):

	chartStr = "http://chart.apis.google.com/chart?cht=" + chartType + "&chs=" + chartSize
	chartData = "&chd=t:"
	chartLabels = ""
	chartMax = 0
	if chartType == 'bhs':
		# just display y axis and data values for bar chart
		chartAxes = '&chxt=y&chm=N,000000,0,-1,11'
	else:
		chartAxes = '&chxt=x,y'
	galaxyCriteria = ''
	if galaxy != None and galaxy <> '':
		galaxyCriteria = ' AND galaxy=' + galaxy

	conn = dbShared.ghConn()
	cursor = conn.cursor()
	if (cursor):
		if groupType == 'user':
			# group by userID charts
			if resType == 'all':
				sqlStr = 'SELECT userID, ' + dataType + ' FROM tUserStats WHERE 1=1' + galaxyCriteria + ' ORDER BY ' + dataType + ' DESC LIMIT 5;'
			else:
				sqlStr = 'SELECT userID, Count(eventTime) AS numActions FROM tResourceEvents INNER JOIN tResources ON tResourceEvents.spawnID = tResources.spawnID INNER JOIN tResourceTypeGroup ON tResources.resourceType = tResourceTypeGroup.resourceType WHERE resourceGroup = \'' + resType + '\'' + galaxyCriteria
				if available != 0:
					sqlStr += ' AND unavailable IS NULL'
				sqlStr += ' AND eventType=\'' + dataType + '\' GROUP BY userID ORDER BY Count(eventTime) DESC LIMIT 5;'
		else:
			# group by time period charts
			if groupType == 'day':
				dateSelect = 'DAY(eventTime)'
				dateGroup = 'YEAR(eventTime), MONTH(eventTime), DAY(eventTime)'
			elif groupType == 'week':
				dateSelect = 'WEEK(eventTime)'
				dateGroup = 'YEAR(eventTime), WEEK(eventTime)'
			else:
				dateSelect = 'YEAR(eventTime)'
				dateGroup = 'YEAR(eventTime)'

			sqlStr = 'SELECT ' + dateSelect + ' AS eDate, Count(eventTime) AS numActions FROM tResourceEvents INNER JOIN tResources ON tResourceEvents.spawnID = tResources.spawnID INNER JOIN tResourceTypeGroup ON tResources.resourceType = tResourceTypeGroup.resourceType WHERE resourceGroup = \'' + resType + '\'' + galaxyCriteria + ' AND eventType=\'' + dataType + '\' AND eventTime > DATE_SUB(CURDATE(),INTERVAL ' + str(available) + ' DAY) GROUP BY ' + dateGroup + ' ORDER BY ' + dateGroup + ';'
		cursor.execute(sqlStr)
		row = cursor.fetchone()

		while (row != None):
			# keep track of maximum data value for scale
			if row[1] > chartMax:
				chartMax = row[1]
			# build chart data and label strings (dont know why labels need to be opposite order for bar charts)
			chartData = chartData + str(row[1]) + ','
			chartLabels = '|' + str(row[0]) + chartLabels
			row = cursor.fetchone()
		    
		cursor.close()
		# strip trailing comma
		if len(chartData) > 1:
			chartData = chartData[:-1]

	conn.close()
	# add proper value scaling to y axis on line chart
	if chartType == 'lc':
		chartAxes = chartAxes + '&chxr=1,0,' + str(chartMax)

	return chartStr + chartData + '&chco=e8d43d&chds=0,' + str(int(chartMax*1.03)) + chartAxes + '&chxl=0:' + chartLabels
示例#23
0
def main():
	resHTML = '<h2>That resource does not exist</h2>'
	resHistory = ''
	useCookies = 1
	linkappend = ''
	logged_state = 0
	currentUser = ''
	galaxy = ''
	spawnName = ''
	uiTheme = ''
	galaxyState = 0
	# Get current url
	try:
		url = os.environ['SCRIPT_NAME']
	except KeyError:
		url = ''

	form = cgi.FieldStorage()
	# Get Cookies

	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', '')
		try:
			uiTheme = cookies['uiTheme'].value
		except KeyError:
			uiTheme = ''
	else:
		loginResult = form.getfirst('loginAttempt', '')
		sid = form.getfirst('gh_sid', '')

	# escape input to prevent sql injection
	sid = dbShared.dbInsertSafe(sid)

	# Get a session
	
	if loginResult == None:
		loginResult = 'success'

	sess = dbSession.getSession(sid, 2592000)
	if (sess != ''):
		logged_state = 1
		currentUser = sess
		if (uiTheme == ''):
			uiTheme = dbShared.getUserAttr(currentUser, 'themeName')
		if (useCookies == 0):
			linkappend = 'gh_sid=' + sid
	else:
		if (uiTheme == ''):
			uiTheme = 'crafter'

	path = ['']
	if os.environ.has_key('PATH_INFO'):
		path = os.environ['PATH_INFO'].split('/')[1:]
		path = [p for p in path if p != '']

	if len(path) > 1:
		galaxy = dbShared.dbInsertSafe(path[0])
		spawnName = dbShared.dbInsertSafe(path[1])
		if galaxy != '':
			conn = dbShared.ghConn()
			spawn = getResource(conn, logged_state, currentUser, None, galaxy, spawnName)
			galaxyState = dbShared.galaxyState(spawn.spawnGalaxy)
			if galaxyState == 1:
				resHTML = spawn.getHTML(logged_state, 0, "")
			else:
				resHTML = spawn.getHTML(0, 0, "")

			resHistory = getResourceHistory(conn, spawn.spawnID)
			conn.close()
		else:
			resHTML = '<h2>No Galaxy/Resource name given</h2>'
	else:
		resHTML = '<h2>No Galaxy/Resource name given</h2>'

	pictureName = dbShared.getUserAttr(currentUser, 'pictureName')
	print 'Content-type: text/html\n'
	env = Environment(loader=FileSystemLoader('templates'))
	env.globals['BASE_SCRIPT_URL'] = ghShared.BASE_SCRIPT_URL
	template = env.get_template('resource.html')
	print template.render(uiTheme=uiTheme, loggedin=logged_state, currentUser=currentUser, loginResult=loginResult, linkappend=linkappend, url=url, pictureName=pictureName, imgNum=ghShared.imgNum, galaxyList=ghLists.getGalaxyList(), planetList=ghLists.getPlanetList(), spawnName=spawnName, resHTML=resHTML, resHistory=resHistory)
示例#24
0
def main():
    # Get current url
    try:
        url = os.environ['SCRIPT_NAME']
    except KeyError:
        url = ''

    form = cgi.FieldStorage()
    uiTheme = ''
    # 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', '')
        try:
            uiTheme = cookies['uiTheme'].value
        except KeyError:
            uiTheme = ''
        try:
            galaxy = cookies['galaxy'].value
        except KeyError:
            galaxy = form.getfirst('galaxy', ghShared.DEFAULT_GALAXY)
    else:
        currentUser = ''
        loginResult = form.getfirst('loginAttempt', '')
        sid = form.getfirst('gh_sid', '')
        galaxy = form.getfirst('galaxy', ghShared.DEFAULT_GALAXY)

    # escape input to prevent sql injection
    sid = dbShared.dbInsertSafe(sid)

    # Get a session
    logged_state = 0
    linkappend = ''
    disableStr = ''
    if loginResult == None:
        loginResult = 'success'

    sess = dbSession.getSession(sid)
    if (sess != ''):
        logged_state = 1
        currentUser = sess
        if (uiTheme == ''):
            uiTheme = dbShared.getUserAttr(currentUser, 'themeName')
        if (useCookies == 0):
            linkappend = 'gh_sid=' + sid
    else:
        disableStr = ' disabled="disabled"'
        if (uiTheme == ''):
            uiTheme = 'crafter'

    # Get recipe id from path
    path = []
    if os.environ.has_key('PATH_INFO'):
        path = os.environ['PATH_INFO'].split('/')[1:]
        path = [p for p in path if p != '']
    recipeHTML = ''
    slotHTML = ''
    schemImageName = ''
    schematicDetailsHTML = ''
    ingTypes = ''
    ingGroups = ''
    pageType = 'recipe'
    if len(path) > 0:
        recipeID = dbShared.dbInsertSafe(path[0])
        url = url + '/' + recipeID
        r = ghObjectRecipe.schematicRecipe()
        if logged_state == 1:
            # Look up recipe info
            try:
                conn = dbShared.ghConn()
                cursor = conn.cursor()
            except Exception:
                recipeHTML = "Error: could not connect to database"

            if (cursor and recipeID.isdigit()):
                cursor.execute(
                    'SELECT recipeID, userID, tRecipe.schematicID, recipeName, (SELECT imageName FROM tSchematicImages si WHERE si.schematicID=tRecipe.schematicID AND si.imageType=1) AS schemImage, schematicName, complexity FROM tRecipe INNER JOIN tSchematic ON tRecipe.schematicID = tSchematic.schematicID WHERE recipeID='
                    + recipeID + ';')
                row = cursor.fetchone()

                if (row != None):
                    if row[1] == currentUser:
                        # main recipe data
                        if (row[4] != None):
                            schemImageName = row[4]
                        else:
                            schemImageName = 'none.jpg'

                        r.recipeID = row[0]
                        r.schematicID = row[2]
                        r.recipeName = row[3]
                        r.schematicImage = schemImageName

                        # schematic quality data
                        schematicDetailsHTML = '<div><a href="' + ghShared.BASE_SCRIPT_URL + 'schematics.py/' + row[
                            2] + '" title="Go to schematic page.">' + row[
                                5] + '</a></div>'
                        schematicDetailsHTML += '<div>Complexity: ' + str(
                            row[6]) + '</div>'
                        expGroup = ''
                        expProp = ''
                        schematicDetailsHTML += '<td valign="top"><h3>Qualities</h3><ul id="qualitiesList" style="margin-top:6px;">'
                        expCursor = conn.cursor()
                        expCursor.execute(
                            'SELECT tSchematicQualities.expQualityID, expProperty, expGroup, statName, statWeight, weightTotal FROM tSchematicQualities INNER JOIN tSchematicResWeights ON tSchematicQualities.expQualityID = tSchematicResWeights.expQualityID WHERE schematicID="'
                            + r.schematicID +
                            '" ORDER BY expGroup, expProperty, statName;')
                        expRow = expCursor.fetchone()
                        while (expRow != None):
                            if (expGroup != expRow[2]):
                                tmpName = expRow[2].replace('_', ' ')
                                schematicDetailsHTML = schematicDetailsHTML + '<li class="groupText">' + tmpName + '</li>'
                                expGroup = expRow[2]
                            if (expProp != expRow[1]):
                                tmpName = expRow[1].replace('_', ' ')
                                schematicDetailsHTML = schematicDetailsHTML + '<li class="schemQualityProperty altText">' + tmpName + '</li>'
                                expProp = expRow[1]

                            schematicDetailsHTML += '<li class="schemQualityItem" tag="' + expRow[
                                3] + ':' + str(
                                    (expRow[4] * 1.0 / expRow[5]) * 100
                                ) + '"><span class="inlineBlock" style="width:100px;">' + ghNames.getStatName(
                                    expRow[3]) + (': </span><span>%.0f' % (
                                        (expRow[4] * 1.0 / expRow[5]) * 100)
                                                  ) + '%</span></li>'

                            expRow = expCursor.fetchone()

                        expCursor.close()
                        # Look up ingredient data
                        ri = None
                        sqlStr = 'SELECT si.ingredientName, ingredientResource, ingredientObject, ingredientQuantity, ingredientContribution, rt.containerType tcontainer, rg.containerType gcontainer, rt.resourceTypeName, rg.groupName, ingredientQuality FROM tSchematicIngredients si LEFT JOIN (SELECT ingredientName, ingredientResource, ingredientQuality FROM tRecipeIngredients WHERE recipeID=' + str(
                            r.recipeID
                        ) + ') ri ON si.ingredientName = ri.ingredientName LEFT JOIN tResourceType rt ON si.ingredientObject = rt.resourceType LEFT JOIN tResourceGroup rg ON si.ingredientObject = rg.resourceGroup WHERE schematicID="' + r.schematicID + '" ORDER BY ingredientQuantity DESC, si.ingredientName'
                        ingCursor = conn.cursor()
                        ingCursor.execute(sqlStr)
                        ingRow = ingCursor.fetchone()
                        while (ingRow != None):
                            if ingRow[5] == None:
                                if ingRow[6] == None:
                                    container = 'default'
                                    objectName = ingRow[2].rpartition(
                                        '/')[2].replace('_', ' ')
                                    if objectName[-4:] == '.iff':
                                        objectName = objectName[:-4]
                                else:
                                    ingGroups += '"' + ingRow[2] + '",'
                                    container = ingRow[6]
                                    objectName = ingRow[8]
                            else:
                                ingTypes += '"' + ingRow[2] + '",'
                                container = ingRow[5]
                                objectName = ingRow[7]

                            # get details of ingredient resource for schematic
                            resDetails = ''
                            if ingRow[1] != None and (ingRow[5] != None
                                                      or ingRow[6] != None):
                                spawn = resource.getResource(
                                    conn, logged_state, currentUser, ingRow[1],
                                    None, None)
                                resDetails = 'Loaded with: ' + spawn.spawnName + ', ' + spawn.resourceTypeName + '<br />' + spawn.getStatList(
                                )
                            r.recipeIngredients.append(
                                ghObjectRecipe.recipeIngredient(
                                    ingRow[2], ingRow[1], ingRow[0], ingRow[3],
                                    container, objectName, ingRow[9],
                                    resDetails))
                            ingRow = ingCursor.fetchone()

                        ingCursor.close()
                        if ingTypes != '':
                            ingTypes = ingTypes[:-1]
                        if ingGroups != '':
                            ingGroups = ingGroups[:-1]
                        slotHTML = r.getIngredientSlots()
                    else:
                        recipeHTML = "That is not your recipe."
                else:
                    recipeHTML = "The recipe ID given could not be found."
                cursor.close()
            else:
                # Render recipe home if any non number in sub path
                pageType = 'home'

            conn.close()
        else:
            recipeHTML = "You must be logged in to manage recipes."
    else:
        recipeHTML = 'You have not specified a recipe to edit, would you like to create a new one?<div style="float:right;"><button type=button value="New Recipe" class="ghButton" onclick="addRecipe();">New Recipe</button></div>'

    pictureName = dbShared.getUserAttr(currentUser, 'pictureName')
    print 'Content-type: text/html\n'
    env = Environment(loader=FileSystemLoader('templates'))
    env.globals['BASE_SCRIPT_URL'] = ghShared.BASE_SCRIPT_URL
    env.globals['MOBILE_PLATFORM'] = ghShared.getMobilePlatform(
        os.environ['HTTP_USER_AGENT'])
    template = env.get_template('recipe.html')
    print template.render(uiTheme=uiTheme,
                          loggedin=logged_state,
                          currentUser=currentUser,
                          loginResult=loginResult,
                          linkappend=linkappend,
                          url=url,
                          pictureName=pictureName,
                          imgNum=ghShared.imgNum,
                          galaxyList=ghLists.getGalaxyList(),
                          professionList=ghLists.getProfessionList(galaxy),
                          recipeHTML=recipeHTML,
                          slotHTML=slotHTML,
                          schematicDetailsHTML=schematicDetailsHTML,
                          ingTypes=ingTypes,
                          ingGroups=ingGroups,
                          pageType=pageType,
                          recipeID=r.recipeID,
                          recipeName=r.recipeName,
                          schemImageName=schemImageName,
                          enableCAPTCHA=ghShared.RECAPTCHA_ENABLED,
                          siteidCAPTCHA=ghShared.RECAPTCHA_SITEID)
示例#25
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', '')

	# Get form info
	schematic = form.getfirst("schematic", "")
	recipeName = form.getfirst("recipeName", "")
	recipeID = form.getfirst("recipeID", "")
	ingredients = form.getfirst("ingredients", "")
	operation = form.getfirst("op", "")
	spawnID = form.getfirst("spawnID", "")
	# escape input to prevent sql injection
	sid = dbShared.dbInsertSafe(sid)
	schematic = dbShared.dbInsertSafe(schematic)
	recipeName = dbShared.dbInsertSafe(recipeName)
	recipeID = dbShared.dbInsertSafe(recipeID)
	ingredients = dbShared.dbInsertSafe(ingredients)
	spawnID = dbShared.dbInsertSafe(spawnID)

	result = ""
	# Get a session
	logged_state = 0

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

	#  Check for errors
	errstr = ""
	if recipeName == "" and operation == "":
		errstr = "Error: You must provide a name for the recipe."
	if schematic == "" and recipeID == "":
		errstr = "Error: You must select a schematic to base the recipe on."
	if logged_state != 1:
		errstr = "Error: You must be logged in to do that."

	# Only process if no errors
	if (errstr == ""):
		result = ""
		if (logged_state > 0):
			conn = dbShared.ghConn()
			if schematic == "":
				#  Make sure user owns recipe
				chkcursor = conn.cursor()
				tempSQL = "SELECT userID, schematicID FROM tRecipe WHERE recipeID=" + recipeID + ";"
				chkcursor.execute(tempSQL)
				row = chkcursor.fetchone()
				if row != None:
					if row[0] == currentUser:
						if operation == "delete":
							result = deleteRecipe(conn, recipeID, currentUser)
						elif operation == "addspawn":
							result = addIngredient(conn, recipeID, spawnID, row[1], currentUser)
						else:
							result = updateRecipe(conn, recipeID, recipeName)
							if ingredients != "":
								result += updateIngredients(conn, recipeID, ingredients, row[1], currentUser)
					else:
						result = "Error: You do not own that recipe."
				else:
					result = "Error: That recipe does not exist."
				chkcursor.close()
			else:
				result = addRecipe(conn, schematic, recipeName, currentUser)
				tmpPos = result.find("ID")
				# Save and strip ID on successful add
				if tmpPos > -1:
					recipeID = result[tmpPos+2:]
					result = result[:tmpPos]
				# Update ingredients if they were provided (saving suggestion)
				if ingredients != '':
					result += updateIngredients(conn, recipeID, ingredients, schematic, currentUser)
			conn.close()
		else:
			result = "Error: must be logged in to do that."
	else:
		result = errstr

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

	eName = doc.createElement("recipeID")
	tName = doc.createTextNode(str(recipeID))
	eName.appendChild(tName)
	eRoot.appendChild(eName)
	eText = doc.createElement("resultText")
	tText = doc.createTextNode(result)
	eText.appendChild(tText)
	eRoot.appendChild(eText)
	print doc.toxml()

	if (result.find("Error:") > -1):
		sys.exit(500)
	else:
		sys.exit(200)
示例#26
0
def main():
    # Get current url
    try:
        url = os.environ['REQUEST_URI']
    except KeyError:
        url = ''
    uiTheme = ''
    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', '')
        try:
            uiTheme = cookies['uiTheme'].value
        except KeyError:
            uiTheme = ''
        try:
            avatarResult = cookies['avatarAttempt'].value
        except KeyError:
            avatarResult = ''
        try:
            galaxy = cookies['galaxy'].value
        except KeyError:
            galaxy = ghShared.DEFAULT_GALAXY
    else:
        currentUser = ''
        loginResult = form.getfirst('loginAttempt', '')
        avatarResult = form.getfirst('avatarAttempt', '')
        sid = form.getfirst('gh_sid', '')
        galaxy = form.getfirst('galaxy', ghShared.DEFAULT_GALAXY)

    # escape input to prevent sql injection
    sid = dbShared.dbInsertSafe(sid)

    # Get a session
    logged_state = 0
    linkappend = ''
    disableStr = ''
    created = datetime.fromtimestamp(time.time())
    inGameInfo = ''
    pictureName = ''
    userPictureName = ''
    friendCountStr = ''
    donateTotal = ''
    userTitle = ''
    donorBadge = ''
    email = ''
    defaultAlertTypes = 0
    sharedInventory = 0
    sharedRecipes = 0
    siteAlertCheckStr = ''
    emailAlertCheckStr = ''
    mobileAlertCheckStr = ''
    reputation = 0
    resScore = 0
    mapScore = 0
    repColor = 'grey'
    resColor = 'grey'
    mapColor = 'grey'
    abilities = []

    if loginResult == None:
        loginResult = 'success'

    sess = dbSession.getSession(sid)
    if (sess != ''):
        logged_state = 1
        currentUser = sess
        if (useCookies == 0):
            linkappend = 'gh_sid=' + sid
        conn = dbShared.ghConn()
        cursor = conn.cursor()
        cursor.execute(
            'SELECT userID, emailAddress, themeName FROM tUsers WHERE userID="'
            + currentUser + '"')
        row = cursor.fetchone()
        if (row != None):
            email = row[1]
            uiTheme = row[2]
        cursor.close()
        conn.close()
    else:
        disableStr = ' disabled="disabled"'
        if (uiTheme == ''):
            uiTheme = 'crafter'

    path = []
    uid = ''
    template = 'user.html'
    userPage = 'root'
    if os.environ.has_key('PATH_INFO'):
        path = os.environ['PATH_INFO'].split('/')[1:]
        path = [p for p in path if p != '']

    # get user attributes
    if len(path) > 0:
        uid = dbShared.dbInsertSafe(path[0])
        if len(path) > 1:
            userPage = path[1]
        if userPage == 'inventory':
            template = 'inventory.html'
        else:
            created = dbShared.getUserAttr(uid, 'created')
            inGameInfo = dbShared.getUserAttr(uid, 'inGameInfo')
            userPictureName = dbShared.getUserAttr(uid, 'pictureName')
            defaultAlerts = dbShared.getUserAttr(uid, 'defaultAlertTypes')
            if defaultAlerts > 0:
                if defaultAlerts % 2 == 1:
                    siteAlertCheckStr = ' checked="checked"'
                if defaultAlerts >= 4:
                    mobileAlertCheckStr = ' checked="checked"'
                if defaultAlerts != 1 and defaultAlerts != 4 and defaultAlerts != 5:
                    emailAlertCheckStr = ' checked="checked"'
            sharedInventory = dbShared.getUserAttr(uid, 'sharedInventory')
            sharedRecipes = dbShared.getUserAttr(uid, 'sharedRecipes')

            donateTotal = dbShared.getUserDonated(uid)
            userTitle = dbShared.getUserTitle(uid)
            userStats = dbShared.getUserStats(uid, galaxy).split(',')
            resScore = int(userStats[0])
            mapScore = int(userStats[1])
            reputation = int(userStats[2])
            if resScore != None:
                if resScore > 2000:
                    resColor = '#ffcc00'
                elif resScore > 500:
                    resColor = '#3366ff'
                elif resScore > 25:
                    resColor = '#009933'

            if mapScore != None:
                if mapScore > 400:
                    mapColor = '#ffcc00'
                elif mapScore > 100:
                    mapColor = '#3366ff'
                elif mapScore > 5:
                    mapColor = '#009933'

            if reputation != None:
                if reputation > 100:
                    repColor = '#ffcc00'
                elif reputation > 50:
                    repColor = '#3366ff'
                elif reputation > 10:
                    repColor = '#009933'
                elif reputation < 0:
                    repColor = '#800000'

            if userPictureName == '':
                userPictureName = 'default.jpg'
            if donateTotal != '':
                donorBadge = '<img src="/images/coinIcon.png" width="16" title="This user has donated to the site" alt="coin" />'
            # get friend count
            conn = dbShared.ghConn()
            cursor = conn.cursor()
            cursor.execute(
                'SELECT Count(uf1.added) FROM tUserFriends uf1 INNER JOIN tUserFriends uf2 ON uf1.friendID=uf2.userID AND uf1.userID=uf2.friendID WHERE uf1.userID="'
                + uid + '"')
            row = cursor.fetchone()
            if (row != None):
                friendCountStr = '(' + str(row[0]) + ')'
            cursor.close()
            conn.close()

        # Load list of unlocked abilities
        for k, v in ghShared.ABILITY_DESCR.iteritems():
            if reputation >= ghShared.MIN_REP_VALS[
                    k] and ghShared.MIN_REP_VALS[k] != -99:
                a = userAbility(k, v, True)
                a.minReputation = ghShared.MIN_REP_VALS[k]
                abilities.append(a)

    convertGI = ghShared.convertText(inGameInfo, "js")
    tmpStat = dbShared.friendStatus(uid, currentUser)
    joinedStr = 'Joined ' + ghShared.timeAgo(created) + ' ago'
    pictureName = dbShared.getUserAttr(currentUser, 'pictureName')

    print 'Content-type: text/html\n'
    env = Environment(loader=FileSystemLoader('templates'))
    env.globals['BASE_SCRIPT_URL'] = ghShared.BASE_SCRIPT_URL
    env.globals['MOBILE_PLATFORM'] = ghShared.getMobilePlatform(
        os.environ['HTTP_USER_AGENT'])
    template = env.get_template(template)
    if userPage == 'inventory':
        print template.render(
            uiTheme=uiTheme,
            loggedin=logged_state,
            currentUser=currentUser,
            loginResult=loginResult,
            linkappend=linkappend,
            url=url,
            pictureName=pictureName,
            imgNum=ghShared.imgNum,
            galaxyList=ghLists.getGalaxyList(),
            professionList=ghLists.getProfessionList(galaxy),
            resourceGroupList=ghLists.getResourceGroupList(),
            resourceTypeList=ghLists.getResourceTypeList(galaxy),
            uid=uid,
            editable=(uid == currentUser and logged_state == 1),
            enableCAPTCHA=ghShared.RECAPTCHA_ENABLED,
            siteidCAPTCHA=ghShared.RECAPTCHA_SITEID)
    else:
        print template.render(uiTheme=uiTheme,
                              loggedin=logged_state,
                              currentUser=currentUser,
                              loginResult=loginResult,
                              linkappend=linkappend,
                              url=url,
                              pictureName=pictureName,
                              imgNum=ghShared.imgNum,
                              galaxyList=ghLists.getGalaxyList(),
                              themeList=ghLists.getThemeList(),
                              uid=uid,
                              convertGI=convertGI,
                              sid=sid,
                              avatarResult=avatarResult,
                              email=email,
                              donorBadge=donorBadge,
                              joinedStr=joinedStr,
                              userPictureName=userPictureName,
                              tmpStat=tmpStat,
                              userTitle=userTitle,
                              friendCountStr=friendCountStr,
                              userAbilities=abilities,
                              resScore=resScore,
                              mapScore=mapScore,
                              reputation=reputation,
                              resColor=resColor,
                              mapColor=mapColor,
                              repColor=repColor,
                              siteAlertCheckStr=siteAlertCheckStr,
                              emailAlertCheckStr=emailAlertCheckStr,
                              mobileAlertCheckStr=mobileAlertCheckStr,
                              sharedInventory=sharedInventory,
                              sharedRecipes=sharedRecipes,
                              inGameInfo=ghShared.convertText(
                                  inGameInfo, 'html'),
                              enableCAPTCHA=ghShared.RECAPTCHA_ENABLED,
                              siteidCAPTCHA=ghShared.RECAPTCHA_SITEID)
示例#27
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', '')

    # Get form info
    schematic = form.getfirst("schematic", "")
    recipeName = form.getfirst("recipeName", "")
    recipeID = form.getfirst("recipeID", "")
    ingredients = form.getfirst("ingredients", "")
    operation = form.getfirst("op", "")
    spawnID = form.getfirst("spawnID", "")
    galaxy = form.getfirst("galaxy", "")
    # escape input to prevent sql injection
    sid = dbShared.dbInsertSafe(sid)
    schematic = dbShared.dbInsertSafe(schematic)
    recipeName = dbShared.dbInsertSafe(recipeName)
    recipeID = dbShared.dbInsertSafe(recipeID)
    ingredients = dbShared.dbInsertSafe(ingredients)
    spawnID = dbShared.dbInsertSafe(spawnID)
    galaxy = dbShared.dbInsertSafe(galaxy)

    result = ""
    # Get a session
    logged_state = 0

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

    #  Check for errors
    errstr = ""
    if recipeName == "" and operation == "":
        errstr = "Error: You must provide a name for the recipe."
    if schematic == "" and recipeID == "":
        errstr = "Error: You must select a schematic to base the recipe on."
    if logged_state != 1:
        errstr = "Error: You must be logged in to do that."
    if galaxy == "" and schematic != "":
        errstr = "Error: You must select a galaxy before creating a recipe."

    # Only process if no errors
    if (errstr == ""):
        result = ""
        if (logged_state > 0):
            conn = dbShared.ghConn()
            if schematic == "":
                #  Make sure user owns recipe
                chkcursor = conn.cursor()
                tempSQL = "".join(
                    ("SELECT userID, schematicID FROM tRecipe WHERE recipeID=",
                     recipeID, " AND userID='", currentUser, "';"))
                chkcursor.execute(tempSQL)
                row = chkcursor.fetchone()
                if row != None:
                    if operation == "delete":
                        result = deleteRecipe(conn, recipeID, currentUser)
                    elif operation == "addspawn":
                        result = addIngredient(conn, recipeID, spawnID, row[1],
                                               currentUser)
                    else:
                        result = updateRecipe(conn, recipeID, recipeName)
                        if ingredients != "":
                            result += updateIngredients(
                                conn, recipeID, ingredients, row[1],
                                currentUser)
                else:
                    result = "Error: That recipe does not exist or is not yours."
                chkcursor.close()
            else:
                result = addRecipe(conn, schematic, recipeName, currentUser,
                                   galaxy)
                tmpPos = result.find("ID")
                # Save and strip ID on successful add
                if tmpPos > -1:
                    recipeID = result[tmpPos + 2:]
                    result = result[:tmpPos]
                # Update ingredients if they were provided (saving suggestion)
                if ingredients != '':
                    result += updateIngredients(conn, recipeID, ingredients,
                                                schematic, currentUser)
            conn.close()
        else:
            result = "Error: must be logged in to do that."
    else:
        result = errstr

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

    eName = doc.createElement("recipeID")
    tName = doc.createTextNode(str(recipeID))
    eName.appendChild(tName)
    eRoot.appendChild(eName)
    eText = doc.createElement("resultText")
    tText = doc.createTextNode(result)
    eText.appendChild(tText)
    eRoot.appendChild(eText)
    print doc.toxml()

    if (result.find("Error:") > -1):
        sys.exit(500)
    else:
        sys.exit(200)
示例#28
0
def main():
    # Get current url
    try:
        url = os.environ['SCRIPT_NAME']
    except KeyError:
        url = ''
    uiTheme = ''
    schematicID = ''
    schemImageAttempt = ''
    schemHTML = '<h2>That schematic does not exist.</h2>'
    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', '')
        try:
            uiTheme = cookies['uiTheme'].value
        except KeyError:
            uiTheme = ''
        try:
            schemImageAttempt = cookies['schemImageAttempt'].value
        except KeyError:
            schemImageAttempt = ''
        try:
            galaxy = cookies['galaxy'].value
        except KeyError:
            galaxy = form.getfirst('galaxy', ghShared.DEFAULT_GALAXY)
    else:
        currentUser = ''
        loginResult = form.getfirst('loginAttempt', '')
        sid = form.getfirst('gh_sid', '')
        schemImageAttempt = form.getfirst('schemImageAttempt', '')
        galaxy = form.getfirst('galaxy', ghShared.DEFAULT_GALAXY)

    forceOp = form.getfirst('forceOp', '')
    # escape input to prevent sql injection
    sid = dbShared.dbInsertSafe(sid)
    # Get a session
    logged_state = 0
    linkappend = ''
    disableStr = ''
    if loginResult == None:
        loginResult = 'success'

    sess = dbSession.getSession(sid)
    if (sess != ''):
        logged_state = 1
        currentUser = sess
        if (uiTheme == ''):
            uiTheme = dbShared.getUserAttr(currentUser, 'themeName')
        if (useCookies == 0):
            linkappend = 'gh_sid=' + sid
    else:
        disableStr = ' disabled="disabled"'
        if (uiTheme == ''):
            uiTheme = 'crafter'

    path = []
    s = None
    if os.environ.has_key('PATH_INFO'):
        path = os.environ['PATH_INFO'].split('/')[1:]
        path = [p for p in path if p != '']

    favHTML = ''
    canEdit = False
    canAdd = False
    profession = ''
    if len(path) > 0:
        schematicID = dbShared.dbInsertSafe(path[0])
        url = url + '/' + schematicID
        try:
            conn = dbShared.ghConn()
        except Exception:
            errorstr = "Error: could not connect to database"
        # Lookup reputation for edit tool option
        stats = dbShared.getUserStats(currentUser, galaxy).split(",")
        userReputation = int(stats[2])
        admin = dbShared.getUserAdmin(conn, currentUser, galaxy)
        canAdd = userReputation >= ghShared.MIN_REP_VALS[
            'ADD_SCHEMATIC'] or admin

        if (schematicID != 'index') and (schematicID != 'home'):
            # Build the schematic object
            cursor = conn.cursor()
            if (cursor):
                cursor.execute(
                    'SELECT schematicName, complexity, xpAmount, (SELECT imageName FROM tSchematicImages tsi WHERE tsi.schematicID=tSchematic.schematicID AND tsi.imageType=1) AS schemImage, galaxy, enteredBy, craftingTab, skillGroup, objectType FROM tSchematic WHERE schematicID=%s;',
                    [schematicID])
                row = cursor.fetchone()

                if (row != None):
                    # main schematic data
                    if (row[3] != None):
                        schemImageName = row[3]
                    else:
                        schemImageName = 'none.jpg'

                    s = ghObjectSchematic.schematic()
                    s.schematicID = schematicID
                    s.schematicName = row[0]
                    s.complexity = row[1]
                    s.xpAmount = row[2]
                    s.schematicImage = schemImageName
                    s.galaxy = row[4]
                    s.enteredBy = row[5]
                    s.craftingTab = row[6]
                    s.skillGroup = row[7]
                    s.objectType = row[8]

                    profession = getProfession(conn, s.skillGroup)

                    ingCursor = conn.cursor()
                    ingCursor.execute(
                        'SELECT ingredientName, ingredientType, ingredientObject, ingredientQuantity, res.resName, containerType FROM tSchematicIngredients LEFT JOIN (SELECT resourceGroup AS resID, groupName AS resName, containerType FROM tResourceGroup UNION ALL SELECT resourceType, resourceTypeName, containerType FROM tResourceType) res ON ingredientObject = res.resID WHERE schematicID="'
                        + schematicID +
                        '" ORDER BY ingredientType, ingredientQuantity DESC;')
                    ingRow = ingCursor.fetchone()
                    while (ingRow != None):
                        tmpObject = ingRow[2]
                        tmpObject = tmpObject.replace('shared_', '')
                        if (ingRow[1] == 0):
                            tmpImage = '/images/resources/{0}.png'.format(
                                ingRow[5])
                            # resource
                            if (ingRow[4] != None):
                                tmpName = ingRow[4]
                                tmpLink = '<a href="' + ghShared.BASE_SCRIPT_URL + 'resourceType.py/' + ingRow[
                                    2] + '">' + tmpName + '</a>'
                            else:
                                tmpLink = '<a href="' + ghShared.BASE_SCRIPT_URL + 'resourceType.py/' + ingRow[
                                    2] + '">' + tmpName + '</a>'
                        else:
                            # component
                            results = getComponentLink(conn, tmpObject,
                                                       ingRow[1]).split('|')
                            tmpLink = results[1]
                            tmpImage = results[0]
                            tmpName = results[2]

                        s.ingredients.append(
                            ghObjectSchematic.schematicIngredient(
                                ingRow[0], ingRow[1], tmpObject, ingRow[3],
                                ingRow[4], tmpLink, tmpImage, tmpName))
                        ingRow = ingCursor.fetchone()

                    ingCursor.close()

                    # schematic quality data
                    expGroup = ''
                    expProp = ''
                    qg = None
                    qp = None
                    expCursor = conn.cursor()
                    expCursor.execute(
                        'SELECT tSchematicQualities.expQualityID, expProperty, expGroup, statName, statWeight, weightTotal FROM tSchematicQualities INNER JOIN tSchematicResWeights ON tSchematicQualities.expQualityID = tSchematicResWeights.expQualityID WHERE schematicID="'
                        + schematicID +
                        '" ORDER BY expGroup, expProperty, statName;')
                    expRow = expCursor.fetchone()
                    while (expRow != None):
                        if expRow[1] != expProp:
                            if qp != None:
                                qg.properties.append(qp)
                                qp = None
                            qp = ghObjectSchematic.schematicQualityProperty(
                                expRow[1], expRow[5])
                            expProp = expRow[1]

                        if expRow[2] != expGroup:
                            if qg != None:
                                s.qualityGroups.append(qg)
                                qg = None
                            qg = ghObjectSchematic.schematicQualityGroup(
                                expRow[2])
                            expGroup = expRow[2]

                        sw = ghObjectSchematic.schematicStatWeight(
                            expRow[0], expRow[3], expRow[4], expRow[5])
                        qp.statWeights.append(sw)
                        expRow = expCursor.fetchone()
                    if qp != None:
                        qg.properties.append(qp)
                    if qg != None:
                        s.qualityGroups.append(qg)
                    expCursor.close()

                    # Get list of schematics this one can be used in
                    useCursor = conn.cursor()
                    useCursor.execute(
                        'SELECT tSchematicIngredients.schematicID, s2.schematicName FROM tSchematicIngredients INNER JOIN tSchematic ON tSchematicIngredients.ingredientObject = tSchematic.objectPath OR tSchematicIngredients.ingredientObject = tSchematic.objectGroup INNER JOIN tSchematic s2 ON tSchematicIngredients.schematicID=s2.schematicID WHERE tSchematic.schematicID = "'
                        + schematicID +
                        '" GROUP BY tSchematicIngredients.schematicID;')
                    useRow = useCursor.fetchone()
                    while (useRow != None):
                        s.schematicsUsedIn.append([useRow[0], useRow[1]])
                        useRow = useCursor.fetchone()

                    useCursor.close()

                    if logged_state > 0:
                        favCursor = conn.cursor()
                        favSQL = ''.join((
                            'SELECT itemID FROM tFavorites WHERE favType=4 AND userID="',
                            currentUser, '" AND favGroup="', schematicID,
                            '" AND galaxy=', galaxy))
                        favCursor.execute(favSQL)
                        favRow = favCursor.fetchone()
                        if favRow != None:
                            favHTML = '  <div class="inlineBlock" style="width:3%;float:left;"><a alt="Favorite" title="Favorite" style="cursor: pointer;" onclick="toggleFavorite(this, 4, \'' + schematicID + '\', $(\'#galaxySel\').val());"><img src="/images/favorite16On.png" /></a></div>'
                        else:
                            favHTML = '  <div class="inlineBlock" style="width:3%;float:left;"><a alt="Favorite" title="Favorite" style="cursor: pointer;" onclick="toggleFavorite(this, 4, \'' + schematicID + '\', $(\'#galaxySel\').val());"><img src="/images/favorite16Off.png" /></a></div>'
                        favCursor.close()

                        if admin or currentUser == s.enteredBy or (
                                s.galaxy != 0 and userReputation >=
                                ghShared.MIN_REP_VALS['EDIT_OTHER_SCHEMATIC']):
                            canEdit = True

                cursor.close()

        conn.close()

    pictureName = dbShared.getUserAttr(currentUser, 'pictureName')
    print 'Content-type: text/html\n'
    env = Environment(loader=FileSystemLoader('templates'))
    env.globals['BASE_SCRIPT_URL'] = ghShared.BASE_SCRIPT_URL
    env.globals['MOBILE_PLATFORM'] = ghShared.getMobilePlatform(
        os.environ['HTTP_USER_AGENT'])
    groupListShort = ""
    if forceOp == 'edit':
        groupListShort = ghLists.getResourceGroupListShort()
        template = env.get_template('schematiceditor.html')
    else:
        template = env.get_template('schematics.html')
    print template.render(
        uiTheme=uiTheme,
        loggedin=logged_state,
        currentUser=currentUser,
        loginResult=loginResult,
        linkappend=linkappend,
        url=url,
        pictureName=pictureName,
        imgNum=ghShared.imgNum,
        galaxyList=ghLists.getGalaxyList(),
        professionList=ghLists.getProfessionList(galaxy),
        schematicTabList=ghLists.getSchematicTabList(),
        objectTypeList=ghLists.getObjectTypeList(),
        noenergyTypeList=ghLists.getOptionList(
            'SELECT resourceType, resourceTypeName FROM tResourceType WHERE resourceCategory != "energy" ORDER BY resourceTypeName;'
        ),
        resourceGroupList=ghLists.getResourceGroupList(),
        resourceGroupListShort=groupListShort,
        statList=ghLists.getStatList(),
        schematicID=schematicID,
        schematic=s,
        favHTML=favHTML,
        canEdit=canEdit,
        profession=profession,
        canAdd=canAdd)
示例#29
0
def addResStats(spawn, resType, CR, CD, DR, FL, HR, MA, PE, OQ, SR, UT, ER,
                forceOp, userID, galaxy):
    # Update stats for a spawn
    returnStr = ""
    needStat = 0
    hasStats = 0
    resStats = [CR, CD, DR, FL, HR, MA, PE, OQ, SR, UT, ER]
    statStr = ""

    conn = dbShared.ghConn()
    cursor = conn.cursor()
    cursor.execute(
        "SELECT CR, CD, DR, FL, HR, MA, PE, OQ, SR, UT, ER, CRmax, CDmax, DRmax, FLmax, HRmax, MAmax, PEmax, OQmax, SRmax, UTmax, ERmax, tResources.resourceType, enteredBy FROM tResources INNER JOIN tResourceType ON tResources.resourceType=tResourceType.resourceType WHERE spawnID="
        + str(spawn) + ";")
    row = cursor.fetchone()
    if row != None:
        for i in range(11):
            if row[i] != None or row[i] > 0:
                statStr = ",".join((statStr, str(row[i])))
            if row[i + 11] > 0 and row[i] == None:
                needStat = 1
            if (resStats[i] > 0 and resStats[i] != "" and resStats[i] != None):
                hasStats = 1
        # override normal behavior of only updating
        # when there are no stats if forceOp is set to edit
        if ((not needStat) and forceOp != "edit"):
            returnStr = "Resource stats already entered."
        else:
            # update resource stats
            # Only allow update if user has positive reputation or was the one who entered resource
            stats = dbShared.getUserStats(userID, galaxy).split(",")
            if int(stats[2]) < ghShared.MIN_REP_VALS[
                    'EDIT_RESOURCE_STATS_TYPE'] and row[23] != userID:
                returnStr = "Error: You must earn a little reputation on the site before you can edit resources.  Try adding or verifying some first. \r\n"
            elif hasStats:
                tempSQL = "UPDATE tResources SET enteredBy='" + userID + "', CR=" + n2n(
                    CR) + ", CD=" + n2n(CD) + ", DR=" + n2n(
                        DR) + ", FL=" + n2n(FL) + ", HR=" + n2n(
                            HR) + ", MA=" + n2n(MA) + ", PE=" + n2n(
                                PE) + ", OQ=" + n2n(OQ) + ", SR=" + n2n(
                                    SR) + ", UT=" + n2n(UT) + ", ER=" + n2n(
                                        ER) + " WHERE spawnID=" + str(
                                            spawn) + ";"
                #sys.stderr.write("sql: " + tempSQL + "\n")
                cursor.execute(tempSQL)
                result = cursor.rowcount
                returnStr = "spawn " + str(spawn) + " stats updated"
                # add resource edit event
                if needStat:
                    dbShared.logEvent(
                        "INSERT INTO tResourceEvents (galaxy, spawnID, userID, eventTime, eventType) VALUES ("
                        + str(galaxy) + "," + str(spawn) + ",'" + userID +
                        "',NOW(),'a');", 'a', userID, galaxy, spawn)
                else:
                    dbShared.logEvent(
                        "INSERT INTO tResourceEvents (galaxy, spawnID, userID, eventTime, eventType, eventDetail) VALUES ("
                        + str(galaxy) + "," + str(spawn) + ",'" + userID +
                        "',NOW(),'e', 'Previous stats: " + statStr + "');",
                        'e', userID, galaxy, spawn)

        if (row[22] != resType and len(resType) > 0):
            tempSQL = "UPDATE tResources SET resourceType='" + resType + "' WHERE spawnID=" + str(
                spawn) + ";"
            cursor.execute(tempSQL)
            returnStr = returnStr + " type updated"

    else:
        returnStr = "Error: could not find that resource " + str(spawn) + "."

    cursor.close()
    conn.close()
    return returnStr
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)
示例#31
0
def getSpawnXML(spawnName, galaxy, currentUser, logged_state):
    RES_STATS = [
        'CR', 'CD', 'DR', 'FL', 'HR', 'MA', 'PE', 'OQ', 'SR', 'UT', 'ER'
    ]
    joinStr = ''
    doc = minidom.Document()
    eRoot = doc.createElement("result")
    doc.appendChild(eRoot)

    eName = doc.createElement("spawnName")
    tName = doc.createTextNode(spawnName)
    eName.appendChild(tName)
    eRoot.appendChild(eName)

    try:
        conn = dbShared.ghConn()
        cursor = conn.cursor()
    except Exception:
        result = "Error: could not connect to database"

    if logged_state == 1:
        joinStr = ''.join((
            joinStr,
            ' LEFT JOIN (SELECT itemID, favGroup, despawnAlert FROM tFavorites WHERE userID="',
            currentUser,
            '" AND favType=1) favs ON tResources.spawnID = favs.itemID'))
        favCols = ', favGroup, despawnAlert'
    else:
        favCols = ', NULL, NULL'

    if (cursor):
        spawnSQL = ''.join((
            'SELECT spawnID, tResources.resourceType, resourceTypeName, CR, CD, DR, FL, HR, MA, PE, OQ, SR, UT, ER, CRmin, CDmin, DRmin, FLmin, HRmin, MAmin, PEmin, OQmin, SRmin, UTmin, ERmin, CRmax, CDmax, DRmax, FLmax, HRmax, MAmax, PEmax, OQmax, SRmax, UTmax, ERmax, containerType, entered, enteredBy, unavailable, unavailableBy, verified, verifiedBy, (SELECT Max(concentration) FROM tWaypoint WHERE tWaypoint.spawnID=tResources.spawnID AND shareLevel=256) AS wpMaxConc',
            favCols,
            ' FROM tResources INNER JOIN tResourceType rt1 ON tResources.resourceType = rt1.resourceType',
            joinStr, ' WHERE galaxy=', galaxy, ' AND spawnName="', spawnName,
            '";'))
        cursor.execute(spawnSQL)
        row = cursor.fetchone()

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

            eSpawn = doc.createElement("spawnID")
            tSpawn = doc.createTextNode(spawnID)
            eSpawn.appendChild(tSpawn)
            eRoot.appendChild(eSpawn)

            eType = doc.createElement("resourceType")
            tType = doc.createTextNode(row[1])
            eType.appendChild(tType)
            eRoot.appendChild(eType)

            eTypeName = doc.createElement("resourceTypeName")
            tTypeName = doc.createTextNode(row[2])
            eTypeName.appendChild(tTypeName)
            eRoot.appendChild(eTypeName)

            for i in range(len(RES_STATS)):
                e = doc.createElement(RES_STATS[i])
                t = doc.createTextNode(str(row[i + 3]))
                e.appendChild(t)
                eRoot.appendChild(e)

                emin = doc.createElement(RES_STATS[i] + "min")
                tmin = doc.createTextNode(str(row[i + 14]))
                emin.appendChild(tmin)
                eRoot.appendChild(emin)

                emax = doc.createElement(RES_STATS[i] + "max")
                tmax = doc.createTextNode(str(row[i + 25]))
                emax.appendChild(tmax)
                eRoot.appendChild(emax)

            eContainer = doc.createElement("containerType")
            tContainer = doc.createTextNode(str(row[36]))
            eContainer.appendChild(tContainer)
            eRoot.appendChild(eContainer)

            eentered = doc.createElement("entered")
            tentered = doc.createTextNode(str(row[37]))
            eentered.appendChild(tentered)
            eRoot.appendChild(eentered)

            eenteredBy = doc.createElement("enteredBy")
            tenteredBy = doc.createTextNode(str(row[38]))
            eenteredBy.appendChild(tenteredBy)
            eRoot.appendChild(eenteredBy)

            if row[39] != None:
                eunavailable = doc.createElement("unavailable")
                tunavailable = doc.createTextNode(
                    row[39].strftime("%Y-%m-%d %H:%M:%S"))
                eunavailable.appendChild(tunavailable)
                eRoot.appendChild(eunavailable)

                eunavailableBy = doc.createElement("unavailableBy")
                tunavailableBy = doc.createTextNode(str(row[40]))
                eunavailableBy.appendChild(tunavailableBy)
                eRoot.appendChild(eunavailableBy)

            if row[41] != None:
                everified = doc.createElement("verified")
                tverified = doc.createTextNode(
                    row[41].strftime("%Y-%m-%d %H:%M:%S"))
                everified.appendChild(tverified)
                eRoot.appendChild(everified)

                everifiedBy = doc.createElement("verifiedBy")
                tverifiedBy = doc.createTextNode(str(row[42]))
                everifiedBy.appendChild(tverifiedBy)
                eRoot.appendChild(everifiedBy)

            if row[43] != None:
                emaxWaypointConc = doc.createElement("maxWaypointConc")
                tmaxWaypointConc = doc.createTextNode(str(row[43]))
                emaxWaypointConc.appendChild(tmaxWaypointConc)
                eRoot.appendChild(emaxWaypointConc)

            if row[44] != None:
                group = row[44]
                if group == "":
                    group = "default"
                efavGroup = doc.createElement("favoriteGroup")
                tfavGroup = doc.createTextNode(group)
                efavGroup.appendChild(tfavGroup)
                eRoot.appendChild(efavGroup)

                edespawnAlert = doc.createElement("despawnAlert")
                tdespawnAlert = doc.createTextNode(str(row[45]))
                edespawnAlert.appendChild(tdespawnAlert)
                eRoot.appendChild(edespawnAlert)

            planetsSQL = ''.join((
                'SELECT tResourcePlanet.planetID, planetName, entered, enteredBy FROM tResourcePlanet INNER JOIN tPlanet ON tResourcePlanet.planetID=tPlanet.planetID WHERE spawnID="',
                spawnID, '";'))
            cursor.execute(planetsSQL)
            row = cursor.fetchone()
            planets = ""
            planetNames = ""
            while (row != None):
                ePlanet = doc.createElement("planet")
                ePlanet.setAttribute("id", str(row[0]))
                ePlanet.setAttribute("entered",
                                     row[2].strftime("%Y-%m-%d %H:%M:%S"))
                ePlanet.setAttribute("enteredBy", str(row[3]))
                tPlanet = doc.createTextNode(row[1])
                ePlanet.appendChild(tPlanet)
                eRoot.appendChild(ePlanet)

                planets = planets + str(row[0]) + ","
                planetNames = planetNames + row[1] + ", "
                row = cursor.fetchone()

            if (len(planetNames) > 0):
                planetNames = planetNames[0:len(planetNames) - 2]

            ePlanets = doc.createElement("Planets")
            tPlanets = doc.createTextNode(planetNames)
            ePlanets.appendChild(tPlanets)
            eRoot.appendChild(ePlanets)

            result = "found"
        else:
            result = "new"
        cursor.close()
        conn.close()
    else:
        result = "Error: could not connect to database"

    eText = doc.createElement("resultText")
    tText = doc.createTextNode(result)
    eText.appendChild(tText)
    eRoot.appendChild(eText)

    eNow = doc.createElement("serverTime")
    tNow = doc.createTextNode(
        datetime.fromtimestamp(time.time()).strftime("%Y-%m-%d %H:%M:%S"))
    eNow.appendChild(tNow)
    eRoot.appendChild(eNow)

    print doc.toxml()
    return result
def updatePlanetSpawns(planetID, classID, resources, galaxyID, userID):
    result = ''
    conn = dbShared.ghConn()
    cursor = conn.cursor()
    spawnAddCount = 0
    spawnVerifyCount = 0
    spawnRemovedCount = 0
    spawnErrorCount = 0
    errors = ''

    for spawn in resources:
        # first check if spawn has been reported or not
        cursor.execute(
            "SELECT unavailable, spawnID, OQ FROM tResources WHERE galaxy=%s AND spawnName=%s;",
            [galaxyID, spawn.spawnName])
        row = cursor.fetchone()
        if row != None:
            if row[0] != None:
                # Resource was previously unavailable - bringing it back
                timeSinceRemoved = datetime.fromtimestamp(time.time()) - row[0]
                # only add back if recently but not too recently marked unavailable
                if (timeSinceRemoved.days < 3 and timeSinceRemoved.days > 0
                    ) or (timeSinceRemoved.days == 0
                          and timeSinceRemoved.seconds > 7200):
                    status = postResource.addResPlanet(row[1], planetID,
                                                       spawn.spawnName, userID,
                                                       galaxyID)
                    if (status.find("Error:") > -1):
                        spawnErrorCount += 1
                        errors = errors + status + '\n<br />'
                    else:
                        spawnAddCount += 1
            else:
                # Verify already listed resource
                status = postResource.addResPlanet(row[1], planetID,
                                                   spawn.spawnName, userID,
                                                   galaxyID)
                if row[2] == None and spawn.stats.OQ > 0:
                    status = postResource.addResStats(
                        row[1], '', spawn.stats.CR, spawn.stats.CD,
                        spawn.stats.DR, spawn.stats.FL, spawn.stats.HR,
                        spawn.stats.MA, spawn.stats.PE, spawn.stats.OQ,
                        spawn.stats.SR, spawn.stats.UT, spawn.stats.ER, '',
                        userID, galaxyID) + '  ' + status
                if (status.find("Error:") > -1):
                    spawnErrorCount += 1
                    errors = errors + status + '\n<br />'
                else:
                    spawnVerifyCount += 1
        else:
            # Post as new resource
            status = postResource.addResource(spawn.spawnName, galaxyID,
                                              spawn.resourceType,
                                              str(spawn.stats.CR),
                                              str(spawn.stats.CD),
                                              str(spawn.stats.DR),
                                              str(spawn.stats.FL),
                                              str(spawn.stats.HR),
                                              str(spawn.stats.MA),
                                              str(spawn.stats.PE),
                                              str(spawn.stats.OQ),
                                              str(spawn.stats.SR),
                                              str(spawn.stats.UT),
                                              str(spawn.stats.ER), userID)
            spawnID = dbShared.getSpawnID(spawn.spawnName, galaxyID)
            status = postResource.addResPlanet(spawnID, planetID,
                                               spawn.spawnName, userID,
                                               galaxyID) + '   ' + status
            if (status.find("Error:") > -1):
                spawnErrorCount += 1
                errors = errors + status + '\n<br />'
            else:
                spawnAddCount += 1

    # Check for resources that have despawned
    if len(resources) > 0 and classID != '' and spawnErrorCount == 0:
        cursor.execute(
            "SELECT tResources.spawnID, spawnName FROM tResources INNER JOIN tResourcePlanet ON tResources.spawnID = tResourcePlanet.spawnID INNER JOIN (SELECT resourceType FROM tResourceTypeGroup WHERE resourceGroup='"
            + classID +
            "' GROUP BY resourceType) rtg ON tResources.resourceType = rtg.resourceType WHERE tResources.galaxy=%s AND tResourcePlanet.unavailable IS NULL AND tResourcePlanet.planetID=%s;",
            [galaxyID, planetID])
        row = cursor.fetchone()
        while row != None:
            stillAvailable = False
            for spawn in resources:
                if row[1] == spawn.spawnName:
                    stillAvailable = True
            if not stillAvailable:
                # available spawn was not in report, so mark it unavailable
                status = markUnavailable.removeSpawn(row[0], planetID, userID,
                                                     galaxyID)
                if (status.find("Error:") > -1):
                    spawnErrorCount += 1
                    errors = errors + status + '\n<br />'
                else:
                    spawnRemovedCount += 1

            row = cursor.fetchone()

    cursor.close()
    conn.close()

    result = "Report Upload Complete...\n<br/>{0} Errors\n<br/>{1} Spawns Added\n<br/>{2} Spawns Verified\n<br/>{3} Spawns Removed.\n<br/>{4}".format(
        spawnErrorCount, spawnAddCount, spawnVerifyCount, spawnRemovedCount,
        errors)
    return result
示例#33
0
def main():
	resHTML = '<h2>That resource type does not exist</h2>'
	resHistory = ''
	useCookies = 1
	linkappend = ''
	logged_state = 0
	currentUser = ''
	typeGroup = 'type'
	typeID = ''
	typeName = ''
	uiTheme = ''
	# Get current url
	try:
		url = os.environ['SCRIPT_NAME']
	except KeyError:
		url = ''

	form = cgi.FieldStorage()
	# Get Cookies

	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', '')
		try:
			uiTheme = cookies['uiTheme'].value
		except KeyError:
			uiTheme = ''
	else:
		loginResult = form.getfirst('loginAttempt', '')
		sid = form.getfirst('gh_sid', '')

	# escape input to prevent sql injection
	sid = dbShared.dbInsertSafe(sid)

	# Get a session
	
	if loginResult == None:
		loginResult = 'success'

	sess = dbSession.getSession(sid, 2592000)
	if (sess != ''):
		logged_state = 1
		currentUser = sess
		if (uiTheme == ''):
			uiTheme = dbShared.getUserAttr(currentUser, 'themeName')
		if (useCookies == 0):
			linkappend = 'gh_sid=' + sid
	else:
		if (uiTheme == ''):
			uiTheme = 'crafter'

	path = ['']
	if os.environ.has_key('PATH_INFO'):
		path = os.environ['PATH_INFO'].split('/')[1:]
		path = [p for p in path if p != '']

	if path[0] != '':
		typeID = dbShared.dbInsertSafe(path[0])

		try:
			conn = dbShared.ghConn()
			cursor = conn.cursor()
		except Exception:
			errorstr = "Error: could not connect to database"

		if (cursor):
			cursor.execute('SELECT resourceTypeName, rg1.groupName, rg2.groupName, rt.containerType, CRmin, CRmax, CDmin, CDmax, DRmin, DRmax, FLmin, FLmax, HRmin, HRmax, MAmin, MAmax, PEmin, PEmax, OQmin, OQmax, SRmin, SRmax, UTmin, UTmax, ERmin, ERmax, rt.resourceCategory, rt.resourceGroup FROM tResourceType rt INNER JOIN tResourceGroup rg1 ON rt.resourceCategory = rg1.resourceGroup INNER JOIN tResourceGroup rg2 ON rt.resourceGroup = rg2.resourceGroup WHERE resourceType="' + typeID + '";')
			row = cursor.fetchone()
			if (row != None):
				typeName = row[0]
			else:
				# look up group info if not found as a type
				typeGroup = 'group'
				cursor.execute('SELECT groupName, (SELECT rg.groupName FROM tResourceGroupCategory rgc INNER JOIN tResourceGroup rg ON rgc.resourceCategory = rg.resourceGroup WHERE rgc.resourceGroup=tResourceGroup.resourceGroup AND rg.groupLevel = tResourceGroup.groupLevel -1) AS resCat, "" AS resourceGroup, Max(tResourceType.containerType) AS contType, Min(CRmin), Max(CRmax), Min(CDmin), Max(CDmax), Min(DRmin), Max(DRmax), Min(FLmin), Max(FLmax), Min(HRmin), Max(HRmax), Min(MAmin), Max(MAmax), Min(PEmin), Max(PEmax), Min(OQmin), Max(OQmax), Min(SRmin), Max(SRmax), Min(UTmin), Max(UTmax), Min(ERmin), Max(ERmax), (SELECT rgc.resourceCategory FROM tResourceGroupCategory rgc INNER JOIN tResourceGroup rg ON rgc.resourceCategory = rg.resourceGroup WHERE rgc.resourceGroup=tResourceGroup.resourceGroup AND rg.groupLevel = tResourceGroup.groupLevel -1) AS catID FROM tResourceGroup, tResourceType WHERE tResourceGroup.resourceGroup="' + typeID + '" AND tResourceType.resourceType IN (SELECT resourceType FROM tResourceTypeGroup WHERE resourceGroup="' + typeID + '" GROUP BY resourceType);')
				row = cursor.fetchone()
				if (row != None):
					typeName = row[0]
				else:
					typeGroup = ''

			if typeName != '' and typeName != None:
				resHTML = '<div style="font-size:16px;font-weight:bold;">' + typeName
				if row != None and row[3] != None:
					if row[1] != typeName:
						resHTML += '<div style="float:right;"><img src="/images/resources/'+row[3]+'.png" /></div></div>'
					else:
						resHTML += '</div>'
					# breadcrumb to resource type if not top level category
					if row[1] != typeName:
						resHTML += '<h3 style="margin-bottom:12px;">'
						if row[26] != 'resource':
							resHTML += '<a href="' + ghShared.BASE_SCRIPT_URL + 'resourceType.py/' + row[26] + '">' + row[1] + '</a>'
						else:
							resHTML += row[1]
						if typeGroup == 'type':
							resHTML += ' > <a href="' + ghShared.BASE_SCRIPT_URL + 'resourceType.py/' + row[27] + '">' + row[2] + '</a>'
						resHTML += ' > ' + typeName + '</h3>'
					# min/max stats table
					resHTML += '<table class="resAttr resourceStats"><tr>'
					resHTML += '<td><td class="header"><span>CR</span></td><td class="header"><span>CD</span></td><td class="header"><span>DR</span></td><td class="header"><span>FL</span></td><td class="header"><span>HR</span></td><td class="header"><span>MA</span></td><td class="header"><span>PE</span></td><td class="header"><span>OQ</span></td><td class="header"><span>SR</span></td><td class="header"><span>UT</span></td><td class="header"><span>ER</span></td></tr>'
					resHTML += '<tr><td class="header">Min</td><td>' + z2b(row[4]) + '</td><td>' + z2b(row[6]) + '</td><td>' + z2b(row[8]) + '</td><td>' + z2b(row[10]) + '</td><td>' + z2b(row[12]) + '</td><td>' + z2b(row[14]) + '</td><td>' + z2b(row[16]) + '</td><td>' + z2b(row[18]) + '</td><td>' + z2b(row[20]) + '</td><td>' + z2b(row[22]) + '</td><td>' + z2b(row[24]) + '</td></tr>'
					resHTML += '<tr><td class="header">Max</td><td>' + z2b(row[5]) + '</td><td>' + z2b(row[7]) + '</td><td>' + z2b(row[9]) + '</td><td>' + z2b(row[11]) + '</td><td>' + z2b(row[13]) + '</td><td>' + z2b(row[15]) + '</td><td>' + z2b(row[17]) + '</td><td>' + z2b(row[19]) + '</td><td>' + z2b(row[21]) + '</td><td>' + z2b(row[23]) + '</td><td>' + z2b(row[25]) + '</td></tr>'
					resHTML += '</table>'
				else:
					resHTML += '</div>'

			cursor.close()
		conn.close()
	else:
		resHTML = '<h1>Resource Type Groups</h1>'
		resHTML += '<div id="resTypeInfo">You have reached the resource type page.  From here, you can browse to any resource type and view things like: best spawns, schematics, creatures, and min/max stats.</div>'

	creature = max([typeID.find('bone_'), typeID.find('hide_'), typeID.find('meat_')])
	if typeID == '':
		# Print the plain group list for pre-IE9 because it does not support rotate css
		tmpAgent = os.environ.get("HTTP_USER_AGENT", "unknown")
		if tmpAgent == 'unknown' or (tmpAgent.find("IE") > -1 and tmpAgent.find("MSIE 9.0") == -1):
			resTree = getResourceGroupsPlain()
		else:
			resTree = getResourceTree()
	else:
		resTree = ''
	pictureName = dbShared.getUserAttr(currentUser, 'pictureName')
	print 'Content-type: text/html\n'
	env = Environment(loader=FileSystemLoader('templates'))
	env.globals['BASE_SCRIPT_URL'] = ghShared.BASE_SCRIPT_URL
	template = env.get_template('resourcetype.html')
	print template.render(uiTheme=uiTheme, loggedin=logged_state, currentUser=currentUser, loginResult=loginResult, linkappend=linkappend, url=url, pictureName=pictureName, imgNum=ghShared.imgNum, galaxyList=ghLists.getGalaxyList(), typeGroup=typeGroup, typeID=typeID, resHTML=resHTML, creature=creature, resTree=resTree)
示例#34
0
def main():
	resHTML = '<h2>That resource does not exist</h2>'
	resHistory = ''
	useCookies = 1
	linkappend = ''
	logged_state = 0
	currentUser = ''
	galaxy = ''
	spawnName = ''
	spawnID = 0
	uiTheme = ''
	galaxyState = 0
	userReputation = 0
	admin = False
	# Get current url
	try:
		url = os.environ['SCRIPT_NAME']
	except KeyError:
		url = ''

	form = cgi.FieldStorage()
	# Get Cookies

	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', '')
		try:
			uiTheme = cookies['uiTheme'].value
		except KeyError:
			uiTheme = ''
	else:
		loginResult = form.getfirst('loginAttempt', '')
		sid = form.getfirst('gh_sid', '')

	# escape input to prevent sql injection
	sid = dbShared.dbInsertSafe(sid)

	# Get a session

	if loginResult == None:
		loginResult = 'success'

	sess = dbSession.getSession(sid)
	if (sess != ''):
		logged_state = 1
		currentUser = sess
		if (uiTheme == ''):
			uiTheme = dbShared.getUserAttr(currentUser, 'themeName')
		if (useCookies == 0):
			linkappend = 'gh_sid=' + sid
	else:
		if (uiTheme == ''):
			uiTheme = 'crafter'

	path = ['']
	if os.environ.has_key('PATH_INFO'):
		path = os.environ['PATH_INFO'].split('/')[1:]
		path = [p for p in path if p != '']

	if len(path) > 1:
		galaxy = dbShared.dbInsertSafe(path[0])
		spawnName = dbShared.dbInsertSafe(path[1])
		if galaxy != '':
			conn = dbShared.ghConn()
			spawn = getResource(conn, logged_state, currentUser, None, galaxy, spawnName)
			if spawn != None:
				spawnID = spawn.spawnID
				galaxyState = dbShared.galaxyState(spawn.spawnGalaxy)
				# Only show update tools if user logged in and has positive reputation
				stats = dbShared.getUserStats(currentUser, galaxy).split(",")
				userReputation = int(stats[2])
				admin = dbShared.getUserAdmin(conn, currentUser, galaxy)

				if logged_state > 0 and galaxyState == 1:
					controlsUser = currentUser
				else:
					controlsUser = ''

				resHTML = spawn.getHTML(0, "", controlsUser, userReputation, admin)

				resHistory = getResourceHistory(conn, spawn.spawnID)
			conn.close()
		else:
			resHTML = '<h2>No Galaxy/Resource name given</h2>'
	else:
		resHTML = '<h2>No Galaxy/Resource name given</h2>'

	pictureName = dbShared.getUserAttr(currentUser, 'pictureName')

	print 'Content-type: text/html\n'
	env = Environment(loader=FileSystemLoader('templates'))
	env.globals['BASE_SCRIPT_URL'] = ghShared.BASE_SCRIPT_URL
	env.globals['MOBILE_PLATFORM'] = ghShared.getMobilePlatform(os.environ['HTTP_USER_AGENT'])
	template = env.get_template('resource.html')
	print template.render(uiTheme=uiTheme, loggedin=logged_state, currentUser=currentUser, loginResult=loginResult, linkappend=linkappend, url=url, pictureName=pictureName, imgNum=ghShared.imgNum, galaxyList=ghLists.getGalaxyList(), spawnName=spawnName, resHTML=resHTML, resHistory=resHistory, showAdmin=(userReputation >= ghShared.MIN_REP_VALS['EDIT_RESOURCE_GALAXY_NAME'] or admin), spawnID=spawnID, spawnGalaxy=galaxy)
示例#35
0
def renderFeed(path):
	newest = dbShared.getLastResourceChange()
	resTitles = ['CR', 'CD', 'DR', 'FL', 'HR', 'MA', 'PE', 'OQ', 'SR', 'UT', 'ER']
	rfc822time = "%a, %d %b %Y %H:%M:%S -0800"
	print "Content-Type: text/xml; charset=iso-8859-15\n"
	print "<?xml version=\"1.0\" encoding=\"iso-8859-15\"?>"
	print "<rss version=\"2.0\""
	print "xmlns:content=\"http://purl.org/rss/1.0/modules/content/\""
	print ">"
	print "<channel>"
	resGroup = ""
	if len(path) >= 1:
		if (path[0] == "creature"):
			resGroup = "creature_resources"
		elif (path[0] == "flora"):
			resGroup = "flora_resources"
		elif (path[0] == "chemical"):
			resGroup = "chemical"
		elif (path[0] == "water"):
			resGroup = "water"
		elif (path[0] == "mineral"):
			resGroup = "mineral"
		elif (path[0] == "gas"):
			resGroup = "gas"
		elif (path[0] == "energy"):
			resGroup = "energy_renewable"
	if resGroup != "":
		print "<title>Galaxy Harvester Resource Activity: " + resGroup + "</title>"
	else:
		print "<title>Galaxy Harvester Resource Activity</title>"
	print "<link>http://gh.apex-games.net</link>"
	print "<description>Latest additions to Galaxy Harvester resource listing</description>"
	print "<pubDate>" + newest.strftime(rfc822time) + "</pubDate>"
	print "<lastBuildDate>" + newest.strftime(rfc822time) + "</lastBuildDate>"
	print "<generator>http://galaxyharvester.net/resourceList.py</generator>"
	print "<language>en</language>"

	# print resources
	conn = dbShared.ghConn()
	cursor = conn.cursor()
	criteriaStr = " WHERE unavailable IS NULL"
	if (cursor):
		if (resGroup != "any" and resGroup != ""):
			criteriaStr = criteriaStr + " AND tResourceType.resourceType IN (SELECT resourceType FROM tResourceTypeGroup WHERE resourceGroup='" + resGroup + "' GROUP BY resourceType)"
		sqlStr1 = 'SELECT spawnID, spawnName, galaxy, entered, enteredBy, tResources.resourceType, resourceTypeName, resourceGroup,'
		sqlStr1 += ' CR, CD, DR, FL, HR, MA, PE, OQ, SR, UT, ER,'
		sqlStr1 += ' CASE WHEN CRmax > 0 THEN ((CR-CRmin) / (CRmax-CRmin))*100 ELSE 0 END AS CRperc, CASE WHEN CDmax > 0 THEN ((CD-CDmin) / (CDmax-CDmin))*100 ELSE 0 END AS CDperc, CASE WHEN DRmax > 0 THEN ((DR-DRmin) / (DRmax-DRmin))*100 ELSE 0 END AS DRperc, CASE WHEN FLmax > 0 THEN ((FL-FLmin) / (FLmax-FLmin))*100 ELSE 0 END AS FLperc, CASE WHEN HRmax > 0 THEN ((HR-HRmin) / (HRmax-HRmin))*100 ELSE 0 END AS HRperc, CASE WHEN MAmax > 0 THEN ((MA-MAmin) / (MAmax-MAmin))*100 ELSE 0 END AS MAperc, CASE WHEN PEmax > 0 THEN ((PE-PEmin) / (PEmax-PEmin))*100 ELSE 0 END AS PEperc, CASE WHEN OQmax > 0 THEN ((OQ-OQmin) / (OQmax-OQmin))*100 ELSE 0 END AS OQperc, CASE WHEN SRmax > 0 THEN ((SR-SRmin) / (SRmax-SRmin))*100 ELSE 0 END AS SRperc, CASE WHEN UTmax > 0 THEN ((UT-UTmin) / (UTmax-UTmin))*100 ELSE 0 END AS UTperc, CASE WHEN ERmax > 0 THEN ((ER-ERmin) / (ERmax-ERmin))*100 ELSE 0 END AS ERperc,'
		sqlStr1 += ' galaxyName FROM tResources INNER JOIN tResourceType ON tResources.resourceType = tResourceType.resourceType INNER JOIN tGalaxy ON tResources.galaxy = tGalaxy.galaxyID'
		sqlStr1 = sqlStr1 + criteriaStr + ' ORDER BY entered DESC LIMIT 25;'
		cursor.execute(sqlStr1)
		row = cursor.fetchone()
		while (row != None):
			print "<item>"
			print "<title>" + row[1] + " Added by " + row[4] + " on " + row[30] + "</title>"
			print "<link>http://galaxyharvester.net/resource.py/" + str(row[2]) + "/" + row[1] + "</link>"
			print "<pubDate>" + row[3].strftime(rfc822time) + "</pubDate>"
			print "<guid isPermalink=\"true\">http://galaxyharvester.net/resource.py/" + str(row[2]) + "/" + row[1] + "</guid>"
			print "<description><![CDATA[ " + row[6] + " ]]></description>"
			print "<content:encoded><![CDATA["
			print "<br />" + row[6] + "<br />"
			for i in range(11):
				if (row[i+8] != None and row[i+19] != None):
					print resTitles[i] + ": " + str(row[i+8]) + " (" + ("%.0f" % float(row[i+19])) + "%)<br />",
			print "]]></content:encoded>"
			print "</item>"
			row = cursor.fetchone()

	print "</channel>"
	print "</rss>"
示例#36
0
def main():
	useCookies = 1
	linkappend = ''
	logged_state = 0
	currentUser = ''
	msgHTML = ''
	galaxy = ''
	uiTheme = ''
	galaxyName = ''
	galaxyState = 0
	galaxyCheckedNGE = ''
	galaxyWebsite = ''
	galaxyAdminList = []
	galaxyPlanetList = []
	availablePlanetList = []
	galaxyAdmins = []
	# Get current url
	try:
		url = os.environ['SCRIPT_NAME']
	except KeyError:
		url = ''

	form = cgi.FieldStorage()
	# Get Cookies

	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', '')
		try:
			uiTheme = cookies['uiTheme'].value
		except KeyError:
			uiTheme = ''
	else:
		loginResult = form.getfirst('loginAttempt', '')
		sid = form.getfirst('gh_sid', '')

	# escape input to prevent sql injection
	sid = dbShared.dbInsertSafe(sid)

	# Get a session

	if loginResult == None:
		loginResult = 'success'

	sess = dbSession.getSession(sid)
	if (sess != ''):
		logged_state = 1
		currentUser = sess
		if (uiTheme == ''):
			uiTheme = dbShared.getUserAttr(currentUser, 'themeName')
		if (useCookies == 0):
			linkappend = 'gh_sid=' + sid
	else:
		if (uiTheme == ''):
			uiTheme = 'crafter'

	path = ['']
	if os.environ.has_key('PATH_INFO'):
		path = os.environ['PATH_INFO'].split('/')[1:]
		path = [p for p in path if p != '']

	if len(path) > 0:
		galaxy = dbShared.dbInsertSafe(path[0])
		conn = dbShared.ghConn()
		galaxyAdminList = dbShared.getGalaxyAdminList(conn, currentUser)
		availablePlanetList = getPlanetList(conn, galaxy, 1)
		if galaxy.isdigit():
			# get the galaxy details for edit
			galaxyCursor = conn.cursor()
			galaxyCursor.execute('SELECT galaxyName, galaxyState, galaxyNGE, website FROM tGalaxy WHERE galaxyID={0};'.format(galaxy))
			galaxyRow = galaxyCursor.fetchone()
			if galaxyRow != None:
				galaxyName = galaxyRow[0]
				galaxyState = galaxyRow[1]
				if galaxyRow[2] > 0:
					galaxyCheckedNGE = 'checked'
				galaxyWebsite = galaxyRow[3]
			galaxyCursor.close()
			galaxyPlanetList = getPlanetList(conn, galaxy, 0)
			galaxyAdmins = dbShared.getGalaxyAdmins(conn, galaxy)
			conn.close()
		else:
			galaxyAdmins = [currentUser]
			msgHTML = '<h2>Please enter galaxy details for review.</h2>'
	else:
		msgHTML = '<h2>No Galaxy found in URL path.</h2>'

	pictureName = dbShared.getUserAttr(currentUser, 'pictureName')
	print 'Content-type: text/html\n'
	env = Environment(loader=FileSystemLoader('templates'))
	env.globals['BASE_SCRIPT_URL'] = ghShared.BASE_SCRIPT_URL
	env.globals['MOBILE_PLATFORM'] = ghShared.getMobilePlatform(os.environ['HTTP_USER_AGENT'])
	template = env.get_template('galaxy.html')
	print template.render(uiTheme=uiTheme, loggedin=logged_state, currentUser=currentUser, pictureName=pictureName, loginResult=loginResult, linkappend=linkappend, url=url, imgNum=ghShared.imgNum, galaxyID=galaxy, galaxyList=ghLists.getGalaxyList(), msgHTML=msgHTML, galaxyName=galaxyName, galaxyState=galaxyState, galaxyCheckedNGE=galaxyCheckedNGE, galaxyWebsite=galaxyWebsite, galaxyStatusList=ghLists.getGalaxyStatusList(), galaxyPlanetList=galaxyPlanetList, availablePlanetList=availablePlanetList, galaxyAdminList=galaxyAdminList, galaxyAdmins=galaxyAdmins, enableCAPTCHA=ghShared.RECAPTCHA_ENABLED, siteidCAPTCHA=ghShared.RECAPTCHA_SITEID)
# escape input to prevent sql injection
resGroup = dbShared.dbInsertSafe(resGroup)
outType = dbShared.dbInsertSafe(outType)

print 'Content-type: text/html\n'
if outType == 'links':
	print '<ul class="plain">'
else:
	print '<option value="none" title="p00000000000">None</option>'

if len(resGroup) > 0:
	criteriaStr = ' AND (resourceGroup = "' + resGroup + '" OR resourceCategory = "' + resGroup + '")'
else:
	criteriaStr = ''

conn = dbShared.ghConn()
cursor = conn.cursor()
if (cursor):
	cursor.execute('SELECT resourceType, resourceTypeName, CONCAT("p", CASE WHEN CRmax>0 THEN "1" ELSE "0" END, CASE WHEN CDmax>0 THEN "1" ELSE "0" END, CASE WHEN DRmax>0 THEN "1" ELSE "0" END, CASE WHEN FLmax>0 THEN "1" ELSE "0" END, CASE WHEN HRmax>0 THEN "1" ELSE "0" END, CASE WHEN MAmax>0 THEN "1" ELSE "0" END, CASE WHEN PEmax>0 THEN "1" ELSE "0" END, CASE WHEN OQmax>0 THEN "1" ELSE "0" END, CASE WHEN SRmax>0 THEN "1" ELSE "0" END, CASE WHEN UTmax>0 THEN "1" ELSE "0" END, CASE WHEN ERmax>0 THEN "1" ELSE "0" END) AS statMask FROM tResourceType WHERE enterable>0' + criteriaStr + ' ORDER BY resourceTypeName;')
	row = cursor.fetchone()
	if row == None and len(resGroup) > 0:
		cursor.execute('select rgc.resourceGroup, rg.groupName, "p11111111111" AS statMask  FROM tResourceGroupCategory rgc INNER JOIN tResourceGroup rg ON rgc.resourceGroup = rg.resourceGroup WHERE rgc.resourceCategory="' + resGroup + '";')
		row = cursor.fetchone()

	while (row != None):
		if outType == 'links':
			print '<li><a href="' + ghShared.BASE_SCRIPT_URL + 'resourceType.py/' + row[0] + '">' + row[1] + '</a></li>'
		else:
			print '<option value="'+str(row[0])+'" title="'+row[2]+'">'+row[1]+'</option>'
		row = cursor.fetchone()
示例#38
0
def main():
	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:
			sid = cookies['gh_sid'].value
		except KeyError:
			sid = form.getfirst('gh_sid', '')
	else:
		currentUser = ''
		sid = form.getfirst('gh_sid', '')

	listFormat = form.getfirst('listFormat', '')
	listType = form.getfirst('listType', '')
	galaxy = form.getfirst('galaxy', '')
	profession = form.getfirst('profession', '')

	# Get a session
	logged_state = 0

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

	# Main program
	errstr = ''
	tmpStr = ''

	if not galaxy.isdigit():
		errstr = 'Error: You must provide a valid galaxy id.'
	if profession != '' and not profession.isdigit():
		errstr = 'Error: That is not a valid profession id.'
	if logged_state != 1:
		errstr = 'Error: You must be logged in to get your recipe list.'

	conn = dbShared.ghConn()
	cursor = conn.cursor()
	if (cursor and errstr == ''):
		headStr = '<table width="100%">'
		if listType == 'suggest':
			rl = getSuggestedRecipes(conn, currentUser, galaxy, profession)
			if len(rl) > 0:
				for r in rl:
					tmpStr += r.getRow(listType)
			else:
				tmpStr = '<tr><td>No suggestions at this time.  Try adding more to your inventory.</td></tr>'
		else:
			sqlStr = 'SELECT recipeID, userID, schematicID, recipeName, (SELECT imageName FROM tSchematicImages img WHERE img.schematicID=tRecipe.schematicID AND img.imageType=1) AS schemImage FROM tRecipe WHERE userID="' + currentUser + '" ORDER BY recipeName;'
			cursor.execute(sqlStr)
			row = cursor.fetchone()

			while (row != None):
				if (row[4] != None):
					schemImageName = row[4]
				else:
					schemImageName = 'none.jpg'
				r = ghObjectRecipe.schematicRecipe()
				r.recipeID = row[0]
				r.schematicID = row[2]
				r.recipeName = row[3]
				r.schematicImage = schemImageName
				sqlStr = 'SELECT si.ingredientName, ingredientResource, ingredientObject, ingredientContribution, ingredientQuality FROM tSchematicIngredients si LEFT JOIN (SELECT ingredientName, ingredientResource, ingredientQuality FROM tRecipeIngredients WHERE recipeID=' + str(r.recipeID) + ') ri ON si.ingredientName = ri.ingredientName WHERE schematicID="' + r.schematicID + '" and ingredientType = 0 ORDER BY ingredientQuantity DESC, si.ingredientName;'
				ingCursor = conn.cursor()
				ingCursor.execute(sqlStr)
				ingRow = ingCursor.fetchone()
				while (ingRow != None):
					ri = ghObjectRecipe.recipeIngredient()
					ri.ingredientObject = ingRow[2]
					ri.ingredientResource = ingRow[1]
					ri.ingredientName = ingRow[0]
					ri.ingredientAmount = ingRow[3]
					ri.resourceQuality = ingRow[4]
					r.recipeIngredients.append(ri)
					ingRow = ingCursor.fetchone()

				ingCursor.close()
				tmpStr += r.getRow('normal',sid)

				row = cursor.fetchone()

		tmpStr = headStr + tmpStr + '</table>'

		cursor.close()
	conn.close()

	print 'Content-type: text/html\n'
	print tmpStr