Ejemplo n.º 1
0
def AddUser(conf,inputs,outputs):
    if is_connected(conf):
        c = auth.getCon(conf)
        prefix=auth.getPrefix(conf)
        if c.is_admin(conf["senv"]["login"]):
            try:
                user = json.loads(inputs["user"]["value"])
            except Exception,e:
                print >> sys.stderr,inputs["user"]["value"]
                print >> sys.stderr,e
                conf["lenv"]["message"] = zoo._("invalid user parameter: ")+inputs["user"]["value"]
                return 4
            for (i,j) in user.items():
                if i!="phone" and not manage_users.check_user_params(i,j):
                    conf["lenv"]["message"] = 'Parametre %s incorrect'%(i)
                    return 4
            if c.add_user(user):
                outputs["Result"]["value"] = zoo._("User successfully inserted")
                #outputs["Result"]["value"] = inputs["user"]["value"]
                if inputs.has_key("group"):
                    if inputs["group"].has_key("length"):
                        for i in range(0,len(inputs["group"]["value"])):
                            linkGroupToUser(conf,c,prefix,inputs["group"]["value"][i],user["login"])
                    else:
                        linkGroupToUser(conf,c,prefix,inputs["group"]["value"],user["login"])
                return 3
            else:
                conf["lenv"]["message"] = zoo._("SQL Error")
                return 4
        else:
            conf["lenv"]["message"]= zoo._("Action not permited")
            return 4
Ejemplo n.º 2
0
def addColumn(conf,inputs,outputs):
    print >> sys.stderr,inputs["dataStore"]["value"]
    db=pgConnection(conf,inputs["dataStore"]["value"])
    db.parseConf()
    req=[]
    if db.connect():
        if inputs["field_type"]["value"]!="18":
            req+=["ALTER TABLE quote_ident("+inputs["table"]["value"]+") ADD COLUMN "+inputs["field_name"]["value"]+" "+fetchType(conf,inputs["field_type"]["value"])]
            outputs["Result"]["value"]=zoo._("Column added")
        else:
            tblInfo=inputs["table"]["value"].split(".")
            if len(tblInfo)==1:
                tmp=tblInfo[0]
                tblInfo[0]="public"
                tblInfo[1]=tmpl
            req+=["SELECT AddGeometryColumn('"+tblInfo[0]+"','"+tblInfo[1]+"','wkb_geometry',(select srid from spatial_ref_sys where auth_name||':'||auth_srid = '"+inputs["proj"]["value"]+"'),'"+inputs["geo_type"]["value"]+"',2)"]
            outputs["Result"]["value"]=zoo._("Geometry column added.")
            if inputs.keys().count("geo_x")>0 and inputs.keys().count("geo_y")>0:
                req+=["CREATE TRIGGER mm_tables_"+inputs["table"]["value"].replace(".","_")+"_update_geom BEFORE UPDATE OR INSERT ON "+inputs["table"]["value"]+" FOR EACH ROW EXECUTE PROCEDURE automatically_update_geom_property('"+inputs["geo_x"]["value"]+"','"+inputs["geo_y"]["value"]+"','"+inputs["proj"]["value"]+"')"]
                outputs["Result"]["value"]+=" "+zoo._("Trigger in place")
            print >> sys.stderr,req
        for i in range(0,len(req)):
            if not(db.execute(req[i])):
                return zoo.SERVICE_FAILED
        db.conn.commit()
        return zoo.SERVICE_SUCCEEDED
    else:
        conf["lenv"]["message"]=zoo._("Unable to connect")
    return zoo.SERVICE_FAILED
Ejemplo n.º 3
0
def GetGroupsUser(conf,inputs,outputs):
	if is_connected(conf):
		c = auth.getCon(conf)
		if not c.connect():
			conf["lenv"]["message"] = zoo._("SQL connection error")
			return 4
		if not re.match(r"(^\d+$)|(NULL)",inputs["id"]["value"]):
			conf["lenv"]["message"] = zoo._("Parameter id invalid")
			return 4
		if not re.match(r"(^\w+\Z)",inputs["order"]["value"]):
                        conf["lenv"]["message"] = zoo._("Parametre order incorrect")
                        return 4
		if not re.match(r"(desc)|(asc)",inputs["sort"]["value"]):
                        conf["lenv"]["message"] = zoo._("Parameter sort invalid")
                        return 4	
		if c.is_admin(conf["senv"]["login"]):
			if inputs["id"]["value"] == "NULL":
				outputs["Result"]["value"] = json.dumps(c.get_groups_user_by_login(conf["senv"]["login"],inputs["order"]["value"],inputs["sort"]["value"]))
			else:
				outputs["Result"]["value"] = json.dumps(c.get_groups_user_by_id(int(inputs["id"]["value"]),inputs["order"]["value"],inputs["sort"]["value"]))
		else:
			outputs["Result"]["value"] = json.dumps(c.get_groups_user_by_login(conf["senv"]["login"],inputs["order"]["value"],inputs["sort"]["value"]))
		return 3

	else:
		conf["lenv"]["message"]=zoo._("User not authenticated")
		return 4
Ejemplo n.º 4
0
def test(conf, inputs, outputs):
    libxml2.initParser()
    xcontent = (
        "<connection><dbname>"
        + inputs["dbname"]["value"]
        + "</dbname><user>"
        + inputs["user"]["value"]
        + "</user><password>"
        + inputs["password"]["value"]
        + "</password><host>"
        + inputs["host"]["value"]
        + "</host><port>"
        + inputs["port"]["value"]
        + "</port></connection>"
    )
    doc = libxml2.parseMemory(xcontent, len(xcontent))
    styledoc = libxml2.parseFile(conf["main"]["dataPath"] + "/" + inputs["type"]["value"] + "/conn.xsl")
    # print >> sys.stderr,conf["main"]["dataPath"]+"/"+inputs["type"]["value"]+"/conn.xsl"
    style = libxslt.parseStylesheetDoc(styledoc)
    result = style.applyStylesheet(doc, None)
    # print >> sys.stderr,"("+result.content+")"
    ds = osgeo.ogr.Open(result.content)
    if ds is None:
        conf["lenv"]["message"] = zoo._("Unable to connect to ") + inputs["name"]["value"]
        return 4
    else:
        outputs["Result"]["value"] = zoo._("Connection to ") + inputs["name"]["value"] + zoo._(" successfull")
    ds = None
    return 3
Ejemplo n.º 5
0
def addColumn(conf,inputs,outputs):
    print >> sys.stderr,inputs["dataStore"]["value"]
    db=pgConnection(conf,inputs["dataStore"]["value"])
    db.parseConf()
    req=[]
    if db.connect():
        if inputs["field_type"]["value"]!="18":
            req+=["ALTER TABLE quote_ident("+inputs["table"]["value"]+") ADD COLUMN "+inputs["field_name"]["value"]+" "+fetchType(conf,inputs["field_type"]["value"])]
            outputs["Result"]["value"]=zoo._("Column added")
        else:
            tblInfo=inputs["table"]["value"].split(".")
            if len(tblInfo)==1:
                tmp=tblInfo[0]
                tblInfo[0]="public"
                tblInfo[1]=tmpl
            req+=["SELECT AddGeometryColumn('"+tblInfo[0]+"','"+tblInfo[1]+"','wkb_geometry',(select srid from spatial_ref_sys where auth_name||':'||auth_srid = '"+inputs["proj"]["value"]+"'),'"+inputs["geo_type"]["value"]+"',2)"]
            outputs["Result"]["value"]=zoo._("Geometry column added.")
            if inputs.keys().count("geo_x")>0 and inputs.keys().count("geo_y")>0:
                req+=["CREATE TRIGGER mm_tables_"+inputs["table"]["value"].replace(".","_")+"_update_geom BEFORE UPDATE OR INSERT ON "+inputs["table"]["value"]+" FOR EACH ROW EXECUTE PROCEDURE automatically_update_geom_property('"+inputs["geo_x"]["value"]+"','"+inputs["geo_y"]["value"]+"','"+inputs["proj"]["value"]+"')"]
                outputs["Result"]["value"]+=" "+zoo._("Trigger in place")
            print >> sys.stderr,req
        for i in range(0,len(req)):
            if not(db.execute(req[i])):
                return zoo.SERVICE_FAILED
        db.conn.commit()
        return zoo.SERVICE_SUCCEEDED
    else:
        conf["lenv"]["message"]=zoo._("Unable to connect")
    return zoo.SERVICE_FAILED
