Ejemplo n.º 1
0
class static(object):
    """docstring for static"""
    def __init__(self, data):
        self.data = data
        self.HEADERS = Headers()
        self.HEADERS.set_headers({"Content-type": "text/plain\n"})
        if data["control"] != None and data["control"] in dir(self):
            exec("self." + data["control"] + "()")

    def plugin(self):
        for elem in rest["model"]["global"].obtenerFilas('Gestor-plugins'):

            if len(rest["args"]) > 1 and elem[0] == self.data["args"][
                    0] and self.data["args"][1] == "screen":

                print "Content-type: image/png" + "\n"
                print file(
                    config.base_root + config.projects_folder +
                    self.data["vista"] + "/screenshot.png", "rb").read()

    def screen(self):
        print "Content-type: image/png" + "\n"
        print file(
            config.base_root + config.projects_folder + self.data["app"] +
            "/screenshot.png", "rb").read()

    def script(self):
        if self.data["file"].endswith(".js"):
            self.HEADERS.show()
            if os.path.isfile(config.base_root + config.static_folder +
                              "js/python/__javascript__/" + self.data["file"]):

                f = open(
                    config.base_root + config.static_folder +
                    "js/python/__javascript__/" + self.data["file"], "r")
                script = convertir2(
                    f.read().replace("\\n",
                                     "\\\\n").replace("\\'", "\\\\'").replace(
                                         '\\"', '\\\\"'), ["<%", "%>"])
                doc = ""
                try:

                    exec(script)
                    print "var True=true;var False=false;var None=null;\n" + doc
                except Exception, e:
                    print e
                f.close()

        else:
Ejemplo n.º 2
0
class apps(object):
    """docstring for apps"""
    def __init__(self, data):
        self.data = data
        self.HEADERS = Headers()
        self.HEADERS.set_headers({"Content-type": "text/plain\n"})
        self.HEADERS.show()
        apps = []
        if self.data["metodo"] == None:
            self.HEADERS.show()
            for elem in self.data["model"]["global"].obtenerFilas("apps"):
                if "Suspendida" in elem[4] and elem[0] == self.data["app"]:
                    self.data["app"] = None
                apps.append(elem[0])

            print {"apps": apps, "default_app": config.default_app}

        pass

    def versiones_disponibles(self):
        versiones = {}

        self.HEADERS.show()
        if len(self.data["args"]) > 2:
            if self.data["args"][2] == "sizes":
                for elem in config.versiones_disponibles:
                    for elem2 in self.data["model"]["global"].obtenerFilas(
                            "Asenzor"):
                        if elem2[1][0]["value"] == elem:
                            versiones[elem2[1][4]
                                      ["value"]] = elem2[1][5]["value"]
                print versiones

        else:

            for elem in config.versiones_disponibles:
                for elem2 in self.data["model"]["global"].obtenerFilas(
                        "Asenzor"):
                    if elem2[1][0]["value"] == elem:
                        versiones[elem] = elem2[1][4]["value"]
            print versiones

    def webapp(self):
        self.HEADERS.show()
        if self.data["action"] == "install":
            import urllib2, urllib

            params = {
                "app": "asenzor",
                "control": self.data["control"],
                "action": "download",
                "item": self.data["item"]
            }

            params = urllib.urlencode(params)

            f = urllib2.urlopen(
                config.asenzor_host + config.controller_folder + "ajax.py",
                params)

            ruta = f.read().strip()
            zred.download2(ruta, config.base_root + config.apps_folder)
            f.close()

            zred.zipextract(config.base_root + config.apps_folder +
                            ruta.split("/")[-1])
            os.remove(config.base_root + config.apps_folder +
                      ruta.split("/")[-1])
            self.data["model"]["global"].instalarApp(self.data["item"])

    def download(self):
        zred.downloader(config,
                        config.base_root + config.projects_folder +
                        self.data["item"] + ".zip",
                        get=False)
        pass

    def unistall(self):
        pass

    def install(self):
        pass

    def allapps(self):

        self.HEADERS.show()
        d = redict({
            "[D|d]estacad[a|o]s?": [],
            "[P|p]opular(es)?": [],
            "[R|r]ecientes?": [],
            "[F|f]avorit[a|o]s?": [],
        })

        for elem in self.data["model"]["global"].obtenerFilas("Gestor-apps"):

            if "Destacada" in elem[-1] or "Destacado" in elem[
                    -1] or "Destacados" in elem[-1] or "Destacadas" in elem[-1]:

                d["Destacada"].append(elem)
            if "Popular" in elem[-1]:
                d["Popular"].append(elem)
            if "Reciente" in elem[-1]:
                d["Reciente"].append(elem)
            if "Favorita" in elem[-1] or "Favoritas" in elem[
                    -1] or "Favoritos" in elem[-1]:
                d["Favorita"].append(elem)

        print d
