示例#1
0
 def delete(self):
     db = Database()
     stmnt = "DELETE FROM BINARIES WHERE BIN_ID = ? ;"
     db.query(stmnt, (self.get_id(),), commit=True)
     configuration = Configuration()
     binary_cache_path = os.path.join(configuration.get_entry("global.binary_cache"),
                                      configuration.get_entry("core.instance_id"))
     os.unlink(os.path.join(binary_cache_path, self.get_filename()))
示例#2
0
文件: rpc.py 项目: skarphed/skarphed
    def restartOperationDaemon(self,params):
        session_user = Session.get_current_session_user()
        if not session_user.check_permission("skarphed.manageserverdata"):
            return False

        configuration = Configuration()
        os.system("python "+configuration.get_entry("core.webpath")+\
                  "/operation_daemon.py restart "+ configuration.get_entry("core.instance_id"))
示例#3
0
文件: css.py 项目: skarphed/skarphed
 def get_css_url(cls):
     """
     Gets the cssFile as URL for the current user
     """
     configuration = Configuration()
     filename = cls.get_css_file()
     filename = filename.replace(configuration.get_entry("global.webpath"), "", 1)
     filename = filename.replace(configuration.get_entry("core.instance_id"), "", 1)
     return filename
示例#4
0
文件: rpc.py 项目: skarphed/skarphed
    def getOperationDaemonStatus(self,params):
        configuration = Configuration()
        res = os.system("python "+configuration.get_entry("core.webpath")+\
                  "/operation_daemon.py status "+ configuration.get_entry("core.instance_id"))

        if res == 0:
            running = True
        else:
            running = False
        return running
示例#5
0
 def get_config_entry(self, entry, widget_id=None):
     """
     Yields a configuration entry for this module.
     If there is a widget id given, it returns the
     configuration value of this widget. (MUST EXIST)
     """
     configuration = Configuration()
     if widget_id is not None:
         widget = Module.get_widget(widget_id)
         return configuration.get_entry(entry,widget=widget)
     else:    
         return configuration.get_entry(entry,module=self)
示例#6
0
    def get_by_filename(cls, filename):
        data_fetched = False
        configuration = Configuration()
        binary_cache_path = os.path.join(configuration.get_entry("global.binary_cache"),
                                         configuration.get_entry("core.instance_id"))

        if not os.path.exists(binary_cache_path):
            os.mkdir(binary_cache_path,True)

        db = Database()
        if os.path.exists(os.path.join(binary_cache_path, filename)):
            cachefile = open(os.path.join(binary_cache_path, filename),"rb")
            data = cachefile.read()
            cachefile.close()

            md5 = md5hash(data).hexdigest()
            sha256 = sha256hash(data).hexdigest()

            stmnt = "SELECT BIN_ID, BIN_MIME,   \
                     (SELECT BIN_DATA FROM BINARIES WHERE BIN_FILENAME = ? AND BIN_MD5 != ? AND BIN_SHA256 != ?) AS BIN_DATA \
                     FROM BINARIES WHERE BIN_FILENAME = ?  ;"
            cur = db.query(stmnt, (filename, md5, sha256, filename))
            row = cur.fetchonemap()
            if row is not None:
                data_fetched = True
                if row["BIN_DATA"] is None:
                    bin = Binary()
                    bin.set_id(row["BIN_ID"])
                    bin.set_filename(filename)
                    bin.set_mime(row["BIN_MIME"])
                    bin.set_data(data)
                    return bin
            else:
                raise BinaryException(BinaryException.get_msg(0, filename))
        if not data_fetched:
            stmnt = "SELECT BIN_ID, BIN_MIME, BIN_DATA FROM BINARIES WHERE BIN_FILENAME = ? ;"
            cur = db.query(stmnt, (filename,))
            row = cur.fetchonemap()
        if row is not None:
            bin = Binary()
            bin.set_id(row["BIN_ID"])
            bin.set_filename(filename)
            bin.set_mime(row["BIN_MIME"])
            bin.set_data(base64.b64decode(row["BIN_DATA"]))

            cachefile = open(os.path.join(binary_cache_path, filename),"wb")
            cachefile.write(bin.get_data())
            cachefile.close()

            return bin
        else:
            raise BinaryException(BinaryException.get_msg(0, filename))