Ejemplo n.º 6
0
def SecureAccess(conf,inputs,outputs):
    global myCookies
    mapfile=conf["main"]["dataPath"]+"/public_maps/project_"+inputs["server"]["value"]+".map"
    try:
    	myMap=mapscript.mapObj(mapfile)
    except:
        conf["lenv"]["message"]=zoo._("Unable to find any project with this name!")
	return zoo.SERVICE_FAILED
    c = auth.getCon(conf)
    prefix=auth.getPrefix(conf)
    if not(validToken(c,prefix,inputs["token"]["value"])):
        conf["lenv"]["message"]=zoo._("Unable to validate your token!")
        return zoo.SERVICE_FAILED
    if not(validIp(conf,c,prefix,inputs["ip"]["value"],0,[inputs["server"]["value"]])):
        conf["lenv"]["message"]=zoo._("You are not allowed to access the ressource using this ip address!")
        return zoo.SERVICE_FAILED
    q=None
    if inputs["Query"]["mimeType"]=="application/json":
        import json
        q=json.loads(inputs["Query"]["value"])
    myAutorizedGroups=myMap.web.metadata.get('mm_access_groups').split(',')
    if myAutorizedGroups.count('public')==0 and not(q is None or q["request"].upper()=="GETCAPABILITIES" or q["request"].upper()=="GETLEGENDGRAPHIC") and not(tryIdentifyUser(conf,inputs["user"]["value"],inputs["password"]["value"])):
        conf["lenv"]["message"]=zoo._("You are not allowed to access the ressource using this user / password!")
        conf["lenv"]["status_code"]="401 Unauthorized"
        print >> sys.stderr,conf["lenv"]
        return zoo.SERVICE_FAILED
    if conf.keys().count("senv")==0:
        conf["senv"]={"group": getGroupFromToken(c,prefix,inputs["token"]["value"])}
    else:
        print >> sys.stderr,conf["senv"]
    try:
    	myCurrentGroups=conf["senv"]["group"].split(',')
    except Exception,e:
    	myCurrentGroups=[]
Ejemplo n.º 7
0
def AddUser(conf,inputs,outputs):
	if is_connected(conf):
		c = auth.getCon(conf)
		prefix=auth.getPrefix(conf)
		if c.is_admin(conf["senv"]["login"]):
			try:
				user = json.loads(inputs["user"]["value"])
                	except Exception,e:
				print >> sys.stderr,inputs["user"]["value"]
                        	print >> sys.stderr,e
                        	conf["lenv"]["message"] = zoo._("invalid user parameter: ")+inputs["user"]["value"]
                        	return 4
			for (i,j) in user.items():
				if not manage_users.check_user_params(i,j):
					conf["lenv"]["message"] = 'Parametre %s incorrect'%(i)
					return 4
			if c.add_user(user):
				outputs["Result"]["value"] = inputs["user"]["value"]
				if inputs.has_key("group"):
					if inputs["group"].has_key("length"):
						for i in range(0,len(inputs["group"]["value"])):
							linkGroupToUser(c,prefix,inputs["group"]["value"],inputs["login"]["value"])
					else:
						linkGroupToUser(c,prefix,inputs["group"]["value"],user["login"])
				return 3
			else:
				conf["lenv"]["message"] = zoo._("SQL Error")
				return 4
		else:
			conf["lenv"]["message"]= zoo._("Action not permited")
			return 4
Ejemplo n.º 8
0
def Intersection(conf,inputs,outputs):
    geometry1=extractInputs(conf,inputs["InputEntity1"])
    geometry2=extractInputs(conf,inputs["InputEntity2"])
    print >> sys.stderr, "***** 1: "+str(len(geometry1))+" 2: "+str(len(geometry2))
    rgeometries=[]
    fids=[]
    i=0
    for i in range(len(geometry1)):
        conf["lenv"]["message"]="("+str(i)+"/"+str(len(geometry1))+") "+zoo._("Running process...")
        zoo.update_status(conf,(i*100)/len(geometry1))
        j=0
        for j in range(len(geometry2)):
            tmp=geometry2[j].Clone()
            #resg=validateGeom(geometry2[j].GetGeometryRef())
            resg=geometry2[j].GetGeometryRef()
            #print >> sys.stderr," ***** 1 : "+str(resg)
            #resg=resg.Intersection(geometry1[i].GetGeometryRef())
            if len(geometry1)==1:
                conf["lenv"]["message"]="("+str(j)+"/"+str(len(geometry2))+") "+zoo._("Run intersection process...")
                zoo.update_status(conf,(j*100)/len(geometry2))
            if geometry1[i].GetGeometryRef().GetGeometryType()==osgeo.ogr.wkbMultiPolygon:
                for k in range(geometry1[i].GetGeometryRef().GetGeometryCount()):
                    try:
                        #tmpGeom=validateGeom(geometry1[i].GetGeometryRef().GetGeometryRef(k))
                        tmpGeom=geometry1[i].GetGeometryRef().GetGeometryRef(k)
                        if tmpGeom.Intersects(resg):
                            tmp1=geometry2[j].Clone()
                            #print >> sys.stderr," ***** 2 : "+str(resg)
                            resg1=tmpGeom.Intersection(resg)
                            #tmp1.SetGeometryDirectly(validateGeom(resg1))
                            tmp1.SetGeometryDirectly(resg1)
                            tmp1.SetFID(len(rgeometries))
                            if resg1 is not None and not(resg1.IsEmpty()):# and fids.count(tmp.GetFID())==0:
                                rgeometries+=[tmp1]
                                fids+=[tmp.GetFID()]
                            else:
                                tmp1.Destroy()
                    except Exception,e:
                        #tmp1.Destroy()
                        print >>sys.stderr,e
                tmp.Destroy()
            else:
                #print >> sys.stderr," ***** 2 : "+str(geometry1[i].GetGeometryRef())
                #resg=validateGeom(geometry1[i].GetGeometryRef()).Intersection(validateGeom(resg))
                #resg=validateGeom(geometry1[i].GetGeometryRef()).Intersection(resg)
                resg=geometry1[i].GetGeometryRef().Intersection(resg)
                #print >> sys.stderr," ***** 3 : "+str(resg)
                try:
                    #tmp.SetGeometryDirectly(validateGeom(resg))
                    tmp.SetGeometryDirectly(resg)
                    tmp.SetFID(len(rgeometries))
                    if resg is not None and not(resg.IsEmpty()):# and fids.count(tmp.GetFID())==0:
                        rgeometries+=[tmp]
                        fids+=[tmp.GetFID()]
                    else:
                        tmp.Destroy()
                except Exception,e:
                    print >>sys.stderr,e
Ejemplo n.º 9
0
def delete(conf,inputs,outputs):
	try: 
		#print >> sys.stderr, conf["main"]["dataPath"]+"/"+inputs["type"]["value"]+"/"+inputs["name"]["value"]+".xml"
		os.unlink(conf["main"]["dataPath"]+"/"+inputs["type"]["value"]+"/"+inputs["name"]["value"]+".xml")
	except:
		conf["lenv"]["message"]=zoo._("Unable to access the database configuration file to remove")
		return 4
	outputs["Result"]["value"]=zoo._("Database ")+inputs["name"]["value"]+zoo._(" was successfully removed from the Datastores")
	return 3
