Esempio n. 1
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(",")
			admin = dbShared.getUserAdmin(conn, userID, galaxy)
			if int(stats[2]) < ghShared.MIN_REP_VALS['EDIT_RESOURCE_STATS_TYPE'] and row[23] != userID and not admin:
				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 removeSpawn(spawnID, planets, userID, galaxy):
	markAll = 0
	try:
		conn = dbShared.ghConn()
		cursor = conn.cursor()
	except Exception:
		result = "Error: could not connect to database"

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

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

			# add cleanup event
			if not planets.isdigit():
				planets = 0
			dbShared.logEvent("INSERT INTO tResourceEvents (galaxy, spawnID, userID, eventTime, eventType, planetID) VALUES (" + str(galaxy) + "," + str(spawnID) + ",'" + userID + "',NOW(),'r'," + str(planets) + ");", 'r', userID, galaxy, str(spawnID))
			result = "Spawn marked unavailable."
		cursor.close()
	else:
		result = "Error: Could not connect to database"
	conn.close()
	
	return result
def getResourceData(conn, resSQL, logged_state, galaxyState, resourceFormat,
                    reputation):
    # get resource data for given criteria
    resourceHTML = '<table width="100%" class=resourceStats>'
    cursor = conn.cursor()

    if (cursor):
        cursor.execute(resSQL)
        row = cursor.fetchone()
        # check first row to see if all quality stats do not belong to resource type
        if (row != None):
            if (row[35] == 0):
                resourceHTML += '<tr><td>Stats do not matter</td></tr>'
            else:
                # print resource rows if stats matter
                while (row != None):
                    s = ghObjects.resourceSpawn()
                    s.spawnID = row[0]
                    s.spawnName = row[1]
                    s.spawnGalaxy = row[2]
                    s.resourceType = row[5]
                    s.resourceTypeName = row[6]
                    s.containerType = row[30]
                    s.stats.CR = row[8]
                    s.stats.CD = row[9]
                    s.stats.DR = row[10]
                    s.stats.FL = row[11]
                    s.stats.HR = row[12]
                    s.stats.MA = row[13]
                    s.stats.PE = row[14]
                    s.stats.OQ = row[15]
                    s.stats.SR = row[16]
                    s.stats.UT = row[17]
                    s.stats.ER = row[18]

                    s.percentStats.CR = row[19]
                    s.percentStats.CD = row[20]
                    s.percentStats.DR = row[21]
                    s.percentStats.FL = row[22]
                    s.percentStats.HR = row[23]
                    s.percentStats.MA = row[24]
                    s.percentStats.PE = row[25]
                    s.percentStats.OQ = row[26]
                    s.percentStats.SR = row[27]
                    s.percentStats.UT = row[28]
                    s.percentStats.ER = row[29]

                    s.entered = row[3]
                    s.enteredBy = row[4]
                    s.verified = row[31]
                    s.verifiedBy = row[32]
                    s.unavailable = row[33]
                    s.unavailableBy = row[34]
                    if row[36] != None:
                        s.favorite = 1
                    if row[37] != None:
                        s.overallScore = row[37] * 1000
                    s.planets = dbShared.getSpawnPlanets(
                        conn, row[0], True, row[2])

                    resourceHTML += '  <tr><td>'
                    if logged_state > 0 and galaxyState == 1:
                        controlsUser = currentUser
                    else:
                        controlsUser = ''
                    resourceHTML += s.getHTML(
                        resourceFormat, "", controlsUser, reputation,
                        dbShared.getUserAdmin(conn, currentUser, galaxy))
                    resourceHTML += '  </td></tr>'
                    row = cursor.fetchone()
        else:
            resourceHTML += '<tr><td>Not Available</td></tr>'
        cursor.close()
    resourceHTML += '</table>'
    return resourceHTML
sess = dbSession.getSession(sid)
if (sess != ''):
	logged_state = 1
	currentUser = sess

userReputation = -9999
# Validation
errstr = ''
result = ''
if logged_state == 1:
	# Lookup reputation to validate abilities
	conn = dbShared.ghConn()
	stats = dbShared.getUserStats(currentUser, galaxy).split(",")
	userReputation = int(stats[2])
	admin = dbShared.getUserAdmin(conn, currentUser, galaxy)
else:
	errstr = 'You must be logged in to add schematic data.'

if forceOp == 'edit':
	if len(schematicID) < 3:
		errstr = errstr + 'Error: Schematic ID must be provided to edit.'