Ejemplo n.º 3
0
 def action(data,p):#manejador de los formularios
  
  sys.path.append(p["base_root"]+"../admin/")


  



  
  debug=False
  contenttype=False



  from config import config



  import settings.routes as routes
  
  import settings.config as settings
  import imp
  from modulos.ztec.zu import redict






  
  sys.path.append(p["base_root"]+"../admin/"+routes.libs_folder)
  sys.path.append(p["base_root"]+"../admin/"+routes.models_folder)

  
  
  
  errores=[]
  for elem in settings.libs_python:
   exec("import "+elem,locals())
  
  import modulos.ztec.zu as zu
  import ztec.zred as zred 


  

  

  
  from modulos.ztec.zred import clienteSock,getCookie,setCookie, redirecter,decode,normalizar,encode,Headers
  HEADERS=Headers()
  if p["method"]=="ajax":
    HEADERS.set_headers({"Content-type":"text/plain"})
  #==============================================================================
  #INICIALIZACION DE LOS MODELOS
  if "model" not in p:
    p["model"]={}
  if "opciones" not in p:
    p["opciones"]={}


  contenido=p["model"]["global"].obtenerContenido(p["app"],"apps")[p["app"]]  

  p["model"]["global"].p=p
  p["model"]["usuarios"].p=p
  for k,db in enumerate(contenido[1]):
    if contenido[1][db]["value"] in settings.dbs:

      exec("from "+contenido[1][db]["value"]+"_model import model as model"+str(k),locals())    
      if "token" not in p:
       
       exec('p["model"][contenido[1][db]["value"]]=model'+str(k)+'(p["base_root"]+"../admin/"+routes.models_folder+contenido[1][db]["value"],p["base_root"]+"../admin/"+routes.request_folder,"user",debug=debug,ext=".py")',locals())
       p["model"][contenido[1][db]["value"]].models["global"]=p["model"]["global"]

       p["model"]["global"].models[contenido[1][db]["value"]]=p["model"][contenido[1][db]["value"]]
       if "Opciones" in p["model"][contenido[1][db]["value"]].db.tablas:
            p["opciones"][contenido[1][db]["value"]]=p["model"][contenido[1][db]["value"]].obtenerFilas("Opciones")
       

      else:

       exec('p["model"][contenido[1][db]["value"]]=model'+str(k)+'(p["base_root"]+"../admin/"+routes.models_folder+contenido[1][db]["value"],p["base_root"]+"../admin/"+routes.request_folder,p["token"],debug=debug,ext=".py")',locals())
       p["model"][contenido[1][db]["value"]].models["global"]=p["model"]["global"]
       p["model"]["global"].models[contenido[1][db]["value"]]=p["model"][contenido[1][db]["value"]]

       if "Opciones" in p["model"][contenido[1][db]["value"]].db.tablas:
            p["opciones"][contenido[1][db]["value"]]=p["model"][contenido[1][db]["value"]].obtenerFilas("Opciones") 
    p["model"][contenido[1][db]["value"]].p=p



    
  
  #===================================================================================
  #MANEJO DE REGISTRO DE ACCIONES DE USARIO(SESION)
  

  cookies=getCookie()
  p["cookies"]=cookies
  token2=None
  tokens={}



  

  if "token" in cookies:

   tokens=normalizar(cookies["token"])
  if "token2" in cookies:
    token2=normalizar(cookies["token2"])
   


   

  if settings.app in tokens and token2==None:

    p["token"]=tokens[settings.app]
    if p["model"]["usuarios"].isUser(token=tokens[settings.app]) and p["model"]["usuarios"].consultarLogin(tokens[settings.app]):
      p["user"]=p["model"]["usuarios"].obtenerUsuario(p["token"])
      p["login"]=True
      p["isGlobalUser"]=False
    else:
      p["login"]=False
    
  elif token2!=None and p["model"]["global"].consultarLogin(token2):
    p["token"]=token2
    p["user"]=p["model"]["global"].obtenerUsuario(p["token"])
    p["login"]=True
    p["isGlobalUser"]=True
  else:
    p["login"]=False
  
  for elem in p["model"]:
   if "token" in p:
    p["model"][elem].token=p["token"]
   else:
    p["model"][elem].token="user"
  #=================================================================================
  #CREAR LOS LANZADORES DEL LOS PLUGINS
  p["plugins"]={}
  for k,plugin in enumerate(p["model"]["main"].obtenerFilas("Plugins")):
    if plugin[1]==True:
      p["plugins"][plugin[0]]=imp.load_source("plugin"+str(k),config.base_root+config.plugins_folder+plugin[0]+"/"+"default.py").Plugin(p["model"])
      p["plugins"][plugin[0]].action(data,p)


      


  #========================================================================================

  if p["cookies"]!={} and normalizar(p["cookies"]["beforeArgs"])!=[]:
    if len(normalizar(p["cookies"]["beforeArgs"]))>0:
      beforeAction=normalizar(p["cookies"]["beforeArgs"])[0]
      if len(normalizar(p["cookies"]["beforeArgs"]))>1:
          indice=normalizar(p["cookies"]["beforeArgs"])[1]
  else:
   try:
     beforeAction=data["action"].value
   except Exception as e:
     beforeAction=""
   indice=None

  #=========================================================================
  #CARGA DE SUBCONTROLADORES 
  
  for elem in settings.global_post_controllers:
   try:


    sub=open("../"+config.controller_folder+config.global_folder+routes.http_folder+elem+".py","r")
    script=sub.read()
    sub.close()
    exec(script,locals())

   except Exception as e:
    print "#error: ",elem," ",e
    errores.append([sys.exc_info(),[p["base_root"]+routes.controller_folder+"default.py",p["base_root"]+routes.controller_folder+routes.http_folder+elem+".py"]])

  for elem in settings.post_controllers:
    
    sub=open(config.base_root+config.apps_folder+p["app"]+"/user/"+config.controles_dir+"/"+routes.http_folder+elem+".py","r")
    script=sub.read()
    try:
     exec(script,locals()) 
    except Exception as e:
     if settings.mod_debug!=False:
      import traceback

      exc_type,exc_obj,exc_tb=sys.exc_info()
      fname = exc_tb.tb_frame.f_code.co_filename
      print "#==================================="
      print "#No se pudo cargar el modulo ",elem
      print "# ","".join(traceback.format_exception(exc_type,fname,exc_tb))
      print "#", e
      print "#==================================="

  for elem in settings.post_custom_controllers:
    sub=open(config.base_root+config.apps_folder+p["app"]+"/user/"+config.controles_dir+"/"+routes.custom_http_folder+elem+".py","r")
    script=sub.read()
    sub.close()
    try:
     exec(script,locals()) 
    except Exception as e:
     if settings.mod_debug!=False:
      import traceback
      exc_type,exc_obj,exc_tb=sys.exc_info()
      fname = exc_tb.tb_frame.f_code.co_filename
      print "#==================================="
      print "#No se pudo cargar el modulo ",elem
      print "# ","".join(traceback.format_exception(exc_type,fname,exc_tb))
      print "#", e
      print "#==================================="