Ejemplo n.º 10
0
def getLostPassword(conf, inputs, outputs):
    import random, string
    if not (conf.has_key("smtp")):
        conf["lenv"]["message"] = zoo._(
            "SMTP is not properly configured on your instance, please follow instructions from the official documentation."
        )
        return zoo.SERVICE_FAILED
    passwd = ''.join(
        random.choice(string.ascii_lowercase + string.digits)
        for x in range(8))
    con = getCon(conf)
    prefix = getPrefix(conf)
    con.connect()
    conn = con.conn
    cur = conn.cursor()
    conn.pexecute_req([
        "SELECT login,mail from " + prefix +
        "users where login=[_login_] or email=[_login1_]", {
            "login": {
                "value": inputs["login"]["value"],
                "format": "s"
            },
            "login": {
                "value": inputs["login"]["value"],
                "format": "s"
            }
        }
    ])
    a = conn.cur.fetchall()
    if len(a) > 0:
        try:
            passwd = ''.join(
                random.choice(string.ascii_lowercase + string.digits)
                for x in range(8))
            h = hashlib.new('ripemd160')
            h.update(passwd)
            conn.cur.pexecute_req([
                'update ' + prefix +
                'users set passwd=[_password_] where login=[_login_]', {
                    "password": {
                        "value": h.hexdigest(),
                        "format": "s"
                    },
                    "login": {
                        "value": a[0][0],
                        "format": "s"
                    }
                }
            ])
            conn.commit()
            sendMail(conf, "recovery", a[0][1], a[0][0], passwd)
        except Exception, e:
            conf["lenv"]["message"] = zoo._(
                "Unable to send the mail containing your new password: "
            ) + str(e)
            return zoo.SERVICE_FAILED
Ejemplo n.º 11
0
def save(conf,inputs,outputs):
	try: 
		f = open(conf["main"]["dataPath"]+"/"+inputs["type"]["value"]+"/"+inputs["name"]["value"]+".txt", 'w')
	except:
		return 4
	try:
		f.write(inputs["url"]["value"]+"\n");
	except:
		return 4
	outputs["Result"]["value"]=zoo._("Data Store ")+inputs["name"]["value"]+zoo._(" created")
	return 3
Ejemplo n.º 12
0
def clogOut(conf,inputs,outputs):
	if conf.keys().count("senv")>0 and conf["senv"].keys().count("loggedin")>0 and conf["senv"]["loggedin"]=="true":
		outputs["Result"]["value"]=zoo._("User disconnected")
		conf["senv"]["loggedin"]="false"
		conf["senv"]["login"]="******"
		return zoo.SERVICE_SUCCEEDED
	else:
		conf["lenv"]["message"]=zoo._("User not authenticated")
		return zoo.SERVICE_FAILED
	conf["lenv"]["message"]=zoo._("User not authenticated")
	return zoo.SERVICE_FAILED
Ejemplo n.º 13
0
def logOut(conf,inputs,outputs):
	if conf.keys().count("senv")>0 and conf["senv"].keys().count("loggedin")>0 and conf["senv"]["loggedin"]=="true":
		outputs["Result"]["value"]=zoo._("User disconnected")
		conf["senv"]["loggedin"]="false"
		#conf["lenv"]["cookie"]="MMID=deleted; expires="+time.strftime("%a, %d-%b-%Y %H:%M:%S GMT",time.gmtime())+"; path=/"
		return zoo.SERVICE_SUCCEEDED
	else:
		conf["lenv"]["message"]=zoo._("User not authenticated")
		return zoo.SERVICE_FAILED
	conf["lenv"]["message"]=zoo._("User not authenticated")
	return zoo.SERVICE_FAILED
Ejemplo n.º 14
0
def delete(conf, inputs, outputs):
    try:
        #print >> sys.stderr, conf["main"]["dataPath"]+"/"+inputs["type"]["value"]+"/"+inputs["name"]["value"]+".xml"
        os.unlink(conf["main"]["dataPath"] + "/" + inputs["type"]["value"] +
                  "/" + inputs["name"]["value"] + ".xml")
    except:
        conf["lenv"]["message"] = zoo._(
            "Unable to access the database configuration file to remove")
        return 4
    outputs["Result"]["value"] = zoo._("Database ") + inputs["name"][
        "value"] + zoo._(" was successfully removed from the Datastores")
    return 3
Ejemplo n.º 15
0
def delete(conf,inputs,outputs):
	try: 
		os.unlink(conf["main"]["dataPath"]+"/"+inputs["type"]["value"]+"/"+inputs["name"]["value"]+".txt")
	except:
		conf["lenv"]["message"]=zoo._("Unable to access the Data Store configuration file to remove")
		return 4
	try:
		os.unlink(conf["main"]["dataPath"]+"/"+inputs["type"]["value"]+"/"+inputs["name"]["value"]+"ds_ows.map")
		os.unlink(conf["main"]["dataPath"]+"/"+inputs["type"]["value"]+"/"+inputs["name"]["value"]+".mmpriv")
	except:
		pass
	outputs["Result"]["value"]=zoo._("Database ")+inputs["name"]["value"]+zoo._(" was successfully removed from the Data Stores")
	return 3
Ejemplo n.º 16
0
def save(conf, inputs, outputs):
    try:
        f = open(
            conf["main"]["dataPath"] + "/" + inputs["type"]["value"] + "/" +
            inputs["name"]["value"] + ".txt", 'w')
    except:
        return 4
    try:
        f.write(inputs["url"]["value"] + "\n")
    except:
        return 4
    outputs["Result"]["value"] = zoo._(
        "Data Store ") + inputs["name"]["value"] + zoo._(" created")
    return 3
Ejemplo n.º 17
0
def logOut(conf, inputs, outputs):
    if conf.keys().count("senv") > 0 and conf["senv"].keys().count(
            "loggedin") > 0 and conf["senv"]["loggedin"] == "true":
        outputs["Result"]["value"] = zoo._("User disconnected")
        conf["senv"]["loggedin"] = "false"
        conf["lenv"]["cookie"] = "MMID=" + conf["senv"][
            "MMID"] + "; expires=" + time.strftime("%a, %d-%b-%Y %H:%M:%S GMT",
                                                   time.gmtime()) + "; path=/"
        return zoo.SERVICE_SUCCEEDED
    else:
        conf["lenv"]["message"] = zoo._("User not authenticated")
        return zoo.SERVICE_FAILED
    conf["lenv"]["message"] = zoo._("User not authenticated")
    return zoo.SERVICE_FAILED
Ejemplo n.º 18
0
def GetUsersGroup(conf,inputs,outputs):
	if is_connected(conf):
		c = auth.getCon(conf)
		if not re.match(r"(^\d+$)",inputs["id"]["value"]):
			conf["lenv"]["message"] = zoo._("Parametre id incorrect")
			return 4
		if c.is_admin(conf["senv"]["login"]):
			outputs["Result"]["value"] = json.dumps(c.get_users_group_by_id(int(inputs["id"]["value"]),inputs["order"]["value"],inputs["sort"]["value"]))
			return 3
		else:
			conf["lenv"]["message"]= zoo._("Action not permited")
			return 4
	else:
		conf["lenv"]["message"]=zoo._("User not authenticated")
		return 4
Ejemplo n.º 19
0
def clogOut(conf,inputs,outputs):
    if conf.keys().count("senv")>0 and conf["senv"].keys().count("loggedin")>0 and conf["senv"]["loggedin"]=="true":
        outputs["Result"]["value"]=zoo._("User disconnected")
        conf["senv"]["loggedin"]="false"
        conf["senv"]["login"]="******"
        conf["senv"]["group"]="public"
        conf["lenv"]["ecookie_length"]="1"
        conf["lenv"]["ecookie"]="sid=empty"
        conf["lenv"]["cookie"]="MMID="+conf["lenv"]["usid"]+"; expires="+time.strftime("%a, %d-%b-%Y %H:%M:%S GMT",time.gmtime())+"; path=/"
        return zoo.SERVICE_SUCCEEDED
    else:
        conf["lenv"]["message"]=zoo._("User not authenticated")
        return zoo.SERVICE_FAILED
    conf["lenv"]["message"]=zoo._("User not authenticated")
    return zoo.SERVICE_FAILED
Ejemplo n.º 20
0
def GetUsersGroup(conf,inputs,outputs):
	if is_connected(conf):
		c = auth.getCon(conf)
		if not re.match(r"(^\d+$)",inputs["id"]["value"]):
			conf["lenv"]["message"] = zoo._("Parametre id incorrect")
			return 4
		if c.is_admin(conf["senv"]["login"]):
			outputs["Result"]["value"] = json.dumps(c.get_users_group_by_id(int(inputs["id"]["value"]),inputs["order"]["value"],inputs["sort"]["value"]))
			return 3
		else:
			conf["lenv"]["message"]= zoo._("Action not permited")
			return 4
	else:
		conf["lenv"]["message"]=zoo._("User not authenticated")
		return 4