示例#7
0
文件: rpc.py 项目: skarphed/skarphed
    def getInstanceId(self, params):
        session_user = Session.get_current_session_user()

        if session_user.check_permission('skarphed.manageserverdata'):
            config = Configuration()
            return config.get_entry('core.instance_id')
        else:
            return None
示例#8
0
文件: css.py 项目: skarphed/skarphed
    def get_css_file(cls):
        """
        Gets the name of the cssFile for the current user
        """
        configuration = Configuration()
        css_folder = "%s%s%s/" % (
            configuration.get_entry("global.webpath"),
            configuration.get_entry("core.instance_id"),
            configuration.get_entry("core.css_folder"),
        )

        db = Database()
        current_session = Session.get_current_session()

        rerendering_necessary = False

        if current_session is not None:
            stmnt = "SELECT CSE_FILE FROM CSSSESSION WHERE CSE_SES_ID = ? AND CSE_OUTDATED = 0 ;"
            cur = db.query(stmnt, (current_session.get_id(),))
            row = cur.fetchonemap()
            if row is not None:
                filename = row["CSE_FILE"]
            else:
                filename = css_folder + current_session.get_id() + ".css"
                stmnt = "UPDATE OR INSERT INTO CSSSESSION (CSE_SES_ID,CSE_FILE,CSE_OUTDATED) VALUES (?,?,0) MATCHING (CSE_SES_ID) ;"
                db.query(stmnt, (current_session.get_id(), filename), commit=True)
                rerendering_necessary = True
        else:
            stmnt = "SELECT CSE_FILE FROM CSSSESSION WHERE CSE_SES_ID = '-1' AND CSE_OUTDATED = 0 ;"
            cur = db.query(stmnt)
            row = cur.fetchonemap()
            if row is not None:
                filename = row["CSE_FILE"]
            else:
                filename = css_folder + "general.css"
                # TODO: This was eventually fail! ↓
                stmnt = "UPDATE OR INSERT INTO CSSSESSION (CSE_SES_ID,CSE_FILE,CSE_OUTDATED) VALUES ('-1',?,0) MATCHING (CSE_SES_ID) ;"
                db.query(stmnt, (filename,), commit=True)
                rerendering_necessary = True

        if not os.path.exists(filename) or rerendering_necessary:
            cls.render_to_file(filename)

        cls.cleanup_css_sessiontable()
        return filename
示例#9
0
文件: rpc.py 项目: skarphed/skarphed
    def getGuiForModule(self, params):
        module_id = int(params[0])

        module = ModuleManager.get_module(module_id)
        moduleguidata = base64.b64encode(module.get_guidata())
        signature = Pki.sign(moduleguidata)

        return {'data':moduleguidata,
                'signature':base64.b64encode(signature),
                'libstring':Configuration.get_entry('global.modpath')}
示例#10
0
    def __init__(self):
        """
        The Database loads connectiondata to the database from the config of Core
        """
        self.__dict__ = Database._borgmind
        if self.__dict__ == {}:
            self._connection = None
            self._ip = None
            self._dbname = None
            self._user = None
            self._password = None

            self._queryCache = QueryCache()
            
            c = Configuration()
            self.set_ip(c.get_entry('db.ip'))
            self.set_db_name(c.get_entry('db.name'))
            self.set_user(c.get_entry('db.user'))
            self.set_password(c.get_entry('db.password'))
            self.connect()
示例#11
0
    def get_guidata(self):
        configuration = Configuration()
        modpath = configuration.get_entry("global.modpath")

        modulepath = modpath+"/"+self._name+"/v"+\
                              str(self._version_major)+"_"+ \
                              str(self._version_minor)+"_"+ \
                              str(self._revision)
        tar = tarfile.open(modulepath+"/gui.tar.gz","w:gz")
        tar.add(modulepath+"/gui")
        tar.close()

        f = open(modulepath+"/gui.tar.gz","r")
        data = f.read()
        f.close()

        os.unlink(modulepath+"/gui.tar.gz")
        return data