Ejemplo n.º 4
0
class Plugin(Controlador):
	"""docstring for Plugin"""
	def __init__(self,plugin,data):
		
		import imp
		Controlador.__init__(self,data)

		self.login=Login(data)
		
		
		import os

		from modulos.ztec.zred import  Headers,gringolizar
		self.app=None
		self.model={}
		self.shortcodes={}
	
		import sys


		self.plugin=plugin

		self.HEADERS=Headers()
		l=self.plugin.navegacion
		if self.data["model"]["main"].update():

			for elem in self.data["model"]["main"].obtenerFilas("AdminMenu"):
						if elem in l:
							l.remove(elem)
		
		for elem2 in l:                
				self.data["model"]["main"].db("AdminMenu").insertar(elem2[0],elem2[1],elem2[2],elem2[3])


		self.HEADERS.set_headers({"Content-type":"text/plain\n"})
		from modulos.ztec.intervalor.control import generar2		
		for w in plugin.widgets:
			if os.path.exists(config.base_root+config.plugins_folder+plugin.name+"/widgets/"+w+".html"):
				 	generar2(config.base_root+config.plugins_folder+plugin.name+"/widgets/"+w+".html",config.base_root+config.plugins_folder+plugin.name+"/widgets/"+w+".py","#!/usr/bin/python\n# -*- coding: utf-8 -*-\n")
			elif os.path.exists(config.base_root+config.plugins_folder+plugin.name+"/widgets/"+w+"/"+w+".html"):
						generar2(config.base_root+config.plugins_folder+plugin.name+"/widgets/"+w+"/"+w+".html",config.base_root+config.plugins_folder+plugin.name+"/widgets/"+w+"/"+w+".py","#!/usr/bin/python\n# -*- coding: utf-8 -*-\n")


		if self.data["app"]!=None:

			import app
			from app import app
			self.app=app()
			from settings import config as settings
			from settings import routes

			
			for elem in plugin.modelos:

				if os.path.exists(config.base_root+config.apps_folder+settings.app+"/admin/"+routes.models_folder+"plugins/"+plugin.name+"/"+elem+"_struct.py"):				
					if os.path.exists(config.base_root+config.plugins_folder+plugin.name+"/modelos/"+elem+"_model.py"):
						self.model[elem]=imp.load_source(elem+"_model",config.base_root+config.plugins_folder+plugin.name+"/modelos/"+elem+"_model.py").model(
							config.base_root+config.apps_folder+settings.app+"/admin/"+routes.models_folder+"plugins/"+plugin.name+"/"+elem,
							config.base_root+config.modelos_folder+"request/","user",ext=".py"
							)
					else:
						print "El modelo: "+elem+" del plugin: "+plugin.name+" no fue encontrado"
					

				else:
					if not os.path.exists(config.base_root+config.apps_folder+settings.app+"/admin/"+routes.models_folder+"plugins/"+plugin.name+"/"):
						os.mkdir(config.base_root+config.apps_folder+settings.app+"/admin/"+routes.models_folder+"plugins/"+plugin.name+"/")
					if os.path.exists(config.base_root+config.plugins_folder+plugin.name+"/modelos/"+elem+"_struct.py"):
						f=open(config.base_root+config.plugins_folder+plugin.name+"/modelos/"+elem+"_struct.py","r")
						struct=f.read()
						f.close()
						f=open(config.base_root+config.apps_folder+settings.app+"/admin/"+routes.models_folder+"plugins/"+plugin.name+"/"+elem+"_struct.py","w")
						f.write(struct)
						f.close()				

						self.model[elem]=imp.load_source(elem+"_model",config.base_root+config.plugins_folder+plugin.name+"/modelos/"+elem+"_model.py").model(

						config.base_root+config.apps_folder+settings.app+"/admin/"+routes.models_folder+"plugins/"+plugin.name+"/"+elem,
							config.base_root+config.modelos_folder+"request/","user",ext=".py"
							)
						



		for elem in plugin.shortcodes:
					
					self.shortcodes[elem]=imp.load_source(elem+"_model",config.base_root+config.plugins_folder+self.plugin.name+"/shortcodes/"+elem+".py").shortcode(self)
					
					self.shortcodes[elem].ruta=self.plugin.__path__+"/widgets/"

					self.shortcodes[elem].url=config.base_url+config.plugins_folder+"/".join(self.plugin.__path__.split("/")[-2:])+"/widgets/"
					

	def sc(self):
			"""
			invoca los shotcodes atrabes de una url
			"""
			
			if len(self.data["args"])>0:
				self.HEADERS.set_headers({"Content-type":"text/html\n"})
				self.HEADERS.show()
				
				print self.incluir(self.data,"head",isglobal=True)

			atts=""
			if "sc" in self.data:
				atts+=" sc='"+self.data["sc"]+"'"
			
			print self.do_shortcode("["+self.plugin.name+"-"+self.data["args"][0]+atts+"]")

	def metodo_desconocido(self):
		pass
		
	def desinstalar(self,data):
		l=self.plugin.navegacion
		if self.data["model"]["main"].request():
			for k,elem in enumerate(self.data["model"]["main"].obtenerFilas("Plugins")):
				if elem[0]==self.plugin.name:
					self.data["model"]["main"].db("Plugins").modificarCampo(k,"Activo",False)
				
			for k,elem in enumerate(self.data["model"]["main"].obtenerFilas("AdminMenu")):
						if elem in l:
							self.db("AminMenu").delFila(k)
		self.data["model"]["main"].grabar()
		

	def action(self,data):
		pass