Ejemplo n.º 21
0
def test(conf,inputs,outputs):
    try:
        if inputs["type"]["value"].upper()=="WMS":
            import osgeo.gdal
            ds=osgeo.gdal.Open(inputs["type"]["value"]+":"+inputs["url"]["value"])
            ds.GetDriver()
        else:
            import osgeo.ogr
            ds=osgeo.ogr.Open(inputs["type"]["value"]+":"+inputs["url"]["value"])
            ds.GetDriver()
        outputs["Result"]["value"]=zoo._("Test connecting the Data Store ")+inputs["name"]["value"]+zoo._(" run successfully")
        return zoo.SERVICE_SUCCEEDED
    except Exception,e:
        conf["lenv"]["message"]=zoo._("Unable to access the Data Store:")+str(e)
        return zoo.SERVICE_FAILED
Ejemplo n.º 22
0
def saveDataStorePrivileges(conf,inputs,outputs):
    path=getPath(conf,inputs["dataStore"]["value"])
    cStr=""
    if inputs["group"].has_key("length"):
        for i in range(0,len(inputs["group"]["value"])):
            if cStr!="":
                cStr+="\n"
            cStr+=inputs["group"]["value"][i]
            for j in ["r","w","x"]:
                if inputs["ds_"+j]["value"][i]=="true":
                    inputs["ds_"+j]["value"][i]="1"
                else:
                    if inputs["ds_"+j]["value"][i]=="false":
                        inputs["ds_"+j]["value"][i]="0"
                cStr+=","+inputs["ds_"+j]["value"][i]
    else:
        cStr+=inputs["group"]["value"]
        for j in ["r","w","x"]:
            if inputs["ds_"+j]["value"]=="true":
                inputs["ds_"+j]["value"]="1"
            else:
                if inputs["ds_"+j]["value"]=="false":
                    inputs["ds_"+j]["value"]="0"
            cStr+=","+inputs["ds_"+j]["value"]
    f=open(path+".mmpriv","wb")
    f.write(cStr)
    f.close()
    outputs["Result"]["value"]=zoo._("Privileges saved")
    return zoo.SERVICE_SUCCEEDED
Ejemplo n.º 23
0
def saveUserPreferences(conf,inputs,outputs):
	con=getCon(conf)
	con.connect()
	conn = con.conn
	prefix=getPrefix(conf)
	j=0
	sqlStr=""
	if inputs["fields"].has_key("length"):
		for i in inputs["fields"]["value"]:
			if i!="login" and inputs["values"]["value"][j]!="NULL":
				if sqlStr!="":
					sqlStr+=", "
				if i=="passwd":
					h = hashlib.new('ripemd160')
					h.update(inputs["values"]["value"][j])
					sqlStr+=i+"='"+h.hexdigest()+"'"
				else:
					sqlStr+=i+"='"+inputs["values"]["value"][j]+"'"
			j+=1
	else:
		sqlStr+=inputs["fields"]["value"]+"='"+inputs["values"]["value"]+"'"		
	print >> sys.stderr,sqlStr
	cur=conn.cursor()
	try:
		sql="UPDATE "+prefix+"users set "+sqlStr+" where login=[_login_]"
		con.pexecute_req([sql,{"login":{"value":conf["senv"]["login"],"format":"s"}}])
		conn.commit()
	except Exception,e:
		conf["lenv"]["message"]=zoo._("Unable to update user preferences: ")+str(e)
		return zoo.SERVICE_FAILED
Ejemplo n.º 24
0
def deleteSymbolFromOrig(conf,inputs,outputs):
    import sys
    import json
    from Cheetah.Template import Template
    f=open(conf["main"]["dataPath"]+"/symbols.sym","r")
    newContent=""
    str=f.read()
    f.close()
    i=0
    if inputs["name"].keys().count("length")==0:
        inputs["name"]["value"]=[inputs["name"]["value"]]
    b=str.split('SYMBOL\n')
    for a in b:
        hasValue=False
        if a!="" and a!='\n':
            for j in range(len(inputs["name"]["value"])):
                if a.count(inputs["name"]["value"][j])>0:
                    hasValue=True
            if not(hasValue):
                if newContent!="":
                    newContent+='SYMBOL\n'+a
                else:
                    newContent+=a
            else:
                if i+1==len(b):
                    newContent+="\nEND\n"
            i+=1
    f=open(conf["main"]["dataPath"]+"/symbols.sym","w")
    f.write(newContent)
    f.close()
    outputs["Result"]["value"]=zoo._("Symbol removed.")
    return 3
Ejemplo n.º 25
0
def load(conf, inputs, outputs):
    #print >> sys.stderr, conf
    # To define
    dbParams = ['dbname', 'user', 'password', 'host', 'port']
    values = "{"
    try:
        parse_options = libxml2.XML_PARSE_DTDLOAD + libxml2.XML_PARSE_NOENT
        libxml2.initParser()
        xqf = libxml2.readFile(
            conf["main"]["dataPath"] + "/" + inputs["type"]["value"] + "/" +
            inputs["name"]["value"] + ".xml", None, parse_options)
        cnt = 0
        for j in dbParams:
            print >> sys.stderr, j
            #print >> sys.stderr, j
            try:
                items = xqf.xpathEval("/connection/" + j)
                for i in items:
                    #print >> sys.stderr, cnt
                    if cnt > 0:
                        values += ', '
                    values += '"' + i.name + '": "' + str(
                        i.children.get_content()) + '"'
                    cnt += 1
            except:
                values += '"' + j + '": ""'
                cnt += 1
                pass
    except Exception, e:
        print >> sys.stderr, e
        conf["lenv"]["message"] = zoo._("Unable to parse the file")
        return 4
Ejemplo n.º 26
0
def cleanUp(conf, inputs, outputs):
    import glob, os
    tmp = inputs["dso"]["value"].split('.')
    for name in glob.glob(conf["main"]["tmpPath"] + "/" + tmp[0] + ".*"):
        os.remove(name.replace("\\", "/"))
    outputs["Result"]["value"] = zoo._("Cleanup done")
    return 3
Ejemplo n.º 27
0
def saveUserPreferences(conf,inputs,outputs):
	con=getCon(conf)
	con.connect()
	conn = con.conn
	prefix=getPrefix(conf)
	j=0
	sqlStr=""
	if inputs["fields"].has_key("length"):
		for i in inputs["fields"]["value"]:
			if i!="login" and inputs["values"]["value"][j]!="NULL":
				if sqlStr!="":
					sqlStr+=", "
				if i=="passwd":
					h = hashlib.new('ripemd160')
					h.update(inputs["values"]["value"][j])
					sqlStr+=i+"='"+h.hexdigest()+"'"
				else:
					sqlStr+=i+"='"+inputs["values"]["value"][j]+"'"
			j+=1
	else:
		sqlStr+=inputs["fields"]["value"]+"='"+inputs["values"]["value"]+"'"		
	print >> sys.stderr,sqlStr
	cur=conn.cursor()
	try:
		sql="UPDATE "+prefix+"users set "+sqlStr+" where login='******'"
		print >> sys.stderr,sql
		cur.execute(sql)
		conn.commit()
	except Exception,e:
		conf["lenv"]["message"]=zoo._("Unable to update user preferences: ")+str(e)
		return zoo.SERVICE_FAILED