else:
	if profession.isdigit() == False:
		errstr = errstr + 'Error: Profession ID must be provided to add a new schematic.'
	if len(skillGroup) < 3:
		errstr = errstr + 'Error: Skill Group must be provided to add a new schematic.'
	if userReputation < ghShared.MIN_REP_VALS['ADD_SCHEMATIC'] and not admin:
		errstr = errstr + 'Error: You have not yet built enough reputation to add schematic data.'
	if galaxy.isdigit() == False or len(galaxy) > 5:
		errstr = errstr + 'Error: A valid numeric galaxy id must be provided to add the new schematic to.'
            if (cursor):
                cursor.execute(
                    'SELECT enteredBy FROM tResourceTypeCreature WHERE resourceType=%s AND speciesName=%s AND galaxy=%s;',
                    (resourceType, creatureName, galaxy))
                row = cursor.fetchone()

                if (row != None):
                    owner = row[0]
                else:
                    owner = ''

                cursor.close()

                # edit it
                if owner == currentUser or userReputation >= ghShared.MIN_REP_VALS[
                        'EDIT_OTHER_CREATURE'] or dbShared.getUserAdmin(
                            conn, currentUser, galaxy):
                    result = "edit: "
                    result = result + updateCreature(
                        conn, resourceType, creatureName, harvestYield,
                        missionLevel, galaxy)
                else:
                    result = "Error: You do not yet have permission to edit others' creature data."
            else:
                result = "Error: No database connection"

        else:
            if userReputation >= ghShared.MIN_REP_VALS[
                    'ADD_CREATURE'] or dbShared.getUserAdmin(
                        conn, currentUser, galaxy):
                result = addCreature(conn, resourceType, creatureName,
                                     harvestYield, missionLevel, galaxy)
Esempio n. 6
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)
Esempio n. 7
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)
Esempio n. 8
0
def getResourceData(conn, resSQL, userReputation, activeUser, formatType):
    # get resource data for given criteria
    resourceHTML = ''
    s = None

    cursor = conn.cursor()
    if (cursor):
        lastValue = None
        cursor.execute(resSQL)
        row = cursor.fetchone()
        if row == None:
            resourceHTML = 'No resources found!'
        while (row != None):
            if s == None:
                if formatType == 'json':
                    resourceHTML = '  [\n'
                else:
                    resourceHTML = '<table width="100%" class=resourceStats>'

            # populate this resource to object and print it
            s = ghObjects.resourceSpawn()
            s.spawnID = row[0]
            s.spawnName = row[1]
            s.spawnGalaxy = row[2]
            s.resourceType = row[5]
            s.resourceTypeName = row[6]
            s.containerType = row[30]
            s.stats.CR = row[8]
            s.stats.CD = row[9]
            s.stats.DR = row[10]
            s.stats.FL = row[11]
            s.stats.HR = row[12]
            s.stats.MA = row[13]
            s.stats.PE = row[14]
            s.stats.OQ = row[15]
            s.stats.SR = row[16]
            s.stats.UT = row[17]
            s.stats.ER = row[18]

            s.percentStats.CR = row[19]
            s.percentStats.CD = row[20]
            s.percentStats.DR = row[21]
            s.percentStats.FL = row[22]
            s.percentStats.HR = row[23]
            s.percentStats.MA = row[24]
            s.percentStats.PE = row[25]
            s.percentStats.OQ = row[26]
            s.percentStats.SR = row[27]
            s.percentStats.UT = row[28]
            s.percentStats.ER = row[29]

            s.entered = row[3]
            s.enteredBy = row[4]
            s.verified = row[31]
            s.verifiedBy = row[32]
            s.unavailable = row[33]
            s.unavailableBy = row[34]
            s.maxWaypointConc = row[39]
            if row[40] != None:
                s.favorite = 1
                s.despawnAlert = row[41]
            if row[42] != None:
                s.units = row[42]
            if sort == "quality":
                s.overallScore = row[43]
            s.planets = dbShared.getSpawnPlanets(conn, row[0], False, row[2])

            if formatType == 'json':
                resourceHTML += '    {'
            else:
                resourceHTML += '  <tr><td>'

            if formatType == 'mobile':
                resourceHTML += s.getMobileHTML(
                    activeUser, userReputation,
                    dbShared.getUserAdmin(conn, currentUser, galaxy))
            elif formatType == 'compare':
                resourceHTML += s.getHTML(
                    1, '', activeUser, userReputation,
                    dbShared.getUserAdmin(conn, currentUser, galaxy))
            elif formatType == 'json':
                resourceHTML += s.getJSON()
            else:
                resourceHTML += s.getHTML(
                    0, '', activeUser, userReputation,
                    dbShared.getUserAdmin(conn, currentUser, galaxy))

            if formatType == 'json':
                resourceHTML += '    }'
            else:
                resourceHTML += '</td></tr>'

            lastValue = row[42]

            row = cursor.fetchone()

            if formatType == 'json':
                resourceHTML += '  ,\n'
            else:
                resourceHTML += '  </table>'

        if fetchSize.isdigit() and cursor.rowcount == int(fetchSize):
            if formatType == 'json':
                resourceHTML += '],\n  "last_value" : ' + str(lastValue)
            else:
                resourceHTML += '<div style="display:none;">maxRowsReached' + str(
                    lastValue) + '</div>'

        cursor.close()
    return resourceHTML
Esempio n. 9
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)