示例#12
0
    def install_from_data(cls, data):
        """
        Receives .tar.gz'ed data and generates templatedata from it
        First validates the data. While validating it tracks all occuring
        errors in the errorlog. If one severe error happens during validation,
        the method stops before actually doing write-operations and returns
        the errorlog to the client
        Otherwise, it executes the installation and returns all 
        non-severe errors (warnings).
        """
        def cleanup(path):
            shutil.rmtree(path)

        #TODO: Mutex this operation

        errorlog = []

        configuration = Configuration()
        webpath = configuration.get_entry("core.webpath")
        temp_installpath = webpath+"/tpl_install"
        os.mkdir(temp_installpath)

        tar = open(temp_installpath+"/tpl.tar.gz","w")
        tar.write(data)
        tar.close()

        tar = tarfile.open(temp_installpath+"/tpl.tar.gz","r:gz")
        tar.extractall(temp_installpath)
        tar.close()

        os.unlink(temp_installpath+"/tpl.tar.gz")

        manifest_file = open(temp_installpath+"/manifest.json","r")
        try:
            manifest = JSONDecoder().decode(manifest_file.read())
        except ValueError,e:
            errorlog.append({'severity':1,
                           'type':'PackageFile',
                           'msg':'JSON seems to be corrupt'})
            cleanup(temp_installpath)
            return errorlog
示例#13
0
文件: view.py 项目: skarphed/skarphed
    def render(self, environ):
        View.set_currently_rendering_view(self)
        frame = """
        <!DOCTYPE html>
        <html>
          <head>
            <title>%(title)s</title>
            <link href="/static/%(page_css)s" rel="stylesheet" type="text/css">
            <link href="%(scv_css)s" rel="stylesheet" type="text/css">
            %(head)s
            <script type="text/javascript">%(ajax_script)s</script>
          </head>
          <body>
            %(body)s
          </body>
        </html>
        """
        js_frame = """<script type="text/javascript" id="%d_scr">%s</script>"""
        page = Page.get_page(self._page) 

        head = page.get_html_head()
        body = page.get_html_body()

        # Find placeholders to substitute
        
        space_name_map = page.get_space_names()
        for space, widget_id in self._space_widget_mapping.items():
            space_name = space_name_map[space]
            widget = ModuleManager.get_widget(widget_id)

            args = {} 
            if self._widget_param_mapping.has_key(widget_id):
                args.update(self._widget_param_mapping[widget_id])
            elif self._widget_param_mapping.has_key(str(widget_id)):
                args.update(self._widget_param_mapping[str(widget_id)])
            
            if self._post_widget_id == widget_id:
                # Check whether the viewjson-string is included here, too:
                # if so, eliminate it.
                post_args = FieldStorage(fp=environ['wsgi.input'],environ=environ)
                for key in post_args.keys():
                    args[key] = post_args[key].value

            widget_html = widget.render_html(args)
            widget_js = widget.render_javascript(args)
            widget_html += js_frame%(widget.get_id(), widget_js)
            body = re.sub(r"<%%\s?space:%s\s?%%>"%space_name,widget_html,body)

        for box, boxcontent in self._box_mapping.items():
            box_orientation, box_name = self.get_box_info(box)
            box_html = StringIO.StringIO()
            for widget_id in boxcontent:
                widget = ModuleManager.get_widget(widget_id)

                args = {} 
                if self._widget_param_mapping.has_key(widget_id):
                    args.update(self._widget_param_mapping[widget_id])
                elif self._widget_param_mapping.has_key(str(widget_id)):
                    args.update(self._widget_param_mapping[str(widget_id)])

                if self._post_widget_id == widget_id:
                    # Check whether the viewjson-string is included here, too:
                    # if so, eliminate it.
                    post_args = FieldStorage(fp=environ['wsgi.input'],environ=environ)
                    for key in post_args.keys():
                        args[key] = post_args[key].value
            
                widget_html = widget.render_html(args)
                widget_js = widget.render_javascript(args)
                widget_html += js_frame%(widget.get_id(), widget_js)
                box_html.write(widget_html)
                if box_orientation == BoxOrientation.VERTICAL:
                    box_html.write("<br>")

            if box_orientation == BoxOrientation.HORIZONTAL:
                body = re.sub(r"<%%\s?hbox:%s\s?%%>"%box_name,box_html.getvalue(),body)
            elif box_orientation == BoxOrientation.VERTICAL:
                body = re.sub(r"<%%\s?vbox:%s\s?%%>"%box_name,box_html.getvalue(),body)

        body = re.sub(r"<%[^%>]+%>","",body) #Replace all unused spaces with emptystring

        css_manager = CSSManager()
        css_url = css_manager.get_css_url()

        configuration = Configuration()
        title = configuration.get_entry("core.name")

        page_css = page.get_css_filename()
        View.set_currently_rendering_view(None)
        return frame%{'title':title,
                      'scv_css':css_url,
                      'page_css':page_css,
                      'ajax_script':AJAXScript,
                      'head':head,
                      'body':body}