Ejemplo n.º 28
0
def saveGeorefProject(conf,inputs,outputs):
    import mmsession
    import mapfile.service as ms

    mapfile=conf["main"]["dataPath"]+"/georeferencer_maps/project_"+inputs["map"]["value"]+".map"
    m = mapscript.mapObj(mapfile)
    conf["senv"]["mmGeoDST"]=m.web.metadata.get("mmGeoDST")
    conf["senv"]["mmGeoDSO"]=m.web.metadata.get("mmGeoDSO")
    if inputs.has_key("dso") and inputs["dso"]["value"]=="NULL":
        inputs["dso"]["value"]=m.getLayer(0).name
    conf["senv"]["mmGeoMap"]=inputs["dso"]["value"]

    import shutil
    ofile=m.getLayer(0).data
    shutil.copy2(ofile,conf["main"]["tmpPath"])
    conf["senv"]["mmGeoImg"]=ofile.split('/')[len(ofile.split('/'))-1]

    mmsession.save(conf)

    if not(os.path.isfile(conf["main"]["dataPath"]+"/georeferencer_maps/project_"+inputs["dso"]["value"]+".map")) or (inputs.has_key("force") and inputs["force"]["value"]=="true"):
	try:
	    os.mkdir(conf["main"]["dataPath"]+"/georeferencer_maps/"+inputs["dso"]["value"])
	    import glob
	    for name in glob.glob(conf["main"]["dataPath"]+"/georeferencer_maps/"+inputs["map"]["value"]+"/*.csv"):
                shutil.copy2(name,conf["main"]["dataPath"]+"/georeferencer_maps/"+inputs["dso"]["value"])
	except:
	    pass
        m.save(conf["main"]["dataPath"]+"/georeferencer_maps/project_"+inputs["dso"]["value"]+".map")
    outputs["Result"]["value"]=zoo._("Georeference Project saved")
    return zoo.SERVICE_SUCCEEDED
Ejemplo n.º 29
0
def loginFlux(conf, h):
    import requests
    print >> sys.stderr, " ***************** TEST 1 **************"
    dataParam = {'mp': h.hexdigest(), 'email': conf["senv"]["mail"]}
    print >> sys.stderr, str(dataParam)
    urlCon = "http://sigcod.geolabs.fr/flux/Services/service_connect"
    try:
        print >> sys.stderr, " ***************** TEST 2 **************"
        myRequest = requests.post(urlCon, data=dataParam)
        print >> sys.stderr, " ***************** TEST 3 **************"
        print >> sys.stderr, myRequest.headers["set-cookie"].split(
            ";")[2].split(",")[1]
        conf["senv"]["ecookie"] = myRequest.headers["set-cookie"].split(
            ";")[2].split(",")[1] + "; path=/"
        conf["senv"]["ecookie_length"] = str(1)
        print >> sys.stderr, dir(myRequest)
        conf["lenv"]["ecookie"] = myRequest.headers["set-cookie"].split(
            ";")[2].split(",")[1] + "; path=/"
        conf["lenv"]["ecookie_length"] = str(1)
        print >> sys.stderr, " ***************** TEST 4 **************"
        return zoo.SERVICE_SUCCEEDED
    except:
        print >> sys.stderr, " ***************** EXCEPT **************"
        conf["lenv"]["message"] = zoo._("Unable to connect to flux")
        return zoo.SERVICE_FAILED
Ejemplo n.º 30
0
def addSymbolToOrig(conf,inputs,outputs):
    import sys
    from Cheetah.Template import Template
    f=open(conf["main"]["dataPath"]+"/symbols.sym","r")
    newContent=""
    str=f.read()
    f.close()
    i=0
    b=str.split('SYMBOL\n')
    for a in b:
        if a!="" and a!='\n':
            if i+1 < len(b):
                if newContent!="":
                    newContent+='SYMBOL\n'+a
                else:
                    newContent+=a
            else:
                print >> sys.stderr,a[:len(a)-4]
                newContent+='SYMBOL\n'+a[:len(a)-5]
            i+=1
    t=Template(file=conf["main"]["templatesPath"]+"/Manager/Styler/Symbols.sym.tmpl",searchList={"conf": conf,"inputs": inputs,"outputs": outputs})
    newContent+=t.__str__().replace('SYMBOLSET\n',"")
    f=open(conf["main"]["dataPath"]+"/symbols.sym","w")
    f.write(newContent)
    f.close()
    outputs["Result"]["value"]=zoo._("Symbol added.")
    return 3
Ejemplo n.º 31
0
def requestGroup(conf,inputs,outputs):
	prefix=auth.getPrefix(conf)
	if inputs.has_key("id"):
		clause="id="+inputs["id"]["value"]
	if inputs["type"]["value"]=="delete":
		req="DELETE from "+prefix+"groups WHERE "+clause
		inputs["type"]["value"]="delet"
	else:
		if inputs["type"]["value"]=="update":
			if inputs.has_key("is_admin") and inputs["is_admin"]["value"]=="true":				
				req="UPDATE "+prefix+"groups set name='"+inputs["name"]["value"]+"', description='"+inputs["desc"]["value"]+"', adm=1 WHERE "+clause
			else:
				req="UPDATE "+prefix+"groups set name='"+inputs["name"]["value"]+"', description='"+inputs["desc"]["value"]+"', adm=0 WHERE "+clause
		else:
			if inputs.has_key("is_admin") and inputs["is_admin"]["value"]=="true":
				req="INSERT INTO "+prefix+"groups (name,description,adm) VALUES('"+inputs["name"]["value"]+"','"+inputs["desc"]["value"]+"',1)"
			else:
				req="INSERT INTO "+prefix+"groups (name,description,adm) VALUES('"+inputs["name"]["value"]+"','"+inputs["desc"]["value"]+"',0)"
	if inputs["type"]["value"]!="insert" and inputs.has_key("user"):
		print >> sys.stderr,inputs["user"]
	
	c = auth.getCon(conf)
	print >> sys.stderr,req
	c.cur.execute(req)
	c.conn.commit()
	c.close()
	outputs["Result"]["value"]=zoo._("Group succcessfully updated")
    #outputs["Result"]["value"]=zoo._("Group succcessfully updated")
	return zoo.SERVICE_SUCCEEDED
Ejemplo n.º 32
0
def isFavSrs(conf, inputs, outputs):
    con = manage_users(conf["main"]["dblink"])
    con.connect(conf)
    clause = "fav and "
    if inputs["srs_field"]["value"] == "id":
        clause += "code="
    else:
        clause += "name="
    clause += "[_val_]"
    v = "SELECT count(*) from spatial_ref_sys WHERE " + clause
    try:
        con.pexecute_req(
            [v, {
                "val": {
                    "value": inputs["srs_id"]["value"],
                    "format": "s"
                }
            }])
        val = con.cur.fetchone()
        print >> sys.stderr, val
        if val[0] > 0:
            outputs["Result"]["value"] = "true"
        else:
            outputs["Result"]["value"] = "false"
    except Exception, e:
        conf["lenv"]["message"] = zoo._("Error occured: ") + str(e)
        return zoo.SERVICE_FAILED
Ejemplo n.º 33
0
def saveDataStorePrivileges(conf, inputs, outputs):
    path = getPath(conf, inputs["dataStore"]["value"])
    cStr = ""
    if inputs["group"].has_key("length"):
        for i in range(0, len(inputs["group"]["value"])):
            if cStr != "":
                cStr += "\n"
            cStr += inputs["group"]["value"][i]
            for j in ["r", "w", "x"]:
                if inputs["ds_" + j]["value"][i] == "true":
                    inputs["ds_" + j]["value"][i] = "1"
                else:
                    if inputs["ds_" + j]["value"][i] == "false":
                        inputs["ds_" + j]["value"][i] = "0"
                cStr += "," + inputs["ds_" + j]["value"][i]
    else:
        cStr += inputs["group"]["value"]
        for j in ["r", "w", "x"]:
            if inputs["ds_" + j]["value"] == "true":
                inputs["ds_" + j]["value"] = "1"
            else:
                if inputs["ds_" + j]["value"] == "false":
                    inputs["ds_" + j]["value"] = "0"
            cStr += "," + inputs["ds_" + j]["value"]
    f = open(path + ".mmpriv", "wb")
    f.write(cStr)
    f.close()
    outputs["Result"]["value"] = zoo._("Privileges saved")
    return zoo.SERVICE_SUCCEEDED
Ejemplo n.º 34
0
def dropLayerFile(conf, inputs, outputs):
    import mapscript
    import shutil
    m = mapscript.mapObj(conf["main"]["dataPath"] +
                         "/georeferencer_maps/project_" +
                         inputs["dso"]["value"] + ".map")
    if inputs.keys().count("layer") > 0:
        ofile = inputs["layer"]["value"]
    else:
        ofileName = m.getLayer(0).data.split("/")
        ofile = ofileName[len(ofileName) - 1]
    if type(ofile) is list:
        outputs["Result"]["value"] = ""
        for i in ofile:
            if outputs["Result"]["value"] != "":
                outputs["Result"]["value"] += ","
            outputs["Result"]["value"] += str(i)
            try:
                os.remove(i)
            except:
                continue
    else:
        outputs["Result"]["value"] += ofile
        os.remove(ofile)
    outputs["Result"]["value"] += zoo._(" deleted")
    return zoo.SERVICE_SUCCEEDED
Ejemplo n.º 35
0
def addSymbolToOrig(conf, inputs, outputs):
    import sys
    from Cheetah.Template import Template
    f = open(conf["main"]["dataPath"] + "/symbols.sym", "r")
    newContent = ""
    str = f.read()
    f.close()
    i = 0
    b = str.split('SYMBOL\n')
    for a in b:
        if a != "" and a != '\n':
            if i + 1 < len(b):
                if newContent != "":
                    newContent += 'SYMBOL\n' + a
                else:
                    newContent += a
            else:
                print >> sys.stderr, a[:len(a) - 5]
                newContent += 'SYMBOL\n' + a[:len(a) - 5]
            i += 1
    t = Template(file=conf["main"]["templatesPath"] +
                 "/Manager/Styler/Symbols.sym.tmpl",
                 searchList={
                     "conf": conf,
                     "inputs": inputs,
                     "outputs": outputs
                 })
    newContent += t.__str__().replace('SYMBOLSET\n', "")
    f = open(conf["main"]["dataPath"] + "/symbols.sym", "w")
    f.write(newContent)
    f.close()
    outputs["Result"]["value"] = zoo._("Symbol added.")
    return 3
Ejemplo n.º 36
0
def requestGroup(conf,inputs,outputs):
	prefix=auth.getPrefix(conf)
	if inputs.has_key("id"):
		clause="id="+inputs["id"]["value"]
	if inputs["type"]["value"]=="delete":
		req="DELETE from "+prefix+"groups WHERE "+clause
		inputs["type"]["value"]="delet"
	else:
		if inputs["type"]["value"]=="update":
			if inputs.has_key("is_admin") and inputs["is_admin"]["value"]=="true":				
				req="UPDATE "+prefix+"groups set name='"+inputs["name"]["value"]+"', description='"+inputs["desc"]["value"]+"', adm=1 WHERE "+clause
			else:
				req="UPDATE "+prefix+"groups set name='"+inputs["name"]["value"]+"', description='"+inputs["desc"]["value"]+"', adm=0 WHERE "+clause
		else:
			if inputs.has_key("is_admin") and inputs["is_admin"]["value"]=="true":
				req="INSERT INTO "+prefix+"groups (name,description,adm) VALUES('"+inputs["name"]["value"]+"','"+inputs["desc"]["value"]+"',1)"
			else:
				req="INSERT INTO "+prefix+"groups (name,description,adm) VALUES('"+inputs["name"]["value"]+"','"+inputs["desc"]["value"]+"',0)"
	if inputs["type"]["value"]!="insert" and inputs.has_key("user"):
		print >> sys.stderr,inputs["user"]
	
	c = auth.getCon(conf)
	print >> sys.stderr,req
	c.cur.execute(req)
	c.conn.commit()
	c.close()
	print >> sys.stderr,dir(c)

	outputs["Result"]["value"]=zoo._("Group succcessfully "+inputs["type"]["value"]+"ed")
	return zoo.SERVICE_SUCCEEDED
Ejemplo n.º 37
0
def saveGeoreferencedProject(conf, inputs, outputs):
    import mmsession
    import mapfile.service as ms

    mapfile = inputs["dst"]["value"] + "ds_ows.map"
    m = mapscript.mapObj(mapfile)
    ms.removeAllLayers(m, inputs["dso"]["value"])

    m.web.metadata.set("mmGeoDST", inputs["dst"]["value"])
    conf["senv"]["mmGeoDST"] = inputs["dst"]["value"]

    m.web.metadata.set("mmGeoDSO", inputs["dso"]["value"])
    conf["senv"]["mmGeoDSO"] = inputs["dso"]["value"]
    conf["senv"]["mmGeoMap"] = inputs["dso"]["value"]

    import shutil
    ofile = m.getLayer(0).data
    shutil.copy2(ofile, conf["main"]["tmpPath"])
    conf["senv"]["mmGeoImg"] = ofile.split('/')[len(ofile.split('/')) - 1]

    if inputs.keys().count("gcpfile") > 0:
        m.web.metadata.set("mmGeoGCPFile", inputs["gcpfile"]["value"])
        conf["senv"]["mmGeoGCPFile"] = inputs["gcpfile"]["value"]
    if inputs.keys().count("size") > 0:
        m.web.metadata.set("mmGeoSize", inputs["size"]["value"])
        conf["senv"]["mmGeoSize"] = inputs["size"]["value"]
    mmsession.save(conf)
    if not (os.path.isfile(conf["main"]["dataPath"] +
                           "/georeferencer_maps/project_" +
                           inputs["dso"]["value"] + ".map")):
        m.save(conf["main"]["dataPath"] + "/georeferencer_maps/project_" +
               inputs["dso"]["value"] + ".map")
    outputs["Result"]["value"] = zoo._("Georeference Project saved")
    return zoo.SERVICE_SUCCEEDED
Ejemplo n.º 38
0
def load(conf,inputs,outputs):
	#print >> sys.stderr, conf
	# To define
	dbParams=['dbname','user','password','host','port']
	values="{"
	try: 
		parse_options = libxml2.XML_PARSE_DTDLOAD + libxml2.XML_PARSE_NOENT
		libxml2.initParser()
		xqf = libxml2.readFile(conf["main"]["dataPath"]+"/"+inputs["type"]["value"]+"/"+inputs["name"]["value"]+".xml", None, parse_options)
		cnt=0
		for j in dbParams:
			print >> sys.stderr,j
			#print >> sys.stderr, j
			try:
				items = xqf.xpathEval("/connection/"+j)
				for i in items:
				#print >> sys.stderr, cnt
					if cnt>0:
						values+=', '
					values+='"'+i.name+'": "'+str(i.children.get_content())+'"'
					cnt+=1
			except:
				values+='"'+j+'": ""'
				cnt+=1
				pass
	except Exception,e:
		print >> sys.stderr,e
		conf["lenv"]["message"]=zoo._("Unable to parse the file")
		return 4
Ejemplo n.º 39
0
def saveGeoreferencedProject(conf,inputs,outputs):
    import mmsession
    import mapfile.service as ms

    mapfile=inputs["dst"]["value"]+"ds_ows.map"
    m = mapscript.mapObj(mapfile)
    ms.removeAllLayers(m,inputs["dso"]["value"])

    m.web.metadata.set("mmGeoDST",inputs["dst"]["value"])
    conf["senv"]["mmGeoDST"]=inputs["dst"]["value"]
    
    m.web.metadata.set("mmGeoDSO",inputs["dso"]["value"])
    conf["senv"]["mmGeoDSO"]=inputs["dso"]["value"]
    conf["senv"]["mmGeoMap"]=inputs["dso"]["value"]

    import shutil
    ofile=m.getLayer(0).data
    shutil.copy2(ofile,conf["main"]["tmpPath"])
    conf["senv"]["mmGeoImg"]=ofile.split('/')[len(ofile.split('/'))-1]

    if inputs.keys().count("gcpfile")>0:
	    m.web.metadata.set("mmGeoGCPFile",inputs["gcpfile"]["value"])
	    conf["senv"]["mmGeoGCPFile"]=inputs["gcpfile"]["value"]
    mmsession.save(conf)
    if not(os.path.isfile(conf["main"]["dataPath"]+"/georeferencer_maps/project_"+inputs["dso"]["value"]+".map")):
        m.save(conf["main"]["dataPath"]+"/georeferencer_maps/project_"+inputs["dso"]["value"]+".map")
    outputs["Result"]["value"]=zoo._("Georeference Project saved")
    return zoo.SERVICE_SUCCEEDED