示例#14
0
文件: view.py 项目: skarphed/skarphed
    def get_from_id(cls, nr):
        """
        returns the view that is given by this id
        """
        db = Database()
        stmnt = "SELECT VIE_NAME, VIE_SIT_ID, VIE_VIE_BASEVIEW, VIE_DEFAULT\
                  FROM VIEWS WHERE VIE_ID = ? ;"
        cur = db.query(stmnt, (int(nr),))
        row = cur.fetchonemap()
        if row is None:
            raise ViewException(ViewException.get_msg(0))
        else:
            configuration = Configuration()
            rendermode = configuration.get_entry("core.rendermode")
            if rendermode == "pure":
                view = PureView()
            elif rendermode == "ajax":
                view = AJAXView()
            view.set_name(row["VIE_NAME"])
            view.set_default(row["VIE_DEFAULT"])
            view.set_page(row["VIE_SIT_ID"])
            view.set_baseview_id(row["VIE_VIE_BASEVIEW"])
            view.set_id(nr)
        
        # get the widget space mapping. if the view has a baseview, also get those of
        # the baseview. store into a dictionary. overwrite the space widget mapping
        # of the baseview with those of the view. the derived view only stores the
        # differences of itself and the baseview (same goes for widget_param_mapping
        # and box_mapping
        stmnt = "SELECT VIW_SPA_ID, VIW_WGT_ID FROM VIEWWIDGETS \
                    WHERE VIW_VIE_ID = (SELECT VIE_VIE_BASEVIEW FROM VIEWS WHERE VIE_ID = ?) \
                 UNION SELECT VIW_SPA_ID, VIW_WGT_ID FROM VIEWWIDGETS WHERE VIW_VIE_ID = ? ;"
        cur = db.query(stmnt, (view.get_id(), view.get_id()))
        rows = cur.fetchallmap()
        space_widget_mapping = {}
        for row in rows:
            space_widget_mapping[row["VIW_SPA_ID"]] = row["VIW_WGT_ID"]
        view.set_space_widget_mapping(space_widget_mapping)
        
        # get the box mapping. this mapping maps box_ids to a list of widget_ids.
        stmnt = "SELECT BOX_ID, BWT_WGT_ID FROM (\
                 SELECT BOX_ID, BWT_WGT_ID, BWT_BOX_ID, BWT_ORDER, 0 AS UNIONSORT \
                     FROM BOXES LEFT JOIN BOXWIDGETS ON (BOX_ID = BWT_BOX_ID) \
                     WHERE BWT_VIE_ID = (SELECT VIE_VIE_BASEVIEW FROM VIEWS WHERE VIE_ID = ?) \
                     OR (BWT_VIE_ID IS NULL AND BOX_SIT_ID = ?) \
                 UNION SELECT BOX_ID, BWT_WGT_ID, BWT_BOX_ID, BWT_ORDER, 1 AS UNIONSORT \
                     FROM BOXES LEFT JOIN BOXWIDGETS ON (BOX_ID = BWT_BOX_ID) \
                     WHERE BWT_VIE_ID = ? OR (BWT_VIE_ID IS NULL AND BOX_SIT_ID = ?)) \
                 ORDER BY UNIONSORT, BWT_BOX_ID, BWT_ORDER ;"
        cur = db.query(stmnt, (view.get_id(), view.get_page(),
                                          view.get_id(), view.get_page()))
        rows = cur.fetchallmap()
        box_mapping = {}
        for row in rows:
            box_id = int(row["BOX_ID"])
            if not box_mapping.has_key(box_id):
                box_mapping[box_id] = []
            if row["BWT_WGT_ID"] is not None:
                box_mapping[box_id].append(row["BWT_WGT_ID"])
        view.set_box_mapping(box_mapping)

        # get the widget_param mapping. this maps a dictionary of parameters to
        # a widget_id
        stmnt = "SELECT VWP_KEY, VWP_VALUE, VWP_WGT_ID FROM ( \
                     SELECT VWP_KEY, VWP_VALUE, VWP_WGT_ID, 0 AS UNIONSORT FROM VIEWWIDGETPARAMS \
                     WHERE VWP_VIE_ID = (SELECT VIE_VIE_BASEVIEW FROM VIEWS WHERE VIE_ID = ?) \
                     UNION \
                     SELECT VWP_KEY, VWP_VALUE, VWP_WGT_ID, 1 AS UNIONSORT FROM VIEWWIDGETPARAMS \
                     WHERE VWP_VIE_ID = ?)\
                 ORDER BY UNIONSORT, VWP_WGT_ID;"
        cur = db.query(stmnt, (view.get_id(),view.get_id()))
        rows = cur.fetchallmap()
        widget_param_mapping = {}
        for row in rows:
            if not widget_param_mapping.has_key(row["VWP_WGT_ID"]):
                widget_param_mapping[row["VWP_WGT_ID"]] = {}
            widget_param_mapping[row["VWP_WGT_ID"]][row["VWP_KEY"]]= row["VWP_VALUE"]
        view.set_widget_param_mapping(widget_param_mapping)

        return view