Ejemplo n.º 40
0
def saveGCPAsCSV(conf, inputs, outputs):
    if os.path.isfile(conf["main"]["dataPath"] + "/georeferencer_maps/" +
                      inputs["dso"]["value"] + "/" + inputs["file"]["value"] +
                      ".csv") and not (inputs.has_key("force")
                                       and inputs["force"]["value"] == "true"):
        conf["lenv"][
            "message"] = "Unable to create your GCP file, it seems that there is already a file with the same name for the project. To force the replacement of the current file by the one you are creating, please run with the  checked."
        return zoo.SERVICE_FAILED
    f = open(
        conf["main"]["dataPath"] + "/georeferencer_maps/" +
        inputs["dso"]["value"] + "/" + inputs["file"]["value"] + ".csv", "w")
    if inputs.keys().count("gcp") > 0:
        for i in range(0, len(inputs["gcp"]["value"])):
            print >> sys.stderr, inputs["gcp"]["value"][i]
            f.write(inputs["gcp"]["value"][i].replace(",", ";") + "\n")
    f.close()
    m = mapscript.mapObj(conf["main"]["dataPath"] +
                         "/georeferencer_maps/project_" +
                         inputs["dso"]["value"] + ".map")

    if m.web.metadata.get(
            "mmGCPCSV") is not None and m.web.metadata.get("mmGCPCSV") != "":
        tmp = m.web.metadata.get("mmGCPCSV")
        if tmp.count(inputs["file"]["value"]) == 0:
            m.web.metadata.set("mmGCPCSV", tmp + "," + inputs["file"]["value"])
            conf["senv"]["mmGCPCSV"] = tmp + "," + inputs["file"]["value"]
    else:
        m.web.metadata.set("mmGCPCSV", inputs["file"]["value"])
        conf["senv"]["mmGCPCSV"] = inputs["file"]["value"]

    m.save(conf["main"]["dataPath"] + "/georeferencer_maps/project_" +
           inputs["dso"]["value"] + ".map")
    outputs["Result"]["value"] = zoo._("CSV file saved.")
    return zoo.SERVICE_SUCCEEDED
Ejemplo n.º 41
0
def copyLayerFile(conf, inputs, outputs):
    import mapscript
    import shutil
    if inputs.has_key("dsto"):
        m = mapscript.mapObj(conf["main"]["dataPath"] + "/dirs/" +
                             inputs["dsto"]["value"] + "/ds_ows.map")
    else:
        m = mapscript.mapObj(conf["main"]["dataPath"] +
                             "/georeferencer_maps/project_" +
                             inputs["layer"]["value"] + ".map")
    if inputs.keys().count("lfile") > 0 and inputs["lfile"]["value"] != "NULL":
        ofile = inputs["lfile"]["value"]
    else:
        if inputs.has_key("dsto"):
            ofile = m.getLayerByName(inputs["layer"]["value"]).data
        else:
            ofile = m.getLayer(0).data
    if inputs.keys().count(
            "target") > 0 and inputs["target"]["value"] != "NULL":
        shutil.copy2(ofile, inputs["target"]["value"])
    else:
        shutil.copy2(ofile, conf["main"]["dataPath"])
    if inputs.has_key("dsto"):
        outputs["Result"]["value"] = ofile.split("/")[len(ofile.split("/")) -
                                                      1]
    else:
        outputs["Result"]["value"] = zoo._("Layer copied")
    return zoo.SERVICE_SUCCEEDED
Ejemplo n.º 42
0
def deleteSymbolFromOrig(conf, inputs, outputs):
    import sys
    import json
    from Cheetah.Template import Template
    f = open(conf["main"]["dataPath"] + "/symbols.sym", "r")
    newContent = ""
    str = f.read()
    f.close()
    i = 0
    if inputs["name"].keys().count("length") == 0:
        inputs["name"]["value"] = [inputs["name"]["value"]]
    b = str.split('SYMBOL\n')
    for a in b:
        hasValue = False
        if a != "" and a != '\n':
            for j in range(len(inputs["name"]["value"])):
                if a.count(inputs["name"]["value"][j]) > 0:
                    hasValue = True
            if not (hasValue):
                if newContent != "":
                    newContent += 'SYMBOL\n' + a
                else:
                    newContent += a
            else:
                if i + 1 == len(b):
                    newContent += "\nEND\n"
            i += 1
    f = open(conf["main"]["dataPath"] + "/symbols.sym", "w")
    f.write(newContent)
    f.close()
    outputs["Result"]["value"] = zoo._("Symbol removed.")
    return 3
Ejemplo n.º 43
0
def sendMail(conf,typ,dest,login,passwd):
	import smtplib
	from email.mime.text import MIMEText
	f0=open(conf["smtp"][typ+"_body"])
	msgTxt=zoo._(f0.read()).replace("[passwd]",passwd).replace("[login]",login).encode('utf-8')
	msg=MIMEText(msgTxt,_charset='utf-8')
	f1=open(conf["smtp"][typ+"_subject"])
	msg['Subject'] = zoo._(f1.read()).replace('\n','').encode("utf-8")
	if conf["smtp"].has_key('ufrom'):
		msg["From"]="<"+conf["smtp"]["from"]+"> "+zoo._(conf["smtp"]["ufrom"])
	else:
		msg["From"]=conf["smtp"]["from"]
	msg["To"]=dest
	serv=smtplib.SMTP(conf["smtp"]["host"],conf["smtp"]["port"])
	if conf["smtp"].has_key("login"):
		serv.login(conf["smtp"]["login"],conf["smtp"]["passwd"])
	serv.sendmail(conf["smtp"]["from"], [dest], msg.as_string())
Ejemplo n.º 44
0
def GetUserInfo(conf,inputs,outputs):
	if is_connected(conf):
		c = auth.getCon(conf)
		outputs["Result"]["value"] = json.dumps(c.get_user_by_login(conf["senv"]["login"]))
		return 3
	else:
		conf["lenv"]["message"]=zoo._("User not authenticated")
		return 4
Ejemplo n.º 45
0
def sendMail(conf,typ,dest,login,passwd):
	import smtplib
	from email.mime.text import MIMEText
	f0=open(conf["smtp"][typ+"_body"])
	msgTxt=zoo._(f0.read()).replace("[passwd]",passwd).replace("[login]",login).encode('utf-8')
	msg=MIMEText(msgTxt,_charset='utf-8')
	f1=open(conf["smtp"][typ+"_subject"])
	msg['Subject'] = zoo._(f1.read()).replace('\n','').encode("utf-8")
	if conf["smtp"].has_key('ufrom'):
		msg["From"]="<"+conf["smtp"]["from"]+"> "+zoo._(conf["smtp"]["ufrom"])
	else:
		msg["From"]=conf["smtp"]["from"]
	msg["To"]=dest
	serv=smtplib.SMTP(conf["smtp"]["host"],conf["smtp"]["port"])
	if conf["smtp"].has_key("login"):
		serv.login(conf["smtp"]["login"],conf["smtp"]["passwd"])
	serv.sendmail(conf["smtp"]["from"], [dest], msg.as_string())
Ejemplo n.º 46
0
def GetUserInfo(conf,inputs,outputs):
	if is_connected(conf):
		c = auth.getCon(conf)
		outputs["Result"]["value"] = json.dumps(c.get_user_by_login(conf["senv"]["login"]))
		return 3
	else:
		conf["lenv"]["message"]=zoo._("User not authenticated")
		return 4
Ejemplo n.º 47
0
def cleanUp(conf,inputs,outputs):
    import glob,os
    tmp=inputs["dso"]["value"].split('.')
    for name in glob.glob(conf["main"]["tmpPath"]+"/"+tmp[0]+".*"):
        print >> sys.stderr,name.replace("\\","/")
        os.remove(name.replace("\\","/"))
    outputs["Result"]["value"]=zoo._("Cleanup done")
    return 3