示例#15
0
文件: view.py 项目: skarphed/skarphed
    def get_from_json(cls, json):
        """
        creates a view from a json that looks like this:

        {'s':<page_id>,
         'v':{'<space_id>':<widget_id>,'<space_id>':<widget_id>,[...]},
         'b':{'<box_id>':[<widget_id>, <widget_id>, [...]]},
         'c':{'<wgt_id>': {<widget_args>},'wgt_id':{<widget_args>},[...]},
         'p':<wgt_id>
        }

        's' is the page that this view is going to be rendered on 
        'v' is a dictionary that maps space_ids to widget_ids
        'b' represents box-packed widgets
        'c' maps parameters to widgets
        'p' is an OPTIONAL parameter. if a html-form is submitted, this 
            contains a widget_id to 
        """

        json = unquote(json)
        jd = JSONDecoder()
        try:
            json = jd.decode(json)
        except ValueError:
            raise ViewException(ViewException.get_msg(7))

        configuration = Configuration()
        rendermode = configuration.get_entry("core.rendermode")
        if rendermode == "pure":
            view = PureView()
        elif rendermode == "ajax":
            view = AJAXView()

        if json.has_key('s'):
            view.set_page(json['s'])
        else:
            raise ViewException(ViewException.get_msg(6))

        if json.has_key('v'):
            for key, value in json['v'].items(): #transform indices back to int
                json['v'][int(key)] = value
                del(json['v'][key])
            view.set_space_widget_mapping(json['v'])
        else:
            view.set_space_widget_mapping({})

        if json.has_key('b'):
            for key, value in json['b'].items(): #transform indices back to int
                json['b'][int(key)] = value
                del(json['b'][key])
            view.set_box_mapping(json['b'])
        else:
            view.set_box_mapping({})

        if json.has_key('c'):
            for key, value in json['c'].items(): #transform indices back to int
                json['c'][int(key)] = value
                del(json['c'][key])
            view.set_widget_param_mapping(json['c'])
        else:
            view.set_widget_param_mapping({})
        if json.has_key('p'):
            view.set_post_widget_id(json['p'])

        return view