Ejemplo n.º 48
0
def access(conf,inputs,outputs):
    #print >> sys.stderr,str(inputs);
    osgeo.gdal.FileFromMemBuffer('/vsimem//temp1',inputs["InputData"]["value"])
    ds = osgeo.ogr.Open('/vsimem//temp1')
    print >> sys.stderr,ds
    if ds is None:
        ds = osgeo.ogr.Open(inputs["InputData"]["cache_file"])
    displayCnt=0
    geometry=[]
    sqlResults=[]
    if inputs["sql"].keys().count("value")>0:
        lyr=ds.ExecuteSQL( inputs["sql"]["value"], None, 'SQLITE' )
        if lyr is None:
            conf["lenv"]["message"]=zoo._("Unable to execute your request: "+inputs["sql"]["value"])
            cnt=0
            #return zoo.SERVICE_FAILED
        else:
            cnt=lyr.GetFeatureCount()
            for a in range(0,cnt):
                if int(inputs["offset"]["value"])+int(inputs["limit"]["value"])>a:
                    tfeat=lyr.GetNextFeature()
                if int(inputs["offset"]["value"])+int(inputs["limit"]["value"])>a and a>=int(inputs["offset"]["value"]):
                    #lyr.FindFieldIndex(lyr.GetFIDColumn())
                    sqlResults+=[tfeat.GetFID()]
        print >> sys.stderr,dir(lyr)
        if cnt>0:
            if cnt==1:
                #feat=lyr.GetNextFeature()
                #feat=sqlResults[0]
                feat=lyr.GetFeature(sqlResults[0])
                if feat is not None:
                    geometry+=[feat.Clone()]
            else:
                ci=0
                for i in range(int(inputs["offset"]["value"]),int(inputs["offset"]["value"])+int(inputs["limit"]["value"])):
                    if i < cnt:
                        #feat=lyr.GetNextFeature()
                        #feat=sqlResults[i]
                        print >> sys.stderr," ***** DEBUG "+str(i)+" ["+str(sqlResults[ci])+"]"
                        feat=lyr.GetFeature(sqlResults[ci])
                        ci+=1
                        if feat is not None:
                            geometry+=[feat.Clone()]
    else:
        lyr = ds.GetLayer(0)
        cnt=lyr.GetFeatureCount()
        if cnt>0:
            for i in range(int(inputs["offset"]["value"]),int(inputs["offset"]["value"])+int(inputs["limit"]["value"])):
                if i < cnt:
                    feat=lyr.GetFeature(i)
                    if feat is not None:
                        geometry+=[feat.Clone()]
    #cnt=lyr.GetFeatureCount()
    outputs["Count"]["value"]=str(cnt)
    ds.Destroy()
    osgeo.gdal.Unlink('/vsimem//temp1')
    outputResult(conf,outputs["Result"],geometry)
    return zoo.SERVICE_SUCCEEDED
Ejemplo n.º 49
0
def delete(conf, inputs, outputs):
    try:
        os.unlink(conf["main"]["dataPath"] + "/" + inputs["type"]["value"] +
                  "/" + inputs["name"]["value"] + ".txt")
    except:
        conf["lenv"]["message"] = zoo._(
            "Unable to access the Data Store configuration file to remove")
        return 4
    try:
        os.unlink(conf["main"]["dataPath"] + "/" + inputs["type"]["value"] +
                  "/" + inputs["name"]["value"] + "ds_ows.map")
        os.unlink(conf["main"]["dataPath"] + "/" + inputs["type"]["value"] +
                  "/" + inputs["name"]["value"] + ".mmpriv")
    except:
        pass
    outputs["Result"]["value"] = zoo._("Database ") + inputs["name"][
        "value"] + zoo._(" was successfully removed from the Data Stores")
    return 3
Ejemplo n.º 50
0
def GetGroupsUser(conf,inputs,outputs):
	if is_connected(conf):
		c = auth.getCon(conf)
		if not re.match(r"(^\d+$)|(NULL)",inputs["id"]["value"]):
			conf["lenv"]["message"] = zoo._("Parameter id invalid")
			return 4
		if c.is_admin(conf["senv"]["login"]):
			if inputs["id"]["value"] == "NULL":
				outputs["Result"]["value"] = json.dumps(c.get_groups_user_by_login(conf["senv"]["login"]))
			else:
				outputs["Result"]["value"] = json.dumps(c.get_groups_user_by_id(int(inputs["id"]["value"])))
		else:
			outputs["Result"]["value"] = json.dumps(c.get_groups_user_by_login(conf["senv"]["login"]))
		return 3

	else:
		conf["lenv"]["message"]=zoo._("User not authenticated")
		return 4
Ejemplo n.º 51
0
def GetGroupsUser(conf,inputs,outputs):
	if is_connected(conf):
		c = auth.getCon(conf)
		if not re.match(r"(^\d+$)|(NULL)",inputs["id"]["value"]):
			conf["lenv"]["message"] = zoo._("Parameter id invalid")
			return 4
		if c.is_admin(conf["senv"]["login"]):
			if inputs["id"]["value"] == "NULL":
				outputs["Result"]["value"] = json.dumps(c.get_groups_user_by_login(conf["senv"]["login"]))
			else:
				outputs["Result"]["value"] = json.dumps(c.get_groups_user_by_id(int(inputs["id"]["value"])))
		else:
			outputs["Result"]["value"] = json.dumps(c.get_groups_user_by_login(conf["senv"]["login"]))
		return 3

	else:
		conf["lenv"]["message"]=zoo._("User not authenticated")
		return 4
Ejemplo n.º 52
0
def demo(conf,inputs,outputs):
    import zoo,time
    i=0
    while i < 100:
        conf["lenv"]["message"]="Step "+str(i)
        zoo.update_status(conf,i)
        time.sleep(0.5)
        i+=1
    conf["lenv"]["message"]=zoo._("Error executing the service")
    return zoo.SERVICE_FAILED
Ejemplo n.º 53
0
def demo(conf, inputs, outputs):
    import zoo, time
    i = 0
    while i < 100:
        conf["lenv"]["message"] = "Step " + str(i)
        zoo.update_status(conf, i)
        time.sleep(0.5)
        i += 1
    conf["lenv"]["message"] = zoo._("Error executing the service")
    return zoo.SERVICE_FAILED
Ejemplo n.º 54
0
def checkDataSourcePriv(conf, m, dst, ds, priv):
    if m is None:
        import mapscript
        import datastores.service as dss
        path = dss.getPath(conf, dst)
        try:
            m = mapscript.mapObj(path + "ds_ows.map")
        except Exception, e:
            conf["lenv"]["message"] = zoo._("Unalbe to open the map ") + str(e)
            return False
Ejemplo n.º 55
0
def linkGroupToUser(conf, c, prefix, gname, login):
    try:
        req = "INSERT INTO " + prefix + "user_group (id_user,id_group) VALUES ((SELECT id from " + prefix + "users where login='******' limit 1),(SELECT id from " + prefix + "groups where name='" + gname + "'))"
        print >> sys.stderr, req
        c.cur.execute(req)
        c.conn.commit()
        return True
    except Exception, e:
        print >> sys.stderr, e
        conf["lenv"]["message"] = zoo._("Error occured: ") + str(e)
        return False
Ejemplo n.º 56
0
def linkGroupToUser(c,prefix,gname,login):
	try:
		req="INSERT INTO "+prefix+"user_group (id_user,id_group) VALUES ((SELECT id from "+prefix+"users where login='******' limit 1),(SELECT id from "+prefix+"groups where name='"+gname+"'))"
		print >> sys.stderr,req
		c.cur.execute(req)
		c.conn.commit()
		return True
	except Exception,e:
		print >> sys.stderr,e
		conf["lenv"]["message"]=zoo._("Error occured: ")+str(e)
		return False
Ejemplo n.º 57
0
def AddGroup(conf,inputs,outputs):
	if is_connected(conf):
		c = auth.getCon(conf)
		if c.is_admin(conf["senv"]["login"]):
			for i in ['name','description']:
				if not manage_users.check_group_params(i,inputs[i]['value']):
					conf['lenv']['message'] = 'Parametre %s incorrect'%(i)
					return 4
			if c.add_group(inputs['name']['value'],inputs['description']["value"]):
				outputs["Result"]["value"] = json.dumps([inputs['name']['value'],inputs['description']['value']])
				return 3
			else:
				conf["lenv"]["message"] = 'Erreur sql'
				return 4
		else:
			conf["lenv"]["message"]= zoo._("Action not permited")
			return 4
	else:
		conf["lenv"]["message"]=zoo._("User not authenticated")
                return 4