commit 256db99d585f784b9c8430b1f2d6967e99b0b819 Author: Israel Figueroa Date: Tue Nov 22 16:01:46 2011 -0300 Repo init diff --git a/BAM/cron/crontasks.php b/BAM/cron/crontasks.php new file mode 100644 index 0000000..966e96c --- /dev/null +++ b/BAM/cron/crontasks.php @@ -0,0 +1,44 @@ +. + * +*/ + + +$conf = simplexml_load_file("../lib/Dazzler.conf"); + +require_once '../lib/class/Db.inc.php'; +require_once '../lib/class/XmlRequest.inc.php'; + +$DB = new Db($conf->db->name, $conf->db->host, $conf->db->user, $conf->db->password, 'pg'); +$XmlRequest = new XmlRequest(); + +$DB->Consulta("select id from projects where estado <= 0;"); +while($info = $DB->SacaTupla()){ + $XmlRequest->setProject($info[0]); + $XmlRequest->createAccounts(); + $XmlRequest->deleteDetaching(); + $XmlRequest->getStats(); + $XmlRequest->saveStatus(); + } + +$log = fopen("crontask.log","w"); +$msg = implode("\n",$XmlRequest->Msg); +fwrite($log,$msg); +fclose($log); + +?> diff --git a/BAM/cron/crontasks.sh b/BAM/cron/crontasks.sh new file mode 100644 index 0000000..00c58ca --- /dev/null +++ b/BAM/cron/crontasks.sh @@ -0,0 +1,4 @@ +#!/bin/sh +cd /home/dazzler/www/BAM/cron +OUT=`/usr/bin/php -q crontasks.php` +echo $OUT >> cron.log diff --git a/BAM/css/dazzler.css b/BAM/css/dazzler.css new file mode 100644 index 0000000..c04bc24 --- /dev/null +++ b/BAM/css/dazzler.css @@ -0,0 +1,156 @@ +a { +color: #1e4176; +} + +a:link{ +color: #1e4176; +} + +a:hover{ +color: #15428b; +} + +/* formato de los paneles */ +.x-panel-body p { + margin:8px 3px !important; +} +.x-panel-body h4{ + color:#083772; + border-bottom:1px dashed #ccc; + margin:8px 0; + padding-bottom:3px; +} + +#Dazzler-header{ + border:0 none; + background:#1E4176 url(/BAM/pics/hd-bg.gif) repeat-x 0 0; + padding-top:3px; + padding-left:3px; +} + +#Dazzler-header .Dazzler-title { + font:normal 16px tahoma, arial, sans-serif; + color:white; + margin:3px; +} + +.Dazzler-nula td{ + color:gray; +} + +.controlBtn img { + padding-left: 4px; + cursor: pointer; + } + +/* + * FileUploadField component styles + */ +.x-form-file-wrap { + position: relative; + height: 22px; +} +.x-form-file-wrap .x-form-file { + position: absolute; + right: 0; + -moz-opacity: 0; + filter:alpha(opacity: 0); + opacity: 0; + z-index: 2; + height: 22px; +} +.x-form-file-wrap .x-form-file-btn { + position: absolute; + right: 0; + z-index: 1; +} +.x-form-file-wrap .x-form-file-text { + position: absolute; + left: 0; + z-index: 3; + color: #777; +} + +/* + * Welcome + */ + + +.x-panel-body { + font: 12px tahoma,arial,sans-serif; + position:relative; + top:0; + left: 0; + zoom:1; +} +.col{ + margin:0 250px 0 10px; + zoom:1; + padding: 10px 0; +} + +.col-last { + width: 220px; + position:absolute; + right:10px; + top:10px; +} + +.block{ + margin-bottom:10px; +} +.block-title{ + color: #1E4176; + font:normal 18px helvetica,arial,tahoma,verdana,sans-serif; + letter-spacing:-1px; + padding: 4px; + padding-left: 8px; +} +.block-body{ + padding:8px; + padding-top:2px; +} +.block-body b{ + color:#333333; + font-size:11px; +} +.block-body em { + display:block; + margin-top:5px; + font-size:11px; + color:gray; + text-align:right; +} +.list{ + list-style: square; + padding-left:20px; + margin-top:5px; +} + +.res-block { + padding-top:5px; + background:transparent url(/BAM/pics/block-top.gif) no-repeat; + width:210px; + margin-bottom:15px; +} +.res-block-inner { + padding:6px 11px; + background:transparent url(/BAM/pics/block-bottom.gif) no-repeat left bottom; +} + +.res-block h3 { +/* font: bold 12px tahoma,arial,sans-serif; */ + color:#555; + margin-bottom:8px; +} + +.res-block ul { + list-style-type: disc; + margin-left:15px; +/* font: normal 12px tahoma,arial,sans-serif; */ + color:#555; +} + +.res-block ul li { + margin:0 0 5px 3px; +} diff --git a/BAM/download/Instalador_BOINC.zip b/BAM/download/Instalador_BOINC.zip new file mode 100644 index 0000000..d5749f8 Binary files /dev/null and b/BAM/download/Instalador_BOINC.zip differ diff --git a/BAM/download/acct_mgr_login.php b/BAM/download/acct_mgr_login.php new file mode 100644 index 0000000..196e183 --- /dev/null +++ b/BAM/download/acct_mgr_login.php @@ -0,0 +1,51 @@ +. + * +*/ + +$conf = simplexml_load_file("../lib/Dazzler.conf"); + +session_start(); +session_name($conf->conf->session_name); +ob_start(); + +require_once $_SERVER['DOCUMENT_ROOT'].'/BAM/lib/class/Db.inc.php'; +$DB = new Db($conf->db->name, $conf->db->host, $conf->db->user, $conf->db->password, 'pg'); + +$n = $DB->Consulta("select users.id,login,weakhash from (usuarios left join users on(users.id = usuarios.id)) where sesion = {$_SESSION['SesionId']}"); +if(!$n) + die("SSID: {$_SESSION['SesionId']}"); + +list($id,$login,$weak) = $DB->SacaTupla(); + +$weakHash = "{$id}_{$weak}"; + +$rand = md5 (time()); //random string + +ob_end_clean(); + +header("Cache-Control: no-store, no-cache"); +header("Expires: Sat, 26 Jul 1997 05:00:00 GMT"); +header("Content-Disposition: attachment; filename=\"acct_mgr_login.xml\""); +echo " +$weakHash +$rand +0 +"; + +?> diff --git a/BAM/download/acct_mgr_url.php b/BAM/download/acct_mgr_url.php new file mode 100644 index 0000000..0854524 --- /dev/null +++ b/BAM/download/acct_mgr_url.php @@ -0,0 +1,32 @@ +. + * +*/ + +$conf = simplexml_load_file("../lib/Dazzler.conf"); + + +header("Cache-Control: no-store, no-cache"); +header("Expires: Sat, 26 Jul 1997 05:00:00 GMT"); +header("Content-Disposition: attachment; filename=\"acct_mgr_url.xml\""); +echo " +{$conf->account_manager->name} +{$conf->account_manager->master_url} +"; + +?> diff --git a/BAM/get_project_config.php b/BAM/get_project_config.php new file mode 100644 index 0000000..1c37bde --- /dev/null +++ b/BAM/get_project_config.php @@ -0,0 +1,43 @@ +. + * +*/ + +$conf = simplexml_load_file("lib/Dazzler.conf"); + +$dom = new DOMDocument('1.0', 'utf-8'); +$dom->formatOutput = true; + +$xml = $dom->createElement('project_config'); +$dom->appendChild($xml); + +//////////////////Encabezado(top)///////////////////////// + +$element = $dom->createElement('name',$conf->account_manager->name); +$xml->appendChild($element); +$element = $dom->createElement('min_passwd_length',$conf->account_manager->min_passwd_length); +$xml->appendChild($element); +$element = $dom->createElement('account_manager'); +$xml->appendChild($element); +$element = $dom->createElement('uses_username'); +$xml->appendChild($element); +$element = $dom->createElement('client_acount_creation_disabled'); +$xml->appendChild($element); + +echo $dom->saveXML(); +?> diff --git a/BAM/index.php b/BAM/index.php new file mode 100644 index 0000000..90e5c3b --- /dev/null +++ b/BAM/index.php @@ -0,0 +1,50 @@ +. + * +*/ + +$conf = simplexml_load_file("lib/Dazzler.conf"); +?> + + + + + Dazzler - VCSC Manager + + + + + + +
+ + + + + + + + + + + + + + + + diff --git a/BAM/js/Core.php b/BAM/js/Core.php new file mode 100644 index 0000000..05a99a3 --- /dev/null +++ b/BAM/js/Core.php @@ -0,0 +1,89 @@ +. + * +*/ + +$conf = simplexml_load_file("../lib/Dazzler.conf"); + +session_start(); +session_name($conf->conf->session_name); +ob_start(); + +require("../lib/RegistraVisita.inc.php"); + +header("Cache-Control: no-store, no-cache"); +header("Expires: Sat, 26 Jul 1997 05:00:00 GMT"); +header("Content-Type: application/x-javascript; charset=UTF-8"); + +if($IdentificadorUsuario == 0){ + ?> + Ext.onReady(function(){ + + Ext.QuickTips.init(); + Ext.Direct.addProvider({ + "type":"remoting", + "url":"\/BAM\/js\/rpc.php", + "actions": {"Remote":[{"name":"login","len":1, "formHandler":true}]} + }); + + + Dazzler.logWin = new Dazzler.core.loginWindow({}); + }); + + + Ext.onReady(function(){ + Ext.QuickTips.init(); + + Ext.Direct.addProvider({ + "type" :"remoting", + "url" :"\/BAM\/js\/rpc.php", + "timeout" : 90000, + "enableBuffer" : 100, + "actions" : { + "core":[{"name":"getTree","len":1},{"name":"Logout","len":0},{"name":"show","len":2},{"name":"userGroups","len":1},{"name":"userSession","len":1},{"name":"UserLoad","len":1},{"name":"UserSave","len":1, "formHandler":true}], + "api":[{"name":"customFn","len":1},{"name":"submitForm","len":1, "formHandler":true},{"name":"loadForm","len":1},{"name":"getTree","len":1},{"name":"DirectRead","len":1},{"name":"DirectCreate","len":1},{"name":"DirectUpdate","len":1},{"name":"DirectDestroy","len":1},{"name":"show","len":2}] + }, + "namespace" : "Dazzler" + }); + + + Ext.Direct.on('lpc',function(e){ + if(e.data == 'login'){ + Ext.Msg.alert('Conexión', 'La conexión ha expirado, debe identificarse nuevamente para utilizar el sistema.',function(){window.location = '/BAM/';}); + } + else if(e.data == 'machine'){ + Ext.Msg.alert('Conexión', 'Ha ingresado desde otra ubicación. Sólo se permite una sessión activa por usuario.',function(){window.location = '/BAM/';}); + } + else{ + Ext.Msg.alert('Advertencia', e.data); + } + }); + + SCV = new Dazzler.core.aplication({ + titleId : 'Dazzler-header', + titleContent: '
Dazzler - account_manager->name ?>
' + }); + + }); + diff --git a/BAM/js/Dazzler.core.js b/BAM/js/Dazzler.core.js new file mode 100644 index 0000000..b5822f3 --- /dev/null +++ b/BAM/js/Dazzler.core.js @@ -0,0 +1,517 @@ +/* ! + * This file is part of Dazzler + * Copyright(c) 2011 USI - Universidad de Concepcion + * + * Dazzler is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Dazzler is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Dazzler. If not, see . + * +*/ + +Ext.ns('Dazzler.core'); + +Dazzler.core.aplication = Ext.extend(Ext.Viewport, { + + constructor: function(config){ + + this.LoadedClass = new Array(); +/* *********************** Tabpanel 1: Informacion de la Cuenta ******************** */ + /* custom Stores */ + this.groupsStore = new Ext.data.Store({ + proxy : new Ext.data.DirectProxy({ directFn: Dazzler.core.userGroups }), + reader : new Ext.data.JsonReader({ + root: 'groups', + totalProperty: 'totalCount', + idProperty: 'id', + messageProperty: 'msg', + fields: ['id', 'nombre'] + }), + remoteSort : true, + sortInfo : {field: 'nombre', direction: 'ASC'} + }); + + this.userSessionDataStore = new Ext.data.Store({ + proxy : new Ext.data.DirectProxy({ directFn: Dazzler.core.userSession }), + reader : new Ext.data.JsonReader({ + root: 'sessions', + totalProperty: 'totalCount', + idProperty: 'id', + messageProperty: 'msg', + fields: ['id', 'inicio','fin','ip','iptxt','ipcls','resolucion','sotxt','socls','navegadortxt','navegadorcls', 'useragent','duracion', 'estado', 'estadotxt'] + }), + remoteSort : true, + sortInfo : {field: 'id', direction: 'DESC'} + }); + + this.userSessionGrid = new Ext.ux.crudGridPanel.rPagingGrid({ + region : 'center', + + title : 'Conexiones del usuario', + defaultDesc : 'sesiones', + iconCls : Ext.ux.TDGi.iconMgr.getIcon('server'), + + defaulPageSize : 10, + store : this.userSessionDataStore, + + buildColumns : this.builSessionColumns + }); + + this.userSessionForm = new Ext.form.FormPanel({ + title : 'Detalle de la conexión', + region : 'east', + frame : true, + monitorValid : true, + width : 550, + defaultType : 'displayfield', + defaults : { anchor: '95%' }, + paramsAsHash : true, + items : this.buildSessionFormItems() + }); + + this.userSessionData = new Ext.Container({ + border : false, + region : 'south', + title : 'Conexiones', + height : 300, + layout : 'border', + items: [ this.userSessionGrid, this.userSessionForm ] + }); + + + this.userGroupGrid = new Ext.ux.crudGridPanel.rPagingGrid({ + region : 'east', + title : 'Grupos del usuario', + width : 350, + defaultDesc : 'grupos', + iconCls : Ext.ux.TDGi.iconMgr.getIcon('server'), + + defaulPageSize : 25, + store : this.groupsStore, + + buildColumns : this.buildGroupColumns + }); + + this.userFormData = new Ext.form.FormPanel({ + title : 'Informaón del usuario', + region : 'center', + frame : true, + monitorValid: true, + paramsAsHash: true, + items : this.buildUserFormItems(), + buttons : this.buildUserFormButtons(), + api : { load: Dazzler.core.UserLoad, submit: Dazzler.core.UserSave } + }); + + this.userPanel = new Ext.Container({ + title : 'Datos de usuario', + iconCls : Ext.ux.TDGi.iconMgr.getIcon('user_magnify'), + layout : 'border', + border : false, + items : [this.userFormData, this.userSessionData, this.userGroupGrid] + }); +/* *********************** Tabpanel 0: Contenido ******************** */ + this.treeSelModel = new Ext.tree.DefaultSelectionModel(); + this.rootTreeNode = new Ext.tree.AsyncTreeNode({ id: 'menunode.1', text: 'MenuRoot', expanded:true }); + + this.mainMenu = new Ext.tree.TreePanel({ + region : 'west', + title : 'Menu', + width : 220, + rootVisible : false, + lines : false, + autoScroll : true, + + loader : this.buildTreeNode(), + selModel : this.treeSelModel, + + root : this.rootTreeNode + }); + + this.mainContent = new Ext.Container({ + layout : 'fit', + region :'center', + border : false + }); + + this.contenido = new Ext.Container({ + layout : 'border', + title : 'Aplicación', + iconCls : Ext.ux.TDGi.iconMgr.getIcon('application_side_tree'), + border : false, + items : [this.mainMenu, this.mainContent] + }); + +/* *********************** Estructura base titulo y contenido ******************** */ + this.titulo = new Ext.BoxComponent({ + id : config.titleId, + border : false, + height : 39, + html : config.titleContent + }); + + this.tabContent = new Ext.TabPanel({ + activeTab : 0, + anchor :'100% -41', + items : [this.contenido, this.userPanel, {title: 'Cerrar sessión', id:'logoutab', iconCls: Ext.ux.TDGi.iconMgr.getIcon('disconnect')} ] + }); + + + config = Ext.apply({ + layout : 'anchor', + items : [this.titulo, this.tabContent] + }, config); + + Dazzler.core.aplication.superclass.constructor.call(this,config); + + this.tabContent.on('beforetabchange',this.logoutTab,this); + this.treeSelModel.on('selectionchange',this.selectTreeNode,this) + + + this.userSessionGrid.on({ + 'rowselect' : this.sessionSelect, + 'rowdeselect' : this.sessionDeselect, + 'datachanged' : this.sessionDeselect, + scope : this + }); + + Ext.get("Dazzler-Title").on('click',this.showDazzler,this); + + this.mainMenu.getLoader().on('load',this.initData,this,{single: true}); + }, + +/* *********************** About Dazzler ******************** */ +showDazzler: function(){ + window.open('http://en.wikipedia.org/wiki/Dazzler','dazzlerWindow','width=800,height=600,toolbar=yes,location=yes,directories=yes,status=yes,menubar=yes,scrollbars=yes,copyhistory=yes,resizable=yes'); +}, + +/* ************************* funciones ************************* */ +buildTreeNode: function(){ + return new Ext.tree.TreeLoader({ + baseAttrs : { expanded: true }, + directFn : Dazzler.core.getTree, + + createNode : function(attr) { + if(attr.xicon){ + attr.iconCls = Ext.ux.TDGi.iconMgr.getIcon(attr.xicon); + } + return Ext.tree.TreeLoader.prototype.createNode.call(this, attr); + } + }); + }, +/* ************************* funciones ************************* */ +buildUserFormItems : function(config){ + return [{ name : 'id', + xtype : 'hidden' + },{ + xtype : 'fieldset', + title : 'Datos de usuario', + defaults: {anchor: '95%'}, + items :[{ + name : 'login', + fieldLabel : 'Usuario', + xtype : 'displayfield' + },{ + name : 'nombre', + fieldLabel : 'Nombre', + xtype : 'textfield', + allowBlank : false + },{ + name : 'correo', + fieldLabel : 'Correo', + xtype : 'displayfield' + }] + },{ + xtype : 'fieldset', + title : 'Cambio de clave de usuario', + defaults: {anchor: '90%'}, + items :[{ + ref : '../fnclave', + name : 'nclave', + xtype : 'textfield', + inputType : 'password', + fieldLabel : 'Nueva Clave', + validator : this.passFunc + },{ + ref : '../fcclave', + name : 'cclave', + xtype : 'textfield', + inputType : 'password', + fieldLabel : 'Confirmación', + validator : this.passFunc + }] + + },{ + xtype : 'textfield', + ref : '../faclave', + name : 'aclave', + inputType : 'password', + fieldLabel : 'Clave actual', + anchor : '40%', + allowBlank : false, + invalidText : 'Debe ingresar la clave actual para realizar cualquier modificación' + }]; + + + }, +buildUserFormButtons : function(config){ + return [{ + text : 'Guardar', + formBind: true, + scope : this, + handler : this.saveUserForm + }]; + }, +buildSessionFormItems: function(){ + return [{ + name : 'id', + fieldLabel : 'Id de Sesión' + },{ + name : 'inicio', + fieldLabel : 'Inicio sesión' + },{ + name : 'fin', + fieldLabel : 'Última acción' + },{ + name : 'duracion', + fieldLabel : 'Duración' + },{ + name : 'estadotxt', + fieldLabel : 'Estado' + },{ + name : 'ip', + fieldLabel : 'Ip' + },{ + name : 'navegadortxt', + fieldLabel : 'Navegador' + },{ + name : 'sotxt', + fieldLabel : 'S.O.' + },{ + name : 'resolucion', + fieldLabel : 'Resolución' + },{ + name : 'useragent', + fieldLabel : 'Agente' + }]; + }, +builSessionColumns: function(){ + return [{ + dataIndex : 'id', + header : 'Sid' + },{ + dataIndex : 'inicio', + header : 'Inicio' + },{ + dataIndex : 'fin', + header : 'Último' + },{ + dataIndex : 'ip', + header : 'Ip' + }]; + }, +buildGroupColumns: function(){ + return [{ + dataIndex: 'nombre', + header: 'Nombre' + }]; + }, +/* ************************* utilitarios ************************* */ +checkPass: function(value){ + if(value.length > 0){ + var pwda = Ext.getCmp('fnclave').getValue(); + var pwdb = Ext.getCmp('fcclave').getValue(); + + if(value.length <= 4) + return "La clave debe tener almenos 5 caracteres"; + else if(value.length >= 20) + return "La clave debe tener 20 caracteres como máximo"; + else if(pwda.length > 0 && pwdb.length > 0){ + if(pwda != pwdb) + return "Las claves ingresadas deben ser idénticas"; + else{ + Ext.getCmp('fnclave').clearInvalid(); + Ext.getCmp('fcclave').clearInvalid(); + } + } + } + return true; + }, +errorPopUp: function(msg){ + if(msg) + Ext.Msg.alert('Error', msg); + else + Ext.Msg.alert('Error', 'Se produjo un error al comuncarse con el servidor, verifique su conexión e intentelo nuevamente.'); + }, +/* ************************* eventos ************************* */ +initData: function(){ + this.treeSelModel.select(this.rootTreeNode.firstChild); + this.userFormData.getForm().load({}); + this.userSessionDataStore.load({params: {start: 0, limit: 10}}); + this.groupsStore.load({params: {start: 0, limit: 25}}); + }, +aboutWin: function(){ + this.aboutWin.show(); + }, +aboutClose: function(){ + this.aboutWin.hide(); + }, +selectTreeNode: function(tree,node){ + if(node.attributes.tipo > 0){ + this.mainContent.getEl().mask('Cargando contenido...','ext-el-mask-msg x-mask-loading'); + + var full = this.LoadedClass.indexOf(node.id) == -1; + + this.mainContent.removeAll(); + + Dazzler.core.show(node.attributes.xid,full,this.showCallback,this); + } + }, + +showCallback: function(result,e){ + if(result.success){ + var full = this.LoadedClass.indexOf(result.nodeid) == -1; + if(full) + this.LoadedClass.push(result.nodeid); + + this.mainContent.update(result.show,true); + } + else{ + this.mainContent.getEl().unmask(); + this.errorPopUp(); + } + }, + +sessionDeselect: function(){ + this.userSessionForm.getForm().reset(); + }, +sessionSelect: function(sm){ + var record = sm.getSelected(); + this.userSessionForm.getForm().loadRecord(record); + }, +saveUserForm: function(){ + this.userFormData.getForm().submit({ + waitTitle:'Porfavor espere...', + waitMsg:'Guardando...', + scope: this, + success:function(form){ + form.reset(); + form.load({}); + }, + failure:function(form,action){ + this.errorPopUp(action.result.error.reason); + form.reset(); + form.load({}); + } + }); + }, +logoutTab: function(t,n,c){ + if(n.id == 'logoutab'){ + Dazzler.core.Logout( + function(result,e){ + Ext.Msg.alert('Fin de sessión', 'Sessión cerrada, presione OK para continuar.',function(){ + window.location = '/'; + }); + } + ); + return false; + } + else{ + return true; + } + } + + }); + + +Dazzler.core.loginWindow = Ext.extend(Ext.Window, { + constructor: function(config){ + this.loginForm = new Ext.form.FormPanel({ + labelWidth : 80, + iconCls : Ext.ux.TDGi.iconMgr.getIcon('application_key'), + frame : true, + title : 'Por favor identifiquese para continuar', + defaultType : 'textfield', + monitorValid: true, + + items : this.buildFormItems(), + api : { submit: Remote.login }, + keys : [{ + key : [ Ext.EventObject.ENTER ], + ctrl : false, + scope : this, + handler : this.gogoLogin + }], + buttons :[{ + text : 'Ingresar', + formBind: true, + scope : this, + handler : this.gogoLogin + }] + }); + + config = Ext.apply({ + layout : 'fit', + width : 300, + height : 150, + closable : false, + resizable : false, + plain : true, + border : false, + initHidden : false, + items : [ this.loginForm ] + }, config); + + Dazzler.core.loginWindow.superclass.constructor.call(this,config); + + }, +buildFormItems: function(){ + return [{ + fieldLabel:'Usuario', + name:'loginUsername', + allowBlank:false, + blankText: 'Debe ingresar un nombre de usuario' + },{ + fieldLabel:'Clave', + name:'loginPassword', + inputType:'password', + allowBlank:false , + blankText: 'La clave no puede estar vacía' + },{ + name:'spixels', + inputType:'hidden', + value: screen.width * screen.height + },{ + name:'swidth', + inputType:'hidden', + value: screen.width + }]; + }, + +gogoLogin: function(){ + this.loginForm.getForm().submit({ + waitTitle : 'Verificando credenciales', + waitMsg : 'Autentificando...', + success : function(){ + window.location = '/BAM/'; + }, + failure : function(form, action){ + if(action.failureType === Ext.form.Action.SERVER_INVALID){ + Ext.Msg.alert('Error de autentificación', action.result.error.reason); + }else{ + Ext.Msg.alert('Error', 'Se produjo un error al comuncarse con el servidor, verifique su conexión e intentelo nuevamente.'); + } + this.loginForm.getForm().reset(); + } + }); + } +}); + diff --git a/BAM/js/Dazzler/Dazzler.admin.content.js b/BAM/js/Dazzler/Dazzler.admin.content.js new file mode 100644 index 0000000..131a228 --- /dev/null +++ b/BAM/js/Dazzler/Dazzler.admin.content.js @@ -0,0 +1,540 @@ +/* ! + * This file is part of Dazzler + * Copyright(c) 2011 USI - Universidad de Concepcion + * + * Dazzler is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Dazzler is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Dazzler. If not, see . + * +*/ + +function App_define(){ + +return " +Ext.ns('Dazzler.admin'); +/* Panel administracion de contenido */ + +Dazzler.admin.contentPanel = function(config){ + this.contentTree = new Ext.tree.TreePanel({ + id:'contentMenu', + region:'west', + title: 'Menú del Sistema', + width: 220, + rootVisible:true, + lines:false, + autoScroll:true, + collapsed: false, + collapsible:true, + selModel: new Ext.tree.DefaultSelectionModel({ + listeners: { + 'selectionchange': function(tree,node){ + //Clean stuff from previous loads + Ext.getCmp('contentForm').getForm().reset(); + Ext.getCmp('contentForm').setDisabled(true); + Ext.getCmp('contentAdminGroups').setDisabled(true); + + Ext.getCmp('contentAddHijo').setDisabled(true); + Ext.getCmp('contentDelHijo').setDisabled(true); + + Ext.getCmp('contentGroupGrid').getStore().load({params:{'contentid':node.attributes.xid,start: 0, limit: 25}}); + Ext.getCmp('comboGroup').getStore().load({params:{'contentid':node.attributes.xid}}); + + + Ext.getCmp('contentForm').getForm().load({ + params:{ 'nodeid': node.id }, + + success:function(){ + //selected, enable buttons + Ext.getCmp('contentAddHijo').setDisabled(false); + Ext.getCmp('contentDelHijo').setDisabled(false); + Ext.getCmp('contentForm').setDisabled(false); + + Ext.getCmp('contentAdminGroups').setDisabled(false); + + Ext.getCmp('btnQuitarGrupo').setDisabled(true); + Ext.getCmp('btnAgregarGrupo').setDisabled(true); + + }, + failure:function(){ + + } + }); + } + } + }), + loader: new Ext.tree.TreeLoader({ + baseAttrs: {expanded: true}, + directFn: Dazzler.api.getTree, + paramsAsHash: true, + baseParams: {xid: %xid%}, + createNode: function(attr) { + if(attr.xicon){ + attr.iconCls = Ext.ux.TDGi.iconMgr.getIcon(attr.xicon); + } + return Ext.tree.TreeLoader.prototype.createNode.call(this, attr); + } + }), + root: new Ext.tree.AsyncTreeNode({ id: 'menunode.1', text: '/', expanded:true }), + bbar: [{ + id: 'refreshTree', + text: 'Actualiza', + iconCls: Ext.ux.TDGi.iconMgr.getIcon('reload'), + handler: function(){ + Ext.getCmp('contentForm').getForm().reset(); + Ext.getCmp('contentForm').setDisabled(true); + Ext.getCmp('contentAddHijo').setDisabled(true); + Ext.getCmp('contentDelHijo').setDisabled(true); + Ext.getCmp('contentAdminGroups').setDisabled(true); + Ext.getCmp('contentMenu').getRootNode().reload(); + } + }], + tbar: [{ + id: 'contentAddHijo', + text: 'Agregar Hijo', + iconCls: Ext.ux.TDGi.iconMgr.getIcon('folder_add'), + disabled: true, + handler: function(){ + var node = Ext.getCmp('contentMenu').getSelectionModel().getSelectedNode(); + Ext.MessageBox.prompt('Confirmación', 'Ingrese el nombre para el hijo del nodo \"'+node.text+'\"' , function(btn,text){ + if(btn == 'ok'){ + Dazzler.api.customFn({'xid': %xid%, 'customFn':'addNode','pid': node.id,'nombre': text},function(result){ + if(result.success){ + Ext.getCmp('contentForm').getForm().reset(); + Ext.getCmp('contentForm').setDisabled(true); + Ext.getCmp('contentAddHijo').setDisabled(true); + Ext.getCmp('contentDelHijo').setDisabled(true); + Ext.getCmp('contentMenu').getRootNode().reload(); + } + else{ + Ext.Msg.alert('Error', 'Se produjo un error al agregar el nodo.'); + } + }); + } + }); + } + },{ + id: 'contentDelHijo', + text: 'Quitar Nodo', + iconCls: Ext.ux.TDGi.iconMgr.getIcon('folder_delete'), + disabled: true, + handler: function(){ + Ext.MessageBox.confirm('Confirmación', '¿Está seguro que desea eliminar el elemento seleccionado?' , function(btn){ + if(btn == 'yes'){ + var node = Ext.getCmp('contentMenu').getSelectionModel().getSelectedNode(); + Dazzler.api.customFn({'xid': %xid%, 'customFn':'delNode','nid': node.id},function(result){ + if(result.success){ + Ext.getCmp('contentForm').getForm().reset(); + Ext.getCmp('contentForm').setDisabled(true); + Ext.getCmp('contentAddHijo').setDisabled(true); + Ext.getCmp('contentDelHijo').setDisabled(true); + Ext.getCmp('contentMenu').getRootNode().reload(); + } + else{ + Ext.Msg.alert('Error', 'Se produjo un error al eliminar el nodo.'); + } + }); + } + }); + } + }] + }); + + this.dataPanel = new Ext.form.FormPanel({ + id:'contentForm', + region:'center', + title: 'Datos del nodo', + baseParams: {xid: %xid%}, + frame:true, + disabled: true, + paramsAsHash: true, + items: [{ //fielset con info + xtype:'fieldset', + title: 'Información sobre el nodo', + collapsible: true, + autoHeight:true, + defaultType: 'textfield', + anchor: '100%', + defaults: {anchor: '90%'}, + items:[ + {id: 'idDelNodo', name: 'id', xtype:'hidden'}, + {name: 'pid', fieldLabel: 'Padre', allowBlank: false}, + {name: 'pos', fieldLabel: 'Posicion', allowBlank: false}, + {name: 'tipo', fieldLabel: 'Tipo', allowBlank: false}, + {name: 'nombre', fieldLabel: 'Titulo', allowBlank: false}, + {name: 'icon', fieldLabel: 'Icono'} + ] + },{ +// id:'contentEditor', hideLabel: true, xtype:'htmleditor', name: 'contenido', anchor: '100% -35', enableSourceEdit: true + id:'contentEditor', hideLabel: true, xtype:'textarea', name: 'contenido', anchor: '100% -40' + }], + + buttons: [ + { + text: 'Guardar', + formBind: true, + handler:function(){ + //Disable other actions + Ext.getCmp('contentForm').getForm().submit({ + waitTitle:'Porfavor espere...', + waitMsg:'Guardando...', + success:function(){ + //Reload menu +// Ext.getCmp('contentMenu').getRootNode().reload(); + }, + + failure:function(form, action){ + //Enable again + Ext.Msg.alert('Error', 'Se produjo un error al guardar los datos.'); + } + }); + } + } + ], + + api: { + load: Dazzler.api.loadForm, + submit: Dazzler.api.submitForm + } + + }); + + this.dataSelectStore = new Ext.data.Store({ + id: 'groupComboStore', + proxy: new Ext.data.DirectProxy({ directFn: Dazzler.api.customFn }), + reader: new Ext.data.JsonReader({ + root: 'groups', + totalProperty: 'totalCount', + idProperty: 'id', + messageProperty: 'msg', + fields: ['id', 'nombre'] + }), + baseParams: {'xid': %xid%, 'customFn': 'contentGroupCombo'}, + remoteSort: true, + sortInfo: {field: 'nombre', direction: 'ASC'} + }); + this.dataGridStore = new Ext.data.Store({ + proxy: new Ext.data.DirectProxy({ directFn: Dazzler.api.customFn }), + reader: new Ext.data.JsonReader({ + root: 'groups', + totalProperty: 'totalCount', + idProperty: 'id', + messageProperty: 'msg', + fields: ['id', 'nombre'] + }), + writer: new Ext.data.JsonWriter({ + encode: false, writeAllFields: true + }), + baseParams: {'xid': %xid%, 'customFn': 'contentGroupGrid'}, + remoteSort: true, + sortInfo: {field: 'nombre', direction: 'ASC'} + }); + + this.dataGroups = new Ext.Panel({ + region:'east', + title: 'Grupos del nodo', + layout: 'border', + width: 300, + collapsible: true, + id: 'contentAdminGroups', + listeners: { + 'afterlayout': { + fn: function(p){ + p.disable(); + }, + single: true // important, as many layouts can occur + } + }, + items : [ + new Ext.FormPanel({ + id: 'contentAddGroup', + region:'north', + frame:true, + height:120, + labelWidth: 45, + items:[{ + xtype: 'fieldset', + title: 'Agregar grupos', + items: [{ + id: 'comboGroup', + xtype: 'combo', + fieldLabel: 'Grupos', + name: 'grupos', + store: this.dataSelectStore, + mode: 'local', + forceSelection: true, + valueField: 'id', + displayField: 'nombre', + editable: false, + triggerAction: 'all', + listeners:{ + 'select': function(){ + Ext.getCmp('btnAgregarGrupo').setDisabled(false); + } + } + }], + buttons: [{ + id: 'btnAgregarGrupo', + text: 'Agregar', + iconCls: Ext.ux.TDGi.iconMgr.getIcon('add'), + handler: function(){ + Ext.getCmp('contentAdminGroups').getEl().mask('Eliminando...','ext-el-mask-msg x-mask-loading'); + var SelContentId = Ext.getCmp('idDelNodo').getValue(); + var SelGroupId = Ext.getCmp('comboGroup').getValue(); + Ext.getCmp('comboGroup').clearValue(); + Ext.getCmp('btnQuitarGrupo').setDisabled(true); + Ext.getCmp('btnAgregarGrupo').setDisabled(true); + Dazzler.api.customFn({'xid': %xid%, 'customFn': 'addContentGroup', 'contentid':SelContentId, 'groupid':SelGroupId, },function(){ + Ext.getCmp('contentGroupGrid').getStore().load({params:{'contentid':SelContentId,start: 0, limit: 25}}); + Ext.getCmp('comboGroup').getStore().load({params:{'contentid':SelContentId}}); + Ext.getCmp('contentAdminGroups').getEl().unmask(); + }); + } + }] + }] + }), + new Ext.grid.GridPanel({ + id: 'contentGroupGrid', + border:'false', + region:'center', + + store: this.dataGridStore, + + colModel: new Ext.grid.ColumnModel({ + defaults: { sortable: true }, + columns: [ + { dataIndex: 'id' , width: 60, header: 'Id' }, + { dataIndex: 'nombre', header: 'Nombre' } ] + }), + + viewConfig: {forceFit: true }, + sm: new Ext.grid.RowSelectionModel({ + singleSelect:true, + listeners:{ + 'rowselect': function(){ + Ext.getCmp('btnQuitarGrupo').setDisabled(false); + } + } + }), + loadMask: {msg:'Cargando datos...'}, + + bbar: new Ext.PagingToolbar({ + pageSize: 25, + store: this.dataGridStore, + displayInfo: true, + displayMsg: 'Mostrando grupos {0} al {1} de {2}', + emptyMsg: 'No existen grupos' + }), + + tbar: [{ + id:'btnQuitarGrupo', + text: 'Quitar', + iconCls: Ext.ux.TDGi.iconMgr.getIcon('delete'), + disabled: true, + handler: function(){ + Ext.getCmp('contentAdminGroups').getEl().mask('Eliminando...','ext-el-mask-msg x-mask-loading'); + var SelContentId = Ext.getCmp('idDelNodo').getValue(); + var SelGroupId = Ext.getCmp('contentGroupGrid').getSelectionModel().getSelected().get('id'); + Ext.getCmp('comboGroup').clearValue(); + Ext.getCmp('btnQuitarGrupo').setDisabled(true); + Ext.getCmp('btnAgregarGrupo').setDisabled(true); + Dazzler.api.customFn({'xid': %xid%, 'customFn': 'delContentGroup', 'contentid':SelContentId, 'groupid':SelGroupId, },function(){ + Ext.getCmp('contentGroupGrid').getStore().load({params:{'contentid':SelContentId,start: 0, limit: 25}}); + Ext.getCmp('comboGroup').getStore().load({params:{'contentid':SelContentId}}); + Ext.getCmp('contentAdminGroups').getEl().unmask(); + }); + + } }] + }) + + ]//-items grupos de contenido + }); + + config = Ext.apply({ + + layout: 'border', + border: false, + items: [ this.contentTree, this.dataPanel, this.dataGroups ]//-items panel editor de aplicacion + + + }, config); + Dazzler.admin.contentPanel.superclass.constructor.call(this,config); + }; + +Ext.extend(Dazzler.admin.contentPanel, Ext.Panel, {}); + +"; +} + +function App_show(){ + +return " +SCV.mainContent.add(new Dazzler.admin.contentPanel() ); +SCV.mainContent.doLayout(); +"; +} + +function getTree($DB, $Data){ + list($crap,$nid) = explode('.',$Data->node); + $tree = array(); + $DB->Consulta("select id as xid,hijos,nombre as text,icon as xicon, tipo from contenido where id > 1 and pid = {$nid} order by pos asc;"); + + while($el = $DB->Sacatupla(false)){ + if ($el['hijos'] > 0) + $el['leaf'] = false; + else + + $el['leaf'] = true; + + $el['id'] = 'menunode.'.$el['xid']; + + $tree[$el['xid']] = $el; + } + return array_values($tree); + } + +function loadForm($DB, $Data){ + list($crap,$nid) = explode('.',$Data->nodeid); + $out = array(); + + $n = $DB->Consulta("select id, pid, pos ,nombre,tipo,icon, contenido from contenido where id = $nid"); + + if($n == 1){ + $out['success'] = true; + $t = $DB->SacaTupla(false); + $out['data'] = $t; + } + else{ + $out['success'] = false; + $out['data'] = array(); + } + return $out; + } + +function submitForm($DB, $Data){ + $out = array(); + + if($Data['tipo'] == 1) + $Data['contenido'] = html_entity_decode($Data['contenido'],ENT_NOQUOTES,'UTF-8'); + + $Esc = $DB->EscapeArray($Data,array('nombre','icon','contenido')); + $DB->Consulta("update contenido set pid={$Data['pid']}, pos={$Data['pos']} ,nombre='{$Esc['nombre']}',tipo={$Data['tipo']},icon='{$Esc['icon']}', contenido='{$Esc['contenido']}' where id = {$Data['id']};"); + + if($DB->Estado){ + $out['success'] = true; + } + else{ + $out['success'] = false; + $out['error']['reason'] = $DB->Error_debug; + } + return $out; + } + +function addNode($DB, $Data){ + $out = array(); + list($crap,$nid) = explode('.',$Data->pid); + + $Nombre = $DB->EscapeString($Data->nombre); + + $n = $DB->Consulta("select id from contenido where pid=$nid;")+1; + + $DB->Consulta("insert into contenido( pid, pos, tipo, icon, contenido, nombre) values($nid,$n,0,'folder','','$Nombre');"); + + if($DB->Estado){ + $out['success'] = true; + } + else{ + $out['success'] = false; + $out['error']['reason'] = $DB->Error_debug; + } + return $out; + } + +function delNode($DB, $Data){ + $out = array(); + list($crap,$nid) = explode('.',$Data->nid); + + + $DB->Consulta("delete from contenido where id = $nid;"); + + if($DB->Estado){ + $out['success'] = true; + } + else{ + $out['success'] = false; + $out['error']['reason'] = $DB->Error_debug; + } + return $out; + } + +function contentGroupGrid($DB, $Data){ +$out = array(); +$out['groups'] = array(); + +$DB->Consulta("select grupos.id, grupos.nombre from (gcontenido + left join grupos on (gcontenido.gid = grupos.id)) + where gcontenido.cid = {$Data->contentid} order by grupos.{$Data->sort} {$Data->dir} offset {$Data->start} limit {$Data->limit};"); +if(!$DB->Estado){ + $out['success'] = false; + $out['msg'] = $DB->Error_debug; + } +else{ + while($t = $DB->SacaTupla(false)){ + $out['groups'][] = $t; + } + $out['success'] = true; + } +return $out; +} + +function contentGroupCombo($DB, $Data){ +$out = array(); +$out['groups'] = array(); + +$DB->Consulta("select id, nombre from grupos where id not in (select gid from gcontenido where cid = {$Data->contentid}) order by {$Data->sort} {$Data->dir};"); + +while($t = $DB->SacaTupla(false)){ + $out['groups'][] = $t; + } +$out['success'] = true; + +return $out; +} + +function delContentGroup($DB, $Data){ +$out = array(); + +$DB->Consulta("delete from gcontenido where cid={$Data->contentid} and gid={$Data->groupid};"); + +if(!$DB->Estado){ + $out['success'] = false; + } +else{ + $out['success'] = true; + } + +return $out; +} + +function addContentGroup($DB, $Data){ +$out = array(); + +$DB->Consulta("insert into gcontenido(cid,gid) values({$Data->contentid},{$Data->groupid});"); + +if(!$DB->Estado){ + $out['success'] = false; + } +else{ + $out['success'] = true; + } + +return $out; +} diff --git a/BAM/js/Dazzler/Dazzler.admin.group.js b/BAM/js/Dazzler/Dazzler.admin.group.js new file mode 100644 index 0000000..e020b22 --- /dev/null +++ b/BAM/js/Dazzler/Dazzler.admin.group.js @@ -0,0 +1,395 @@ +/* ! + * This file is part of Dazzler + * Copyright(c) 2011 USI - Universidad de Concepcion + * + * Dazzler is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Dazzler is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Dazzler. If not, see . + * +*/ + +function App_define(){ +return " +Ext.ns('Dazzler.admin'); +/* Panel administracion de grupos */ + +Dazzler.admin.groupData = function(config){ + config = Ext.apply({ + proxy: new Ext.data.DirectProxy({ + api: { + read: Dazzler.api.DirectRead, + create: Dazzler.api.DirectCreate, + update: Dazzler.api.DirectUpdate, + destroy: Dazzler.api.DirectDestroy + }, + listeners: { + exception : function(proxy, type, action, options, res, arg) { + var vMsg = ''; + if(type == 'response'){ + vMsg = 'Ocurrio un error al comunicarse al servidor, verifique la conexión de red e intente la operación nuevamente'; + } + else{ + vMsg = res.msg; + } + Ext.Msg.show({title: 'Error',msg: vMsg,icon: Ext.MessageBox.ERROR, buttons: Ext.Msg.OK}); + } + + } +// baseParams: {type: 'dataquery'}, +// method: 'POST', +// directFn: Dazzler.api.DirectFn + }), + reader: new Ext.data.JsonReader({ + root: 'groups', + totalProperty: 'totalCount', + idProperty: 'id', + messageProperty: 'msg', + fields: ['id','nombre','usuarios','contenido'] + }), + writer: new Ext.data.JsonWriter({ + encode: false, writeAllFields: false + }), + + baseParams: {xid: %xid%}, + remoteSort: true, + sortInfo: {field: 'id', direction: 'ASC'}, + autoLoad: {params:{start: 0, limit: 25}} + }, config); + + Dazzler.admin.groupData.superclass.constructor.call(this,config); + }; + +Ext.extend(Dazzler.admin.groupData, Ext.data.Store, {}); + +Dazzler.admin.groupGrid = function(config){ + this.ds = new Dazzler.admin.groupData({id:'storeAdminGroup'}); + this.msm = new Ext.grid.RowSelectionModel( { singleSelect:true }); + + this.onAddGroup = config.onAddGroup ? config.onAddGroup : function(){}, + this.onEditGroup = config.onEditGroup ? config.onEditGroup : function(){}, + this.onDeleteGroup = config.onDeleteGroup ? config.onDeleteGroup : function(){}, + + config = Ext.apply({ + store: this.ds, + colModel: new Ext.grid.ColumnModel({ + defaults: { sortable: true }, + columns: [ + { dataIndex: 'id' , width: 60, header: 'Id' }, + { dataIndex: 'nombre', header: 'Nombre' }, + { dataIndex: 'usuarios', header: 'Usuarios', sortable: false }, + { dataIndex: 'contenido', header: 'Paginas', sortable: false }] + }), + viewConfig: {forceFit: true }, + sm: this.msm, + loadMask: {msg:'Cargando datos...'}, + + tbar: [{ + text: 'Agregar Grupo', + iconCls: Ext.ux.TDGi.iconMgr.getIcon('group_add'), + handler: this.onAddGroup + } , '->', { + text: 'Editar Grupo', + ref: '../EdtButton', + iconCls: Ext.ux.TDGi.iconMgr.getIcon('group_edit'), + disabled: true, + handler: this.onEditGroup + } , '-', { + text: 'Quitar Grupo', + ref: '../DelButton', + iconCls: Ext.ux.TDGi.iconMgr.getIcon('group_delete'), + disabled: true, + handler: this.onDeleteGroup + } ], + + bbar: new Ext.PagingToolbar({ + pageSize: 25, + store: this.ds, + displayInfo: true, + displayMsg: 'Mostrando grupos {0} al {1} de {2}', + emptyMsg: 'No existen grupos' + }) + }, config); + + Dazzler.admin.groupGrid.superclass.constructor.call(this,config); + + this.msm.on('rowselect', + function(sm){ + var SelGroupId = this.getSelectionModel().getSelected().get('id'); + this.EdtButton.setDisabled(false); + this.DelButton.setDisabled(false); + + } , this); + + this.msm.on('rowdeselect', + function(sm){ + Ext.getCmp('groupAdminGrid').EdtButton.setDisabled(true); + Ext.getCmp('groupAdminGrid').DelButton.setDisabled(true); + } , this) + + }; + +Ext.extend(Dazzler.admin.groupGrid, Ext.grid.GridPanel, { +/* + onAdd : function(){},//funciones auxiliares para comunicarse con los otros paneles. + onEdit : function(){}, + onDelete : function(){} +*/ +}); + + +Dazzler.admin.groupEditForm = function(config){ +// funciones auxiliares para comunicarse con los otros paneles. + + this.onSaveGroup = config.onSaveGroup ? config.onSaveGroup : function() {}, + this.onBackToGrid = config.onBackToGrid ? config.onBackToGrid : function() {}, + this.groupRecord = null, + + config = Ext.apply({ + frame: true, + items: [{ + xtype:'fieldset', + title: 'Datos de Grupo', + defaultType: 'textfield', + labelWidth: 150, + anchor: '99%', + defaults: {anchor: '90%'}, + items: [{ name: 'nombre', fieldLabel: 'Nombre', allowBlank: false } ] + }], + buttons: [{ text: 'Guardar', iconCls: Ext.ux.TDGi.iconMgr.getIcon('disk'), handler: this.onSaveGroup }, + { text: 'Volver', iconCls: Ext.ux.TDGi.iconMgr.getIcon('bullet_left'), handler: this.onBackToGrid }] + + }, config); + + Dazzler.admin.groupEditForm.superclass.constructor.call(this,config); + }; +Ext.extend(Dazzler.admin.groupEditForm, Ext.FormPanel, { }); + +/* Window container of the form */ +Dazzler.admin.groupEditWindow = function(config){ + + config = Ext.apply({ + id: 'groupEditWindow', + closable: false, + resizable: false, + modal: true, + closable: false, + resizable: false, + items: [ new Dazzler.admin.groupEditForm({ + id: 'groupEditForm', + + onBackToGrid: function(){ + Ext.getCmp('groupEditWindow').close(); + }, + onSaveGroup: function(){ + var form = Ext.getCmp('groupEditForm'); + if (!form.getForm().isValid()) { + Ext.Msg.show({ + title: 'Error al modificar', + msg: 'Los datos ingresados no son validos, intentelo nuevamente', + icon: Ext.MessageBox.ERROR, + buttons: Ext.Msg.OK + }); + return false; + } + form.getForm().updateRecord(form.groupRecord); + Ext.getCmp('groupEditWindow').close(); + } + }) ] + + }, config); + + Dazzler.admin.groupEditWindow.superclass.constructor.call(this,config); +} + +Ext.extend(Dazzler.admin.groupEditWindow, Ext.Window, { }); + +/* Window container of the form */ +Dazzler.admin.groupAddWindow = function(config){ + + config = Ext.apply({ + id: 'groupAddWindow', + closable: false, + resizable: false, + modal: true, + items: [ new Dazzler.admin.groupEditForm({ + id: 'groupAddForm', + + onBackToGrid: function(){ + Ext.getCmp('groupAddWindow').close(); + }, + onSaveGroup: function(){ + var form = Ext.getCmp('groupAddForm'); + if (!form.getForm().isValid()) { + Ext.Msg.show({ + title: 'Error al ingresar', + msg: 'Los datos del Grupo ingresados no son validos, intentelo nuevamente', + icon: Ext.MessageBox.ERROR, + buttons: Ext.Msg.OK + }); + return false; + } + var store = Ext.getCmp('groupAdminGrid').getStore(); + var record = new store.recordType(form.getForm().getValues()); + store.add(record); +// form.getForm().updateRecord(form.groupRecord); + Ext.getCmp('groupAddWindow').close(); + store.reload(); + } + }) ] + + }, config); + + Dazzler.admin.groupAddWindow.superclass.constructor.call(this,config); +} + +Ext.extend(Dazzler.admin.groupAddWindow, Ext.Window, { }); + +/* Panel de administracion de Grupo (contenedor) */ + + +Dazzler.admin.groupPanel = function(config){ + + var GroupGrid = new Dazzler.admin.groupGrid({ + id: 'groupAdminGrid', + region:'center', + title: 'Grupos del sistema', + onEditGroup: function(){ + var rec = Ext.getCmp('groupAdminGrid').getSelectionModel().getSelected(); + if (!rec) { + return false; + } + var mywin = new Dazzler.admin.groupEditWindow({ + title: 'Modificacion de Grupo', + width: 500 + }); + + Ext.getCmp('groupEditForm').getForm().loadRecord(rec); + Ext.getCmp('groupEditForm').groupRecord = rec; + + mywin.show(); + }, + onAddGroup: function(){ + var mywin = new Dazzler.admin.groupAddWindow({ + title: 'Agregar de Grupo', + width: 500 + }); + + mywin.show(); + }, + onDeleteGroup: function(){ + Ext.MessageBox.confirm('Confirmación', '¿Está seguro que desea eliminar al Grupo seleccionado?' , function(btn){ + if(btn == 'yes'){ + var groupgrid = Ext.getCmp('groupAdminGrid'); + groupgrid.getStore().remove(groupgrid.getSelectionModel().getSelected()); + groupgrid.EdtButton.setDisabled(true); + groupgrid.DelButton.setDisabled(true); + } + }); + } + }); + + config = Ext.apply({ + id: 'groupAdminPanel', + layout: 'border', + border: false, + items: [ GroupGrid ] + + }, config); + + Dazzler.admin.groupPanel.superclass.constructor.call(this,config); + }; + +Ext.extend(Dazzler.admin.groupPanel, Ext.Panel, {}); +"; +} + +function App_show(){ + +return " +SCV.mainContent.add( new Dazzler.admin.groupPanel() ); +SCV.mainContent.doLayout(); +"; + +} + +function DirectRead($DB, $Data){ +$out = array(); +$out['groups'] = array(); + +$DB->Consulta("select id, nombre from grupos order by {$Data->sort} {$Data->dir} offset {$Data->start} limit {$Data->limit};"); + +while($t = $DB->SacaTupla(false)){ + $out['groups'][] = $t; + } + +foreach($out['groups'] as $k => $grupo){ + $out['groups'][$k]['usuarios'] = $DB->Consulta("select uid from gusuarios where gid = {$grupo['id']};"); + $out['groups'][$k]['contenido'] = $DB->Consulta("select cid from gcontenido where gid = {$grupo['id']};"); + } +$out['success'] = true; + +return $out; + +} + +function DirectCreate($DB, $Data){ +$out = array(); + +$DB->Consulta("select nextval('grupos_id_seq'::regclass);"); +list($nextid) = $DB->SacaTupla(); + +$DB->Consulta("insert into grupos( id,nombre ) values($nextid,'{$Data->groups->nombre}');"); +if($DB->Estado){ + $out['success'] = true; + $out['groups'] = array('id'=>$nextid, 'nombre'=>$Data->groups->nombre ); + } +else{ + $out['success'] = false; + $out['groups'] = array(); + $out['msg'] = "Error al crear el Grupo, verifique que el nombre no exista y vuelva a intentarlo"; + } +return $out; +} + +function DirectUpdate($DB, $Data){ +$out = array(); +$out['groups'] = array(); + +$DB->Consulta("update grupos set nombre='{$Data->groups->nombre}' where id = {$Data->groups->id}"); + +if($DB->Estado){ + $out['success'] = true; + $out['groups'] = array('id'=>$Data->groups->id, 'nombre'=>$Data->groups->nombre ); + } +else{ + $out['success'] = false; + $out['msg'] = "Error al actualizar el Grupo."; + } + +return $out; +} + +function DirectDestroy($DB, $Data){ +$out = array(); +$out['groups'] = array(); +$out['success'] = true; + +$DB->Consulta("delete from grupos where id = {$Data->groups};"); + +if(!$DB->Estado){ + $out['success'] = false; + $out['msg'] = "Error al eliminar el grupo."; + } + +return $out; +} + diff --git a/BAM/js/Dazzler/Dazzler.admin.user.js b/BAM/js/Dazzler/Dazzler.admin.user.js new file mode 100644 index 0000000..5b8848b --- /dev/null +++ b/BAM/js/Dazzler/Dazzler.admin.user.js @@ -0,0 +1,628 @@ +/* ! + * This file is part of Dazzler + * Copyright(c) 2011 USI - Universidad de Concepcion + * + * Dazzler is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Dazzler is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Dazzler. If not, see . + * +*/ + +function App_define(){ +return " +Ext.ns('Dazzler.admin'); +/* Panel administracion de usuarios */ + +Dazzler.admin.userData = function(config){ + config = Ext.apply({ + proxy: new Ext.data.DirectProxy({ + api: { + read: Dazzler.api.DirectRead, + create: Dazzler.api.DirectCreate, + update: Dazzler.api.DirectUpdate, + destroy: Dazzler.api.DirectDestroy + }, + listeners: { + exception : function(proxy, type, action, options, res, arg) { + var vMsg = ''; + if(type == 'response'){ + vMsg = 'Ocurrio un error al comunicarse al servidor, verifique la conexión de red e intente la operación nuevamente'; + } + else{ + vMsg = res.msg; + } + Ext.Msg.show({title: 'Error',msg: vMsg,icon: Ext.MessageBox.ERROR, buttons: Ext.Msg.OK}); + } + + } +// baseParams: {type: 'dataquery'}, +// method: 'POST', +// directFn: Dazzler.api.DirectFn + }), + reader: new Ext.data.JsonReader({ + root: 'users', + totalProperty: 'totalCount', + idProperty: 'id', + messageProperty: 'msg', + fields: ['id','login','clave', 'nombre', 'correo', {name: 'activo', type: 'boolean' }] + }), + writer: new Ext.data.JsonWriter({ + encode: false, writeAllFields: true + }), + + baseParams: {xid: %xid%}, + remoteSort: true, + sortInfo: {field: 'id', direction: 'ASC'}, + autoLoad: {params:{start: 0, limit: 25}} + }, config); + + Dazzler.admin.userData.superclass.constructor.call(this,config); + }; + +Ext.extend(Dazzler.admin.userData, Ext.data.Store, {}); + +Dazzler.admin.userGrid = function(config){ + this.ds = new Dazzler.admin.userData({id:'storeAdminUser'}); + this.msm = new Ext.grid.RowSelectionModel( { singleSelect:true }); + + this.onAddUser = config.onAddUser ? config.onAddUser : function(){}, + this.onEditUser = config.onEditUser ? config.onEditUser : function(){}, + this.onDeleteUser = config.onDeleteUser ? config.onDeleteUser : function(){}, + + config = Ext.apply({ + store: this.ds, + colModel: new Ext.grid.ColumnModel({ + defaults: { sortable: true }, + columns: [ + { dataIndex: 'id' , width: 60, header: 'Id' }, + { dataIndex: 'login' , width: 150, header: 'Login' }, + { dataIndex: 'nombre', header: 'Nombre' }, + { dataIndex: 'correo', header: 'Correo electronico'}, + { dataIndex: 'activo', width: 80, header: 'Estado', xtype: 'booleancolumn', falseText: 'Desactivada', trueText: 'Activada', align: 'center', width: 50} ] + }), + viewConfig: {forceFit: true }, + sm: this.msm, + loadMask: {msg:'Cargando datos...'}, + + tbar: [{ + text: 'Agregar usuario', + iconCls: Ext.ux.TDGi.iconMgr.getIcon('user_add'), + handler: this.onAddUser + } , '->', { + text: 'Editar Usuario', + ref: '../EdtButton', + iconCls: Ext.ux.TDGi.iconMgr.getIcon('user_edit'), + disabled: true, + handler: this.onEditUser + } , '-', { + text: 'Quitar Usuario', + ref: '../DelButton', + iconCls: Ext.ux.TDGi.iconMgr.getIcon('user_delete'), + disabled: true, + handler: this.onDeleteUser + } ], + + bbar: new Ext.PagingToolbar({ + pageSize: 25, + store: this.ds, + displayInfo: true, + displayMsg: 'Mostrando usuarios {0} al {1} de {2}', + emptyMsg: 'No existen usuarios' + }) + }, config); + + Dazzler.admin.userGrid.superclass.constructor.call(this,config); + + this.msm.on('rowselect', + function(sm){ + var SelUserId = this.getSelectionModel().getSelected().get('id'); + this.EdtButton.setDisabled(false); + this.DelButton.setDisabled(false); + Ext.getCmp('userAdminGroups').setDisabled(false); + + Ext.getCmp('userGroupGrid').getStore().load({params:{'userid':SelUserId,start: 0, limit: 25}}); + Ext.getCmp('comboGroup').getStore().load({params:{'userid':SelUserId}}); + Ext.getCmp('btnQuitarGrupo').setDisabled(true); + Ext.getCmp('btnAgregarGrupo').setDisabled(true); + } , this); + + this.msm.on('rowdeselect', + function(sm){ + Ext.getCmp('userAdminGrid').EdtButton.setDisabled(true); + Ext.getCmp('userAdminGrid').DelButton.setDisabled(true); + Ext.getCmp('userAdminGroups').setDisabled(true); + } , this) + + }; + +Ext.extend(Dazzler.admin.userGrid, Ext.grid.GridPanel, { +/* + onAdd : function(){},//funciones auxiliares para comunicarse con los otros paneles. + onEdit : function(){}, + onDelete : function(){} +*/ +}); + + +Dazzler.admin.userEditForm = function(config){ +// funciones auxiliares para comunicarse con los otros paneles. + + this.onSaveUser = config.onSaveUser ? config.onSaveUser : function() {}, + this.onBackToGrid = config.onBackToGrid ? config.onBackToGrid : function() {}, + this.userRecord = null, + + config = Ext.apply({ + frame: true, + items: [{ + xtype:'fieldset', + title: 'Datos de usuario', + defaultType: 'textfield', + labelWidth: 150, + anchor: '99%', + defaults: {anchor: '90%'}, + items: [ + // { name: 'uid' , header: 'Id' }, + { name: 'login' , fieldLabel: 'Login', allowBlank: false }, + { name: 'nombre', fieldLabel: 'Nombre', allowBlank: false }, + { name: 'clave', fieldLabel: 'Clave', allowBlank: false, + inputType: 'password', + minLengthText: 'La clave debe tener de 6 a 20 caracteres', + minLength: 6, + maxLengthText: 'La clave debe tener de 6 a 20 caracteres', + maxLength: 20 }, + { name: 'correo', fieldLabel: 'Correo electronico', allowBlank: false, vtype: 'email'}, + { name: 'activo', fieldLabel: 'Cuenta activa', xtype: 'checkbox'} ] + }], + buttons: [{ text: 'Guardar', iconCls: Ext.ux.TDGi.iconMgr.getIcon('disk'), handler: this.onSaveUser }, + { text: 'Volver', iconCls: Ext.ux.TDGi.iconMgr.getIcon('bullet_left'), handler: this.onBackToGrid }] + + }, config); + + Dazzler.admin.userEditForm.superclass.constructor.call(this,config); + }; +Ext.extend(Dazzler.admin.userEditForm, Ext.FormPanel, { }); + +/* Window container of the form */ +Dazzler.admin.userEditWindow = function(config){ + + config = Ext.apply({ + id: 'userEditWindow', + closable: false, + resizable: false, + modal: true, + closable: false, + resizable: false, + items: [ new Dazzler.admin.userEditForm({ + id: 'userEditForm', + + onBackToGrid: function(){ + Ext.getCmp('userEditWindow').close(); + }, + onSaveUser: function(){ + var form = Ext.getCmp('userEditForm'); + if (!form.getForm().isValid()) { + Ext.Msg.show({ + title: 'Error al modificar', + msg: 'Los datos ingresados no son validos, intentelo nuevamente', + icon: Ext.MessageBox.ERROR, + buttons: Ext.Msg.OK + }); + return false; + } + form.getForm().updateRecord(form.userRecord); + Ext.getCmp('userEditWindow').close(); + } + }) ] + + }, config); + + Dazzler.admin.userEditWindow.superclass.constructor.call(this,config); +} + +Ext.extend(Dazzler.admin.userEditWindow, Ext.Window, { }); + +/* Window container of the form */ +Dazzler.admin.userAddWindow = function(config){ + + config = Ext.apply({ + id: 'userAddWindow', + closable: false, + resizable: false, + modal: true, + items: [ new Dazzler.admin.userEditForm({ + id: 'userAddForm', + + onBackToGrid: function(){ + Ext.getCmp('userAddWindow').close(); + }, + onSaveUser: function(){ + var form = Ext.getCmp('userAddForm'); + if (!form.getForm().isValid()) { + Ext.Msg.show({ + title: 'Error al ingresar', + msg: 'Los datos del usuario ingresados no son validos, intentelo nuevamente', + icon: Ext.MessageBox.ERROR, + buttons: Ext.Msg.OK + }); + return false; + } + var store = Ext.getCmp('userAdminGrid').getStore(); + var record = new store.recordType(form.getForm().getValues()); + store.add(record); +// form.getForm().updateRecord(form.userRecord); + Ext.getCmp('userAddWindow').close(); + store.reload(); + } + }) ] + + }, config); + + Dazzler.admin.userAddWindow.superclass.constructor.call(this,config); +} + +Ext.extend(Dazzler.admin.userAddWindow, Ext.Window, { }); + +/* Panel de administracion de usuario (contenedor) */ + +Dazzler.admin.userGroups = function(config){ + + var userAddGroup = new Ext.FormPanel({ + id: 'userAddGroup', + region:'north', + frame:true, + height:120, + labelWidth: 45, + items:[{ + xtype: 'fieldset', + title: 'Agregar grupos', + items: [{ + id: 'comboGroup', + xtype: 'combo', + fieldLabel: 'Grupos', + name: 'grupos', + store: new Ext.data.Store({ + id: 'groupComboStore', + proxy: new Ext.data.DirectProxy({ directFn: Dazzler.api.customFn }), + reader: new Ext.data.JsonReader({ + root: 'groups', + totalProperty: 'totalCount', + idProperty: 'id', + messageProperty: 'msg', + fields: ['id', 'nombre'] + }), + baseParams: {'xid': %xid%, 'customFn': 'userGroupCombo'}, + remoteSort: true, + sortInfo: {field: 'nombre', direction: 'ASC'} + }), + mode: 'local', + forceSelection: true, + valueField: 'id', + displayField: 'nombre', + editable: false, + triggerAction: 'all', + listeners:{ + 'select': function(){ + Ext.getCmp('btnAgregarGrupo').setDisabled(false); + } + } + }], + buttons: [{ + id: 'btnAgregarGrupo', + text: 'Agregar', + iconCls: Ext.ux.TDGi.iconMgr.getIcon('add'), + handler: function(){ + Ext.getCmp('userAdminGroups').getEl().mask('Eliminando...','ext-el-mask-msg x-mask-loading'); + var SelUserId = Ext.getCmp('userAdminGrid').getSelectionModel().getSelected().get('id'); + var SelGroupId = Ext.getCmp('comboGroup').getValue(); + Ext.getCmp('comboGroup').clearValue(); + Ext.getCmp('btnQuitarGrupo').setDisabled(true); + Ext.getCmp('btnAgregarGrupo').setDisabled(true); + Dazzler.api.customFn({'xid': %xid%, 'customFn': 'addUserGroup', 'userid':SelUserId, 'groupid':SelGroupId, },function(){ + Ext.getCmp('userGroupGrid').getStore().load({params:{'userid':SelUserId,start: 0, limit: 25}}); + Ext.getCmp('comboGroup').getStore().load({params:{'userid':SelUserId}}); + Ext.getCmp('userAdminGroups').getEl().unmask(); + }); + } + }] + }] + }); + + var userGroupStore = new Ext.data.Store({ + proxy: new Ext.data.DirectProxy({ directFn: Dazzler.api.customFn }), + reader: new Ext.data.JsonReader({ + root: 'groups', + totalProperty: 'totalCount', + idProperty: 'id', + messageProperty: 'msg', + fields: ['id', 'nombre'] + }), + writer: new Ext.data.JsonWriter({ + encode: false, writeAllFields: true + }), + baseParams: {'xid': %xid%, 'customFn': 'userGroupGrid'}, + remoteSort: true, + sortInfo: {field: 'nombre', direction: 'ASC'} + }); + + var userGroupGrid = new Ext.grid.GridPanel({ + id: 'userGroupGrid', + border:'false', + region:'center', + + store: userGroupStore, + + colModel: new Ext.grid.ColumnModel({ + defaults: { sortable: true }, + columns: [ + { dataIndex: 'id' , width: 60, header: 'Id' }, + { dataIndex: 'nombre', header: 'Nombre' } ] + }), + + viewConfig: {forceFit: true }, + sm: new Ext.grid.RowSelectionModel( { + singleSelect:true, + listeners:{ + 'rowselect': function(){ + Ext.getCmp('btnQuitarGrupo').setDisabled(false); + } + } + } ), + loadMask: {msg:'Cargando datos...'}, + + bbar: new Ext.PagingToolbar({ + pageSize: 25, + store: userGroupStore, + displayInfo: true, + displayMsg: 'Mostrando grupos {0} al {1} de {2}', + emptyMsg: 'No existen grupos' + }), + + tbar: [{ + id:'btnQuitarGrupo', + text: 'Quitar', + iconCls: Ext.ux.TDGi.iconMgr.getIcon('delete'), + disabled: true, + handler: function(){ + Ext.getCmp('userAdminGroups').getEl().mask('Eliminando...','ext-el-mask-msg x-mask-loading'); + var SelUserId = Ext.getCmp('userAdminGrid').getSelectionModel().getSelected().get('id'); + var SelGroupId = Ext.getCmp('userGroupGrid').getSelectionModel().getSelected().get('id'); + Ext.getCmp('comboGroup').clearValue(); + Ext.getCmp('btnQuitarGrupo').setDisabled(true); + Ext.getCmp('btnAgregarGrupo').setDisabled(true); + Dazzler.api.customFn({'xid': %xid%, 'customFn': 'delUserGroup', 'userid':SelUserId, 'groupid':SelGroupId, },function(){ + Ext.getCmp('userGroupGrid').getStore().load({params:{'userid':SelUserId,start: 0, limit: 25}}); + Ext.getCmp('comboGroup').getStore().load({params:{'userid':SelUserId}}); + Ext.getCmp('userAdminGroups').getEl().unmask(); + }); + + } }] + }); + + config = Ext.apply({ + layout: 'border', + width: 300, + collapsible: true, + id: 'userAdminGroups', + disabled: true, + items : [userAddGroup, userGroupGrid] + }, config); + Dazzler.admin.userGroups.superclass.constructor.call(this,config); +} +Ext.extend(Dazzler.admin.userGroups, Ext.Panel, { }); + + +Dazzler.admin.userPanel = function(config){ + + var UserGrid = new Dazzler.admin.userGrid({ + id: 'userAdminGrid', + region:'center', + title: 'Usuarios del sistema', + onEditUser: function(){ + var rec = Ext.getCmp('userAdminGrid').getSelectionModel().getSelected(); + if (!rec) { + return false; + } + var mywin = new Dazzler.admin.userEditWindow({ + title: 'Modificacion de usuario', + width: 500 + }); + + Ext.getCmp('userEditForm').getForm().loadRecord(rec); + Ext.getCmp('userEditForm').userRecord = rec; + + mywin.show(); + }, + onAddUser: function(){ + var mywin = new Dazzler.admin.userAddWindow({ + title: 'Agregar de usuario', + width: 500 + }); + + mywin.show(); + }, + onDeleteUser: function(){ + Ext.MessageBox.confirm('Confirmación', '¿Está seguro que desea eliminar al usuario seleccionado?' , function(btn){ + if(btn == 'yes'){ + var usergrid = Ext.getCmp('userAdminGrid'); + usergrid.getStore().remove(usergrid.getSelectionModel().getSelected()); + usergrid.EdtButton.setDisabled(true); + usergrid.DelButton.setDisabled(true); + } + }); + } + }); + + var UserGroup = new Dazzler.admin.userGroups({region:'east',title: 'Grupos del usuario'}); + + config = Ext.apply({ + id: 'userAdminPanel', + layout: 'border', + border: false, + items: [ UserGrid, UserGroup ] + + }, config); + + Dazzler.admin.userPanel.superclass.constructor.call(this,config); + }; + +Ext.extend(Dazzler.admin.userPanel, Ext.Panel, {}); +"; +} + +function App_show(){ + +return " +SCV.mainContent.add( new Dazzler.admin.userPanel() ); +SCV.mainContent.doLayout(); +"; + +} + +function DirectRead($DB, $Data){ +$out = array(); +$out['users'] = array(); + +$DB->Consulta("select id, login, clave, activo, nombre, correo from usuarios order by {$Data->sort} {$Data->dir} offset {$Data->start} limit {$Data->limit};"); + +while($t = $DB->SacaTupla(false)){ + $out['users'][] = $t; + } +$out['success'] = true; + +return $out; + +} + +function DirectCreate($DB, $Data){ +$out = array(); +$Esc = $DB->EscapeObject($Data->users,array('login','clave','nombre','correo')); + +if($Data->users->activo == 'on') + $activo = 1; +else + $activo = 0; + +$DB->Consulta("insert into usuarios( login, clave, activo, nombre, correo) values('{$Esc['login']}','{$Esc['clave']}',$activo,'{$Esc['nombre']}','{$Esc['correo']}');"); +if($DB->Estado){ + $out['success'] = true; + $out['users'] = array('id'=>$DB->UltimoId, 'activo'=>$activo,'login'=>$Data->users->login,'clave'=>$Data->users->clave,'nombre'=>$Data->users->nombre,'correo'=>$Data->users->correo ); + } +else{ + $out['success'] = false; + $out['users'] = array(); + $out['msg'] = "Error al crear el usuario, verifique que el login no exista y vuelva a intentarlo"; + } +return $out; +} + +function DirectUpdate($DB, $Data){ +$out = array(); +$out['users'] = array(); +$Esc = $DB->EscapeObject($Data->users,array('login','clave','nombre','correo')); + +if($Data->users->activo) + $activo = 1; +else + $activo = 0; + +$DB->Consulta("update usuarios set login='{$Esc['login']}', clave='{$Esc['clave']}', correo='{$Esc['correo']}', nombre='{$Esc['nombre']}', activo=$activo where id = {$Data->users->id}"); + +if($DB->Estado){ + $out['success'] = true; + $out['users'] = array('id'=>$Data->users->id, 'activo'=>$activo,'login'=>$Data->users->login,'clave'=>$Data->users->clave,'nombre'=>$Data->users->nombre,'correo'=>$Data->users->correo ); + } +else{ + $out['success'] = false; + $out['msg'] = "Error al actualizar el usuario."; + } + +return $out; +} + +function DirectDestroy($DB, $Data){ +$out = array(); +$out['users'] = array(); +$out['success'] = true; + +$DB->Consulta("delete from usuarios where id = {$Data->users};"); + +if(!$DB->Estado){ + $out['success'] = false; + $out['msg'] = "Error al eliminar el usuario."; + } + +return $out; +} + +function userGroupGrid($DB, $Data){ +$out = array(); +$out['groups'] = array(); + +$DB->Consulta("select grupos.id, grupos.nombre from (gusuarios + left join grupos on (gusuarios.gid = grupos.id)) + where gusuarios.uid = {$Data->userid} order by grupos.{$Data->sort} {$Data->dir} offset {$Data->start} limit {$Data->limit};"); +if(!$DB->Estado){ + $out['success'] = false; + $out['msg'] = $DB->Error_debug; + } +else{ + while($t = $DB->SacaTupla(false)){ + $out['groups'][] = $t; + } + $out['success'] = true; + } +return $out; +} + +function userGroupCombo($DB, $Data){ +$out = array(); +$out['groups'] = array(); + +$DB->Consulta("select id, nombre from grupos where id not in (select gid from gusuarios where uid = {$Data->userid}) order by {$Data->sort} {$Data->dir};"); + +while($t = $DB->SacaTupla(false)){ + $out['groups'][] = $t; + } +$out['success'] = true; + +return $out; +} + +function delUserGroup($DB, $Data){ +$out = array(); + +$DB->Consulta("delete from gusuarios where uid={$Data->userid} and gid={$Data->groupid};"); + +if(!$DB->Estado){ + $out['success'] = false; + } +else{ + $out['success'] = true; + } + +return $out; +} + +function addUserGroup($DB, $Data){ +$out = array(); + +$DB->Consulta("insert into gusuarios(uid,gid) values({$Data->userid},{$Data->groupid});"); + +if(!$DB->Estado){ + $out['success'] = false; + } +else{ + $out['success'] = true; + } + +return $out; +} diff --git a/BAM/js/Dazzler/Dazzler.apphome.js b/BAM/js/Dazzler/Dazzler.apphome.js new file mode 100644 index 0000000..e60c09a --- /dev/null +++ b/BAM/js/Dazzler/Dazzler.apphome.js @@ -0,0 +1,42 @@ +/* ! + * This file is part of Dazzler + * Copyright(c) 2011 USI - Universidad de Concepcion + * + * Dazzler is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Dazzler is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Dazzler. If not, see . + * +*/ + + +function App_define(){ + +return " +Ext.ns('Dazzler'); +/* Panel administracion de contenido */ + +Dazzler.appHome = Ext.extend(Ext.Panel, { + title: 'SCV Home', + autoScroll: true, + autoLoad: '/BAM/js/Welcome.html' + }); +"; +} + +function App_show(){ + +return " +SCV.mainContent.add(new Dazzler.appHome() ); +SCV.mainContent.doLayout(); +"; +} + diff --git a/BAM/js/Dazzler/Dazzler.manager.hosts.js b/BAM/js/Dazzler/Dazzler.manager.hosts.js new file mode 100644 index 0000000..b512721 --- /dev/null +++ b/BAM/js/Dazzler/Dazzler.manager.hosts.js @@ -0,0 +1,194 @@ +/* ! + * This file is part of Dazzler + * Copyright(c) 2011 USI - Universidad de Concepcion + * + * Dazzler is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Dazzler is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Dazzler. If not, see . + * +*/ + +function App_define(){ +global $IconsURL; +return " +Ext.ns('Dazzler.manager'); +/* Panel administracion de grupos de maquinas */ + +Dazzler.manager.unknownHostsPanel = Ext.extend( Ext.ux.crudGridPanel.cruPagingGrid, { + + constructor: function(config){ + + this.usersStore = new Ext.data.Store({ + proxy : new Ext.data.DirectProxy({ directFn: Dazzler.api.customFn }), + reader : new Ext.data.JsonReader({ + root: 'root', + totalProperty: 'totalCount', + idProperty: 'id', + messageProperty: 'msg', + fields: ['id', 'nombre'] + }), + baseParams : {'xid': %xid%, 'customFn': 'usersCombo'}, + remoteSort : true, + sortInfo : {field: 'nombre', direction: 'ASC'}, + autoLoad : true + }); + + + config = Ext.apply({ + configStore : { buildFields: this.storeFields }, + baseParams : {xid: %xid%}, + configForm : { + items : this.formFields(), + labelWidth : 80, + height : 80, + width : 350 + }, + + viewConfig : this.buildViewConf(), + tbar : this.buildTbar(), + buildColumns : this.gridColumns, + + defaultDesc : 'Equipos', + title : 'Equipos sin cuenta en el sistema', + defaulPageSize : 25, + + editButtonText : 'Asignar usuario', + + }, config); + + Dazzler.manager.unknownHostsPanel.superclass.constructor.call(this,config); + + this.store.on('update',this.onUpdateHost,this); + + }, + + storeFields: function(){ + return ['id','uid', 'name', 'ipaddr', 'cpus', 'mips', 'flops', 'last', 'hits' ]; + }, + onUpdateHost: function(){ + this.store.reload({}); + }, + gridColumns: function(){ + return [{ dataIndex: 'name', header: 'Nombre'}, + { dataIndex: 'user', header: 'UserLogin'}, + { dataIndex: 'cpus', header: 'N° CPU'}, + { dataIndex: 'mips', header: 'MIPS'}, + { dataIndex: 'flops', header: 'Flops'}, + { dataIndex: 'ipaddr', header: 'Ip'}, + { dataIndex: 'hits', header: 'Contactos'}, + { dataIndex: 'last', header: 'Último contacto'}, + { dataIndex: 'id', header: 'Request', + renderer: function(){ + return '
'; + } + } ]; + }, + + + buildTbar: function(){ + + return [ '->', { + text : this.editButtonText, + ref : '../editBtn', + iconCls : Ext.ux.TDGi.iconMgr.getIcon('bullet_edit'), + disabled: true, + scope : this, + handler : this.onEdit + } ]; + }, + + formFields: function(){ + return [{ name: 'usuario', fieldLabel: 'Administrador', xtype:'combo', allowBlank: false, store: this.usersStore, mode: 'local',forceSelection: true, hiddenName: 'uid',valueField: 'id',displayField: 'nombre', triggerAction: 'all' } ]; + } + +}); +"; + +} + +function App_show(){ + +return " +SCV.mainContent.add( new Dazzler.manager.unknownHostsPanel() ); +SCV.mainContent.doLayout(); +"; + +} + +function DirectRead($DB, $Data){ +global $conf; +$out = array(); + +$out['root'] = array(); + +$DB->Consulta("select count(*) from hosts where gid = {$conf->conf->defaultGroup};"); +$t = $DB->SacaTupla(); +$out['totalCount'] = $t[0]; + + +$DB->Consulta("select id, name, ipaddr, cpus, mips, flops, last_contact as last,hits from hosts where gid = {$conf->conf->defaultGroup} order by {$Data->sort} {$Data->dir} offset {$Data->start} limit {$Data->limit};"); +while($t = $DB->SacaTupla(false)){ + $t['ipaddr'] = long2ip(sprintf("%u",$t['ipaddr'])); + $t['last'] = date('d/m/Y H:i', $t['last']); + $t['uid'] = "0"; + $out['root'][] = $t; + } + +$out['success'] = true; + +return $out; +} + +function DirectUpdate($DB, $Data){ +$out = array(); +$out['root'][] = array(); + +$hid = intval($Data->root->id); +$uid = intval($Data->root->uid); +if(($hid > 0) && ($uid > 0)){ + $DB->Consulta("select group_default from users where id = $uid"); + list( $gid ) = $DB->SacaTupla(); + if($gid > 0){ + $DB->Consulta("select correo from usuarios where id = $uid"); + list( $correo ) = $DB->SacaTupla(); + + $DB->Consulta("select cpid from hosts where id = $hid"); + list( $cpid ) = $DB->SacaTupla(); + + $xcpid = $DB->EscapeString(md5($correo.$cpid)); + + $DB->Consulta("update hosts set gid=$gid, xcpid='$xcpid' where id = $hid"); + $out['success'] = true; + } + else + $out['success'] = false; + } +else + $out['success'] = false; + +return $out; +} + +function usersCombo($DB, $Data){ +$out['root'] = array(); +$out['totalCount'] = $DB->Consulta("select users.id, nombre,tipo from (users left join usuarios on (users.id = usuarios.id)) order by {$Data->sort} {$Data->dir};"); + +while($t = $DB->SacaTupla(false)){ + if($t['tipo'] & 2)/* list only providers */ + $out['root'][] = $t; + } + +$out['success'] = true; + +return $out; +} + diff --git a/BAM/js/Dazzler/Dazzler.manager.projects.js b/BAM/js/Dazzler/Dazzler.manager.projects.js new file mode 100644 index 0000000..8c33814 --- /dev/null +++ b/BAM/js/Dazzler/Dazzler.manager.projects.js @@ -0,0 +1,214 @@ +/* ! + * This file is part of Dazzler + * Copyright(c) 2011 USI - Universidad de Concepcion + * + * Dazzler is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Dazzler is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Dazzler. If not, see . + * +*/ + +function App_define(){ +global $IconsURL; +return " +Ext.ns('Dazzler.manager'); +/* Panel administracion de grupos de maquinas */ + +Dazzler.manager.projectPanel = Ext.extend(Ext.ux.crudGridPanel.cruPagingGrid, { + + constructor: function(config){ + + config = Ext.apply({ + configStore : { buildFields: this.storeFields }, + baseParams: {xid: %xid%}, + configForm : { + items : this.formFields(), + labelWidth : 80, + height : 250, + width : 400 + }, + + buildColumns : this.gridColumns + }, config); + + Dazzler.manager.projectPanel.superclass.constructor.call(this,config); + }, + + defaultDesc: 'Proyectos', + title: 'Proyectos del sistema', + baseParams: {xid: %xid%}, + defaulPageSize: 25, + + addButtonText : 'Agregar proyecto', + editButtonText : 'Editar proyecto', + + + storeFields: function(){ + return ['id', 'uid', 'user', 'name', 'url', 'url_signature', 'estado', 'hosts' ]; + }, + + gridColumns: function(){ + return [{ dataIndex: 'name', header: 'Proyecto'}, + { dataIndex: 'url', header: 'Url'}, + { dataIndex: 'user', header: 'Administrador'}, + { dataIndex: 'estado', header: 'Estado', renderer: function (value){ + var img; + if(value == 0) + img = '
'; + else if(value == 1) + img = '
'; + else + img = '
'; + return img; + }} ]; + }, + + formFields: function(){ + var researcherStore = new Ext.data.Store({ + proxy : new Ext.data.DirectProxy({ directFn: Dazzler.api.customFn }), + reader : new Ext.data.JsonReader({ + root: 'root', + totalProperty: 'totalCount', + idProperty: 'id', + messageProperty: 'msg', + fields: ['id', 'nombre'] + }), + baseParams : {'xid': %xid%, 'customFn': 'researchCombo'}, + remoteSort : true, + sortInfo : {field: 'nombre', direction: 'ASC'}, + autoLoad : {} + }); + + return [{ name: 'user', fieldLabel: 'Administrador', xtype:'combo', allowBlank: false, store: researcherStore, mode: 'local',forceSelection: true, hiddenName: 'uid',valueField: 'id',displayField: 'nombre', triggerAction: 'all' }, + { name: 'name', fieldLabel: 'Nombre', allowBlank: false }, + { name: 'url', fieldLabel: 'Url', allowBlank: false }, + { name: 'url_signature', fieldLabel: 'Firma', allowBlank: false, xtype: 'textarea' }, + { name: 'estado', fieldLabel: 'Suspendido', xtype: 'checkbox' } + ]; + } +}); +"; + +} + +function App_show(){ + +return " +SCV.mainContent.add( new Dazzler.manager.projectPanel() ); +SCV.mainContent.doLayout(); +"; +} + +function DirectRead($DB, $Data){ +$out = array(); + +$out['root'] = array(); +$DB->Consulta("select count(*) from projects;"); +$t = $DB->SacaTupla(); +$out['totalCount'] = $t[0]; + +$DB->Consulta("select projects.id, uid, nombre as user, name, url, url_signature, estado from (projects left join usuarios on (projects.uid = usuarios.id)) order by {$Data->sort} {$Data->dir} offset {$Data->start} limit {$Data->limit};"); + +while($t = $DB->SacaTupla(false)){ + $out['root'][] = $t; + } +$out['success'] = true; + +return $out; +} + +function DirectCreate($DB, $Data){ +$out = array(); + +$DB->Consulta("select nextval('projects_id_seq'::regclass);"); +list($nextid) = $DB->SacaTupla(); + +if($Data->root->estado) + $status = 1; +else + $status = 0; + +$uid = intval($Data->root->uid); +$Escaped = $DB->EscapeObject($Data->root,array('name','url','url_signature')); + + +$DB->Consulta("insert into projects( id,uid,name,url,url_signature,estado ) values($nextid,$uid,'{$Escaped['name']}','{$Escaped['url']}','{$Escaped['url_signature']}',$status);"); + +if($DB->Estado){ + $out['success'] = true; + $out['root'] = array('id'=>$nextid, 'uid'=>$uid, 'name'=>$Data->root->name, 'user'=>$Data->root->user, 'url'=>$Data->root->url, 'url_signature'=>$Data->root->url_signature, 'estado'=>$status ); + } +else{ + $out['success'] = false; + $out['root'] = array(); + $out['msg'] = "Error al crear el Proyecto, verifique que el nombre no exista y vuelva a intentarlo"; + } + +return $out; +} + +function DirectUpdate($DB, $Data){ +$out = array(); +$out['root'] = array(); + +if($Data->root->estado) + $status = 1; +else + $status = 0; + +$uid = intval($Data->root->uid); +$Escaped = $DB->EscapeObject($Data->root,array('name','url','url_signature')); + +$DB->Consulta("update projects set uid=$uid, name='{$Escaped['name']}', url='{$Escaped['url']}', url_signature='{$Escaped['url_signature']}', estado={$status} where id = {$Data->root->id}"); + +if($DB->Estado){ + $out['success'] = true; + $out['groups'] = array('id'=>$Data->root->id, 'uid'=>$uid, 'name'=>$Data->root->name, 'user'=>$Data->root->user, 'url'=>$Data->root->url, 'url_signature'=>$Data->root->url_signature, 'estado'=>$status ); + } +else{ + $out['success'] = false; + $out['msg'] = "Error al actualizar el Proyecto."; + } + +return $out; +} + +function DirectDestroy($DB, $Data){ +$out = array(); + +$out['root'] = array(); +$out['success'] = true; +$pid = intval($Data->root); +$DB->Consulta("delete from projects where id = $pid;"); + +if(!$DB->Estado){ + $out['success'] = false; + $out['msg'] = "Error al eliminar el Proyecto."; + } + +return $out; +} + +function researchCombo($DB, $Data){ +$out = array(); +$out['root'] = array(); + +$DB->Consulta("select users.id, nombre from (users left join usuarios on (usuarios.id=users.id)) where tipo&4=4 order by {$Data->sort} {$Data->dir};"); + +while($t = $DB->SacaTupla(false)){ + $out['root'][] = $t; + } +$out['success'] = true; + +return $out; +} + diff --git a/BAM/js/Dazzler/Dazzler.manager.users.js b/BAM/js/Dazzler/Dazzler.manager.users.js new file mode 100644 index 0000000..97fa2c6 --- /dev/null +++ b/BAM/js/Dazzler/Dazzler.manager.users.js @@ -0,0 +1,250 @@ +/* ! + * This file is part of Dazzler + * Copyright(c) 2011 USI - Universidad de Concepcion + * + * Dazzler is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Dazzler is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Dazzler. If not, see . + * +*/ + +function App_define(){ +global $IconsURL; +return " +Ext.ns('Dazzler.manager'); +/* Panel administracion de grupos de maquinas */ + +Dazzler.manager.usersPanel = Ext.extend(Ext.ux.crudGridPanel.cruPagingGrid, { + + constructor: function(config){ + + config = Ext.apply({ + configStore : { buildFields: this.storeFields }, + baseParams: {xid: %xid%}, + + configForm : { + items : this.formFields(), + labelWidth : 80, + height : 250, + width : 400 + }, + + buildColumns : this.gridColumns + }, config); + + Dazzler.manager.usersPanel.superclass.constructor.call(this,config); + }, + + defaultDesc: 'Usuarios', + title: 'Usuarios del sistema', + defaulPageSize: 25, + + addButtonText : 'Agregar usuario', + editButtonText : 'Editar usuario', + + + storeFields: function(){ + return ['id', 'login', 'nombre', 'correo', 'clave', 'tipo1', 'tipo2', 'tipo3', 'hosts', 'proyectos' ]; + }, + + gridColumns: function(){ + return [{ dataIndex: 'login', header: 'Login'}, + { dataIndex: 'nombre', header: 'Nombre'}, + { dataIndex: 'correo', header: 'Correo'}, + { dataIndex: 'hosts', header: 'Equipos'}, + { dataIndex: 'projects', header: 'Proyectos'}, + { dataIndex: 'tipo1', header: ' ', renderer: function (value, metaData, record){ + var img = '
'; + + if(record.get('tipo1')) + img += ''; + + if(record.get('tipo2')) + img += ''; + + if(record.get('tipo3')) + img += ''; + + img += '
'; + return img; + }} ]; + }, + + formFields: function(){ + return [{ name: 'login' , fieldLabel: 'Login', allowBlank: false }, + { name: 'nombre', fieldLabel: 'Nombre', allowBlank: false }, + { name: 'clave', fieldLabel: 'Clave', allowBlank: false, + inputType: 'password', + minLengthText: 'La clave debe tener de 6 a 20 caracteres', + minLength: 6, + maxLengthText: 'La clave debe tener de 6 a 20 caracteres', + maxLength: 20 }, + { name: 'correo', fieldLabel: 'Correo electronico', allowBlank: false, vtype: 'email'}, + { name: 'tipo1', fieldLabel: 'Administrador', xtype: 'checkbox' }, + { name: 'tipo2', fieldLabel: 'Proveedor', xtype: 'checkbox' }, + { name: 'tipo3', fieldLabel: 'Investigador', xtype: 'checkbox' } + ]; + } + +}); +"; + +} + +function App_show(){ + +return " +SCV.mainContent.add( new Dazzler.manager.usersPanel() ); +SCV.mainContent.doLayout(); +"; + +} + +function DirectRead($DB, $Data){ +$out = array(); + +$out['root'] = array(); +$DB->Consulta("select count(*) from users;"); +$t = $DB->SacaTupla(); +$out['totalCount'] = $t[0]; + +$DB->Consulta("select users.id, login, nombre, clave, correo, tipo from (users left join usuarios on (users.id = usuarios.id)) order by {$Data->sort} {$Data->dir} offset {$Data->start} limit {$Data->limit};"); + +while($t = $DB->SacaTupla(false)){ + $t['tipo1'] = ($t['tipo'] & 1)&&1; + $t['tipo2'] = ($t['tipo'] & 2)&&1; + $t['tipo3'] = ($t['tipo'] & 4)&&1; + + $out['root'][] = $t; + } +$out['success'] = true; + +return $out; +} + +function DirectCreate($DB, $Data){ +$out = array(); + +$tipo = 0; + +if($Data->root->tipo1) + $tipo += 1; +if($Data->root->tipo2) + $tipo += 2; +if($Data->root->tipo3) + $tipo += 4; + +$salt = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"; +srand((double)microtime()*1000000); // start the random generator +$password=""; // set the inital variable +for ($i=0;$i<64;$i++) // loop and create password + $password = $password . substr ($salt, rand() % strlen($salt), 1); + +$weakhash = md5($password); +$login = $DB->EscapeString($Data->root->login); +$nombre = $DB->EscapeString($Data->root->nombre); +$clave = $DB->EscapeString($Data->root->clave); +$correo = $DB->EscapeString($Data->root->correo); + +$DB->Consulta("select nextval('usuarios_id_seq'::regclass);"); +list($uid) = $DB->SacaTupla(); +$DB->Consulta("select nextval('groups_id_seq'::regclass);"); +list($gid) = $DB->SacaTupla(); + +$DB->Consulta("begin;"); +$DB->Consulta("insert into usuarios( id,login,nombre,clave,correo ) values($uid,'$login','$nombre','$clave','$correo');"); +$DB->Consulta("insert into users( id,weakhash,group_default,tipo ) values($uid,'$weakhash',$gid,$tipo);"); +$DB->Consulta("insert into groups( id,uid,name,info ) values($gid,$uid,'Default','Grupo por defecto');"); + +if($Data->root->tipo1) + $DB->Consulta("insert into gusuarios(gid,uid) values(1001,$uid);"); +if($Data->root->tipo2) + $DB->Consulta("insert into gusuarios(gid,uid) values(1002,$uid);"); +if($Data->root->tipo3) + $DB->Consulta("insert into gusuarios(gid,uid) values(1003,$uid);"); + +$DB->Consulta("commit;"); + + +if($DB->Estado){ + $out['success'] = true; + $out['root'] = array('id'=>$uid, 'login'=>$Data->root->login, 'nombre'=>$Data->root->nombre, 'correo'=>$Data->root->correo, 'clave'=>$Data->root->clave, 'tipo1'=>$Data->root->tipo1, 'tipo2'=>$Data->root->tipo2, 'tipo3'=>$Data->root->tipo3 ); + } +else{ + $out['success'] = false; + $out['root'] = array(); + $out['msg'] = "Error al crear el usuario, verifique que el nombre no exista y vuelva a intentarlo"; + } + +return $out; +} + +function DirectUpdate($DB, $Data){ +$out = array(); +$out['root'] = array(); + +if($Data->root->tipo1) + $tipo += 1; +if($Data->root->tipo2) + $tipo += 2; +if($Data->root->tipo3) + $tipo += 4; + +$DB->Consulta("begin;"); +$DB->Consulta("update usuarios set nombre='{$Data->root->nombre}', clave='{$Data->root->clave}' where id = {$Data->root->id}"); +$DB->Consulta("update users set tipo=$tipo where id = {$Data->root->id}"); +$DB->Consulta("commit;"); +if($DB->Estado){ + if($Data->root->tipo1) + $DB->Consulta("insert into gusuarios(gid,uid) values(1001,{$Data->root->id});"); + else + $DB->Consulta("delete from gusuarios where gid=1001 and uid={$Data->root->id};"); + + if($Data->root->tipo2) + $DB->Consulta("insert into gusuarios(gid,uid) values(1002,{$Data->root->id});"); + else + $DB->Consulta("delete from gusuarios where gid=1002 and uid={$Data->root->id};"); + + if($Data->root->tipo3) + $DB->Consulta("insert into gusuarios(gid,uid) values(1003,{$Data->root->id});"); + else + $DB->Consulta("delete from gusuarios where gid=1003 and uid={$Data->root->id};"); + + $out['success'] = true; + $out['root'] = array('id'=>$Data->root->id, 'login'=>$Data->root->login, 'correo'=>$Data->root->correo, 'nombre'=>$Data->root->nombre, 'clave'=>$Data->root->clave, 'tipo1'=>$Data->root->tipo1, 'tipo2'=>$Data->root->tipo2, 'tipo3'=>$Data->root->tipo3 ); + } +else{ + $out['success'] = false; + $out['msg'] = "Error al actualizar el Usuario."; + } + +return $out; +} + +function DirectDestroy($DB, $Data){ +$out = array(); + +$out['root'] = array(); +$out['success'] = true; +$DB->Consulta("begin;"); +$DB->Consulta("delete from users where id = {$Data->root};"); +$DB->Consulta("delete from usuarios where id = {$Data->root};"); +$DB->Consulta("commit;"); + +if(!$DB->Estado){ + $out['success'] = false; + $out['msg'] = "Error al eliminar el Usuario."; + } + +return $out; +} + diff --git a/BAM/js/Dazzler/Dazzler.proveedor.group.js b/BAM/js/Dazzler/Dazzler.proveedor.group.js new file mode 100644 index 0000000..7383db1 --- /dev/null +++ b/BAM/js/Dazzler/Dazzler.proveedor.group.js @@ -0,0 +1,889 @@ +/* ! + * This file is part of Dazzler + * Copyright(c) 2011 USI - Universidad de Concepcion + * + * Dazzler is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Dazzler is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Dazzler. If not, see . + * +*/ + +function App_define(){ +global $IconsURL; +return " +Ext.ns('Dazzler.proveedor'); +/* Panel administracion de grupos de maquinas */ + +Dazzler.proveedor.groupAdminPanel = Ext.extend(Ext.Container, { + constructor: function(config){ + + /* custom Stores for Forms Combo */ + this.projectsStore = new Ext.data.Store({ + ref : 'ProjectsStore', + proxy : new Ext.data.DirectProxy({ directFn: Dazzler.api.customFn }), + reader : new Ext.data.JsonReader({ + root: 'root', + totalProperty: 'totalCount', + idProperty: 'id', + messageProperty: 'msg', + fields: ['id', 'nombre'] + }), + baseParams : {'xid': %xid%, 'customFn': 'projectCombo'}, + remoteSort : true, + sortInfo : {field: 'nombre', direction: 'ASC'} + }); + + this.groupsStore = new Ext.data.Store({ + proxy : new Ext.data.DirectProxy({ directFn: Dazzler.api.customFn }), + reader : new Ext.data.JsonReader({ + root: 'root', + totalProperty: 'totalCount', + idProperty: 'id', + messageProperty: 'msg', + fields: ['id', 'nombre'] + }), + baseParams : {'xid': %xid%, 'customFn': 'groupCombo'}, + remoteSort : true, + sortInfo : {field: 'nombre', direction: 'ASC'} + }); + /* Creacion de paneles */ + this.infoForm = new Ext.FormPanel({ + frame : true, + title :'Resumen', + iconCls : Ext.ux.TDGi.iconMgr.getIcon('information'), + defaultType :'displayfield', + baseParams : {xid: %xid%, 'form': 'info'}, + api : {load: Dazzler.api.loadForm }, + paramsAsHash : true, + items : this.buildInfoForm() + }); + + this.preferencesForm = new Ext.FormPanel({ + frame : true, + title :'Preferencias', + iconCls : Ext.ux.TDGi.iconMgr.getIcon('application_form_edit'), + defaultType :'displayfield', + labelWidth : 180, + baseParams : {xid: %xid%, 'form': 'pref'}, + api : {load: Dazzler.api.loadForm, submit: Dazzler.api.submitForm }, + monitorValid : true, + paramsAsHash : true, + items : this.buildPreferencesForm(), + buttons : this.buildPreferencesButtons() + }); + + this.hostGrid = new Ext.ux.crudGridPanel.cruPagingGrid({ + + defaultDesc : 'hosts', + iconCls : Ext.ux.TDGi.iconMgr.getIcon('computer'), + title : 'Equipos (hosts)', + baseParams : {xid: %xid%, 'store': 'hosts'}, + defaulPageSize : 25, + configStore : { buildFields: this.buildStoreHosts, autoLoad: false, sortInfo : {field: 'name', direction: 'ASC'} }, + configForm : { + items : this.buildFormHosts(), + labelWidth : 80, + height : 150, + width : 400 + }, + buildColumns : this.buildColumnsHosts, + editIconCls : Ext.ux.TDGi.iconMgr.getIcon('computer_edit'), + + editButtonText : 'Cambiar de grupo', + /* custom tbar, only for moving the host to other groups */ + buildTbar: function(){ + return [ '->', { + text : this.editButtonText, + ref : '../editBtn', + iconCls : this.editIconCls, + disabled: true, + scope : this, + handler : this.onEdit + } ]; + } + }); + + this.projectGrid = new Ext.ux.crudGridPanel.crudPagingGrid({ + defaultDesc : 'proyectos', + title : 'Proyectos', + iconCls : Ext.ux.TDGi.iconMgr.getIcon('world'), + baseParams : {xid: %xid%, 'store': 'projects' }, + defaulPageSize : 25, + configStore : { buildFields: this.buildStoreProject, autoLoad: false, sortInfo : {field: 'name', direction: 'ASC'} }, + configForm : { + items : this.buildFormProject(), + labelWidth : 150, + height : 150, + width : 400 + }, + configEditForm : { + items : this.buildFormEditProject(), + labelWidth : 150, + height : 150, + width : 400 + }, + buildColumns : this.buildColumnsProject, + doDeleteProject : this.doDeleteProject, + onDelete : this.onDeleteProject, + + addIconCls : Ext.ux.TDGi.iconMgr.getIcon('world_add'), + editIconCls : Ext.ux.TDGi.iconMgr.getIcon('world_edit'), + deleteIconCls : Ext.ux.TDGi.iconMgr.getIcon('world_delete'), + addButtonText : 'Nuevo proyecto', + editButtonText : 'Editar proyecto', + deleteButtonText: 'Eliminar proyecto', + + deleteMsg : '' + }); + + this.groupGrid = new Ext.ux.crudGridPanel.crudPagingGrid({ + region:'west', + width: 300, + collapsible: false, + + defaultDesc : 'grupos', + title : 'Grupos de Máquinas (Granjas)', + iconCls : Ext.ux.TDGi.iconMgr.getIcon('server'), + baseParams : {xid: %xid%, 'store': 'groups'}, + defaulPageSize : 25, + configStore : { buildFields: this.buildStoreGroup, sortInfo : {field: 'id', direction: 'ASC'} }, + configForm : { + items : this.buildFormGroup(), + labelWidth : 80, + height : 150, + width : 400 + }, + buildColumns : this.buildColumnsGroup, + + addIconCls : Ext.ux.TDGi.iconMgr.getIcon('server_add'), + editIconCls : Ext.ux.TDGi.iconMgr.getIcon('server_edit'), + deleteIconCls : Ext.ux.TDGi.iconMgr.getIcon('server_delete'), + addButtonText : 'Nuevo grupo', + editButtonText : 'Editar grupo', + deleteButtonText: 'Eliminar grupo', + + deleteMsg : 'Debe quitar todos los host existentes antes de realizar esta operación. ¿Está seguro que desea continuar con la eliminación el grupo?' + + + }); + + this.tabPanel = new Ext.TabPanel({ + activeTab: 0, + plain:true, + region:'center', + items: [ this.infoForm, this.hostGrid, this.preferencesForm, this.projectGrid ] + }); + + config = Ext.apply({ + layout: 'border', + border: false, + items: [ this.groupGrid, this.tabPanel ] + + }, config); + + Dazzler.proveedor.groupAdminPanel.superclass.constructor.call(this,config); + + this.projectGrid.store.on('save',this.onUpdateProjects,this); + this.hostGrid.store.on('update',this.onUpdateHosts,this); + + this.groupGrid.on('rowselect',this.onSelectGroup,this); + + this.groupGrid.store.on('datachanged',this.onViewReady,this); + + }, +/* ************************* configuracion de los diferentes Stores ************************* */ + /* Group Grid Store definition */ + buildStoreGroup: function(){ + return ['id', 'name', 'info']; + }, + /* Project Grid Store definition */ + buildStoreProject: function(){ + return ['id', 'name', 'url', 'resource_share', {name: 'suspend', type: 'boolean'}, {name: 'detach_when_done', type: 'boolean'} ]; + }, + /* Hosts Grid Store definition */ + buildStoreHosts: function(){ + return ['id', 'gid', 'name', 'ipaddr', 'cpus', 'mips', 'flops', 'last', 'hits' ]; + }, + + +/* ************************* Configuracion de los diferentes Grid Columns ************************* */ + /* Group Grid Columns definition */ + buildColumnsGroup: function(){ + return [{ dataIndex: 'name', header: 'Nombre'}, + { dataIndex: 'info', header: 'Descrip'} ]; + }, + /* Project Grid Columns definition */ + buildColumnsProject: function(){ + return [{ dataIndex: 'name', header: 'Nombre'}, + { dataIndex: 'url', header: 'Url'}, + { dataIndex: 'resource_share', header: 'Prioridad'}, + { dataIndex: 'detach_when_done', header: 'Estado', renderer: function (value, metaData, record){ + var img; + if(record.get('suspend')) + img = '
'; + else if(record.get('detach_when_done')) + img = '
'; + else + img = '
'; + return img; + }} ]; + }, + buildColumnsHosts: function(){ + return [{ dataIndex: 'name', header: 'Nombre'}, + { dataIndex: 'cpus', header: 'N° CPU'}, + { dataIndex: 'mips', header: 'MIPS'}, + { dataIndex: 'flops', header: 'Flops'}, + { dataIndex: 'ipaddr', header: 'Ip'}, + { dataIndex: 'hits', header: 'Contactos'}, + { dataIndex: 'last', header: 'Último contacto'} ]; + }, + +/* ************************* Configuracion de los diferentes Grid Forms ************************* */ + buildFormGroup: function(){ + return [{ name: 'name', fieldLabel: 'Nombre', allowBlank: false }, + { name: 'info', fieldLabel: 'Descripción', allowBlank: false } ]; + }, + buildFormProject: function(){ + + return [{ name: 'name', fieldLabel: 'Proyecto', xtype:'combo', allowBlank: false, store: this.projectsStore, mode: 'local',forceSelection: true, hiddenName: 'id',valueField: 'id',displayField: 'nombre', triggerAction: 'all' }, + { xtype: 'numberfield', name: 'resource_share', fieldLabel: 'Prioridad', maxValue: 1000,minValue: 0,allowDecimals: false }, + { xtype: 'checkbox', name: 'suspend', fieldLabel: 'Pausado' }, + { xtype: 'checkbox', name: 'detach_when_done', fieldLabel: 'Marcado para eliminación' } ]; + }, + buildFormEditProject: function(){ + return [{ xtype: 'displayfield', name: 'name', fieldLabel: 'Proyecto' }, + { xtype: 'numberfield', name: 'resource_share', fieldLabel: 'Prioridad', maxValue: 1000,minValue: 0,allowDecimals: false }, + { xtype: 'checkbox', name: 'suspend', fieldLabel: 'Pausado' }, + { xtype: 'checkbox', name: 'detach_when_done', fieldLabel: 'Marcado para eliminación' } ]; + }, + + buildFormHosts: function(){ + return [{ name: 'group', fieldLabel: 'Grupo', xtype:'combo', allowBlank: false, store: this.groupsStore, mode: 'local',forceSelection: true, hiddenName: 'gid',valueField: 'id',displayField: 'nombre', triggerAction: 'all' } ]; + }, +/* ************************* Configuracion de los otros Forms ************************* */ + buildInfoForm: function(){ + return [{ + fieldLabel:'Nombre', + name:'name' + },{ + fieldLabel:'Descripción', + name:'info' + },{ + fieldLabel:'Equipos', + name:'hosts' + },{ + fieldLabel:'Proyectos', + name:'projects' + },{ + fieldLabel:'Procesadores', + name:'proc' + },{ + fieldLabel:'MIPS', + name:'mips' + },{ + fieldLabel:'Flops', + name:'flops' + }]; + }, + buildPreferencesForm: function(){ + return[{ + xtype:'fieldset', + title: 'Preferencias del grupo', + autoHeight:true, + items: [{ + xtype: 'hidden', + name: 'id' + },{ + xtype: 'displayfield', + fieldLabel: 'Última modificación', + name: 'mod_time' + },{ + xtype: 'checkbox', + fieldLabel: 'Funcionar siempre', + name: 'run_if_user_active' + },{ + xtype: 'compositefield', + fieldLabel: 'Horario de funcionamiento', + items: [{ + xtype: 'timefield', + format: 'H:i', + width: 100, + name: 'start_hour' + },{ + xtype: 'timefield', + width: 100, + format: 'H:i', + name: 'end_hour' + }] + },{ + xtype: 'compositefield', + fieldLabel: 'Uso máximo de cpu', + items: [{ + xtype: 'numberfield', + name: 'cpu_usage_limit', + width: 60, + maxValue: 100, + minValue: 1, + invalidText: 'Debe ingresar un numero entre 1 y 100', + allowDecimals: false + },{ + xtype: 'displayfield', + value: '%' + }] + },{ + xtype: 'compositefield', + fieldLabel: 'Iniciar si esta inactivo', + items: [{ + xtype: 'numberfield', + name: 'idle_time_to_run', + width: 60, + maxValue: 60, + minValue: 1, + invalidText: 'Debe ingresar un numero entre 1 y 60', + allowDecimals: false + },{ + xtype: 'displayfield', + value: 'minutos' + }] + + }] + },{ + xtype: 'buttongroup', + columns: 3, + width: 400, + height: 50, + title: 'Configuraciones predefinidas', + items: [{ + text: 'Sin restricciones', + iconCls: Ext.ux.TDGi.iconMgr.getIcon('play_green'), + handler: this.prefAllways, + scope: this + },{ + text: 'Usar solo si está inactivo', + iconCls: Ext.ux.TDGi.iconMgr.getIcon('computer_off'), + handler: this.prefInactive, + scope: this + },{ + text: 'Recuros limitados', + iconCls: Ext.ux.TDGi.iconMgr.getIcon('play_blue'), + handler: this.prefLimit, + scope: this + }] + }]; + }, +/* ************************* preference pre-settings ************************* */ + prefAllways: function(){ + this.preferencesForm.getForm().setValues({ + run_if_user_active: 1, + start_hour:'00:00', + end_hour:'00:00', + cpu_usage_limit: 100, + idle_time_to_run: 1 + }); + }, + prefInactive: function(){ + this.preferencesForm.getForm().setValues({ + run_if_user_active: 0, + start_hour:'00:00', + end_hour:'00:00', + cpu_usage_limit: 100, + idle_time_to_run: 5 + }); + }, + prefLimit: function(){ + this.preferencesForm.getForm().setValues({ + run_if_user_active: 1, + start_hour:'00:00', + end_hour:'00:00', + cpu_usage_limit: 75, + idle_time_to_run: 1 + }); + }, + +/* ************************* preference controls ************************* */ + buildPreferencesButtons: function(){ + return [{ + text:'Deshacer cambios', + iconCls: Ext.ux.TDGi.iconMgr.getIcon('arrow_undo'), + formBind: true, + scope: this, + handler: this.undoPrefs + },{ + text:'Guardar', + iconCls: Ext.ux.TDGi.iconMgr.getIcon('disk'), + formBind: true, + scope: this, + handler: this.savePrefs + }]; + }, + + savePrefs: function(){ + var GroupId = this.groupGrid.getSelectionModel().getSelected().get('id'); + this.preferencesForm.getForm().submit({ + waitTitle:'Guardando Preferencias', + waitMsg:'Enviando...', + params: {'gid': GroupId}, + success:function(form, action){ + form.load({params: {'gid': GroupId}}); + }, + failure:function(form, action){ + Ext.Msg.alert('Error', 'Se produjo un error al enviar las preferencias.'); + } + }); + }, + undoPrefs: function(){ + var GroupId = this.groupGrid.getSelectionModel().getSelected().get('id'); + this.preferencesForm.getForm().load({params: {'gid': GroupId}}); + }, + +/* ************************* custom project deletion ************************* */ + onDeleteProject: function(){ + Ext.MessageBox.show({ + closable: false, + title : 'Confirmacion', + msg : 'Desea eliminar el projecto de inmediato?\\nYes: Lo elimina de inmediato\\nNo: Espera que termine los trabajos actuales y elimina.\\nCancel: Cancela la operación y vuelve al menu.' , + buttons: Ext.MessageBox.YESNOCANCEL, + fn : this.doDeleteProject, + scope : this + }); + }, + doDeleteProject: function(Button){ + if(Button == 'yes'){ + this.store.remove(this.selModel.getSelected()); + + /* Call method to disable buttons (now no row is selected)*/ + this.onRowDeselect(this.selModel); + } + else if(Button == 'no'){ + this.selModel.getSelected().set('detach_when_done',1); + } + }, + +/* ************************* event on Group Select ************************* */ + onUpdateProjects: function(){ + this.projectsStore.reload({}); + }, + onUpdateHosts: function(){ + this.hostGrid.store.reload({}); + }, + onSelectGroup: function(SelectionModel){ + var GroupId = SelectionModel.getSelected().get('id'); + if(GroupId){ + this.projectGrid.store.setBaseParam('gid',GroupId); + this.hostGrid.store.setBaseParam('gid',GroupId); + this.projectsStore.setBaseParam('gid',GroupId); + + this.infoForm.getForm().load({params: {'gid': GroupId}}); + this.preferencesForm.getForm().load({params: {'gid': GroupId}}); + + this.projectsStore.reload({}); + this.projectGrid.store.reload({params:{start: 0, limit: 25}}); + this.hostGrid.store.reload({params:{start: 0, limit: 25}}); + } + }, + onViewReady: function(){ + this.groupGrid.getSelectionModel().selectFirstRow(); + this.groupsStore.reload({}); + } +}); +"; + +} + +function App_show(){ + +return " +SCV.mainContent.add( new Dazzler.proveedor.groupAdminPanel() ); +SCV.mainContent.doLayout(); +"; + +} + +function DirectRead($DB, $Data){ +$out = array(); + +if($Data->store == 'groups'){ + $out['root'] = array(); + $DB->Consulta("select count(*) from groups where uid = %uid%;"); + $t = $DB->SacaTupla(); + $out['totalCount'] = $t[0]; + + $DB->Consulta("select id, name, info from groups where uid = %uid% order by {$Data->sort} {$Data->dir} offset {$Data->start} limit {$Data->limit};"); + + while($t = $DB->SacaTupla(false)){ + $out['root'][] = $t; + } + $out['success'] = true; + } +else if($Data->store == 'hosts'){ + $out['root'] = array(); + $gid = intval($Data->gid); + if($gid > 0){ + $DB->Consulta("select count(*) from hosts where gid = $gid;"); + $t = $DB->SacaTupla(); + $out['totalCount'] = $t[0]; + + + $DB->Consulta("select id, gid, name, ipaddr, cpus, cpus*mips as mips, cpus*flops as flops, last_contact as last, hits from hosts where gid = $gid order by {$Data->sort} {$Data->dir} offset {$Data->start} limit {$Data->limit};"); + while($t = $DB->SacaTupla(false)){ + $t['ipaddr'] = long2ip(sprintf("%u",$t['ipaddr'])); + $t['last'] = date('d/m/Y H:i', $t['last']); + $out['root'][] = $t; + } + } + $out['success'] = true; + } +else if($Data->store == 'projects'){ + $out['root'] = array(); + $gid = intval($Data->gid); + if($gid > 0){ + $DB->Consulta("select count(*) from configProjects where gid = $gid;"); + $t = $DB->SacaTupla(); + $out['totalCount'] = $t[0]; + + $DB->Consulta("select projects.id, name, url, resource_share, suspend, LEAST(detach_when_done,1) as detach_when_done from (configprojects left join projects on (configprojects.pid = projects.id)) where gid = $gid order by {$Data->sort} {$Data->dir} offset {$Data->start} limit {$Data->limit};"); + + while($t = $DB->SacaTupla(false)){ + + $out['root'][] = $t; + } + } + $out['success'] = true; + } +return $out; + +} + +function DirectCreate($DB, $Data){ +$out = array(); + +$out['root'] = array(); + +if($Data->store == 'groups'){ + $DB->Consulta("select nextval('groups_id_seq'::regclass);"); + list($nextid) = $DB->SacaTupla(); + + $Escaped = $DB->EscapeObject($Data->root,array('name','info')); + + $now = time()+43200; + + $DB->Consulta("insert into groups( id,uid,name,info,mod_time ) values($nextid,%uid%,'{$Escaped['name']}','{$Escaped['info']}',$now);"); + + if($DB->Estado){ + $out['success'] = true; + $out['root'] = array('id'=>$nextid, 'name'=>$Data->root->name, 'info'=>$Data->root->info ); + } + else{ + $out['success'] = false; + $out['root'] = array(); + $out['msg'] = "Error al crear el Grupo, verifique que el nombre no exista y vuelva a intentarlo"; + } + } +else if($Data->store == 'projects'){ + $gid = intval($Data->gid); + if($gid > 0){ + + $now = time(); + if($Data->root->suspend) + $suspend = 1; + else + $suspend = 0; + + if($Data->root->detach_when_done) + $dwd = $now+14*24*3600; + else + $dwd = 0; + + $pid = intval($Data->root->id); + $rs = intval ($Data->root->resource_share); + + $DB->MostrarConsultas = 1; + $hasAccount = $DB->Consulta("select authenticator from authenticators where pid=$pid and uid=%uid%;"); + + $DB->Consulta("begin;"); + if(!$hasAccount) + $DB->Consulta("insert into authenticators( uid,pid ) values(%uid%,$pid);"); + + + $DB->Consulta("insert into configprojects( gid,pid,resource_share,suspend,detach_when_done,mod_time ) values( $gid,$pid,$rs,$suspend,$dwd,$now );"); + $DB->Consulta("commit;"); + if($DB->Estado){ + $dwd = $dwd && 1; + $out['success'] = true; + $out['root'] = array('id'=>$pid, 'resource_share'=>$rs, 'suspend'=>$suspend, 'detach_when_done'=>$dwd ); + } + else{ + $out['success'] = false; + $out['root'] = array(); + $out['msg'] = "Error al crear el Proyecto"; + } + } + } +return $out; +} + +function DirectUpdate($DB, $Data){ +$out = array(); +$out['root'] = array(); + +if($Data->store == 'groups'){ + $Escaped = $DB->EscapeObject($Data->root,array('name','info')); + $gid = intval($Data->root->id); + + $DB->Consulta("update groups set name='{$Escaped['name']}', info='{$Escaped['info']}' where id = $gid"); + + if($DB->Estado){ + $out['success'] = true; + $out['root'] = array('id'=>$Data->root->id, 'name'=>$Data->root->name, 'info'=>$Data->root->info ); + } + else{ + $out['success'] = false; + $out['msg'] = "Error al actualizar el Grupo."; + } + } +else if($Data->store == 'hosts'){ + + $hid = intval($Data->root->id); + $gid = intval($Data->root->gid); + if(($hid > 0) && ($gid > 0)){ + + $DB->Consulta("update hosts set gid=$gid where id = $hid"); + $DB->Consulta("select id, gid, name, ipaddr, cpus, cpus*mips as mips, cpus*flops as flops, last_contact as last,hits from hosts where id = $hid;"); + + $t = $DB->SacaTupla(false); + $t['ipaddr'] = long2ip(sprintf("%u",$t['ipaddr'])); + $t['last'] = date('d/m/Y H:i', $t['last']); + + $out['root'][] = $t; + $out['success'] = true; + + } + else + $out['success'] = false; + } +else if($Data->store == 'projects'){ + $gid = intval($Data->gid); + if($gid > 0){ + $DB->Consulta("select detach_when_done from configprojects where gid=$gid and pid=$pid;"); + list( $ldwd ) = $DB->SacaTupla(); + $now = time(); + + if($Data->root->suspend) + $suspend = 1; + else + $suspend = 0; + + if($Data->root->detach_when_done){ + if($ldwd > 0) + $dwd = $ldwd; + else + $dwd = $now+14*24*3600; + } + else + $dwd = 0; + + $pid = intval($Data->root->id); + $rs = intval ($Data->root->resource_share); + + $DB->Consulta("update configprojects set resource_share=$rs,suspend=$suspend,detach_when_done=$dwd,mod_time=$now where gid=$gid and pid=$pid;"); + if($DB->Estado){ + $dwd = $dwd && 1; + $out['success'] = true; + $out['root'] = array('id'=>$pid,'name'=>$Data->root->name,'url'=>$Data->root->url, 'resource_share'=>$rs, 'suspend'=>$suspend, 'detach_when_done'=>$dwd ); + } + else{ + $out['success'] = false; + $out['root'] = array(); + $out['msg'] = "Error al actualizar proyecto"; + } + } + } + +return $out; +} + +function DirectDestroy($DB, $Data){ +$out = array(); +if($Data->store == 'groups'){ + $out['root'] = array(); + $out['success'] = true; + + $Gdel = intval($Data->root); + + $DB->Consulta("select group_default from users where id = %uid%;"); + list( $dg ) = $DB->SacaTupla(); + + $greenlight = $DB->Consulta("select id from groups where id=$Gdel and uid = %uid%;"); + + if($dg == $Gdel){ + $out['success'] = false; + $out['msg'] = "No se puede elimitar el grupo."; + } + else if($greenlight){ + $DB->Consulta("delete from groups where gid = $Gdel;"); + if(!$DB->Estado){ + $out['success'] = false; + $out['msg'] = "Error al eliminar el grupo, debe vaciarlo antes de borrarlo."; + } + } + else { + $out['success'] = false; + $out['msg'] = "Error de permisos."; + } + } +else if($Data->store == 'projects'){ + $gid = intval($Data->gid); + if($gid > 0){ + $greenlight = $DB->Consulta("select id from groups where id=$gid and uid = %uid%;"); + if($greenlight){ + $pid = intval($Data->root); + $DB->Consulta("delete from configprojects where gid=$gid and pid=$pid;"); + } + else { + $out['success'] = false; + $out['msg'] = "Error de permisos."; + } + } + } +return $out; +} + +function submitForm($DB, $Data){ +$out = array(); + +$id = intval($Data['id']); +$gid = intval($Data['gid']); + +if(($id == 0) || ($gid == 0) || ($id != $gid)){ + $out['success'] = false; + } +else{ + $now = time(); + + list($horaStr, $minutosStr) = explode(':',$Data['start_hour']); + $hora = intval($horaStr); + $minutos = intval($minutosStr); + $startH = $hora + $minutos / 60; + + list($horaStr, $minutosStr) = explode(':',$Data['end_hour']); + $hora = intval($horaStr); + $minutos = intval($minutosStr); + $endH = $hora + $minutos / 60; + + $cpuUsage = intval($Data['cpu_usage_limit']); + $idleTime = intval($Data['idle_time_to_run']); + + if($Data['run_if_user_active'] == 'on') + $runActive = 1; + else + $runActive = 0; + + + $DB->Consulta("update groups set mod_time=$now,start_hour=$startH,end_hour=$endH,cpu_usage_limit=$cpuUsage,run_if_user_active=$runActive,idle_time_to_run=$idleTime where id = $gid;"); + $out['success'] = true; + } + +return $out; +} + +function loadForm($DB, $Data){ +$out = array(); +if($Data->form == 'pref'){ + $out['data'] = array(); + $gid = intval($Data->gid); + $DB->Consulta("select id,mod_time, start_hour,end_hour,cpu_usage_limit,run_if_user_active,idle_time_to_run from groups where id = $gid;"); + $pref = $DB->SacaTupla(false); + + $hora = intval($pref['start_hour']); + $minutos = intval(($pref['start_hour'] - $hora) * 60); + $pref['start_hour'] = sprintf("%02d:%02d", $hora,$minutos); + + $hora = intval($pref['end_hour']); + $minutos = intval(($pref['end_hour'] - $hora) * 60); + $pref['end_hour'] = sprintf("%02d:%02d", $hora,$minutos); + + $pref['mod_time'] = date('d/m/Y H:i', $pref['mod_time'] ); + + $out['data'] = $pref; + $out['success'] = true; + } +else if($Data->form == 'info'){ + $out['data'] = array(); + $twoweeks = time() - 13.5 * 24 * 3600; + $gid = intval($Data->gid); + + $DB->Consulta("select name, info from groups where id = $gid;"); + $Grupos = $DB->SacaTupla(false); + + $DB->Consulta("select count(*) as hosts, sum(cpus) as proc, sum(cpus*mips) as mips, sum(cpus*flops) as flops from hosts where gid = $gid and last_contact >= $twoweeks;"); + $Hosts = $DB->SacaTupla(false); + if($Hosts['hosts'] == 0){ + $Hosts = array('hosts'=>'0','proc'=>'0','mips'=>'0','flops'=>'0'); + } + + $DB->Consulta("select count(*) as hosts, sum(cpus) as proc, sum(cpus*mips) as mips, sum(cpus*flops) as flops from hosts where gid = $gid and last_contact < $twoweeks;"); + $InactiveHosts = $DB->SacaTupla(); + if($InactiveHosts['hosts'] > 0){ + $Hosts['hosts'] .= " (" . $InactiveHosts['hosts'] . " inactivos)"; + $Hosts['proc'] .= " (" . $InactiveHosts['proc'] . " inactivos)"; + $Hosts['mips'] .= " (" . $InactiveHosts['mips'] . " inactivos)"; + $Hosts['flops'] .= " (" . $InactiveHosts['flops'] . " inactivos)"; + } + + $Proyectos = $DB->Consulta("select pid from configprojects where gid = $gid;"); + $POut = $DB->Consulta("select pid from configprojects where gid = $gid and detach_when_done > 0;"); + $PDetenidos = $DB->Consulta("select pid from (configprojects left join projects on (projects.id = configproject.pid)) where gid = $gid and detach_when_done = 0 and (configproject.suspend > 0 OR projects.estado > 0);"); + + $Pactivos = $Proyectos - $PDetenidos - $POut; + + $Proj['projects'] = "$Pactivos activos"; + + if($PDetenidos > 0) + $Proj['projects'] .= " / $PDetenidos pausados"; + + if($POut > 0) + $Proj['projects'] .= " / $POut en eliminacion"; + + $out['data'] = array_merge($Grupos, $Hosts, $Proj); + $out['success'] = true; + } +return $out; +} + +function groupCombo($DB, $Data){ +$out['root'] = array(); +$out['totalCount'] = $DB->Consulta("select id, name as nombre from groups where uid = %uid% order by {$Data->sort} {$Data->dir};"); + +while($t = $DB->SacaTupla(false)){ + $out['root'][] = $t; + } + +$out['success'] = true; + +return $out; +} + +function projectCombo($DB, $Data){ +$out['root'] = array(); + +$gid = intval($Data->gid); + +$out['totalCount'] = $DB->Consulta("select id, name as nombre from projects where id not in (select pid from configprojects where gid={$gid}) and estado < 2 order by {$Data->sort} {$Data->dir};"); + +while($t = $DB->SacaTupla(false)){ + $out['root'][] = $t; + } + +$out['success'] = true; + +return $out; +} diff --git a/BAM/js/Dazzler/Dazzler.proveedor.install.js b/BAM/js/Dazzler/Dazzler.proveedor.install.js new file mode 100644 index 0000000..bfaa0fc --- /dev/null +++ b/BAM/js/Dazzler/Dazzler.proveedor.install.js @@ -0,0 +1,61 @@ +/* ! + * This file is part of Dazzler + * Copyright(c) 2011 USI - Universidad de Concepcion + * + * Dazzler is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Dazzler is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Dazzler. If not, see . + * +*/ + +function App_define(){ +global $IconsURL; +return " +Ext.ns('Dazzler.manager'); +/* Panel administracion de grupos de maquinas */ + +Dazzler.manager.installPanel = Ext.extend(Ext.Panel, { + + constructor: function(config){ + + config = Ext.apply({ + }, config); + + Dazzler.manager.installPanel.superclass.constructor.call(this,config); + }, + + title: 'Información sobre la Instalacion de nuevos nodos', + + html: '

Metodo de instalación de BOINC

\ +

Esta es la manera recomendada para agregar nuevos nodos a su cuenta de SCV. Este procedimiento es compatible con las versiones de windows 2000, XP, Vista y 7

\ +
    \ +
  • Descarge la última version del cliente de BOINC aqui.\ +
  • Descargue los scripts de instalación aqui.\ +
  • Descarque el archivo de dazzler aqui.\ +
  • Descarque el archivo de autentificación de su cuenta aqui.\ +
\ +

Descomprima los scripts de instalación y copie el archivo de autentificación descargado. Luego copie el archivo de instalación del cliente de boinc cambiando su nombre (ej: boinc_6.10.60_windows_intelx86.exe ) por boinc_windows.exe

\ +

Ejecute el archivo de Instalar.bat, que se encargará de instalar y configurar de manera automatica el cliente de boinc al sistema, podrá ver de inmediato el nuevo equipo en el sistema.

\ +

Para informacion adicional de instalaciones personalizadas o de instalación en otras plataformas contactarse con scv@ing.udec.cl.

' +}); +"; + +} + +function App_show(){ + +return " +SCV.mainContent.add( new Dazzler.manager.installPanel() ); +SCV.mainContent.doLayout(); +"; +} + diff --git a/BAM/js/Dazzler/Dazzler.proveedor.projects.js b/BAM/js/Dazzler/Dazzler.proveedor.projects.js new file mode 100644 index 0000000..83b5fb1 --- /dev/null +++ b/BAM/js/Dazzler/Dazzler.proveedor.projects.js @@ -0,0 +1,212 @@ +/* ! + * This file is part of Dazzler + * Copyright(c) 2011 USI - Universidad de Concepcion + * + * Dazzler is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Dazzler is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Dazzler. If not, see . + * +*/ + +function App_define(){ +global $IconsURL; +return " +Ext.ns('Dazzler.manager'); +/* Panel administracion de grupos de maquinas */ + +Dazzler.manager.projectPanel = Ext.extend(Ext.ux.crudGridPanel.crPagingGrid, { + + constructor: function(config){ + + config = Ext.apply({ + configStore : { buildFields: this.storeFields }, + baseParams: {xid: %xid%}, + configForm : { + items : this.formFields(), + labelWidth : 80, + height : 250, + width : 400 + }, + + buildColumns : this.gridColumns + }, config); + + Dazzler.manager.projectPanel.superclass.constructor.call(this,config); + }, + + defaultDesc: 'Proyectos', + title: 'Proyectos configurados', + baseParams: {xid: %xid%}, + defaulPageSize: 25, + + addButtonText : 'Agregar autentificador', + + + storeFields: function(){ + return ['id', 'name', 'url', 'auth' ,'estado', 'hosts' ]; + }, + + gridColumns: function(){ + return [{ dataIndex: 'name', header: 'Proyecto'}, + { dataIndex: 'url', header: 'Url'}, + { dataIndex: 'estado', header: 'Estado', renderer: function (value){ + var img; + if(value == 0) + img = '
'; + else if(value == 1) + img = '
'; + else + img = '
'; + return img; + }} ]; + }, + + formFields: function(){ + var researcherStore = new Ext.data.Store({ + proxy : new Ext.data.DirectProxy({ directFn: Dazzler.api.customFn }), + reader : new Ext.data.JsonReader({ + root: 'root', + totalProperty: 'totalCount', + idProperty: 'id', + messageProperty: 'msg', + fields: ['id', 'nombre'] + }), + baseParams : {'xid': %xid%, 'customFn': 'researchCombo'}, + remoteSort : true, + sortInfo : {field: 'nombre', direction: 'ASC'}, + autoLoad : {} + }); + + return [{ name: 'user', fieldLabel: 'Administrador', xtype:'combo', allowBlank: false, store: researcherStore, mode: 'local',forceSelection: true, hiddenName: 'uid',valueField: 'id',displayField: 'nombre', triggerAction: 'all' }, + { name: 'name', fieldLabel: 'Nombre', allowBlank: false }, + { name: 'url', fieldLabel: 'Url', allowBlank: false }, + { name: 'url_signature', fieldLabel: 'Firma', allowBlank: false, xtype: 'textarea' }, + { name: 'estado', fieldLabel: 'Suspendido', xtype: 'checkbox' } + ]; + } +}); +"; + +} + +function App_show(){ + +return " +SCV.mainContent.add( new Dazzler.manager.projectPanel() ); +SCV.mainContent.doLayout(); +"; +} + +function DirectRead($DB, $Data){ +$out = array(); + +$out['root'] = array(); +$DB->Consulta("select count(*) from projects;"); +$t = $DB->SacaTupla(); +$out['totalCount'] = $t[0]; + +$DB->Consulta("select projects.id, uid, nombre as user, name, url, url_signature, estado from (projects left join usuarios on (projects.uid = usuarios.id)) order by {$Data->sort} {$Data->dir} offset {$Data->start} limit {$Data->limit};"); + +while($t = $DB->SacaTupla(false)){ + $out['root'][] = $t; + } +$out['success'] = true; + +return $out; +} + +function DirectCreate($DB, $Data){ +$out = array(); + +$DB->Consulta("select nextval('projects_id_seq'::regclass);"); +list($nextid) = $DB->SacaTupla(); + +if($Data->root->estado) + $status = 1; +else + $status = 0; + +$uid = intval($Data->root->uid); +$Escaped = $DB->EscapeObject($Data->root,array('name','url','url_signature')); + + +$DB->Consulta("insert into projects( id,uid,name,url,url_signature,estado ) values($nextid,$uid,'{$Escaped['name']}','{$Escaped['url']}','{$Escaped['url_signature']}',$status);"); + +if($DB->Estado){ + $out['success'] = true; + $out['root'] = array('id'=>$nextid, 'uid'=>$uid, 'name'=>$Data->root->name, 'user'=>$Data->root->user, 'url'=>$Data->root->url, 'url_signature'=>$Data->root->url_signature, 'estado'=>$status ); + } +else{ + $out['success'] = false; + $out['root'] = array(); + $out['msg'] = "Error al crear el Proyecto, verifique que el nombre no exista y vuelva a intentarlo"; + } + +return $out; +} + +function DirectUpdate($DB, $Data){ +$out = array(); +$out['root'] = array(); + +if($Data->root->estado) + $status = 1; +else + $status = 0; + +$uid = intval($Data->root->uid); +$Escaped = $DB->EscapeObject($Data->root,array('name','url','url_signature')); + +$DB->Consulta("update projects set uid=$uid, name='{$Escaped['name']}', url='{$Escaped['url']}', url_signature='{$Escaped['url_signature']}', estado={$status} where id = {$Data->root->id}"); + +if($DB->Estado){ + $out['success'] = true; + $out['groups'] = array('id'=>$Data->root->id, 'uid'=>$uid, 'name'=>$Data->root->name, 'user'=>$Data->root->user, 'url'=>$Data->root->url, 'url_signature'=>$Data->root->url_signature, 'estado'=>$status ); + } +else{ + $out['success'] = false; + $out['msg'] = "Error al actualizar el Proyecto."; + } + +return $out; +} + +function DirectDestroy($DB, $Data){ +$out = array(); + +$out['root'] = array(); +$out['success'] = true; +$pid = intval($Data->root); +$DB->Consulta("delete from projects where id = $pid;"); + +if(!$DB->Estado){ + $out['success'] = false; + $out['msg'] = "Error al eliminar el Proyecto."; + } + +return $out; +} + +function researchCombo($DB, $Data){ +$out = array(); +$out['root'] = array(); + +$DB->Consulta("select users.id, nombre from (users left join usuarios on (usuarios.id=users.id)) where tipo&4=4 order by {$Data->sort} {$Data->dir};"); + +while($t = $DB->SacaTupla(false)){ + $out['root'][] = $t; + } +$out['success'] = true; + +return $out; +} + diff --git a/BAM/js/Dazzler/Dazzler.proveedor.resumen.js b/BAM/js/Dazzler/Dazzler.proveedor.resumen.js new file mode 100644 index 0000000..a5cd2c2 --- /dev/null +++ b/BAM/js/Dazzler/Dazzler.proveedor.resumen.js @@ -0,0 +1,184 @@ +/* ! + * This file is part of Dazzler + * Copyright(c) 2011 USI - Universidad de Concepcion + * + * Dazzler is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Dazzler is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Dazzler. If not, see . + * +*/ + +function App_define(){ +global $IconsURL; +return " +Ext.ns('Dazzler.proveedor'); +/* Panel administracion de grupos de maquinas */ + +Dazzler.proveedor.resumenPanel = Ext.extend(Ext.TabPanel, { + constructor: function(config){ + + + /* Creacion de paneles */ + this.infoForm = new Ext.FormPanel({ + frame : true, + title :'Resumen', + iconCls : Ext.ux.TDGi.iconMgr.getIcon('information'), + defaultType :'displayfield', + baseParams : {xid: %xid%, 'form': 'info'}, + listeners : {afterrender : this.afterrender, scope: this.infoForm }, + api : {load: Dazzler.api.loadForm }, + paramsAsHash : true, + items : this.buildInfoForm() + }); + + + this.projectGrid = new Ext.ux.crudGridPanel.rPagingGrid({ + defaultDesc : 'proyectos', + title : 'Recursos por proyecto', + iconCls : Ext.ux.TDGi.iconMgr.getIcon('world'), + baseParams : {xid: %xid%, 'store': 'projects' }, + defaulPageSize : 25, + configStore : { buildFields: this.buildStoreProject }, + + buildColumns : this.buildColumnsProject + + }); + + + config = Ext.apply({ + activeTab: 0, + plain:true, + region:'center', + items: [ this.infoForm, this.projectGrid ] + }, config); + + Dazzler.proveedor.resumenPanel.superclass.constructor.call(this,config); + }, +/* ************************* configuracion de los diferentes Stores ************************* */ + /* Project Grid Store definition */ + buildStoreProject: function(){ + return ['id', 'name', 'url', 'resource_share', {name: 'suspend', type: 'boolean'}, {name: 'detach_when_done', type: 'boolean'} ]; + }, + +/* ************************* Configuracion de los diferentes Grid Columns ************************* */ + /* Project Grid Columns definition */ + buildColumnsProject: function(){ + return [{ dataIndex: 'name', header: 'Nombre'}, + { dataIndex: 'url', header: 'Url'}, + { dataIndex: 'resource_share', header: 'Prioridad'}, + { dataIndex: 'detach_when_done', header: 'Estado', renderer: function (value, metaData, record){ + var img; + if(record.get('suspend')) + img = '
'; + else if(record.get('detach_when_done')) + img = '
'; + else + img = '
'; + return img; + }} ]; + }, +/* ************************* Configuracion de los otros Forms ************************* */ + afterrender: function(){ + this.getForm().load({ }); + }, + buildInfoForm: function(){ + return [{ + fieldLabel:'Nombre', + name:'name' + },{ + fieldLabel:'Descripción', + name:'info' + },{ + fieldLabel:'Equipos', + name:'hosts' + },{ + fieldLabel:'Proyectos', + name:'projects' + },{ + fieldLabel:'Procesadores', + name:'proc' + },{ + fieldLabel:'MIPS', + name:'mips' + },{ + fieldLabel:'Flops', + name:'flops' + }]; + } + +}); +"; + +} + +function App_show(){ + +return " +SCV.mainContent.add( new Dazzler.proveedor.resumenPanel() ); +SCV.mainContent.doLayout(); +"; + +} + +function DirectRead($DB, $Data){ +$out = array(); + +$out['root'] = array(); + +$DB->Consulta("select count(distinct(pid)) from configProjects where gid in (select id from groups where uid = %uid%);"); +$t = $DB->SacaTupla(); +$out['totalCount'] = $t[0]; + +$DB->Consulta("select distinct(projects.id), name, url from (configprojects left join projects on (configprojects.pid = projects.id)) where gid in (select id from groups where uid = %uid%) order by {$Data->sort} {$Data->dir} offset {$Data->start} limit {$Data->limit};"); + +while($t = $DB->SacaTupla(false)){ + + $out['root'][] = $t; + } + +$out['success'] = true; +return $out; + +} + +function loadForm($DB, $Data){ +$out = array(); + +$out['data'] = array(); +$twoweeks = time() - 13.5 * 24 * 3600; + +$AH = $DB->Consulta("select count(*) as hosts, sum(cpus) as proc, sum(cpus*mips) as mips, sum(cpus*flops) as flops from hosts where gid in (select id from groups where uid = %uid%) and last_contact >= $twoweeks;"); +if($AH > 0){ + $Hosts = $DB->SacaTupla(false); + } +else{ + $Hosts = array('hosts'=>'0','proc'=>'0','mips'=>'0','flops'=>'0'); + } + +$DB->Consulta("select count(*) as hosts, sum(cpus) as proc, sum(cpus*mips) as mips, sum(cpus*flops) as flops from hosts where gid in (select id from groups where uid = %uid%) and last_contact < $twoweeks;"); +$InactiveHosts = $DB->SacaTupla(); +if($InactiveHosts['hosts'] > 0){ + $Hosts['hosts'] .= " (" . $InactiveHosts['hosts'] . " inactivos)"; + $Hosts['proc'] .= " (" . $InactiveHosts['proc'] . " inactivos)"; + $Hosts['mips'] .= " (" . $InactiveHosts['mips'] . " inactivos)"; + $Hosts['flops'] .= " (" . $InactiveHosts['flops'] . " inactivos)"; + } + +$Proyectos = $DB->Consulta("select distinct(pid) from configprojects where gid in (select id from grupos where uid = %uid%);"); +$Proj['projects'] = "$Proyectos activos"; + + +$out['data'] = array_merge($Hosts, $Proj); +$out['success'] = true; + +return $out; +} diff --git a/BAM/js/Welcome.html b/BAM/js/Welcome.html new file mode 100644 index 0000000..440de96 --- /dev/null +++ b/BAM/js/Welcome.html @@ -0,0 +1,27 @@ +

Bienvenido a Dazzler!

+

Estamos trabajando para serviorle xD

+ +
+ +
+ +
+
+ diff --git a/BAM/js/crudGridPanel.js b/BAM/js/crudGridPanel.js new file mode 100644 index 0000000..1ad85d1 --- /dev/null +++ b/BAM/js/crudGridPanel.js @@ -0,0 +1,873 @@ +/* ! + * This file is part of Dazzler + * Copyright(c) 2011 USI - Universidad de Concepcion + * + * Dazzler is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Dazzler is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Dazzler. If not, see . + * +*/ + + +Ext.ns('Ext.ux', 'Ext.ux.crudGridPanel'); + +/* Basic Read Store - no write capabilities */ +Ext.ux.crudGridPanel.rStore = Ext.extend(Ext.data.Store, { + + constructor: function(config){ + if(config.defaultLimit) + this.defaultLimit = config.defaultLimit; + + if(config.buildFields) + this.buildFields = config.buildFields; + + config = Ext.apply({ + proxy : this.buildProxy(), + reader : this.buildReader(), + remoteSort : true, + sortInfo : {field: 'id', direction: 'DESC'}, + autoLoad : {params:{start: 0, limit: this.defaultLimit}} + }, config); + + Ext.ux.crudGridPanel.rStore.superclass.constructor.call(this,config); + }, + + defaultLimit: 25, + + buildFields: function(){ + return ['id','name']; + }, + + buildReader: function(){ + return new Ext.data.JsonReader({ + root : 'root', + totalProperty : 'totalCount', + idProperty : 'id', + messageProperty : 'msg', + fields : this.buildFields() + }); + + }, + + buildProxy: function(){ + return new Ext.data.DirectProxy({ + api: { + read: Dazzler.api.DirectRead + } + }); + } +}); + +/* Read/Create/Update Store - no delete capabilities */ +Ext.ux.crudGridPanel.cruStore = Ext.extend(Ext.ux.crudGridPanel.rStore, { + constructor: function(config){ + config = Ext.apply({ + proxy : this.buildProxy(), + writer : this.buildWriter() + }, config); + Ext.ux.crudGridPanel.cruStore.superclass.constructor.call(this,config); + }, + + buildProxy: function(){ + return new Ext.data.DirectProxy({ + api: { + read : Dazzler.api.DirectRead, + update : Dazzler.api.DirectUpdate, + create : Dazzler.api.DirectCreate + } + }); + }, + + buildWriter: function(){ + return new Ext.data.JsonWriter({encode: false, writeAllFields: true }); + } + +}); + +/* Full Store */ +Ext.ux.crudGridPanel.crudStore = Ext.extend(Ext.ux.crudGridPanel.cruStore, { + constructor: function(config){ + + config = Ext.apply({ + proxy: this.buildProxy() + }, config); + + Ext.ux.crudGridPanel.crudStore.superclass.constructor.call(this,config); + }, + + buildProxy: function(){ + return new Ext.data.DirectProxy({ + api: { + read : Dazzler.api.DirectRead, + update : Dazzler.api.DirectUpdate, + destroy : Dazzler.api.DirectDestroy, + create : Dazzler.api.DirectCreate + } + }); + } +}); + + +/* Basic Add/Edit Form */ +/* A simple form for creation and edit of the records */ +Ext.ux.crudGridPanel.baseForm = Ext.extend(Ext.FormPanel, { + constructor: function(config){ + this.backIconCls = config.backIconCls ? config.backIconCls : Ext.ux.TDGi.iconMgr.getIcon('bullet_left'); + this.saveIconCls = config.saveIconCls ? config.saveIconCls : Ext.ux.TDGi.iconMgr.getIcon('disk'); + this.previewIconCls = config.previewIconCls ? config.previewIconCls : Ext.ux.TDGi.iconMgr.getIcon('page_white_magnify'); + + if(config.buildFields) + this.buildFields = config.buildFields; + + if(config.buildButtons) + this.buildButtons = config.buildButtons; + + if(config.buildPreview) + this.buildPreview = config.buildPreview; + + if(config.backButtonText) + this.backButtonText = config.backButtonText; + if(config.saveButtonText) + this.saveButtonText = config.saveButtonText; + if(config.previewButtonText) + this.previewButtonText = config.previewButtonText; + + configForm = Ext.apply({ + }, config.configForm); + + /* Form setup */ + config = Ext.apply({ +// frame : true, + border : false, + width : 400, + height : 90, + defaultType : 'textfield', + defaults : {anchor: '100%'}, + buttonAlign : 'left', + bodyStyle : "background-color: transparent", + padding : 10, +// trackResetOnLoad: false, + items : this.buildFields(), + buttons : this.buildButtons() + }, config); + + Ext.ux.crudGridPanel.baseForm.superclass.constructor.call(this,config); + + this.addEvents('savebtn'); + this.addEvents('closebtn'); + this.addEvents('previewbtn'); + }, + +/* default form definition */ + buildFields: function() { + return [{ + name : 'name', + fieldLabel : 'Nombre' + }]; + }, + + buildButtons: function() { + if(this.buildPreview) + return [{ + text : this.backButtonText, + scope : this, + handler : this.onBack, + iconCls : this.backIconCls + },'->',{ + text : this.previewButtonText, + scope : this, + handler : this.onPreview, + iconCls : this.previewIconCls + },{ + text : this.saveButtonText, + scope : this, + handler : this.onSave, + iconCls : this.saveIconCls + + }]; + else + return [{ + text : this.backButtonText, + scope : this, + handler : this.onBack, + iconCls : this.backIconCls + },'->',{ + text : this.saveButtonText, + scope : this, + handler : this.onSave, + iconCls : this.saveIconCls + + }]; + }, + +/* Form Actions*/ + onSave: function() { + this.fireEvent('savebtn', this); + }, + onPreview: function() { + this.fireEvent('previewbtn', this); + }, + onBack: function() { + this.fireEvent('closebtn', this); + }, + buildPreview : false, + + backButtonText : 'Volver', + saveButtonText : 'Guardar', + previewButtonText : 'Vista previa', + previewIconCls : '', + backIconCls : '', + saveIconCls : '' + + }); + +/* Window container of the form for modal presentation */ +Ext.ux.crudGridPanel.baseWindowForm = Ext.extend(Ext.Window, { + constructor: function(config){ + + configForm = Ext.apply({ + }, config.configForm); + + this.form = new Ext.ux.crudGridPanel.baseForm(configForm); + + delete config.configForm; + +/* setup default listeners */ + listeners = Ext.apply({ + scope : this, + closebtn: this.onClose + }, config.listeners); + + delete config.listeners; + + config = Ext.apply({ + autoDestroy : false, + closable : false, + resizable : false, + modal : true, + layout : 'fit', + listeners : listeners, + items : [ this.form ] + }, config); + + Ext.ux.crudGridPanel.baseWindowForm.superclass.constructor.call(this,config); + + this.relayEvents(this.form, ['savebtn','closebtn','previewbtn']); + }, +/* behave like the formPanel, returning the basicForm directly */ + getForm: function (){ + return this.form.getForm(); + }, + currentRecord: null + }); + + +/* Basic Customizable Grid */ +/* it creates a series of funcion for building for future overloading */ + +Ext.ux.crudGridPanel.baseGrid = Ext.extend(Ext.grid.GridPanel, { + constructor: function(config) { + this.selModel = config.selModel ? config.selModel : this.buildSelModel(); + this.buildColumns = config.buildColumns ? config.buildColumns : this.defaultColumns(); + + if(config.buildTbar) + this.buildTbar = config.buildTbar; + + if(config.buildBbar) + this.buildBbar = config.buildBbar; + + if(config.buildColModel) + this.buildColModel = config.buildColModel; + + if(config.buildViewConf) + this.buildViewConf = config.buildViewConf; + + config = Ext.apply({ + colModel : this.buildColModel(), + viewConfig : this.buildViewConf(), + selModel : this.selModel, + tbar : this.buildTbar(), + bbar : this.buildBbar(), + loadMask : {msg:'Cargando datos...'} + }, config); + + Ext.ux.crudGridPanel.baseGrid.superclass.constructor.call(this,config); + + this.relayEvents(this.selModel, ['selectionchange','rowdeselect','rowselect']); + }, +/* simple default methods for future overloading */ + buildSelModel: function() { + return new Ext.grid.RowSelectionModel( {singleSelect:true } ); + }, + + buildColumns: function() { + return [{ dataIndex: 'id',header: 'Id'},{ dataIndex: 'name', header: 'Name'}]; + }, + + buildColModel: function() { + return new Ext.grid.ColumnModel({defaults: { sortable: true }, columns: this.buildColumns() }); + }, + + buildViewConf: function() { + return new Ext.grid.GridView( {forceFit: true}); + }, + + buildTbar: function() { + return null; + }, + + buildBbar: function() { + return null; + } +}); + +/* GridPanel read only */ +/* It creates the base GridPanel w Paging toolbar attached */ + +/* + These are the new parameters add by the class: + + defaulPageSize : Number of records/page (default: 25) + defaultDesc : Default description of the records (default: 'Records') + configStore : Configuration object for the store creation + (Store can be provided directly by 'store' parameter as usual) + configPagingToolbar : Configuration object for the Paging Toolbar + +overload functions: + + buildStoreFields : function that returns the field parameter for the store Reader object (default: ['id','name']) + buildColumns : function thar returns the columns parameter for the ColumnModel object +*/ + + +Ext.ux.crudGridPanel.rPagingGrid = Ext.extend(Ext.ux.crudGridPanel.baseGrid, { + constructor: function(config){ + + this.baseParams = config.baseParams; + + if(config.defaultDesc) + this.defaultDesc = config.defaultDesc; + + if(config.defaulPageSize) + this.defaulPageSize = config.defaulPageSize; + + /* configuration of the Store */ + configStore = Ext.apply({ + defaultLimit: this.defaulPageSize, + baseParams : this.baseParams + }, config.configStore); + + this.store = config.store ? config.store : this.buildStore ( configStore ); + + /* configuration of the Pagin Toolbar */ + configPagingToolbar = Ext.apply({ + pageSize : this.defaulPageSize, + store : this.store, + displayInfo : true, + displayMsg : 'Mostrando '+this.defaultDesc+' {0} al {1} de {2}', + emptyMsg : 'No existen '+this.defaultDesc + }, config.configPagingToolbar); + + + /* Grid Configuration */ + config = Ext.apply({ + store : this.store, + bbar : this.buildBbar(configPagingToolbar) + }, config); + + Ext.ux.crudGridPanel.rPagingGrid.superclass.constructor.call(this,config); + + this.relayEvents(this.store, ['datachanged']); + }, + + buildBbar: function(configPagingToolbar){ + return new Ext.PagingToolbar(configPagingToolbar); + }, + buildStore: function(configStore){ + return new Ext.ux.crudGridPanel.rStore(configStore); + }, + + defaultDesc : "Records", + defaulPageSize : 25, + baseParams : {} + +}); + + +/* GridPanel update/create mode enabled */ + +/* + inherits rPagingGrid configuration parameters. These are added by the class: + + + configForm : Configuration object for the Form creation + configEditForm : Custom form, for update values + + invalidTitle : Title of the Error msgBox form data is invalid (defult: 'Error al inrgesar') + invalidMsg : Msg of the Error msgBox form data is invalid (defult: 'Los datos ingresados no son validos') + + addWindowTitle : Title of the Form Window when Adding an item (defult: 'Nuevo elemento') + addButtonText : Text of the Gridpanel Add button (defult: 'Agregar') + addIconCls : iconCls of the Add button and Add Form Window (default: TDGi.iconMgr 'add' ) + + editWindowTitle : Title of the Form Window when Adding an item (defult: 'Editar elemento') + editButtonText : Text of the Gridpanel Add button (defult: 'Editar') + editIconCls : iconCls of the Add button and Add Form Window (default: TDGi.iconMgr 'bullet_edit' ) + +*/ +Ext.ux.crudGridPanel.cruPagingGrid = Ext.extend(Ext.ux.crudGridPanel.rPagingGrid, { + constructor: function(config){ + this.addIconCls = config.addIconCls ? config.addIconCls : Ext.ux.TDGi.iconMgr.getIcon('add'); + this.editIconCls = config.editIconCls ? config.editIconCls : Ext.ux.TDGi.iconMgr.getIcon('bullet_edit'); + + if(config.addButtonText) + this.addButtonText = config.addButtonText; + if(config.editButtonText) + this.editButtonText = config.editButtonText; + + + /* Grid Configuration */ + config = Ext.apply({ + }, config); + + Ext.ux.crudGridPanel.cruPagingGrid.superclass.constructor.call(this,config); + + if(!config.listeners){ + this.addListener( this.setListeners() ); + } + + this.formAdd = this.buildFormAdd(config.configForm); + if(config.configEditForm) + this.formEdit = this.buildFormEdit(config.configEditForm); + else + this.formEdit = this.buildFormEdit(config.configForm); + + }, + buildFormAdd: function(config){ + configWindow = { + title : this.addWindowTitle, + iconCls : this.addIconCls, + listeners : { + scope : this, + savebtn : this.onCreate, + closebtn : this.onCloseCreate + }, + configForm: config + }; + + return new Ext.ux.crudGridPanel.baseWindowForm(configWindow); + }, + buildFormEdit: function(config){ + configWindow = { + title : this.editWindowTitle, + iconCls : this.editIconCls, + listeners : { + scope : this, + savebtn : this.onUpdate, + closebtn : this.onCloseEdit + }, + configForm: config + }; + + return new Ext.ux.crudGridPanel.baseWindowForm(configWindow); + }, + onCloseCreate: function(){ + this.formAdd.hide(); + }, + onCloseEdit: function(){ + this.formEdit.hide(); + }, + /* default top bar in the cru mode */ + buildTbar: function(){ + return [ { + text : this.addButtonText, + iconCls : this.addIconCls, + scope : this, + handler : this.onAdd + } , '->', { + text : this.editButtonText, + ref : '../editBtn', + iconCls : this.editIconCls, + disabled: true, + scope : this, + handler : this.onEdit + } ]; + }, + /* manually destroy the form window */ + onDestroy: function(){ + this.formAdd.destroy(); + this.formEdit.destroy(); + }, + cleanSaveListener: function(){ + }, + /* show a clean form to create a new record */ + onAdd: function(){ + /* Cleanup! */ + this.formAdd.getForm().reset(); + this.formAdd.show(); + }, + /* Take te form values and add the record to the storage (if valid)*/ + onCreate: function(){ + if (!this.formAdd.getForm().isValid()){ + Ext.Msg.show({ + title : this.invalidTitle, + msg : this.invalidMsg, + icon : Ext.MessageBox.ERROR, + buttons : Ext.Msg.OK + }); + return false; + } + else{ + var record = new this.store.recordType(this.formAdd.getForm().getValues()); + this.store.add(record); + this.store.reload(); + this.formAdd.hide(); + } + }, + /* Show the current record values in the form */ + onEdit: function(){ + /* verify that a valid record is selected */ + var record = this.selModel.getSelected(); + if (!record) { + return false; + } + this.formEdit.currentRecord = record; + this.formEdit.getForm().loadRecord(record); + this.formEdit.show(); + }, + /* Modify the record values to the ones in the form (if valid)*/ + onUpdate: function(){ + if (!this.formEdit.getForm().isValid()){ + Ext.Msg.show({ + title : this.invalidTitle, + msg : this.invalidMsg, + icon : Ext.MessageBox.ERROR, + buttons : Ext.Msg.OK + }); + return false; + } + else{ + /* update the record information */ + this.formEdit.getForm().updateRecord(this.formEdit.currentRecord); + this.formEdit.hide(); + } + }, + /* enable disable edit button */ + onRowSelect: function(SelectionModel){ + this.editBtn.setDisabled(false); + }, + onRowDeselect: function(SelectionModel){ + this.editBtn.setDisabled(true); + }, + /* overload of the storage creation method */ + buildStore: function(configStore){ + return new Ext.ux.crudGridPanel.cruStore(configStore); + }, + setListeners: function(){ + return { + scope : this, + rowselect : this.onRowSelect, + datachanged : this.onRowDeselect, + rowdeselect : this.onRowDeselect, + beforedestroy : this.onDestroy + }; + }, + /* Basic parameters of the object */ + invalidTitle : 'Error al inrgesar', + invalidMsg : 'Los datos ingresados no son validos', + addWindowTitle : 'Nuevo elemento', + editWindowTitle : 'Editar elemento', + addButtonText : 'Agregar', + editButtonText : 'Editar', + addIconCls : '', + editIconCls : '', + +}); + + +/* GridPanel update/create/delete mode enabled */ +/* + inherits cruPagingGrid configuration parameters. These are added by the class: + + + deleteTitle : Title of the Delete msgBox confirmation dialog (defult: 'Confirmación') + deleteMsg : Msg of the Delete msgBox confirmation dialog (defult: '¿Está seguro que desea eliminar el registro seleccionado?') + + deleteButtonText : Text of the Gridpanel Delete button (defult: 'Eliminar') + deleteIconCls : iconCls of the Delete button default: TDGi.iconMgr 'delete' ) + +*/ +Ext.ux.crudGridPanel.crudPagingGrid = Ext.extend(Ext.ux.crudGridPanel.cruPagingGrid, { + constructor: function(config){ + this.deleteIconCls = config.deleteIconCls ? config.deleteIconCls : Ext.ux.TDGi.iconMgr.getIcon('delete'); + + if(config.deleteButtonText) + this.deleteButtonText = config.deleteButtonText; + if(config.onDelete) + this.onDelete = config.onDelete; + + /* Grid Configuration */ + config = Ext.apply({ + + }, config); + + Ext.ux.crudGridPanel.crudPagingGrid.superclass.constructor.call(this,config); + }, + /* default top bar in the crud mode */ + buildTbar: function(){ + return [ { + text : this.addButtonText, + iconCls : this.addIconCls, + scope : this, + handler : this.onAdd + } , '->', { + text : this.editButtonText, + ref : '../editBtn', + iconCls : this.editIconCls, + disabled: true, + scope : this, + handler : this.onEdit + },{ + text : this.deleteButtonText, + ref : '../deleteBtn', + iconCls : this.deleteIconCls, + disabled: true, + scope : this, + handler : this.onDelete + } ]; + }, + onDelete: function(){ + Ext.MessageBox.confirm(this.deleteTitle, this.deleteMsg , this.doDelete, this); + }, + doDelete: function(Button){ + if(Button == 'yes'){ + this.store.remove(this.selModel.getSelected()); + + /* Call method to disable buttons (now no row is selected)*/ + this.onRowDeselect(this.selModel); + } + }, + + /* enable disable edit button */ + onRowSelect: function(SelectionModel){ + this.deleteBtn.setDisabled(false); + Ext.ux.crudGridPanel.crudPagingGrid.superclass.onRowSelect.call(this); + }, + onRowDeselect: function(SelectionModel){ + this.deleteBtn.setDisabled(true); + Ext.ux.crudGridPanel.crudPagingGrid.superclass.onRowDeselect.call(this); + }, + /* overload of the storage creation method */ + buildStore: function(configStore){ + return new Ext.ux.crudGridPanel.crudStore(configStore); + }, + /* Basic parameters of the object */ + deleteTitle : 'Confirmación', + deleteMsg : '¿Está seguro que desea eliminar el registro seleccionado?', + deleteButtonText: 'Eliminar', + deleteIconCls : '' + +}); + +/* GridPanel create mode enabled and special nullified w/o delete the record */ + +/* + + inherits rPagingGrid configuration parameters. These are added by the class: + + + configForm : Configuration object for the Form creation + + invalidTitle : Title of the Error msgBox form data is invalid (defult: 'Error al inrgesar') + invalidMsg : Msg of the Error msgBox form data is invalid (defult: 'Los datos ingresados no son validos') + + addWindowTitle : Title of the Form Window when Adding an item (defult: 'Nuevo elemento') + addButtonText : Text of the Gridpanel Add button (defult: 'Agregar') + addIconCls : iconCls of the Add button and Add Form Window (default: TDGi.iconMgr 'add' ) + + cancelButtonText : Text of the Gridpanel Cancel/Null button (defult: 'Anular') + cancelIconCls : iconCls of the Cancel button (default: TDGi.iconMgr 'error' ) + + cancelTitle : Title of the Cancel msgBox confirmation (defult: 'Confirmación') + cancelMsg : Msg of the Cancel msgBox confirmation (defult: '¿Está seguro que desea anular el registro seleccionado?') + + validFielName : Field of the record where the valid bool parameter is stored (default: 'valid') + canceledCls : Aditional CSS class for the invalid records (default: '') + +*/ +Ext.ux.crudGridPanel.crPagingGrid = Ext.extend(Ext.ux.crudGridPanel.rPagingGrid, { + constructor: function(config){ + this.addIconCls = config.addIconCls ? config.addIconCls : Ext.ux.TDGi.iconMgr.getIcon('add'); + this.cancelIconCls = config.editIconCls ? config.editIconCls : Ext.ux.TDGi.iconMgr.getIcon('error'); + + if(config.validFieldName) + this.validFieldName = config.validFieldName; + if(config.canceledCls) + this.canceledCls = config.canceledCls; + + if(config.addButtonText) + this.addButtonText = config.addButtonText; + if(config.cancelButtonText) + this.cancelButtonText = config.cancelButtonText; + /* Grid Configuration */ + config = Ext.apply({ + listeners : this.setListeners() + }, config); + + Ext.ux.crudGridPanel.crPagingGrid.superclass.constructor.call(this,config); + + this.form = this.buildForm(config.configForm); + + }, + buildForm: function(config){ + configWindow = { + title : this.addWindowTitle, + iconCls : this.addIconCls, + listeners : { + scope : this, + savebtn : this.onCreate, + previewbtn : this.onPreview, + closebtn : this.onClose + }, + configForm: config + }; + + return new Ext.ux.crudGridPanel.baseWindowForm(configWindow); + }, + /* default top bar in the cru mode */ + buildTbar: function(){ + return [ { + text : this.addButtonText, + iconCls : this.addIconCls, + scope : this, + handler : this.onAdd + } , '->', { + text : this.cancelButtonText, + ref : '../cancelBtn', + iconCls : this.cancelIconCls, + disabled: true, + scope : this, + handler : this.onCancel + } ]; + }, + /* manually destroy the form window */ + onDestroy: function(){ + this.form.destroy(); + }, + onPreview: Ext.emptyFn, + /* show a clean form to create a new record */ + onAdd: function(){ + /* Cleanup! */ + this.form.show(); + this.form.getForm().reset(); + }, + /* Take te form values and add the record to the storage (if valid)*/ + onCreate: function(){ + if (!this.form.getForm().isValid()){ + Ext.Msg.show({ + title : this.invalidTitle, + msg : this.invalidMsg, + icon : Ext.MessageBox.ERROR, + buttons : Ext.Msg.OK + }); + return false; + } + else{ + /* force each new creation to be valid */ + var record = new this.store.recordType(this.form.getForm().getValues()); + record.set(this.validFieldName,"on"); + this.store.add(record); + this.store.reload(); + this.form.hide(); + } + }, + onCancel: function(){ + Ext.MessageBox.confirm(this.cancelTitle, this.cancelMsg , this.doCancel, this); + }, + doCancel: function(Button){ + if(Button == 'yes'){ + var record = this.selModel.getSelected(); + if(!record) + return false; + + record.set(this.validFieldName,false); + record.commit(); + + /* Call method to disable buttons */ + this.onRowDeselect(); + } + }, + /* customize the viewConf to give the canceled records a special class */ + buildViewConf: function() { + + return new Ext.grid.GridView({ + forceFit : true, + validFieldName : this.validFieldName, + canceledCls : this.canceledCls, + getRowClass : this.getRowClass + }); + + }, + getRowClass: function(Record){ + if(!Record.get(this.validFieldName)) + return this.canceledCls; + }, + /* back button pressed, changes dissmised*/ + onClose: function(){ + this.form.hide(); + }, + /* enable/disable buttons */ + onRowSelect: function(SelectionModel){ + var record = this.selModel.getSelected(); + if(!record){ + this.cancelBtn.setDisabled(true); + return false; + } + + if(!record.get(this.validFieldName)) + this.cancelBtn.setDisabled(true); + else + this.cancelBtn.setDisabled(false); + + }, + onRowDeselect: function(SelectionModel){ + this.cancelBtn.setDisabled(true); + }, + /* overload of the storage creation method */ + buildStore: function(configStore){ + return new Ext.ux.crudGridPanel.cruStore(configStore); + }, + setListeners: function(){ + return { + scope : this, + datachanged : this.onRowDeselect, + rowselect : this.onRowSelect, + rowdeselect : this.onRowDeselect, + beforedestroy : this.onDestroy + }; + }, + /* Basic parameters of the object */ + invalidTitle : 'Error al inrgesar', + invalidMsg : 'Los datos ingresados no son validos', + addWindowTitle : 'Nuevo elemento', + addButtonText : 'Agregar', + cancelButtonText: 'Anular', + + cancelTitle : 'Confirmación', + cancelMsg : '¿Está seguro que desea anular el registro seleccionado?', + + addIconCls : '', + cancelIconCls : '', + validFielName : 'valid', + canceledCls : '' + +}); diff --git a/BAM/js/rpc.php b/BAM/js/rpc.php new file mode 100644 index 0000000..b8f9628 --- /dev/null +++ b/BAM/js/rpc.php @@ -0,0 +1,49 @@ +. + * +*/ + +$conf = simplexml_load_file("../lib/Dazzler.conf"); +require ('../lib/class/Response.inc.php'); +$IconsURL = $conf->conf->iconMgr_base_url; +session_start(); +session_name($conf->conf->session_name); + +ob_start(); + +require("../lib/RegistraVisita.inc.php"); +$Respuesta = new Response($HTTP_RAW_POST_DATA,$_POST, $_FILES); + +if($IdentificadorUsuario == 0){//Usuario no autentificado, acceso solo a rutinas de logeo + $Respuesta->guestRequests(); + } +else{ + $Respuesta->userRequest(); + } +$warnings = ob_get_clean(); +if(!empty($warnings)){ + $event = array('type'=>'exception','where'=>'dummy','message'=>$warnings); + $Respuesta->addResponse($event); + } +if(!empty($LogedOn)){ + $event = array('type'=>'event','name'=>'lpc','data'=>'machine'); + $Respuesta->addResponse($event); + } + +$Respuesta->echoResponse(); +?> diff --git a/BAM/lib/.htaccess b/BAM/lib/.htaccess new file mode 100644 index 0000000..b8927cb --- /dev/null +++ b/BAM/lib/.htaccess @@ -0,0 +1,2 @@ +# no one gets in here! +deny from all diff --git a/BAM/lib/Dazzler.conf.sample b/BAM/lib/Dazzler.conf.sample new file mode 100644 index 0000000..d30acc7 --- /dev/null +++ b/BAM/lib/Dazzler.conf.sample @@ -0,0 +1,56 @@ + + + + + dbuser + dbpass + dbhost + dbname + pg + + + + + 1001 + 1 + /BAM/pics/nologo.png + Dazzler_sample + /BAM/ext/ext-3.3.0 + /BAM/ext/ext-3.3.0/examples/ux + /BAM/ext/iconMgr + /BAM/ext/fam_icons + + + + + Dazzler Long Name + http://BAM_URL/BAM/ + 8 + 1 + 28800 + + + 600 + + + + + 60 + 8 + 0 + 50 + 90 + 10 + 10 + 0,1 + 0 + 0 + 0 + 0 + 75 + 0 + 0 + 0 + 60 + + diff --git a/BAM/lib/GeoIp/GeoIP.dat b/BAM/lib/GeoIp/GeoIP.dat new file mode 100644 index 0000000..046e8c0 Binary files /dev/null and b/BAM/lib/GeoIp/GeoIP.dat differ diff --git a/BAM/lib/GeoIp/geoip.inc.php b/BAM/lib/GeoIp/geoip.inc.php new file mode 100644 index 0000000..0b68095 --- /dev/null +++ b/BAM/lib/GeoIp/geoip.inc.php @@ -0,0 +1,497 @@ + 0, "AP" => 1, "EU" => 2, "AD" => 3, "AE" => 4, "AF" => 5, +"AG" => 6, "AI" => 7, "AL" => 8, "AM" => 9, "AN" => 10, "AO" => 11, +"AQ" => 12, "AR" => 13, "AS" => 14, "AT" => 15, "AU" => 16, "AW" => 17, +"AZ" => 18, "BA" => 19, "BB" => 20, "BD" => 21, "BE" => 22, "BF" => 23, +"BG" => 24, "BH" => 25, "BI" => 26, "BJ" => 27, "BM" => 28, "BN" => 29, +"BO" => 30, "BR" => 31, "BS" => 32, "BT" => 33, "BV" => 34, "BW" => 35, +"BY" => 36, "BZ" => 37, "CA" => 38, "CC" => 39, "CD" => 40, "CF" => 41, +"CG" => 42, "CH" => 43, "CI" => 44, "CK" => 45, "CL" => 46, "CM" => 47, +"CN" => 48, "CO" => 49, "CR" => 50, "CU" => 51, "CV" => 52, "CX" => 53, +"CY" => 54, "CZ" => 55, "DE" => 56, "DJ" => 57, "DK" => 58, "DM" => 59, +"DO" => 60, "DZ" => 61, "EC" => 62, "EE" => 63, "EG" => 64, "EH" => 65, +"ER" => 66, "ES" => 67, "ET" => 68, "FI" => 69, "FJ" => 70, "FK" => 71, +"FM" => 72, "FO" => 73, "FR" => 74, "FX" => 75, "GA" => 76, "GB" => 77, +"GD" => 78, "GE" => 79, "GF" => 80, "GH" => 81, "GI" => 82, "GL" => 83, +"GM" => 84, "GN" => 85, "GP" => 86, "GQ" => 87, "GR" => 88, "GS" => 89, +"GT" => 90, "GU" => 91, "GW" => 92, "GY" => 93, "HK" => 94, "HM" => 95, +"HN" => 96, "HR" => 97, "HT" => 98, "HU" => 99, "ID" => 100, "IE" => 101, +"IL" => 102, "IN" => 103, "IO" => 104, "IQ" => 105, "IR" => 106, "IS" => 107, +"IT" => 108, "JM" => 109, "JO" => 110, "JP" => 111, "KE" => 112, "KG" => 113, +"KH" => 114, "KI" => 115, "KM" => 116, "KN" => 117, "KP" => 118, "KR" => 119, +"KW" => 120, "KY" => 121, "KZ" => 122, "LA" => 123, "LB" => 124, "LC" => 125, +"LI" => 126, "LK" => 127, "LR" => 128, "LS" => 129, "LT" => 130, "LU" => 131, +"LV" => 132, "LY" => 133, "MA" => 134, "MC" => 135, "MD" => 136, "MG" => 137, +"MH" => 138, "MK" => 139, "ML" => 140, "MM" => 141, "MN" => 142, "MO" => 143, +"MP" => 144, "MQ" => 145, "MR" => 146, "MS" => 147, "MT" => 148, "MU" => 149, +"MV" => 150, "MW" => 151, "MX" => 152, "MY" => 153, "MZ" => 154, "NA" => 155, +"NC" => 156, "NE" => 157, "NF" => 158, "NG" => 159, "NI" => 160, "NL" => 161, +"NO" => 162, "NP" => 163, "NR" => 164, "NU" => 165, "NZ" => 166, "OM" => 167, +"PA" => 168, "PE" => 169, "PF" => 170, "PG" => 171, "PH" => 172, "PK" => 173, +"PL" => 174, "PM" => 175, "PN" => 176, "PR" => 177, "PS" => 178, "PT" => 179, +"PW" => 180, "PY" => 181, "QA" => 182, "RE" => 183, "RO" => 184, "RU" => 185, +"RW" => 186, "SA" => 187, "SB" => 188, "SC" => 189, "SD" => 190, "SE" => 191, +"SG" => 192, "SH" => 193, "SI" => 194, "SJ" => 195, "SK" => 196, "SL" => 197, +"SM" => 198, "SN" => 199, "SO" => 200, "SR" => 201, "ST" => 202, "SV" => 203, +"SY" => 204, "SZ" => 205, "TC" => 206, "TD" => 207, "TF" => 208, "TG" => 209, +"TH" => 210, "TJ" => 211, "TK" => 212, "TM" => 213, "TN" => 214, "TO" => 215, +"TL" => 216, "TR" => 217, "TT" => 218, "TV" => 219, "TW" => 220, "TZ" => 221, +"UA" => 222, "UG" => 223, "UM" => 224, "US" => 225, "UY" => 226, "UZ" => 227, +"VA" => 228, "VC" => 229, "VE" => 230, "VG" => 231, "VI" => 232, "VN" => 233, +"VU" => 234, "WF" => 235, "WS" => 236, "YE" => 237, "YT" => 238, "RS" => 239, +"ZA" => 240, "ZM" => 241, "ME" => 242, "ZW" => 243, "A1" => 244, "A2" => 245, +"O1" => 246, "AX" => 247, "GG" => 248, "IM" => 249, "JE" => 250 +); + var $GEOIP_COUNTRY_CODES = array( +"", "AP", "EU", "AD", "AE", "AF", "AG", "AI", "AL", "AM", "AN", "AO", "AQ", +"AR", "AS", "AT", "AU", "AW", "AZ", "BA", "BB", "BD", "BE", "BF", "BG", "BH", +"BI", "BJ", "BM", "BN", "BO", "BR", "BS", "BT", "BV", "BW", "BY", "BZ", "CA", +"CC", "CD", "CF", "CG", "CH", "CI", "CK", "CL", "CM", "CN", "CO", "CR", "CU", +"CV", "CX", "CY", "CZ", "DE", "DJ", "DK", "DM", "DO", "DZ", "EC", "EE", "EG", +"EH", "ER", "ES", "ET", "FI", "FJ", "FK", "FM", "FO", "FR", "FX", "GA", "GB", +"GD", "GE", "GF", "GH", "GI", "GL", "GM", "GN", "GP", "GQ", "GR", "GS", "GT", +"GU", "GW", "GY", "HK", "HM", "HN", "HR", "HT", "HU", "ID", "IE", "IL", "IN", +"IO", "IQ", "IR", "IS", "IT", "JM", "JO", "JP", "KE", "KG", "KH", "KI", "KM", +"KN", "KP", "KR", "KW", "KY", "KZ", "LA", "LB", "LC", "LI", "LK", "LR", "LS", +"LT", "LU", "LV", "LY", "MA", "MC", "MD", "MG", "MH", "MK", "ML", "MM", "MN", +"MO", "MP", "MQ", "MR", "MS", "MT", "MU", "MV", "MW", "MX", "MY", "MZ", "NA", +"NC", "NE", "NF", "NG", "NI", "NL", "NO", "NP", "NR", "NU", "NZ", "OM", "PA", +"PE", "PF", "PG", "PH", "PK", "PL", "PM", "PN", "PR", "PS", "PT", "PW", "PY", +"QA", "RE", "RO", "RU", "RW", "SA", "SB", "SC", "SD", "SE", "SG", "SH", "SI", +"SJ", "SK", "SL", "SM", "SN", "SO", "SR", "ST", "SV", "SY", "SZ", "TC", "TD", +"TF", "TG", "TH", "TJ", "TK", "TM", "TN", "TO", "TL", "TR", "TT", "TV", "TW", +"TZ", "UA", "UG", "UM", "US", "UY", "UZ", "VA", "VC", "VE", "VG", "VI", "VN", +"VU", "WF", "WS", "YE", "YT", "RS", "ZA", "ZM", "ME", "ZW", "A1", "A2", "O1", +"AX", "GG", "IM", "JE" +); + var $GEOIP_COUNTRY_CODES3 = array( +"","AP","EU","AND","ARE","AFG","ATG","AIA","ALB","ARM","ANT","AGO","AQ","ARG", +"ASM","AUT","AUS","ABW","AZE","BIH","BRB","BGD","BEL","BFA","BGR","BHR","BDI", +"BEN","BMU","BRN","BOL","BRA","BHS","BTN","BV","BWA","BLR","BLZ","CAN","CC", +"COD","CAF","COG","CHE","CIV","COK","CHL","CMR","CHN","COL","CRI","CUB","CPV", +"CX","CYP","CZE","DEU","DJI","DNK","DMA","DOM","DZA","ECU","EST","EGY","ESH", +"ERI","ESP","ETH","FIN","FJI","FLK","FSM","FRO","FRA","FX","GAB","GBR","GRD", +"GEO","GUF","GHA","GIB","GRL","GMB","GIN","GLP","GNQ","GRC","GS","GTM","GUM", +"GNB","GUY","HKG","HM","HND","HRV","HTI","HUN","IDN","IRL","ISR","IND","IO", +"IRQ","IRN","ISL","ITA","JAM","JOR","JPN","KEN","KGZ","KHM","KIR","COM","KNA", +"PRK","KOR","KWT","CYM","KAZ","LAO","LBN","LCA","LIE","LKA","LBR","LSO","LTU", +"LUX","LVA","LBY","MAR","MCO","MDA","MDG","MHL","MKD","MLI","MMR","MNG","MAC", +"MNP","MTQ","MRT","MSR","MLT","MUS","MDV","MWI","MEX","MYS","MOZ","NAM","NCL", +"NER","NFK","NGA","NIC","NLD","NOR","NPL","NRU","NIU","NZL","OMN","PAN","PER", +"PYF","PNG","PHL","PAK","POL","SPM","PCN","PRI","PSE","PRT","PLW","PRY","QAT", +"REU","ROU","RUS","RWA","SAU","SLB","SYC","SDN","SWE","SGP","SHN","SVN","SJM", +"SVK","SLE","SMR","SEN","SOM","SUR","STP","SLV","SYR","SWZ","TCA","TCD","TF", +"TGO","THA","TJK","TKL","TLS","TKM","TUN","TON","TUR","TTO","TUV","TWN","TZA", +"UKR","UGA","UM","USA","URY","UZB","VAT","VCT","VEN","VGB","VIR","VNM","VUT", +"WLF","WSM","YEM","YT","SRB","ZAF","ZMB","MNE","ZWE","A1","A2","O1", +"ALA","GGY","IMN","JEY" + ); + var $GEOIP_COUNTRY_NAMES = array( +"", "Asia/Pacific Region", "Europe", "Andorra", "United Arab Emirates", +"Afghanistan", "Antigua and Barbuda", "Anguilla", "Albania", "Armenia", +"Netherlands Antilles", "Angola", "Antarctica", "Argentina", "American Samoa", +"Austria", "Australia", "Aruba", "Azerbaijan", "Bosnia and Herzegovina", +"Barbados", "Bangladesh", "Belgium", "Burkina Faso", "Bulgaria", "Bahrain", +"Burundi", "Benin", "Bermuda", "Brunei Darussalam", "Bolivia", "Brazil", +"Bahamas", "Bhutan", "Bouvet Island", "Botswana", "Belarus", "Belize", +"Canada", "Cocos (Keeling) Islands", "Congo, The Democratic Republic of the", +"Central African Republic", "Congo", "Switzerland", "Cote D'Ivoire", "Cook +Islands", "Chile", "Cameroon", "China", "Colombia", "Costa Rica", "Cuba", "Cape +Verde", "Christmas Island", "Cyprus", "Czech Republic", "Germany", "Djibouti", +"Denmark", "Dominica", "Dominican Republic", "Algeria", "Ecuador", "Estonia", +"Egypt", "Western Sahara", "Eritrea", "Spain", "Ethiopia", "Finland", "Fiji", +"Falkland Islands (Malvinas)", "Micronesia, Federated States of", "Faroe +Islands", "France", "France, Metropolitan", "Gabon", "United Kingdom", +"Grenada", "Georgia", "French Guiana", "Ghana", "Gibraltar", "Greenland", +"Gambia", "Guinea", "Guadeloupe", "Equatorial Guinea", "Greece", "South Georgia +and the South Sandwich Islands", "Guatemala", "Guam", "Guinea-Bissau", +"Guyana", "Hong Kong", "Heard Island and McDonald Islands", "Honduras", +"Croatia", "Haiti", "Hungary", "Indonesia", "Ireland", "Israel", "India", +"British Indian Ocean Territory", "Iraq", "Iran, Islamic Republic of", +"Iceland", "Italy", "Jamaica", "Jordan", "Japan", "Kenya", "Kyrgyzstan", +"Cambodia", "Kiribati", "Comoros", "Saint Kitts and Nevis", "Korea, Democratic +People's Republic of", "Korea, Republic of", "Kuwait", "Cayman Islands", +"Kazakstan", "Lao People's Democratic Republic", "Lebanon", "Saint Lucia", +"Liechtenstein", "Sri Lanka", "Liberia", "Lesotho", "Lithuania", "Luxembourg", +"Latvia", "Libyan Arab Jamahiriya", "Morocco", "Monaco", "Moldova, Republic +of", "Madagascar", "Marshall Islands", "Macedonia", +"Mali", "Myanmar", "Mongolia", "Macau", "Northern Mariana Islands", +"Martinique", "Mauritania", "Montserrat", "Malta", "Mauritius", "Maldives", +"Malawi", "Mexico", "Malaysia", "Mozambique", "Namibia", "New Caledonia", +"Niger", "Norfolk Island", "Nigeria", "Nicaragua", "Netherlands", "Norway", +"Nepal", "Nauru", "Niue", "New Zealand", "Oman", "Panama", "Peru", "French +Polynesia", "Papua New Guinea", "Philippines", "Pakistan", "Poland", "Saint +Pierre and Miquelon", "Pitcairn Islands", "Puerto Rico", "Palestinian Territory", +"Portugal", "Palau", "Paraguay", "Qatar", "Reunion", "Romania", +"Russian Federation", "Rwanda", "Saudi Arabia", "Solomon Islands", +"Seychelles", "Sudan", "Sweden", "Singapore", "Saint Helena", "Slovenia", +"Svalbard and Jan Mayen", "Slovakia", "Sierra Leone", "San Marino", "Senegal", +"Somalia", "Suriname", "Sao Tome and Principe", "El Salvador", "Syrian Arab +Republic", "Swaziland", "Turks and Caicos Islands", "Chad", "French Southern +Territories", "Togo", "Thailand", "Tajikistan", "Tokelau", "Turkmenistan", +"Tunisia", "Tonga", "Timor-Leste", "Turkey", "Trinidad and Tobago", "Tuvalu", +"Taiwan", "Tanzania, United Republic of", "Ukraine", +"Uganda", "United States Minor Outlying Islands", "United States", "Uruguay", +"Uzbekistan", "Holy See (Vatican City State)", "Saint Vincent and the +Grenadines", "Venezuela", "Virgin Islands, British", "Virgin Islands, U.S.", +"Vietnam", "Vanuatu", "Wallis and Futuna", "Samoa", "Yemen", "Mayotte", +"Serbia", "South Africa", "Zambia", "Montenegro", "Zimbabwe", +"Anonymous Proxy","Satellite Provider","Other", +"Aland Islands","Guernsey","Isle of Man","Jersey" +); +} +function geoip_load_shared_mem ($file) { + + $fp = fopen($file, "rb"); + if (!$fp) { + print "error opening $file: $php_errormsg\n"; + exit; + } + $s_array = fstat($fp); + $size = $s_array['size']; + if ($shmid = @shmop_open (GEOIP_SHM_KEY, "w", 0, 0)) { + shmop_delete ($shmid); + shmop_close ($shmid); + } + $shmid = shmop_open (GEOIP_SHM_KEY, "c", 0644, $size); + shmop_write ($shmid, fread($fp, $size), 0); + shmop_close ($shmid); +} + +function _setup_segments($gi){ + $gi->databaseType = GEOIP_COUNTRY_EDITION; + $gi->record_length = STANDARD_RECORD_LENGTH; + if ($gi->flags & GEOIP_SHARED_MEMORY) { + $offset = @shmop_size ($gi->shmid) - 3; + for ($i = 0; $i < STRUCTURE_INFO_MAX_SIZE; $i++) { + $delim = @shmop_read ($gi->shmid, $offset, 3); + $offset += 3; + if ($delim == (chr(255).chr(255).chr(255))) { + $gi->databaseType = ord(@shmop_read ($gi->shmid, $offset, 1)); + $offset++; + + if ($gi->databaseType == GEOIP_REGION_EDITION_REV0){ + $gi->databaseSegments = GEOIP_STATE_BEGIN_REV0; + } else if ($gi->databaseType == GEOIP_REGION_EDITION_REV1){ + $gi->databaseSegments = GEOIP_STATE_BEGIN_REV1; + } else if (($gi->databaseType == GEOIP_CITY_EDITION_REV0)|| + ($gi->databaseType == GEOIP_CITY_EDITION_REV1) + || ($gi->databaseType == GEOIP_ORG_EDITION) + || ($gi->databaseType == GEOIP_ISP_EDITION) + || ($gi->databaseType == GEOIP_ASNUM_EDITION)){ + $gi->databaseSegments = 0; + $buf = @shmop_read ($gi->shmid, $offset, SEGMENT_RECORD_LENGTH); + for ($j = 0;$j < SEGMENT_RECORD_LENGTH;$j++){ + $gi->databaseSegments += (ord($buf[$j]) << ($j * 8)); + } + if (($gi->databaseType == GEOIP_ORG_EDITION)|| + ($gi->databaseType == GEOIP_ISP_EDITION)) { + $gi->record_length = ORG_RECORD_LENGTH; + } + } + break; + } else { + $offset -= 4; + } + } + if (($gi->databaseType == GEOIP_COUNTRY_EDITION)|| + ($gi->databaseType == GEOIP_PROXY_EDITION)|| + ($gi->databaseType == GEOIP_NETSPEED_EDITION)){ + $gi->databaseSegments = GEOIP_COUNTRY_BEGIN; + } + } else { + $filepos = ftell($gi->filehandle); + fseek($gi->filehandle, -3, SEEK_END); + for ($i = 0; $i < STRUCTURE_INFO_MAX_SIZE; $i++) { + $delim = fread($gi->filehandle,3); + if ($delim == (chr(255).chr(255).chr(255))){ + $gi->databaseType = ord(fread($gi->filehandle,1)); + if ($gi->databaseType == GEOIP_REGION_EDITION_REV0){ + $gi->databaseSegments = GEOIP_STATE_BEGIN_REV0; + } + else if ($gi->databaseType == GEOIP_REGION_EDITION_REV1){ + $gi->databaseSegments = GEOIP_STATE_BEGIN_REV1; + } else if (($gi->databaseType == GEOIP_CITY_EDITION_REV0) || + ($gi->databaseType == GEOIP_CITY_EDITION_REV1) || + ($gi->databaseType == GEOIP_ORG_EDITION) || + ($gi->databaseType == GEOIP_ISP_EDITION) || + ($gi->databaseType == GEOIP_ASNUM_EDITION)){ + $gi->databaseSegments = 0; + $buf = fread($gi->filehandle,SEGMENT_RECORD_LENGTH); + for ($j = 0;$j < SEGMENT_RECORD_LENGTH;$j++){ + $gi->databaseSegments += (ord($buf[$j]) << ($j * 8)); + } + if ($gi->databaseType == GEOIP_ORG_EDITION) { + $gi->record_length = ORG_RECORD_LENGTH; + } + } + break; + } else { + fseek($gi->filehandle, -4, SEEK_CUR); + } + } + if (($gi->databaseType == GEOIP_COUNTRY_EDITION)|| + ($gi->databaseType == GEOIP_PROXY_EDITION)|| + ($gi->databaseType == GEOIP_NETSPEED_EDITION)){ + $gi->databaseSegments = GEOIP_COUNTRY_BEGIN; + } + fseek($gi->filehandle,$filepos,SEEK_SET); + } + return $gi; +} + +function geoip_open($filename, $flags) { + $gi = new GeoIP; + $gi->flags = $flags; + if ($gi->flags & GEOIP_SHARED_MEMORY) { + $gi->shmid = @shmop_open (GEOIP_SHM_KEY, "a", 0, 0); + } else { + $gi->filehandle = fopen($filename,"rb"); + if ($gi->flags & GEOIP_MEMORY_CACHE) { + $s_array = fstat($gi->filehandle); + $gi->memory_buffer = fread($gi->filehandle, $s_array[size]); + } + } + + $gi = _setup_segments($gi); + return $gi; +} + +function geoip_close($gi) { + if ($gi->flags & GEOIP_SHARED_MEMORY) { + return true; + } + + return fclose($gi->filehandle); +} + +function geoip_country_id_by_name($gi, $name) { + $addr = gethostbyname($name); + if (!$addr || $addr == $name) { + return false; + } + return geoip_country_id_by_addr($gi, $addr); +} + +function geoip_country_code_by_name($gi, $name) { + $country_id = geoip_country_id_by_name($gi,$name); + if ($country_id !== false) { + return $gi->GEOIP_COUNTRY_CODES[$country_id]; + } + return false; +} + +function geoip_country_name_by_name($gi, $name) { + $country_id = geoip_country_id_by_name($gi,$name); + if ($country_id !== false) { + return $gi->GEOIP_COUNTRY_NAMES[$country_id]; + } + return false; +} + +function geoip_country_id_by_addr($gi, $addr) { + $ipnum = ip2long($addr); + return _geoip_seek_country($gi, $ipnum) - GEOIP_COUNTRY_BEGIN; +} + +function geoip_country_code_by_addr($gi, $addr) { + if ($gi->databaseType == GEOIP_CITY_EDITION_REV1) { + $record = geoip_record_by_addr($gi,$addr); + return $record->country_code; + } else { + $country_id = geoip_country_id_by_addr($gi,$addr); + if ($country_id !== false) { + return $gi->GEOIP_COUNTRY_CODES[$country_id]; + } + } + return false; +} + +function geoip_country_name_by_addr($gi, $addr) { + if ($gi->databaseType == GEOIP_CITY_EDITION_REV1) { + $record = geoip_record_by_addr($gi,$addr); + return $record->country_name; + } else { + $country_id = geoip_country_id_by_addr($gi,$addr); + if ($country_id !== false) { + return $gi->GEOIP_COUNTRY_NAMES[$country_id]; + } + } + return false; +} + +function _geoip_seek_country($gi, $ipnum) { + $offset = 0; + for ($depth = 31; $depth >= 0; --$depth) { + if ($gi->flags & GEOIP_MEMORY_CACHE) { + $buf = substr($gi->memory_buffer, + 2 * $gi->record_length * $offset, + 2 * $gi->record_length); + } elseif ($gi->flags & GEOIP_SHARED_MEMORY) { + $buf = @shmop_read ($gi->shmid, + 2 * $gi->record_length * $offset, + 2 * $gi->record_length ); + } else { + fseek($gi->filehandle, 2 * $gi->record_length * $offset, SEEK_SET) == 0 + or die("fseek failed"); + $buf = fread($gi->filehandle, 2 * $gi->record_length); + } + $x = array(0,0); + for ($i = 0; $i < 2; ++$i) { + for ($j = 0; $j < $gi->record_length; ++$j) { + $x[$i] += ord($buf[$gi->record_length * $i + $j]) << ($j * 8); + } + } + if ($ipnum & (1 << $depth)) { + if ($x[1] >= $gi->databaseSegments) { + return $x[1]; + } + $offset = $x[1]; + } else { + if ($x[0] >= $gi->databaseSegments) { + return $x[0]; + } + $offset = $x[0]; + } + } + trigger_error("error traversing database - perhaps it is corrupt?", E_USER_ERROR); + return false; +} + +function _get_org($gi,$ipnum){ + $seek_org = _geoip_seek_country($gi,$ipnum); + if ($seek_org == $gi->databaseSegments) { + return NULL; + } + $record_pointer = $seek_org + (2 * $gi->record_length - 1) * $gi->databaseSegments; + if ($gi->flags & GEOIP_SHARED_MEMORY) { + $org_buf = @shmop_read ($gi->shmid, $record_pointer, MAX_ORG_RECORD_LENGTH); + } else { + fseek($gi->filehandle, $record_pointer, SEEK_SET); + $org_buf = fread($gi->filehandle,MAX_ORG_RECORD_LENGTH); + } + $org_buf = substr($org_buf, 0, strpos($org_buf, 0)); + return $org_buf; +} + +function geoip_org_by_addr ($gi,$addr) { + if ($addr == NULL) { + return 0; + } + $ipnum = ip2long($addr); + return _get_org($gi, $ipnum); +} + +function _get_region($gi,$ipnum){ + if ($gi->databaseType == GEOIP_REGION_EDITION_REV0){ + $seek_region = _geoip_seek_country($gi,$ipnum) - GEOIP_STATE_BEGIN_REV0; + if ($seek_region >= 1000){ + $country_code = "US"; + $region = chr(($seek_region - 1000)/26 + 65) . chr(($seek_region - 1000)%26 + 65); + } else { + $country_code = $gi->GEOIP_COUNTRY_CODES[$seek_region]; + $region = ""; + } + return array ($country_code,$region); + } else if ($gi->databaseType == GEOIP_REGION_EDITION_REV1) { + $seek_region = _geoip_seek_country($gi,$ipnum) - GEOIP_STATE_BEGIN_REV1; + //print $seek_region; + if ($seek_region < US_OFFSET){ + $country_code = ""; + $region = ""; + } else if ($seek_region < CANADA_OFFSET) { + $country_code = "US"; + $region = chr(($seek_region - US_OFFSET)/26 + 65) . chr(($seek_region - US_OFFSET)%26 + 65); + } else if ($seek_region < WORLD_OFFSET) { + $country_code = "CA"; + $region = chr(($seek_region - CANADA_OFFSET)/26 + 65) . chr(($seek_region - CANADA_OFFSET)%26 + 65); + } else { + $country_code = $gi->GEOIP_COUNTRY_CODES[($seek_region - WORLD_OFFSET) / FIPS_RANGE]; + $region = ""; + } + return array ($country_code,$region); + } +} + +function geoip_region_by_addr ($gi,$addr) { + if ($addr == NULL) { + return 0; + } + $ipnum = ip2long($addr); + return _get_region($gi, $ipnum); +} + +function getdnsattributes ($l,$ip){ + $r = new Net_DNS_Resolver(); + $r->nameservers = array("ws1.maxmind.com"); + $p = $r->search($l."." . $ip .".s.maxmind.com","TXT","IN"); + $str = is_object($p->answer[0])?$p->answer[0]->string():''; + ereg("\"(.*)\"",$str,$regs); + $str = $regs[1]; + return $str; +} + +?> diff --git a/BAM/lib/RegistraVisita.inc.php b/BAM/lib/RegistraVisita.inc.php new file mode 100644 index 0000000..e068898 --- /dev/null +++ b/BAM/lib/RegistraVisita.inc.php @@ -0,0 +1,42 @@ +. + * +*/ + +$IdentificadorUsuario = 0; +if(isset($_SESSION['SesionId'])){ + + require_once $_SERVER['DOCUMENT_ROOT'].'/BAM/lib/class/Db.inc.php'; + $DB = new Db($conf->db->name, $conf->db->host, $conf->db->user, $conf->db->password, 'pg'); + $n = $DB->Consulta("select id from usuarios where sesion = {$_SESSION['SesionId']}"); + if($n){ + list ($IdentificadorUsuario) = $DB->Sacatupla(); + $now = time(); + $DB->Consulta("update sesiones set fin=$now where id = {$_SESSION['SesionId']}"); + } + else{ + $n = $DB->Consulta("select estado from sesiones where id = {$_SESSION['SesionId']}"); + if($n){ + list ($estado) = $DB->Sacatupla(); + if($estado == 3) + $LogedOn = true; + } + } + unset( $DB ); + } +?> diff --git a/BAM/lib/class/Db.inc.php b/BAM/lib/class/Db.inc.php new file mode 100644 index 0000000..a77cc56 --- /dev/null +++ b/BAM/lib/class/Db.inc.php @@ -0,0 +1,204 @@ +. + * +*/ + +//version 1.2.2 +$NumeroDeConsultas = 0; +$NumeroDeConexiones = 0; + +class DB { + protected $TipoBaseDatos; + protected $Identificador; + + public $ResultadoConsulta; + public $UltimoId; + public $NumeroResultados; + + public $Estado; + public $MostrarConsultas; + public $Error; + public $Error_debug; + + function __construct($BaseDatos="MySQL",$Servidor="localhost",$Usuario="root",$Contrasena="",$Tipo = "MySQL"){ + global $NumeroDeConexiones; + $this->Error = ""; + $this->Error_debug = ""; + $this->Estado = 1; + $this->TipoBaseDatos = ""; + $this->ResultadoConsulta = 0; + $this->NumeroResultados = 0; + $this->UltimoId = 0; + $this->MostrarConsultas = 0; + + if($Tipo == "MySQL" || (strcasecmp($Tipo, "my") == 0)){ + $this->TipoBaseDatos = "MySQL"; + $this->Identificador = @mysql_connect($Servidor,$Usuario,$Contrasena,1); + if ($this->Identificador == 0){ + $this->Error = "Error al Conectar $Tipo ($Usuario@$Servidor => $BaseDatos)
"; + $this->Error_debug = "Error al Conectar $Tipo ($Usuario:$Contrasena@$Servidor => $BaseDatos)
"; + $this->Estado = 0; + } + else{ + $bit = @mysql_select_db($BaseDatos,$this->Identificador); + $NumeroDeConexiones++; + if ($bit == 0){ + $this->Error = "Error al Seleccionar Base de Datos $Tipo ($Usuario@$Servidor => $BaseDatos)
"; + $this->Error_debug = "Error al Seleccionar Base de Datos $Tipo ($Usuario:$Contrasena@$Servidor => $BaseDatos)
"; + $this->Estado = 0; + } + else{ + mysql_query("SET NAMES 'utf8';",$this->Identificador); + } + } + } + elseif($Tipo == "PosgreSQL" || strcasecmp($Tipo, "pg") == 0){ + $this->TipoBaseDatos = "PosgreSQL"; + $conectar = "dbname=$BaseDatos host=$Servidor user=$Usuario password=$Contrasena"; + $this->Identificador = @pg_connect($conectar,PGSQL_CONNECT_FORCE_NEW); + if ($this->Identificador == FALSE){ + $this->Error = "Error al Conectar $Tipo ($Usuario@$Servidor => $BaseDatos)
"; + $this->Error_debug = "Error al Conectar $Tipo ($Usuario:$Contrasena@$Servidor => $BaseDatos)
"; + $this->Estado = 0; + } + else{ + $NumeroDeConexiones++; + $this->Consulta("SET CLIENT_ENCODING TO 'LATIN1'"); + } + + } + else{ + $this->Error = "Error, Tipo de Base de Datos Incorrecta: $Tipo ($Usuario@$Servidor => $BaseDatos)
"; + $this->Error_debug = "Error, Tipo de Base de Datos Incorrecta: $Tipo ($Usuario:$Contrasena@$Servidor => $BaseDatos)
"; + $this->Estado = 0; + } + } + + function __destruct() { + if($this->TipoBaseDatos == "MySQL"){ + return @mysql_close($this->Identificador); + } + else{ + return @pg_close($this->Identificador); + } + } + function EscapeString($InputData){ + if($this->TipoBaseDatos == "MySQL"){ + return @mysql_escape_string($InputData); + } + else{ + return @pg_escape_string($InputData); + } + } + + + function EscapeArray($InputData, $EscapeKeys = NULL){ + if(is_string($EscapeKeys)){ + $EscapeKeys = array( "$EscapeKeys" ); + } + else if(!is_array($EscapeKeys)){ + $EscapeKeys = array_keys($InputData); + } + if($this->TipoBaseDatos == "MySQL"){ + foreach($EscapeKeys as $k){ + $InputData[$k] = mysql_escape_string($InputData[$k]); + } + } + else{ + foreach($EscapeKeys as $k){ + $InputData[$k] = pg_escape_string($InputData[$k]); + } + } + return $InputData; + } + function EscapeObject($InputData, $EscapeKeys = NULL){ + + return $this->EscapeArray(get_object_vars($InputData),$EscapeKeys); + + } + + function Consulta($Query){ + global $NumeroDeConsultas; + $this->Estado = 1; + if (!is_string($Query)){ + $this->Error_debug = $this->Error = "Consulta \"$Query\" no válida
"; + $this->Estado = $this->NumeroResultados = 0; + return $this->NumeroResultados; + } + if($this->MostrarConsultas) + echo nl2br($Query)."
"; + + if($this->TipoBaseDatos == "MySQL"){ + if ($this->ResultadoConsulta != 0) + @mysql_free_result($this->ResultadoConsulta); + + $NumeroDeConsultas++; + $this->ResultadoConsulta = @mysql_query($Query,$this->Identificador); + $this->UltimoId = @mysql_insert_id($this->Identificador); + if($this->ResultadoConsulta == 0){ + $this->Error = "Error Realizar la Consulta \"$Query\"
"; + $this->Error_debug = "Error Realizar la Consulta \"$Query\" (". @mysql_error($this->Identificador) .")
"; + $this->Estado = $this->NumeroResultados = 0; + } + else + $this->NumeroResultados = @mysql_affected_rows($this->Identificador); + } + else{ + if ($this->ResultadoConsulta != 0) + @pg_free_result($this->ResultadoConsulta); + + $NumeroDeConsultas++; + $this->ResultadoConsulta = @pg_query($this->Identificador,$Query); + + if($this->ResultadoConsulta == FALSE){ + $this->Error = "Error Realizar la Consulta \"$Query\"
"; + $this->Error_debug = "Error Realizar la Consulta \"$Query\" (". @pg_last_error($this->Identificador) .")
"; + $this->Estado = $this->NumeroResultados = 0; + } + else + $this->NumeroResultados = @pg_num_rows($this->ResultadoConsulta); + } + return $this->NumeroResultados; + } + + function SacaTupla($full = true){ + if($this->TipoBaseDatos == "MySQL"){ + if($full) + return @mysql_fetch_array($this->ResultadoConsulta); + else + return @mysql_fetch_assoc($this->ResultadoConsulta); + } + else{ + if($full) + return @pg_fetch_array($this->ResultadoConsulta); + else + return @pg_fetch_assoc($this->ResultadoConsulta); + } + + } + + function MuestraError($Debug = 0){ + + if($Debug) + echo $this->Error_debug; + else + echo $this->Error; + $this->Estado = 1; + } + } +?> diff --git a/BAM/lib/class/Plataforma.inc.php b/BAM/lib/class/Plataforma.inc.php new file mode 100644 index 0000000..c32f9d2 --- /dev/null +++ b/BAM/lib/class/Plataforma.inc.php @@ -0,0 +1,892 @@ +. + * +*/ + +class Plataforma{ + + // Crear un objeto usuario, criterios Login, Rut. + protected $browser_user_agent; + public $NumOs; + public $NumBrow; + + +public $SO = array(0 => 'Desconocido', + 101 => 'Windows 95', + 102 => 'Windows 98', + 103 => 'Windows Millenium', + 104 => 'Windows 2000', + 105 => 'Windows XP', + 106 => 'Windows Vista', + 107 => 'Windows 7', + 113 => 'Windows NT3', + 114 => 'Windows NT4', + 115 => 'Windows 2003', + 119 => 'Windows CE', + + 201 => 'Macintosh', + + 301 => 'Unix (*nix)', + + 401 => 'Ubuntu', + 402 => 'Kubuntu', + 403 => 'Xubuntu', + 404 => 'Debian', + 405 => 'Opensuse', + 406 => 'Suse', + 407 => 'Fedora', + 408 => 'RedHat', + 409 => 'Gentoo', + 410 => 'Linux' ); + +public $SO_ico = array(0 => 'desconocido', + 101 => 'win95', + 102 => 'win98', + 103 => 'winme', + 104 => 'win2000', + 105 => 'winxp', + 106 => 'winvista', + 107 => 'win7', + 113 => 'winnt', + 114 => 'winnt', + 115 => 'win2003', + 119 => 'wince', + + 201 => 'macosx', + + 301 => 'otro', + + 401 => 'ubuntu', + 402 => 'kubuntu', + 403 => 'xubuntu', + 404 => 'debian', + 405 => 'linux', + 406 => 'linux', + 407 => 'linux', + 408 => 'redhat', + 409 => 'gentoo', + 410 => 'linux' ); + +public $Navegador = array(0 => 'Desconocido', + 100 => 'Firefox', + 200 => 'Internet Explorer', + 300 => 'Opera', + 400 => 'Chrome', + 500 => 'Safari', + 900 => 'Webkit', + 800 => 'Mozilla', + 1000 => 'Web Spider'); + +public $Navegador_ico = array(0 => 'Desconocido', + 100 => 'ff', + 200 => 'ie', + 300 => 'opera', + 400 => 'chrome', + 500 => 'safari', + 900 => 'webkit', + 800 => 'mozilla', + 1000 => 'bot'); + +public $GEOIP_COUNTRY_CODES = array( +"xx", "ap", "eu", "ad", "ae", "af", "ag", "ai", "al", "am", "an", "ao", "aq", +"ar", "as", "at", "au", "aw", "az", "ba", "bb", "bd", "be", "bf", "bg", "bh", +"bi", "bj", "bm", "bn", "bo", "br", "bs", "bt", "bv", "bw", "by", "bz", "ca", +"cc", "cd", "cf", "cg", "ch", "ci", "ck", "cl", "cm", "cn", "co", "cr", "cu", +"cv", "cx", "cy", "cz", "de", "dj", "dk", "dm", "do", "dz", "ec", "ee", "eg", +"eh", "er", "es", "et", "fi", "fj", "fk", "fm", "fo", "fr", "fx", "ga", "gb", +"gd", "ge", "gf", "gh", "gi", "gl", "gm", "gn", "gp", "gq", "gr", "gs", "gt", +"gu", "gw", "gy", "hk", "hm", "hn", "hr", "ht", "hu", "id", "ie", "il", "in", +"io", "iq", "ir", "is", "it", "jm", "jo", "jp", "ke", "kg", "kh", "ki", "km", +"kn", "kp", "kr", "kw", "ky", "kz", "la", "lb", "lc", "li", "lk", "lr", "ls", +"lt", "lu", "lv", "ly", "ma", "mc", "md", "mg", "mh", "mk", "ml", "mm", "mn", +"mo", "mp", "mq", "mr", "ms", "mt", "mu", "mv", "mw", "mx", "my", "mz", "na", +"nc", "ne", "nf", "ng", "ni", "nl", "no", "np", "nr", "nu", "nz", "om", "pa", +"pe", "pf", "pg", "ph", "pk", "pl", "pm", "pn", "pr", "ps", "pt", "pw", "py", + +"qa", "re", "ro", "ru", "rw", "sa", "sb", "sc", "sd", "se", "sg", "sh", "si", +"sj", "sk", "sl", "sm", "sn", "so", "sr", "st", "sv", "sy", "sz", "tc", "td", +"tf", "tg", "th", "tj", "tk", "tm", "tn", "to", "tl", "tr", "tt", "tv", "tw", +"tz", "ua", "ug", "um", "us", "uy", "uz", "va", "vc", "ve", "vg", "vi", "vn", +"vu", "wf", "ws", "ye", "yt", "rs", "za", "zm", "me", "zw", "a1", "a2", "o1", +"ax", "gg", "im", "je" +); + +public $GEOIP_COUNTRY_NAMES = array( +"Desconocido", "Asia/Pacific Region", "Europe", "Andorra", "United Arab Emirates", +"Afghanistan", "Antigua and Barbuda", "Anguilla", "Albania", "Armenia", +"Netherlands Antilles", "Angola", "Antarctica", "Argentina", "American Samoa", +"Austria", "Australia", "Aruba", "Azerbaijan", "Bosnia and Herzegovina", +"Barbados", "Bangladesh", "Belgium", "Burkina Faso", "Bulgaria", "Bahrain", +"Burundi", "Benin", "Bermuda", "Brunei Darussalam", "Bolivia", "Brazil", +"Bahamas", "Bhutan", "Bouvet Island", "Botswana", "Belarus", "Belize", +"Canada", "Cocos (Keeling) Islands", "Congo, The Democratic Republic of the", +"Central African Republic", "Congo", "Switzerland", "Cote D'Ivoire", "Cook +Islands", "Chile", "Cameroon", "China", "Colombia", "Costa Rica", "Cuba", "Cape +Verde", "Christmas Island", "Cyprus", "Czech Republic", "Germany", "Djibouti", +"Denmark", "Dominica", "Dominican Republic", "Algeria", "Ecuador", "Estonia", +"Egypt", "Western Sahara", "Eritrea", "Spain", "Ethiopia", "Finland", "Fiji", +"Falkland Islands (Malvinas)", "Micronesia, Federated States of", "Faroe +Islands", "France", "France, Metropolitan", "Gabon", "United Kingdom", +"Grenada", "Georgia", "French Guiana", "Ghana", "Gibraltar", "Greenland", +"Gambia", "Guinea", "Guadeloupe", "Equatorial Guinea", "Greece", "South Georgia +and the South Sandwich Islands", "Guatemala", "Guam", "Guinea-Bissau", +"Guyana", "Hong Kong", "Heard Island and McDonald Islands", "Honduras", +"Croatia", "Haiti", "Hungary", "Indonesia", "Ireland", "Israel", "India", +"British Indian Ocean Territory", "Iraq", "Iran, Islamic Republic of", +"Iceland", "Italy", "Jamaica", "Jordan", "Japan", "Kenya", "Kyrgyzstan", +"Cambodia", "Kiribati", "Comoros", "Saint Kitts and Nevis", "Korea, Democratic +People's Republic of", "Korea, Republic of", "Kuwait", "Cayman Islands", +"Kazakstan", "Lao People's Democratic Republic", "Lebanon", "Saint Lucia", +"Liechtenstein", "Sri Lanka", "Liberia", "Lesotho", "Lithuania", "Luxembourg", +"Latvia", "Libyan Arab Jamahiriya", "Morocco", "Monaco", "Moldova, Republic +of", "Madagascar", "Marshall Islands", "Macedonia", +"Mali", "Myanmar", "Mongolia", "Macau", "Northern Mariana Islands", +"Martinique", "Mauritania", "Montserrat", "Malta", "Mauritius", "Maldives", +"Malawi", "Mexico", "Malaysia", "Mozambique", "Namibia", "New Caledonia", +"Niger", "Norfolk Island", "Nigeria", "Nicaragua", "Netherlands", "Norway", +"Nepal", "Nauru", "Niue", "New Zealand", "Oman", "Panama", "Peru", "French +Polynesia", "Papua New Guinea", "Philippines", "Pakistan", "Poland", "Saint +Pierre and Miquelon", "Pitcairn Islands", "Puerto Rico", "Palestinian Territory", +"Portugal", "Palau", "Paraguay", "Qatar", "Reunion", "Romania", +"Russian Federation", "Rwanda", "Saudi Arabia", "Solomon Islands", +"Seychelles", "Sudan", "Sweden", "Singapore", "Saint Helena", "Slovenia", +"Svalbard and Jan Mayen", "Slovakia", "Sierra Leone", "San Marino", "Senegal", +"Somalia", "Suriname", "Sao Tome and Principe", "El Salvador", "Syrian Arab +Republic", "Swaziland", "Turks and Caicos Islands", "Chad", "French Southern + +Territories", "Togo", "Thailand", "Tajikistan", "Tokelau", "Turkmenistan", +"Tunisia", "Tonga", "Timor-Leste", "Turkey", "Trinidad and Tobago", "Tuvalu", +"Taiwan", "Tanzania, United Republic of", "Ukraine", +"Uganda", "United States Minor Outlying Islands", "United States", "Uruguay", +"Uzbekistan", "Holy See (Vatican City State)", "Saint Vincent and the +Grenadines", "Venezuela", "Virgin Islands, British", "Virgin Islands, U.S.", +"Vietnam", "Vanuatu", "Wallis and Futuna", "Samoa", "Yemen", "Mayotte", +"Serbia", "South Africa", "Zambia", "Montenegro", "Zimbabwe", +"Anonymous Proxy","Satellite Provider","Other", +"Aland Islands","Guernsey","Isle of Man","Jersey" +); + + + function __construct($user_agent = ''){ + + if(empty($user_agent)) + $this->browser_user_agent = ( isset( $_SERVER['HTTP_USER_AGENT'] ) ) ? strtolower( $_SERVER['HTTP_USER_AGENT'] ) : ''; + else + $this->browser_user_agent = strtolower( $user_agent ); + + $this->Load(); + } + + function Load($user_agent = ''){ + $this->NumBrow = 0; + $this->NumOs = 0; + + if(!empty($user_agent)) + $this->browser_user_agent = strtolower( $user_agent );; + + $this->GetBrowser(); + $this->GetOS(); + + } + + function GetBrowser(){ + + //initialize all variables with default values to prevent error + $a_browser_math_number = ''; + $a_full_assoc_data = ''; + $a_full_data = ''; + $a_mobile_data = ''; + $a_moz_data = ''; + $a_os_data = ''; + $a_unhandled_browser = ''; + $a_webkit_data = ''; + $b_dom_browser = false; + $b_os_test = true; + $b_mobile_test = true; + $b_safe_browser = false; + $b_success = false;// boolean for if browser found in main test + $browser_math_number = ''; + $browser_temp = ''; + $browser_working = ''; + $browser_number = ''; + $ie_version = ''; + $mobile_test = ''; + $moz_release_date = ''; + $moz_rv = ''; + $moz_rv_full = ''; + $moz_type = ''; + $moz_number = ''; + $NumOsber = ''; + $os_type = ''; + $run_time = ''; + $true_ie_number = ''; + $ua_type = 'bot';// default to bot since you never know with bots + $webkit_type = ''; + $webkit_type_number = ''; + + $a_browser_types = array( + array( 'opera', true, 'op', 'bro' ), + array( 'msie', true, 'ie', 'bro' ), + // webkit before gecko because some webkit ua strings say: like gecko + array( 'webkit', true, 'webkit', 'bro' ), + // konq will be using webkit soon + array( 'konqueror', true, 'konq', 'bro' ), + // covers Netscape 6-7, K-Meleon, Most linux versions, uses moz array below + array( 'gecko', true, 'moz', 'bro' ), + array( 'netpositive', false, 'netp', 'bbro' ),// beos browser + array( 'lynx', false, 'lynx', 'bbro' ), // command line browser + array( 'elinks ', false, 'elinks', 'bbro' ), // new version of links + array( 'elinks', false, 'elinks', 'bbro' ), // alternate id for it + array( 'links2', false, 'links2', 'bbro' ), // alternate links version + array( 'links ', false, 'links', 'bbro' ), // old name for links + array( 'links', false, 'links', 'bbro' ), // alternate id for it + array( 'w3m', false, 'w3m', 'bbro' ), // open source browser, more features than lynx/links + array( 'webtv', false, 'webtv', 'bbro' ),// junk ms webtv + array( 'amaya', false, 'amaya', 'bbro' ),// w3c browser + array( 'dillo', false, 'dillo', 'bbro' ),// linux browser, basic table support + array( 'ibrowse', false, 'ibrowse', 'bbro' ),// amiga browser + array( 'icab', false, 'icab', 'bro' ),// mac browser + array( 'crazy browser', true, 'ie', 'bro' ),// uses ie rendering engine + + // search engine spider bots: + array( 'googlebot', false, 'google', 'bot' ),// google + array( 'mediapartners-google', false, 'adsense', 'bot' ),// google adsense + array( 'yahoo-verticalcrawler', false, 'yahoo', 'bot' ),// old yahoo bot + array( 'yahoo! slurp', false, 'yahoo', 'bot' ), // new yahoo bot + array( 'yahoo-mm', false, 'yahoomm', 'bot' ), // gets Yahoo-MMCrawler and Yahoo-MMAudVid bots + array( 'inktomi', false, 'inktomi', 'bot' ), // inktomi bot + array( 'slurp', false, 'inktomi', 'bot' ), // inktomi bot + array( 'fast-webcrawler', false, 'fast', 'bot' ),// Fast AllTheWeb + array( 'msnbot', false, 'msn', 'bot' ),// msn search + array( 'ask jeeves', false, 'ask', 'bot' ), //jeeves/teoma + array( 'teoma', false, 'ask', 'bot' ),//jeeves teoma + array( 'scooter', false, 'scooter', 'bot' ),// altavista + array( 'openbot', false, 'openbot', 'bot' ),// openbot, from taiwan + array( 'ia_archiver', false, 'ia_archiver', 'bot' ),// ia archiver + array( 'zyborg', false, 'looksmart', 'bot' ),// looksmart + array( 'almaden', false, 'ibm', 'bot' ),// ibm almaden web crawler + array( 'baiduspider', false, 'baidu', 'bot' ),// Baiduspider asian search spider + array( 'psbot', false, 'psbot', 'bot' ),// psbot image crawler + array( 'gigabot', false, 'gigabot', 'bot' ),// gigabot crawler + array( 'naverbot', false, 'naverbot', 'bot' ),// naverbot crawler, bad bot, block + array( 'surveybot', false, 'surveybot', 'bot' ),// + array( 'boitho.com-dc', false, 'boitho', 'bot' ),//norwegian search engine + array( 'objectssearch', false, 'objectsearch', 'bot' ),// open source search engine + array( 'answerbus', false, 'answerbus', 'bot' ),// http://www.answerbus.com/, web questions + array( 'sohu-search', false, 'sohu', 'bot' ),// chinese media company, search component + array( 'iltrovatore-setaccio', false, 'il-set', 'bot' ), + + // various http utility libaries + array( 'w3c_validator', false, 'w3c', 'lib' ), // uses libperl, make first + array( 'wdg_validator', false, 'wdg', 'lib' ), // + array( 'libwww-perl', false, 'libwww-perl', 'lib' ), + array( 'jakarta commons-httpclient', false, 'jakarta', 'lib' ), + array( 'python-urllib', false, 'python-urllib', 'lib' ), + + // download apps + array( 'getright', false, 'getright', 'dow' ), + array( 'wget', false, 'wget', 'dow' ),// open source downloader, obeys robots.txt + + // netscape 4 and earlier tests, put last so spiders don't get caught + array( 'mozilla/4.', false, 'ns', 'bbro' ), + array( 'mozilla/3.', false, 'ns', 'bbro' ), + array( 'mozilla/2.', false, 'ns', 'bbro' ) + ); + + //array( '', false ); // browser array template + + /* + moz types array + note the order, netscape6 must come before netscape, which is how netscape 7 id's itself. + rv comes last in case it is plain old mozilla. firefox/netscape/seamonkey need to be later + Thanks to: http://www.zytrax.com/tech/web/firefox-history.html + */ + $a_moz_types = array( 'bonecho', 'camino', 'epiphany', 'firebird', 'flock', 'galeon', 'iceape', 'icecat', 'k-meleon', 'minimo', 'multizilla', 'phoenix', 'songbird', 'swiftfox', 'seamonkey', 'shiretoko', 'iceweasel', 'firefox', 'minefield', 'netscape6', 'netscape', 'rv' ); + + /* + webkit types, this is going to expand over time as webkit browsers spread + konqueror is probably going to move to webkit, so this is preparing for that + It will now default to khtml. gtklauncher is the temp id for epiphany, might + change. Defaults to applewebkit, and will all show the webkit number. + */ + $a_webkit_types = array( 'arora', 'chrome', 'epiphany', 'gtklauncher', 'konqueror', 'midori', 'omniweb', 'safari', 'uzbl', 'applewebkit', 'webkit' ); + /* + run through the browser_types array, break if you hit a match, if no match, assume old browser + or non dom browser, assigns false value to $b_success. + */ + $i_count = count( $a_browser_types ); + for ( $i = 0; $i < $i_count; $i++ ){ + //unpacks browser array, assigns to variables, need to not assign til found in string + $browser_temp = $a_browser_types[$i][0];// text string to id browser from array + + if ( strstr( $this->browser_user_agent, $browser_temp ) ) + { + /* + it defaults to true, will become false below if needed + this keeps it easier to keep track of what is safe, only + explicit false assignment will make it false. + */ + $b_safe_browser = true; + $browser_name = $browser_temp;// text string to id browser from array + + // assign values based on match of user agent string + $b_dom_browser = $a_browser_types[$i][1];// hardcoded dom support from array + $browser_working = $a_browser_types[$i][2];// working name for browser + $ua_type = $a_browser_types[$i][3];// sets whether bot or browser + + switch ( $browser_working ) + { + // this is modified quite a bit, now will return proper netscape version number + // check your implementation to make sure it works + case 'ns': + $b_safe_browser = false; + $browser_number = $this->get_item_version( $this->browser_user_agent, 'mozilla' ); + $this->NumBrow = 10; + break; + case 'moz': + /* + note: The 'rv' test is not absolute since the rv number is very different on + different versions, for example Galean doesn't use the same rv version as Mozilla, + neither do later Netscapes, like 7.x. For more on this, read the full mozilla + numbering conventions here: http://www.mozilla.org/releases/cvstags.html + */ + // this will return alpha and beta version numbers, if present + $moz_rv_full = $this->get_item_version( $this->browser_user_agent, 'rv' ); + // this slices them back off for math comparisons + $moz_rv = substr( $moz_rv_full, 0, 3 ); + + // this is to pull out specific mozilla versions, firebird, netscape etc.. + $j_count = count( $a_moz_types ); + for ( $j = 0; $j < $j_count; $j++ ) + { + if ( strstr( $this->browser_user_agent, $a_moz_types[$j] ) ) + { + $moz_type = $a_moz_types[$j]; + $moz_number = $this->get_item_version( $this->browser_user_agent, $moz_type ); + break; + } + } + /* + this is necesary to protect against false id'ed moz'es and new moz'es. + this corrects for galeon, or any other moz browser without an rv number + */ + if ( !$moz_rv ) + { + // you can use this if you are running php >= 4.2 + if ( function_exists( 'floatval' ) ) + { + $moz_rv = floatval( $moz_number ); + } + else + { + $moz_rv = substr( $moz_number, 0, 3 ); + } + $moz_rv_full = $moz_number; + } + // this corrects the version name in case it went to the default 'rv' for the test + if ( $moz_type == 'rv' ) + { + $moz_type = 'mozilla'; + } + + //the moz version will be taken from the rv number, see notes above for rv problems + $browser_number = $moz_rv; + // gets the actual release date, necessary if you need to do functionality tests + $this->get_set_count( 'set', 0 ); + $moz_release_date = $this->get_item_version( $this->browser_user_agent, 'gecko/' ); + /* + Test for mozilla 0.9.x / netscape 6.x + test your javascript/CSS to see if it works in these mozilla releases, if it + does, just default it to: $b_safe_browser = true; + */ + if ( ( $moz_release_date < 20020400 ) || ( $moz_rv < 1 ) ) + { + $b_safe_browser = false; + } + + if($moz_type == 'firefox') + $this->NumBrow = 100 + intval($moz_number*10); + else + $this->NumBrow = 800+$j; + break; + case 'ie': + /* + note we're adding in the trident/ search to return only first instance in case + of msie 8, and we're triggering the break last condition in the test, as well + as the test for a second search string, trident/ + */ + $browser_number = $this->get_item_version( $this->browser_user_agent, $browser_name, true, 'trident/' ); + // construct the proper real number if it's in compat mode and msie 8.0/9.0 + if ( strstr( $browser_number, '7.' ) && strstr( $this->browser_user_agent, 'trident/5' ) ) + { + // note that 7.0 becomes 9 when adding 1, but if it's 7.1 it will be 9.1 + $true_ie_number = $browser_number + 2; + } + elseif ( strstr( $browser_number, '7.' ) && strstr( $this->browser_user_agent, 'trident/4' ) ) + { + // note that 7.0 becomes 8 when adding 1, but if it's 7.1 it will be 8.1 + $true_ie_number = $browser_number + 1; + } + // the 9 series is finally standards compatible, html 5 etc, so worth a new id + if ( $browser_number >= 9 ) + { + $ie_version = 'ie9x'; + } + // 7/8 were not yet quite to standards levels but getting there + elseif ( $browser_number >= 7 ) + { + $ie_version = 'ie7x'; + } + // then test for IE 5x mac, that's the most problematic IE out there + elseif ( strstr( $this->browser_user_agent, 'mac') ) + { + $ie_version = 'ieMac'; + } + // ie 5/6 are both very weak in standards compliance + elseif ( $browser_number >= 5 ) + { + $ie_version = 'ie5x'; + } + elseif ( ( $browser_number > 3 ) && ( $browser_number < 5 ) ) + { + $b_dom_browser = false; + $ie_version = 'ie4'; + // this depends on what you're using the script for, make sure this fits your needs + $b_safe_browser = true; + } + else + { + $ie_version = 'old'; + $b_dom_browser = false; + $b_safe_browser = false; + } + $this->NumBrow = 200 + $browser_number; + break; + case 'op': + $browser_number = $this->get_item_version( $this->browser_user_agent, $browser_name ); + // opera is leaving version at 9.80 (or xx) for 10.x - see this for explanation + // http://dev.opera.com/articles/view/opera-ua-string-changes/ + if ( strstr( $browser_number, '9.' ) && strstr( $this->browser_user_agent, 'version/' ) ) + { + get_set_count( 'set', 0 ); + $browser_number = $this->get_item_version( $this->browser_user_agent, 'version/' ); + } + + if ( $browser_number < 5 )// opera 4 wasn't very useable. + { + $b_safe_browser = false; + } + $this->NumBrow = 300 + $browser_number; + break; + /* + note: webkit returns always the webkit version number, not the specific user + agent version, ie, webkit 583, not chrome 0.3 + */ + case 'webkit': + // note that this is the Webkit version number + $browser_number = $this->get_item_version( $this->browser_user_agent, $browser_name ); + // this is to pull out specific webkit versions, safari, google-chrome etc.. + $j_count = count( $a_webkit_types ); + for ( $j = 0; $j < $j_count; $j++ ) + { + if ( strstr( $this->browser_user_agent, $a_webkit_types[$j] ) ) + { + $webkit_type = $a_webkit_types[$j]; + /* + and this is the webkit type version number, like: chrome 1.2 + if omni web, we want the count 2, not default 1 + */ + if ( $webkit_type == 'omniweb' ) + { + $this->get_set_count( 'set', 2 ); + } + $webkit_type_number = $this->get_item_version( $this->browser_user_agent, $webkit_type ); + // epiphany hack + if ( $a_webkit_types[$j] == 'gtklauncher' ) + { + $browser_name = 'epiphany'; + } + else + { + $browser_name = $a_webkit_types[$j]; + } + if($webkit_type == 'chrome') + $this->NumBrow = 400 + $webkit_type_number; + elseif($webkit_type == 'safari') + $this->NumBrow = 500 + $webkit_type_number; + else + $this->NumBrow = 900+$j; + break; + } + } + break; + default: + $browser_number = $this->get_item_version( $this->browser_user_agent, $browser_name ); + if($browser_number < 50) + $this->NumBrow = 50 + $browser_number; + else + $this->NumBrow = 50; + + break; + } + // the browser was id'ed + $b_success = true; + break; + } + } + //assigns defaults if the browser was not found in the loop test + if ( !$b_success ) + { + + $browser_name = 'NA'; + $browser_number = 'NA'; + + } + + $this->dataAssoc = array( + 'browser_working' => $browser_working, + 'browser_number' => $browser_number, + 'ie_version' => $ie_version, + 'dom' => $b_dom_browser, + 'safe' => $b_safe_browser, + 'os' => $os_type, + 'NumOsber' => $NumOsber, + 'browser_name' => $browser_name, + 'ua_type' => $ua_type, + 'browser_math_number' => $browser_math_number, + 'moz_data' => $a_moz_data, + 'webkit_data' => $a_webkit_data, + 'mobile_test' => $mobile_test, + 'mobile_data' => $a_mobile_data, + 'true_ie_number' => $true_ie_number, + 'run_time' => $run_time + ); + + + $this->fullData = array( + $browser_working, + $browser_number, + $ie_version, + $b_dom_browser, + $b_safe_browser, + $os_type, + $NumOsber, + $browser_name, + $ua_type, + $browser_math_number, + $a_moz_data, + $a_webkit_data, + $mobile_test, + $a_mobile_data, + $true_ie_number, + $run_time + ); + + } + function GetOS() + { + // initialize variables + $os_working_type = ''; + $os_working_number = ''; + + $pv_browser_string = $this->browser_user_agent; + $pv_browser_name = $this->fullData[0]; + $pv_version_number = $this->fullData[1]; + + $this->NumOs= 0; + /* + packs the os array. Use this order since some navigator user agents will put 'macintosh' + in the navigator user agent string which would make the nt test register true + */ + $a_mac = array( 'intel mac', 'ppc mac', 'mac68k' );// this is not used currently + // same logic, check in order to catch the os's in order, last is always default item + $a_unix_types = array( 'dragonfly', 'freebsd', 'openbsd', 'netbsd', 'bsd', 'unixware', 'solaris', 'sunos', 'sun4', 'sun5', 'suni86', 'sun', 'irix5', 'irix6', 'irix', 'hpux9', 'hpux10', 'hpux11', 'hpux', 'hp-ux', 'aix1', 'aix2', 'aix3', 'aix4', 'aix5', 'aix', 'sco', 'unixware', 'mpras', 'reliant', 'dec', 'sinix', 'unix' ); + // only sometimes will you get a linux distro to id itself... + $a_linux_distros = array( 'ubuntu', 'kubuntu', 'xubuntu', 'debian', 'opensuse', 'suse', 'fedora', 'redhat', 'gentoo', 'linux' ); + $a_linux_process = array ( 'i386', 'i586', 'i686' );// not use currently + // note, order of os very important in os array, you will get failed ids if changed + $a_os_types = array( 'android', 'blackberry', 'iphone', 'palmos', 'palmsource', 'symbian', 'beos', 'os2', 'amiga', 'webtv', 'mac', 'nt', 'win', $a_unix_types, $a_linux_distros ); + + //os tester + $i_count = count( $a_os_types ); + for ( $i = 0; $i < $i_count; $i++ ) + { + // unpacks os array, assigns to variable $a_os_working + $os_working_data = $a_os_types[$i]; + /* + assign os to global os variable, os flag true on success + !strstr($pv_browser_string, "linux" ) corrects a linux detection bug + */ + if ( !is_array( $os_working_data ) && strstr( $pv_browser_string, $os_working_data ) && !strstr( $pv_browser_string, "linux" ) ) + { + $os_working_type = $os_working_data; + + switch ( $os_working_type ) + { + // most windows now uses: NT X.Y syntax + case 'nt': + if ( strstr( $pv_browser_string, 'nt 6.1' ) )// windows 7 + { + $os_working_number = 6.1; + $this->NumOs = 107; + } + elseif ( strstr( $pv_browser_string, 'nt 6.0' ) )// windows vista/server 2008 + { + $os_working_number = 6.0; + $this->NumOs = 106; + } + elseif ( strstr( $pv_browser_string, 'nt 5.2' ) )// windows server 2003 + { + $os_working_number = 5.2; + $this->NumOs = 115; + } + elseif ( strstr( $pv_browser_string, 'nt 5.1' ) || strstr( $pv_browser_string, 'xp' ) )// windows xp + { + $os_working_number = 5.1;// + $this->NumOs = 105; + } + elseif ( strstr( $pv_browser_string, 'nt 5' ) || strstr( $pv_browser_string, '2000' ) )// windows 2000 + { + $os_working_number = 5.0; + $this->NumOs = 104; + } + elseif ( strstr( $pv_browser_string, 'nt 4' ) )// nt 4 + { + $os_working_number = 4; + $this->NumOs = 113; + } + elseif ( strstr( $pv_browser_string, 'nt 3' ) )// nt 4 + { + $os_working_number = 3; + $this->NumOs = 114; + } + break; + case 'win': + if ( strstr( $pv_browser_string, 'vista' ) )// windows vista, for opera ID + { + $os_working_number = 6.0; + $os_working_type = 'nt'; + $this->NumOs = 106; + } + elseif ( strstr( $pv_browser_string, 'xp' ) )// windows xp, for opera ID + { + $os_working_number = 5.1; + $os_working_type = 'nt'; + $this->NumOs = 105; + } + elseif ( strstr( $pv_browser_string, '2003' ) )// windows server 2003, for opera ID + { + $os_working_number = 5.2; + $os_working_type = 'nt'; + $this->NumOs = 115; + } + elseif ( strstr( $pv_browser_string, 'windows ce' ) )// windows CE + { + $os_working_number = 'ce'; + $os_working_type = 'nt'; + $this->NumOs = 119; + } + elseif ( strstr( $pv_browser_string, '95' ) ) + { + $os_working_number = '95'; + $this->NumOs = 101; + } + elseif ( ( strstr( $pv_browser_string, '9x 4.9' ) ) || ( strstr( $pv_browser_string, ' me' ) ) ) + { + $os_working_number = 'me'; + $this->NumOs = 103; + } + elseif ( strstr( $pv_browser_string, '98' ) ) + { + $os_working_number = '98'; + $this->NumOs = 102; + } + elseif ( strstr( $pv_browser_string, '2000' ) )// windows 2000, for opera ID + { + $os_working_number = 5.0; + $os_working_type = 'nt'; + $this->NumOs = 104; + } + break; + case 'mac': + if ( strstr( $pv_browser_string, 'os x' ) ) + { + $this->NumOs = 201; + // if it doesn't have a version number, it is os x; + if ( strstr( $pv_browser_string, 'os x ' ) ) + { + // numbers are like: 10_2.4, others 10.2.4 + $os_working_number = str_replace( '_', '.', $this->get_item_version( $pv_browser_string, 'os x' ) ); + } + else + { + $os_working_number = 10; + } + } + /* + this is a crude test for os x, since safari, camino, ie 5.2, & moz >= rv 1.3 + are only made for os x + */ + elseif ( ( $pv_browser_name == 'saf' ) || ( $pv_browser_name == 'cam' ) || + ( ( $pv_browser_name == 'moz' ) && ( $pv_version_number >= 1.3 ) ) || + ( ( $pv_browser_name == 'ie' ) && ( $pv_version_number >= 5.2 ) ) ) + { + $os_working_number = 10; + $this->NumOs = 201; + } + break; + case 'iphone': + $os_working_number = 10; + break; + default: + break; + } + break; + } + /* + check that it's an array, check it's the second to last item + in the main os array, the unix one that is + */ + elseif ( is_array( $os_working_data ) && ( $i == ( $i_count - 2 ) ) ) + { + $j_count = count($os_working_data); + for ($j = 0; $j < $j_count; $j++) + { + if ( strstr( $pv_browser_string, $os_working_data[$j] ) ) + { + $this->NumOs = 301+$j; + $os_working_type = 'unix'; //if the os is in the unix array, it's unix, obviously... + $os_working_number = ( $os_working_data[$j] != 'unix' ) ? $os_working_data[$j] : '';// assign sub unix version from the unix array + break; + } + } + } + /* + check that it's an array, check it's the last item + in the main os array, the linux one that is + */ + elseif ( is_array( $os_working_data ) && ( $i == ( $i_count - 1 ) ) ) + { + $j_count = count($os_working_data); + for ($j = 0; $j < $j_count; $j++) + { + if ( strstr( $pv_browser_string, $os_working_data[$j] ) ) + { + $this->NumOs = 401+$j; + $os_working_type = 'lin'; + // assign linux distro from the linux array, there's a default + //search for 'lin', if it's that, set version to '' + $os_working_number = ( $os_working_data[$j] != 'linux' ) ? $os_working_data[$j] : ''; + break; + } + } + } + } + + // pack the os data array for return to main function + $a_os_data = array( $os_working_type, $os_working_number ); + + return $a_os_data; + } + + +function get_item_version( $pv_browser_user_agent, $pv_search_string, $pv_b_break_last='', $pv_extra_search='' ) +{ + // 12 is the longest that will be required, handles release dates: 20020323; 0.8.0+ + $substring_length = 15; + $start_pos = 0; // set $start_pos to 0 for first iteration + //initialize browser number, will return '' if not found + $string_working_number = ''; + /* + use the passed parameter for $pv_search_string + start the substring slice right after these moz search strings + there are some cases of double msie id's, first in string and then with then number + $start_pos = 0; + this test covers you for multiple occurrences of string, only with ie though + with for example google bot you want the first occurance returned, since that's where the + numbering happens + */ + for ( $i = 0; $i < 4; $i++ ) + { + //start the search after the first string occurrence + if ( strpos( $pv_browser_user_agent, $pv_search_string, $start_pos ) !== false ) + { + // update start position if position found + $start_pos = strpos( $pv_browser_user_agent, $pv_search_string, $start_pos ) + strlen( $pv_search_string ); + /* + msie (and maybe other userAgents requires special handling because some apps inject + a second msie, usually at the beginning, custom modes allow breaking at first instance + if $pv_b_break_last $pv_extra_search conditions exist. Since we only want this test + to run if and only if we need it, it's triggered by caller passing these values. + */ + if ( !$pv_b_break_last || ( $pv_extra_search && strstr( $pv_browser_user_agent, $pv_extra_search ) ) ) + { + break; + } + } + else + { + break; + } + } + /* + Handles things like extra omniweb/v456, gecko/, blackberry9700 + also corrects for the omniweb 'v' + */ + $start_pos += $this->get_set_count( 'get' ); + $string_working_number = substr( $pv_browser_user_agent, $start_pos, $substring_length ); + + // Find the space, ;, or parentheses that ends the number + $string_working_number = substr( $string_working_number, 0, strcspn($string_working_number, ' );/') ); + + //make sure the returned value is actually the id number and not a string + // otherwise return '' + // strcspn( $string_working_number, '0123456789.') == strlen( $string_working_number) + // if ( preg_match("/\\d/", $string_working_number) == 0 ) + if ( !is_numeric( substr( $string_working_number, 0, 1 ) ) ) + { + $string_working_number = ''; + } + //$string_working_number = strrpos( $pv_browser_user_agent, $pv_search_string ); + return $string_working_number; +} + +function get_set_count( $pv_type, $pv_value='' ) +{ + static $slice_increment; + $return_value = ''; + switch ( $pv_type ) + { + case 'get': + // set if unset, ie, first use. note that empty and isset are not good tests here + if ( is_null( $slice_increment ) ) + { + $slice_increment = 1; + } + $return_value = $slice_increment; + $slice_increment = 1; // reset to default + return $return_value; + break; + case 'set': + $slice_increment = $pv_value; + break; + } +} + +} +?> diff --git a/BAM/lib/class/Response.inc.php b/BAM/lib/class/Response.inc.php new file mode 100644 index 0000000..1222046 --- /dev/null +++ b/BAM/lib/class/Response.inc.php @@ -0,0 +1,698 @@ +. + * +*/ + + +require_once $_SERVER['DOCUMENT_ROOT'].'/BAM/lib/class/Db.inc.php'; +require_once $_SERVER['DOCUMENT_ROOT'].'/BAM/lib/class/Usuario.inc.php'; +class BogusAction { + public $action; + public $method; + public $data; + public $tid; +} + +class Response{ + + public $Peticiones; + + public $dataout; + public $datain; + + public $Loaded; + + public $Error; + public $isForm; + public $isUpload; + public $Valido; + +// Conexiones a Bases de Datos + protected $User; + protected $DB; //Conexion de Base de datos del Objeto. + + // Crear un objeto usuario, criterios Login, Rut. + function __construct($rawdata,$post, $files){ + global $IdentificadorUsuario; + global $conf; + $this->DB = new Db($conf->db->name, $conf->db->host, $conf->db->user, $conf->db->password, 'pg'); + $this->User = new Usuario($IdentificadorUsuario); + $this->Loaded = array(); + + $this->Load($rawdata,$post, $files); + + return $this->Valido; + } + + function Load($rawdata,$post=array(), $files=array()){ + + if(isset($rawdata)){ +// header('Content-Type: text/javascript'); + $this->datain = json_decode($rawdata); + + $this->isForm = false; + $this->isUpload = false; + $this->Valido = true; + $this->Peticiones = count($this->datain); + $this->dataout = null; + + }else if(isset($post['extAction'])){ // form post + $this->datain = new BogusAction(); + $this->datain->action = $post['extAction']; + $this->datain->method = $post['extMethod']; + $this->datain->tid = isset($post['extTID']) ? $post['extTID'] : null; // not set for upload + $this->datain->data = array_merge($post, $files); + + $this->dataout = null; + $this->isUpload = $post['extUpload'] == 'true'; + $this->isForm = true; + $this->Valido = true; + $this->Peticiones = 1; + }else{ + $this->dataout = null; + $this->Valido = false; + $this->Error = "Invalid Request"; + $this->Peticiones = 0; + } + + } + function addResponse($res){ + if($this->dataout == null) + $this->dataout = $res; + elseif(!isset($this->dataout[0])){ + $this->dataout = array($this->dataout); + $this->dataout[] = $res; + } + else{ + $this->dataout[] = $res; + } + } + + function echoResponse(){ + header("Cache-Control: no-store, no-cache"); + echo json_encode($this->dataout); + } + + function guestRequests(){ + if($this->Peticiones == 1) + $this->doGuestRPC($this->datain); + else{ + foreach($this->datain as $datain){ + $this->doGuestRPC($datain); + } + } + } + + function userRequest(){ + if($this->Peticiones == 1) + $this->doUserRPC($this->datain); + else{ + foreach($this->datain as $datain){ + $this->doUserRPC($datain); + } + } + } + + function doGuestRPC($request){ + global $IdentificadorUsuario; + $response = array('type'=>'rpc','tid'=>$request->tid,'action'=>$request->action,'method'=>$request->method,'level'=>'Guest' ); + if(!strcmp($request->action, 'Remote')){ /* Accion unica */ + if(!strcmp($request->method, 'login')){/* Metodo único, logueo */ + + $params = isset($request->data) && is_array($request->data) ? $request->data : array(); + $loginUsername = isset($params["loginUsername"]) ? $params["loginUsername"] : ""; + $elogin = $this->DB->EscapeString($loginUsername); + $epass = $this->DB->EscapeString($params["loginPassword"]); + + $n = $this->DB->Consulta("select id,activo from usuarios where login = '{$elogin}' and clave = '{$epass}'"); + if ($n == 1){ + list ($IdentificadorUsuario,$activo) = $this->DB->Sacatupla(); + // Check for current sessions + $this->DB->Consulta("select sesion from usuarios where id = {$IdentificadorUsuario}"); + list ($lasSSID) = $this->DB->SacaTupla(); + if( $lasSSID > 0){ //- dirty logout! + $this->DB->Consulta("select fin,estado from sesiones where id = {$lasSSID}"); + list ($UltimoT, $EstadoF) = $this->DB->SacaTupla(); + $Delta = $UltimoT - time(); + if(($EstadoF == 0) && ($Delta < 900)){ + //- conectado y ultimo acceso hace menos de 15 minutos + //- Considera desconexion por logeo de otra ubicacion + $this->DB->Consulta("update sesiones set estado=3 where id = {$lasSSID}"); + } + elseif($EstadoF == 0){ + //- conectado y ultimo acceso hace +15 minutos + //- Considera timeout + $this->DB->Consulta("update sesiones set estado=2 where id = {$lasSSID}"); + } + else{ + //- no conectado? + //- Considera error + } + } + + + //Fill session data! + if (!empty($HTTP_SERVER_VARS["HTTP_X_FORWARDED_FOR"])){ + $Ip = $HTTP_SERVER_VARS["HTTP_X_FORWARDED_FOR"]; + }else{ + $Ip = $_SERVER["REMOTE_ADDR"]; + } + require($_SERVER['DOCUMENT_ROOT'].'/BAM/lib/GeoIp/geoip.inc.php'); + + $gi = geoip_open($_SERVER['DOCUMENT_ROOT']."/BAM/lib/GeoIp/GeoIP.dat",GEOIP_STANDARD); + $cid = geoip_country_id_by_addr($gi, $Ip); + + require_once $_SERVER['DOCUMENT_ROOT'].'/BAM/lib/class/Plataforma.inc.php'; + $Plat = new Plataforma($_SERVER['HTTP_USER_AGENT']); + + $pixels = intval($params["spixels"]); + $ancho = intval($params["swidth"]); + + $IpL = ip2long($Ip); + $EUA = $this->DB->EscapeString($_SERVER['HTTP_USER_AGENT']); + + $Ahora = time(); + $this->DB->Consulta("select nextval('sesiones_id_seq'::regclass)"); + list($nextid) = $this->DB->SacaTupla(); + if($activo == 0){ + $this->DB->Consulta("insert into sesiones (id,inicio,fin,usuario,estado,ip,useragent,so,navegador,pais,p,w) Values($nextid,$Ahora,$Ahora,$IdentificadorUsuario,5,$IpL,'$EUA',{$Plat->NumOs},{$Plat->NumBrow},$cid,$pixels,$ancho)"); + $this->DB->Consulta("update usuarios set sesion=0 where id = {$IdentificadorUsuario}"); + $response['result']["success"] = false; + $response['result']["error"]["reason"] = "Esta cuenta ha sido desactivada por el administrador del sistema."; + } + else{ + $this->DB->Consulta("insert into sesiones (id,inicio,fin,usuario,estado,ip,useragent,so,navegador,pais,p,w) Values($nextid,$Ahora,$Ahora,$IdentificadorUsuario,0,$IpL,'$EUA',{$Plat->NumOs},{$Plat->NumBrow},$cid,$pixels,$ancho)"); + + $_SESSION['SesionId'] = $nextid; + $this->DB->Consulta("update usuarios set sesion=$nextid where id = {$IdentificadorUsuario}"); + + $response['result']["success"] = true; + } + } + else { + $response['result']["success"] = false; + $response['result']["error"]["reason"] = "Nombre de usuario o clave incorrecta. Inténtelo nuevamente."; + } + } + else{ + $response['result']["success"] = false; + $response['result']["error"]["reason"] = "Método desconocido: ".$request->action.".".$request->method; + } + } + elseif(!strcmp($request->action, 'core')){ /* Acciones de la aplicacion */ + if(!strcmp($request->method, 'Logout')){ + unset($_SESSION); + $response['result']["success"] = true; + } + else{ + /* Cualquier otro evento indica que el usuario esta realmente deslogueado */ + + $event = array('type'=>'event','name'=>'lpc','data'=>'login'); + $this->addResponse($event); + $response['result']["success"] = false; + $response['result']["error"]["reason"] = "Método desconocido: ".$request->action.".".$request->method; + } + } + else{ + $response['result']["success"] = false; + $response['result']["error"]["reason"] = "Acción desconocida: ".$request->action; + + /* Se asume que intento acceder una RPC de usuario logueado, envia evento de logeo */ + + $event = array('type'=>'event','name'=>'lpc','data'=>'login'); + $this->addResponse($event); + } + $this->addResponse($response); + } + + function doUserRPC($request){ + + $response = array('type'=>'rpc','tid'=>$request->tid,'action'=>$request->action,'method'=>$request->method,'level'=>'User' ); + + if(!strcmp($request->action, 'core')){ /* Acciones de la aplicacion */ + if(!strcmp($request->method, 'getTree')){/* Metodo para obtener los nodos del Treepanel */ + list($crap,$nid) = explode('.',$request->data[0]); + $tree = array(); + $this->DB->Consulta("select contenido.id as xid,contenido.tipo,contenido.hijos,contenido.nombre as text,contenido.icon as xicon from + (contenido + left join gcontenido on (contenido.id = gcontenido.cid)) + where contenido.id > 1 and contenido.pid = {$nid} and gcontenido.gid in (select gid from gusuarios where uid = {$this->User->Uid}) order by contenido.pos asc;"); + + while($el = $this->DB->Sacatupla(false)){ + if ($el['hijos'] > 0) + $el['leaf'] = false; + else + $el['leaf'] = true; + + $el['id'] = 'menunode.'.$el['xid']; + + $tree[$el['xid']] = $el; + } + $response['result'] = array_values($tree); + } + elseif(!strcmp($request->method, 'show')){ + $contentId = intval($request->data[0]); + if($contentId > 0){ + if(!in_array($contentId,$this->Loaded)){ + $this->DB->Consulta("select contenido,tipo from contenido where id = $contentId;"); + list($code,$tipo) = $this->DB->SacaTupla(); + if($tipo == 2){ + $code = file_get_contents( $_SERVER['DOCUMENT_ROOT'].'/BAM/js/Dazzler/'.$code , null, null, 0, 1024*500 ); + } + $code = str_replace(array("%xid%","%uid%"), array($contentId,$this->User->Uid), $code); + eval( $code ); + $this->Loaded[] = $contentId; + } + if(function_exists ( "App_show" )){ + $show = App_show(); + $response['result']["success"] = true; + $response['result']["nodeid"] = $contentId; + + if($request->data[1]){ + if(function_exists ( "App_define" )){ + $define = App_define(); + } + $response['result']['show'] = ""; + + } + else{ + $response['result']['show'] = ""; + } + } + else{ + $response['result']["success"] = false; + $response['result']["error"]["reason"] = "Show is undefined for $contentId"; + } + } + else{ + $response['result']["success"] = false; + $response['result']["error"]["reason"] = "Invalid Id:".$contentId; + } + } + elseif(!strcmp($request->method, 'Logout')){ + $now = time(); + $this->DB->Consulta("update sesiones set fin=$now,estado=1 where id = {$_SESSION['SesionId']}"); + $this->DB->Consulta("update usuarios set sesion=0 where id = {$this->User->Uid}"); + session_destroy(); + $response['result']["success"] = true; + } + elseif(!strcmp($request->method, 'userGroups')){ + $response['result'] = array(); + $response['result']['groups'] = array(); + $this->DB->Consulta("select count(*) from gusuarios where uid={$this->User->Uid}"); + list ($response['result']['totalCount']) = $this->DB->SacaTupla(); + + $this->DB->Consulta("select id,nombre from grupos where id in (select gid from gusuarios where uid = {$this->User->Uid}) order by {$request->data[0]->sort} {$request->data[0]->dir} offset {$request->data[0]->start} limit {$request->data[0]->limit};"); + + while($t = $this->DB->SacaTupla(false)){ + $response['result']['groups'][] = $t; + } + $response['result']['success'] = true; + + } + elseif(!strcmp($request->method, 'userSession')){ + $response['result'] = array(); + $response['result']['sessions'] = array(); + $this->DB->Consulta("select count(*) from sesiones where usuario={$this->User->Uid}"); + list ($response['result']['totalCount']) = $this->DB->SacaTupla(); + require_once $_SERVER['DOCUMENT_ROOT'].'/BAM/lib/class/Plataforma.inc.php'; + $Plat = new Plataforma(); + + $this->DB->Consulta("select id,inicio,fin,ip, estado, useragent,so,navegador,pais,p,w from sesiones where usuario={$this->User->Uid} order by {$request->data[0]->sort} {$request->data[0]->dir} offset {$request->data[0]->start} limit {$request->data[0]->limit};"); + + while($t = $this->DB->SacaTupla(false)){ + $o['ip'] = long2ip($t['ip']); + $o['iptxt'] = $Plat->GEOIP_COUNTRY_NAMES[$t['pais']] . " ({$o['ip']})"; + $o['ipcls'] = $Plat->GEOIP_COUNTRY_CODES[$t['pais']]; + + $o['inicio'] = date('H:i:s d/m/Y',$t['inicio']); + $o['fin'] = date('H:i:s d/m/Y',$t['fin']); + + $duracion = $t['fin']-$t['inicio']; + $o['duracion'] = ''; + $d=$h=$m=0; + if($duracion > 86400){ + $d = floor($duracion / 86400); + $duracion -= $d * 86400; + } + if($duracion > 3600){ + $h = floor($duracion / 3600); + $duracion -= $h * 3600; + } + if($duracion > 60){ + $m = floor($duracion / 60); + $duracion -= $m * 60; + } + + if($d>1) + $o['duracion'] .= "$d días, "; + elseif($d) + $o['duracion'] .= "1 día, "; + if($h>1) + $o['duracion'] .= "$h horas, "; + elseif($h) + $o['duracion'] .= "1 hora, "; + if($m>1) + $o['duracion'] .= "$m minutos, "; + elseif($m) + $o['duracion'] .= "1 minuto, "; + + if($duracion!=1) + $o['duracion'] .= "$duracion segundos"; + else + $o['duracion'] .= "1 segundo"; + + + $o['resolucion'] = $t['w'].'x'.$t['p']/$t['w']; + + $o['sotxt'] = $Plat->SO[$t['so']]; + $o['socls'] = $Plat->SO_ico[$t['so']]; + $tmp = 100* intval($t['navegador']/100); + $o['navegadortxt'] = $Plat->Navegador[$tmp]; + $o['navegadorcls'] = $Plat->Navegador_ico[$tmp]; + + $o['useragent'] = $t['useragent']; + + $o['estado'] = $t['estado']; + if($t['estado'] == '0'){ + $o['estadotxt'] = "Conectado"; + } + elseif($t['estado'] == '1'){ + $o['estadotxt'] = "Desconectado"; + } + elseif($t['estado'] == '2'){ + $o['estadotxt'] = "Timeout"; + } + elseif($t['estado'] == '3'){ + $o['estadotxt'] = "Inicio desde otra ubicación"; + } + elseif($t['estado'] == '5'){ + $o['estadotxt'] = "Usuario desactivado"; + } + + + $o['id'] = $t['id']; + + $response['result']['sessions'][] = $o; + } + $response['result']['success'] = true; + } + elseif(!strcmp($request->method, 'UserLoad')){ + $response['result'] = array(); + $response['result']['data'] = array(); + $response['result']['data']['login'] = $this->User->Login; + $response['result']['data']['nombre']= $this->User->Nombre; + $response['result']['data']['cargo']= $this->User->Cargo; + $response['result']['data']['correo']= $this->User->Correo; + $response['result']['success'] = true; + } + elseif(!strcmp($request->method, 'UserSave')){ + if(!strcmp($request->data['aclave'],$this->User->Contrasena)){ + $Escaped = $this->DB->EscapeArray($request->data,array('nclave','nombre','correo','cargo')); + if(!strcmp($request->data['cclave'],$request->data['nclave']) && (strlen($request->data['nclave']) >= 6 )){ + $this->DB->Consulta("update usuarios set clave='{$Escaped['nclave']}', nombre='{$Escaped['nombre']}' where id = {$this->User->Uid}"); + } + else{ + $this->DB->Consulta("update usuarios set nombre='{$Escaped['nombre']}' where id = {$this->User->Uid}"); + } + $response['result'] = array(); + $response['result']['success'] = true; + } + else{ + $response['result'] = array(); + $response['result']["error"]["reason"] = "La clave ingresada es incorrecta."; + $response['result']['success'] = false; + } + } + else{ + $response['result']["success"] = false; + $response['result']["error"]["reason"] = "Método desconocido: ".$request->action.".".$request->method; + } + } + elseif(!strcmp($request->action, 'api')){ /* Acciones de la API */ + if(!strcmp($request->method, 'DirectRead')){ + $contentId = intval($request->data[0]->xid); + if($contentId > 0){ + if(!in_array($contentId,$this->Loaded)){ + $this->DB->Consulta("select contenido,tipo from contenido where id = $contentId;"); + list($code,$tipo) = $this->DB->SacaTupla(); + if($tipo == 2){ + $code = @file_get_contents( $_SERVER['DOCUMENT_ROOT'].'/BAM/js/Dazzler/'.$code , null, null, 0, 1024*500 ); + } + $code = str_replace(array("%xid%","%uid%"), array($contentId,$this->User->Uid), $code); + eval( $code ); + $this->Loaded[] = $contentId; + } + + if(function_exists ( "DirectRead" )){ + $response['result'] = DirectRead($this->DB,$request->data[0]); + + } + else{ + $response['result']["success"] = false; + $response['result']["msg"] = "DirectRead is undefined for $contentId"; + } + } + else{ + $response['result']["success"] = false; + $response['result']["msg"] = "Invalid Id:".$contentId; + } + } + elseif(!strcmp($request->method, 'DirectCreate')){ + $contentId = intval($request->data[0]->xid); + if($contentId > 0){ + + if(!in_array($contentId,$this->Loaded)){ + $this->DB->Consulta("select contenido,tipo from contenido where id = $contentId;"); + list($code,$tipo) = $this->DB->SacaTupla(); + if($tipo == 2){ + $code = @file_get_contents( $_SERVER['DOCUMENT_ROOT'].'/BAM/js/Dazzler/'.$code , null, null, 0, 1024*500 ); + } + $code = str_replace(array("%xid%","%uid%"), array($contentId,$this->User->Uid), $code); + eval( $code ); + $this->Loaded[] = $contentId; + } + + if(function_exists ( "DirectCreate" )){ + $response['result'] = DirectCreate($this->DB,$request->data[0]); + + } + else{ + $response['result']["success"] = false; + $response['result']["msg"] = "DirectCreate is undefined for $contentId"; + } + } + else{ + $response['result']["success"] = false; + $response['result']["msg"] = "Invalid Id:".$contentId; + } + } + elseif(!strcmp($request->method, 'DirectUpdate')){ + $contentId = intval($request->data[0]->xid); + if($contentId > 0){ + + if(!in_array($contentId,$this->Loaded)){ + $this->DB->Consulta("select contenido,tipo from contenido where id = $contentId;"); + list($code,$tipo) = $this->DB->SacaTupla(); + if($tipo == 2){ + $code = @file_get_contents( $_SERVER['DOCUMENT_ROOT'].'/BAM/js/Dazzler/'.$code , null, null, 0, 1024*500 ); + } + $code = str_replace(array("%xid%","%uid%"), array($contentId,$this->User->Uid), $code); + eval( $code ); + $this->Loaded[] = $contentId; + } + + if(function_exists ( "DirectUpdate" )){ + $response['result'] = DirectUpdate($this->DB,$request->data[0]); + + } + else{ + $response['result']["users"] = array(); + $response['result']["success"] = false; + $response['result']["msg"] = "DirectUpdate is undefined for $contentId"; + } + } + else{ + $response['result']["success"] = false; + $response['result']["msg"] = "Invalid Id:".$contentId; + } + } + elseif(!strcmp($request->method, 'DirectDestroy')){ + $contentId = intval($request->data[0]->xid); + if($contentId > 0){ + + if(!in_array($contentId,$this->Loaded)){ + $this->DB->Consulta("select contenido,tipo from contenido where id = $contentId;"); + list($code,$tipo) = $this->DB->SacaTupla(); + if($tipo == 2){ + $code = @file_get_contents( $_SERVER['DOCUMENT_ROOT'].'/BAM/js/Dazzler/'.$code , null, null, 0, 1024*500 ); + } + $code = str_replace(array("%xid%","%uid%"), array($contentId,$this->User->Uid), $code); + + eval( $code ); + $this->Loaded[] = $contentId; + } + + if(function_exists ( "DirectDestroy" )){ + $response['result'] = DirectDestroy($this->DB,$request->data[0]); + + } + else{ + $response['result']["success"] = false; + $response['result']["msg"] = "DirectDestroy is undefined for $contentId"; + } + } + else{ + $response['result']["success"] = false; + $response['result']["msg"] = "Invalid Id:".$contentId; + } + } + elseif(!strcmp($request->method, 'getTree')){ + $contentId = intval($request->data[0]->xid); + if($contentId > 0){ + + if(!in_array($contentId,$this->Loaded)){ + $this->DB->Consulta("select contenido,tipo from contenido where id = $contentId;"); + list($code,$tipo) = $this->DB->SacaTupla(); + if($tipo == 2){ + $code = @file_get_contents( $_SERVER['DOCUMENT_ROOT'].'/BAM/js/Dazzler/'.$code , null, null, 0, 1024*500 ); + } + eval( $code ); + $this->Loaded[] = $contentId; + } + + if(function_exists ( "getTree" )){ + $response['result'] = getTree($this->DB,$request->data[0]); + + } + else{ + $response['result']["success"] = false; + $response['result']["msg"] = "getTree is undefined for $contentId"; + } + } + else{ + $response['result']["success"] = false; + $response['result']["msg"] = "Invalid Id:".$contentId; + } + } + elseif(!strcmp($request->method, 'loadForm')){ + $contentId = intval($request->data[0]->xid); + if($contentId > 0){ + + if(!in_array($contentId,$this->Loaded)){ + $this->DB->Consulta("select contenido,tipo from contenido where id = $contentId;"); + list($code,$tipo) = $this->DB->SacaTupla(); + if($tipo == 2){ + $code = @file_get_contents( $_SERVER['DOCUMENT_ROOT'].'/BAM/js/Dazzler/'.$code , null, null, 0, 1024*500 ); + } + $code = str_replace(array("%xid%","%uid%"), array($contentId,$this->User->Uid), $code); + eval( $code ); + $this->Loaded[] = $contentId; + } + + if(function_exists ( "loadForm" )){ + $response['result'] = loadForm($this->DB,$request->data[0]); + + } + else{ + $response['result']["success"] = false; + $response['result']["msg"] = "loadForm is undefined for $contentId"; + } + } + else{ + $response['result']["success"] = false; + $response['result']["msg"] = "Invalid Id:".$contentId; + } + } + elseif(!strcmp($request->method, 'submitForm')){ + $contentId = intval($request->data['xid']); + if($contentId > 0){ + + if(!in_array($contentId,$this->Loaded)){ + $this->DB->Consulta("select contenido,tipo from contenido where id = $contentId;"); + list($code,$tipo) = $this->DB->SacaTupla(); + if($tipo == 2){ + $code = @file_get_contents( $_SERVER['DOCUMENT_ROOT'].'/BAM/js/Dazzler/'.$code , null, null, 0, 1024*500 ); + } + $code = str_replace(array("%xid%","%uid%"), array($contentId,$this->User->Uid), $code); + eval( $code ); + $this->Loaded[] = $contentId; + } + + if(function_exists ( "submitForm" )){ + $response['result'] = submitForm($this->DB,$request->data); + + } + else{ + $response['result']["success"] = false; + $response['result']["msg"] = "submitForm is undefined for $contentId"; + } + } + else{ + $response['result']["success"] = false; + $response['result']["msg"] = "Invalid Id:".$contentId; + } + } + elseif(!strcmp($request->method, 'customFn')){ + $contentId = intval($request->data[0]->xid); + if($contentId > 0){ + + if(!in_array($contentId,$this->Loaded)){ + $this->DB->Consulta("select contenido from contenido where id = $contentId;"); + list($code) = $this->DB->SacaTupla(); + if($tipo == 0){ + $code = @file_get_contents( $_SERVER['DOCUMENT_ROOT'].'/BAM/js/Dazzler/'.$code , null, null, 0, 1024*500 ); + } + $code = str_replace(array("%xid%","%uid%"), array($contentId,$this->User->Uid), $code); + eval( $code ); + $this->Loaded[] = $contentId; + } + + if(function_exists ( $request->data[0]->customFn )){ + $response['result'] = call_user_func($request->data[0]->customFn, $this->DB,$request->data[0]); + + } + else{ + $response['result']["success"] = false; + $response['result']["msg"] = "{$request->data[0]->customFn} is undefined for $contentId"; + } + } + else{ + $response['result']["success"] = false; + $response['result']["msg"] = "Invalid Id:".$contentId; + } + } + else{ + $response['result']["success"] = false; + $response['result']["error"]["reason"] = "Método desconocido: ".$request->action.".".$request->method; + } + } + else{ + $response['result']["success"] = false; + $response['result']["error"]["reason"] = "Acción desconocida: ".$request->action ; + + /* Se asume que intento acceder una RPC de usuario logueado, envia evento de logeo */ + + $event = array('type'=>'event','name'=>'lpc','data'=>'login'); + $this->addResponse($event); + } + $this->addResponse($response); + } + +} +?> diff --git a/BAM/lib/class/Usuario.inc.php b/BAM/lib/class/Usuario.inc.php new file mode 100644 index 0000000..c580386 --- /dev/null +++ b/BAM/lib/class/Usuario.inc.php @@ -0,0 +1,93 @@ +. + * +*/ + + +class Usuario{ +// Variables de Usuario del sitio + public $Uid; + +// var $Rut; + public $Login; + public $Contrasena; + + public $Nombre; + + public $Correo; + public $Cargo; + + + public $Grupos; + + public $Valido; + public $Error; + +// Conexiones a Bases de Datos + protected $DB; //Conexion de Base de datos del Objeto. + + // Crear un objeto usuario, criterios Login, Rut. + function __construct($id){ + global $conf; + $this->DB = new Db($conf->db->name, $conf->db->host, $conf->db->user, $conf->db->password, 'pg'); + + $Consulta = "select id, login, clave, nombre, correo from usuarios where id = $id"; + + $this->Valido = false; + $this->Grupos = array(); + $this->Error = ""; + + $n = $this->DB->Consulta($Consulta); + + if ($n == 1){ + // Obtiene los datos generales de la Cuenta + $Data = $this->DB->Sacatupla(); + $this->Uid = $Data["id"]; + + $this->Login = $Data["login"]; + $this->Contrasena = $Data["clave"]; + + $this->Nombre = $Data["nombre"]; + + $this->Correo = $Data["correo"]; + + $this->Cargo = $Data["cargo"]; +// $n = $this->DB->Consulta("select gid from gusuarios where uid = {$this->Uid}"); +// while($gid = $this->DB->Sacatupla()) +// $this->Grupos[] = $gid; + + $this->Valido = true; + return true; + } + else{ + $this->Vaciar(); + $this->Error = "No se encontró el usuario"; + return false; + } + } + + function Vaciar(){ + $this->Valido = false; + $this->Uid = 0; + $this->Login = ""; + $this->Contrasena = ""; + + $this->Nombre = ""; + } +} +?> diff --git a/BAM/lib/class/XmlReply.inc.php b/BAM/lib/class/XmlReply.inc.php new file mode 100644 index 0000000..218ffe9 --- /dev/null +++ b/BAM/lib/class/XmlReply.inc.php @@ -0,0 +1,433 @@ +. + * +*/ + +require_once $_SERVER['DOCUMENT_ROOT'].'/BAM/lib/class/Db.inc.php'; + +class XmlReply{ + + public $xmlIn; + public $xmlOut; + public $xmlAcc; + + + public $hInfo; + public $pInfo; + + public $Valido; + + public $strReq; + public $debugXml; + public $debug; + + protected $DB; + function __construct(){ + global $conf; + $this->DB = new Db($conf->db->name, $conf->db->host, $conf->db->user, $conf->db->password, 'pg'); + $this->debug = true; + $this->initXmlOut(); + } + + function loadXml($rawdata){ + + $this->xmlIn = simplexml_load_string($rawdata); + if(!$this->xmlIn){ + $this->addError('Invalid RPC, see http://boinc.berkeley.edu/trac/wiki/AccountManagement for details.'); + return false; + } + else{ + $this->strReq = $rawdata; + return true; + } + } + + function initXmlOut(){ + global $conf; + $this->xmlOut = new DOMDocument('1.0', 'utf-8'); + $this->xmlOut->formatOutput = true; + + $this->xmlAcc = $this->xmlOut->createElement('acct_mgr_reply'); + $this->xmlOut->appendChild($this->xmlAcc); + + $element = $this->xmlOut->createElement('name',$conf->account_manager->name); + $this->xmlAcc->appendChild($element); + + $element = $this->xmlOut->createElement('version',"0.1"); + $this->xmlAcc->appendChild($element); + + $element = $this->xmlOut->createElement('signing_key',$conf->account_manager->public_signature); + $this->xmlAcc->appendChild($element); + + /* add some random delay to te request */ + list($u, $s) = explode(' ',microtime()); + $repeatSec = $conf->account_manager->repeat_sec + round(900 * $u) - 450; //+- 15 min + + $element = $this->xmlOut->createElement("repeat_sec",$repeatSec); + $this->xmlAcc->appendChild($element); + + if($this->debug){ + $this->debugXml = $this->xmlOut->createElement("debug"); + $this->xmlAcc->appendChild($this->debugXml); + } + } + + function checkHost(){ + + /* **************************** gather host info ************************************ */ + + $now = time(); + $cpid = $this->DB->EscapeString($this->xmlIn->host_cpid); + $lcpid = $this->DB->EscapeString($this->xmlIn->previous_host_cpid); + + $flops = round(floatval($this->xmlIn->host_info->p_fpops)/1000000.0); + $mips = round(floatval($this->xmlIn->host_info->p_iops)/1000000.0); + + if (!empty($this->xmlIn->host_info->ip_addr)){ + $ip = ip2long($this->xmlIn->host_info->ip_addr); + }else{ + $ip = ip2long($_SERVER["REMOTE_ADDR"]); + } + + if (!empty($this->xmlIn->host_info->domain_name)){ + $name = $this->DB->EscapeString($this->xmlIn->host_info->domain_name); + }else{ + $name = $this->DB->EscapeString($this->xmlIn->domain_name); + } + + if (!empty($this->xmlIn->host_info->p_ncpus)){ + $cpus = intval($this->xmlIn->host_info->p_ncpus); + }else{ + $cpus = 1; + } + + $ereq = $this->DB->EscapeString($this->strReq); + + /* **************************** get DB host info ************************************ */ + $dazzlerId = intval($this->xmlIn->opaque->dazzlerid); + if($dazzlerId > 0){ + $hValid = $this->DB->Consulta("select hosts.id, gid, uid, mod_time, start_hour, end_hour ,cpu_usage_limit, run_if_user_active, idle_time_to_run,hits,last_contact from (hosts left join groups on (groups.id = hosts.gid)) where hosts.id=$dazzlerId;"); + if($hValid){ + $this->hInfo = $this->DB->SacaTupla(); + } + } + + if(!$dazzlerId || !$hValid){ + $hValid = $this->DB->Consulta("select hosts.id, gid, uid, mod_time, start_hour, end_hour ,cpu_usage_limit, run_if_user_active, idle_time_to_run,hits,last_contact from (hosts left join groups on (groups.id = hosts.gid)) where cpid='$cpid';"); + if($hValid){ + $this->hInfo = $this->DB->SacaTupla(); + } + } + + if(!$hValid && strcmp($lcpid,$cpid)){ + $hValid = $this->DB->Consulta("select hosts.id, gid, uid, mod_time, start_hour, end_hour ,cpu_usage_limit, run_if_user_active, idle_time_to_run,hits,last_contact from (hosts left join groups on (groups.id = hosts.gid)) where cpid='$lcpid';"); + if($hValid){ + $this->hInfo = $this->DB->SacaTupla(); + } + } + + + if(!$hValid){ + /* **************************** host doesn't exist, create an entry for it ************************************ */ + + + /* **************************** search for user ************************************ */ + $uValid = 0; + /* Try Weak Authentifier first */ + + if(!strpos($this->xmlIn->name,"_") === false){ + + list($weakId, $weakHash) = explode("_", $this->xmlIn->name,2); + + $weakId = intval($weakId); + $weakHash = $this->DB->EscapeString($weakHash); + + $uValid = $this->DB->Consulta("select users.id,group_default,correo from (usuarios left join users on (usuarios.id = users.id)) where users.id=$weakId and users.weakhash='$weakHash';"); + if($uValid == 1){ + list($uId, $defaultGroup, $correo) = $this->DB->SacaTupla(); + } + } + + /* if not authentified, try something else */ + if($uValid != 1){ + $userName = $this->DB->EscapeString($this->xmlIn->name); + $passwordHash = $this->DB->EscapeString($this->xmlIn->password_hash); + + $uValid = $this->DB->Consulta("select users.id,group_default,correo from (usuarios left join users on (usuarios.id = users.id)) where login='$userName' and md5(clave)='$passwordHash';"); + if($uValid != 1){ + global $conf; + $uId = $conf->conf->adminUid; + $defaultGroup = $conf->conf->defaultGroup; + $correo = 'noemail@foo.bar'; + } + else{ + /* **************************** user valid, check for host ************************************ */ + list($uId, $defaultGroup, $correo) = $this->DB->SacaTupla(); + } + } + + $xcpid = $this->DB->EscapeString(md5($this->xmlIn->host_cpid.$correo)); + /* **************************** create host info ************************************ */ + $this->DB->Consulta("select nextval('hosts_id_seq'::regclass);"); + list($nextid) = $this->DB->SacaTupla(); + + $this->DB->Consulta("insert into hosts(id,gid,name,cpus,mips,flops,ipaddr,cpid,xcpid,first_contact,last_contact,last_request,hits) Values($nextid,$defaultGroup,'$name',$cpus,$mips,$flops,$ip,'$cpid','$xcpid',$now,$now,'$ereq',1);"); + + $hValid = $this->DB->Consulta("select hosts.id, gid, uid, mod_time, start_hour, end_hour ,cpu_usage_limit, run_if_user_active, idle_time_to_run,hits,last_contact from (hosts left join groups on (groups.id = hosts.gid)) where hosts.id=$nextid;"); + $this->hInfo = $this->DB->SacaTupla(); + + } + else{ + /* **************************** update host info ************************************ */ + + if(strcmp($lcpid,$cpid)){/* cpid updated */ + $this->DB->Consulta("select correo from usuarios where id = (select uid from groups where id = {$this->hInfo['gid']});"); + list ( $correo ) = $this->DB->SacaTupla(); + $xcpid = $this->DB->EscapeString(md5($this->xmlIn->host_cpid.$correo)); + + $this->DB->Consulta("update hosts set name='$name',cpus=$cpus,mips=$mips,flops=$flops,ipaddr=$ip,cpid='$cpid',xcpid='$xcpid',last_contact=$now,last_request='$ereq',hits=hits+1 where id={$this->hInfo['id']};"); + } + else{ + $this->DB->Consulta("update hosts set name='$name',cpus=$cpus,mips=$mips,flops=$flops,ipaddr=$ip,last_contact=$now,last_request='$ereq',hits=hits+1 where id={$this->hInfo['id']};"); + } + } + + /* **************************** get client version ************************************ */ + list($mayor, $minor, $none) = explode('.',$this->xmlIn->client_version,3); + $this->hInfo['client_version'] = intval($mayor)*100+intval($minor); + + /* **************************** get project information for the group/host ************************************ */ + $this->pInfo = array(); + + $this->DB->Consulta("select * from configprojects left join (select * from myprojects where uid = {$this->hInfo['uid']}) as my on (configprojects.pid = my.id) where gid = {$this->hInfo['gid']} and authenticator notnull;"); + while($projData = $this->DB->SacaTupla()){ + $this->pInfo[$projData['url']] = $projData; + } + + $this->addMsg("hId: ".$this->hInfo['id']); + $this->addMsg("Contactos: ".$this->hInfo['hits']); + + $this->addDebug("uId: ".$this->hInfo['uid']); + $this->addDebug("gId: ".$this->hInfo['gid']); + $this->addDebug("hId: ".$this->hInfo['id']); + + $this->addDebug("mtime: ".$this->hInfo['mod_time']); + $this->addDebug("proj: ".count($this->pInfo)); + + } + + function addPreferences(){ + + $mod_time = intval ($this->xmlIn->global_preferences->mod_time); + if($mod_time < $this->hInfo['mod_time']){ + global $conf; + + $global_preferences = $this->xmlOut->createElement('global_preferences'); + $this->xmlAcc->appendChild($global_preferences); + + /* ************* group defined preferences ********** */ + $userDefined = array('mod_time','run_if_user_active','idle_time_to_run','cpu_usage_limit','start_hour','end_hour'); + foreach($userDefined as $pref){ + $element = $this->xmlOut->createElement($pref,$this->hInfo[$pref]); + $global_preferences->appendChild($element); + } + + /* ************* fixed preferences ********** */ + $element = $this->xmlOut->createElement('host_specific'); + $global_preferences->appendChild($element); + + $element = $this->xmlOut->createElement('source_project',$conf->account_manager->master_url); + $global_preferences->appendChild($element); + + //general + $element = $this->xmlOut->createElement('cpu_scheduling_period_minutes',$conf->base_preferences->cpu_scheduling_period_minutes); + $global_preferences->appendChild($element); + $element = $this->xmlOut->createElement('max_cpus',$conf->base_preferences->max_cpus); + $global_preferences->appendChild($element); + $element = $this->xmlOut->createElement('run_on_batteries',$conf->base_preferences->run_on_batteries); + $global_preferences->appendChild($element); + $element = $this->xmlOut->createElement('work_buf_min_days',$conf->base_preferences->work_buf_min_days); + $global_preferences->appendChild($element); + + //resources + $element = $this->xmlOut->createElement('ram_max_used_busy_pct',$conf->base_preferences->ram_max_used_busy_pct); + $global_preferences->appendChild($element); + $element = $this->xmlOut->createElement('ram_max_used_idle_pct',$conf->base_preferences->ram_max_used_idle_pct); + $global_preferences->appendChild($element); + $element = $this->xmlOut->createElement('max_bytes_sec_up',$conf->base_preferences->max_bytes_sec_up); + $global_preferences->appendChild($element); + $element = $this->xmlOut->createElement('max_bytes_sec_down',$conf->base_preferences->max_bytes_sec_down); + $global_preferences->appendChild($element); + $element = $this->xmlOut->createElement('net_start_hour',$conf->base_preferences->net_start_hour); + $global_preferences->appendChild($element); + $element = $this->xmlOut->createElement('net_end_hour',$conf->base_preferences->net_end_hour); + $global_preferences->appendChild($element); + $element = $this->xmlOut->createElement('vm_max_used_pct',$conf->base_preferences->vm_max_used_pct); + $global_preferences->appendChild($element); + $element = $this->xmlOut->createElement('disk_max_used_gb',$conf->base_preferences->disk_max_used_gb); + $global_preferences->appendChild($element); + $element = $this->xmlOut->createElement('disk_min_free_gb',$conf->base_preferences->disk_min_free_gb); + $global_preferences->appendChild($element); + + $element = $this->xmlOut->createElement('leave_apps_in_memory',$conf->base_preferences->leave_apps_in_memory); + $global_preferences->appendChild($element); + $element = $this->xmlOut->createElement('confirm_before_connecting',$conf->base_preferences->confirm_before_connecting); + $global_preferences->appendChild($element); + $element = $this->xmlOut->createElement('hangup_if_dialed',$conf->base_preferences->hangup_if_dialed); + $global_preferences->appendChild($element); + $element = $this->xmlOut->createElement('disk_interval',$conf->base_preferences->disk_interval); + $global_preferences->appendChild($element); + } + } + + function addProjects($fullSync = false){ + $toDeletion = array(); + + + foreach($this->xmlIn->project as $ProjIn){ + + $Url = strval($ProjIn->url); + + if(empty($Url)) + continue; + + $this->addDebug("ProjIn: ".$Url); + /* Project is in current project list */ + if (!empty($this->pInfo[$Url])){ + + if(!empty($this->pInfo[$Url]['weak']) && ($this->hInfo['client_version'] > 612)){ + $this->pInfo[$Url]['authenticator'] = $this->pInfo[$Url]['weak']; + } + + /* check if project parameters are OK */ + $projectSync = true; + + /* marked for deletion */ + if((($this->pInfo[$Url]['detach_when_done'] > 0) || ($this->pInfo[$Url]['estado'] == 2)) xor ($ProjIn->detach_when_done > 0)){ + $projectSync = false; + } + + /* project paused */ + if((($this->pInfo[$Url]['suspend'] > 0) || ($this->pInfo[$Url]['estado'] == 1)) xor ($ProjIn->suspend > 0)){ + $projectSync = false; + } + + if(!$projectSync){ + $this->addDebug("attNoSync: ".$Url); + $this->addProject($this->pInfo[$Url]); + } + else{ + /* project updated */ + if($this->pInfo[$Url]['mod_time'] > $this->hInfo['last_contact']){ + + $diff = $this->pInfo[$Url]['mod_time'] - $this->hInfo['last_contact']; + $this->addDebug("attUpd:[$diff] ".$Url); + + $this->addProject($this->pInfo[$Url]); + } + else{ + $this->addDebug("attSync: ".$Url); + } + } + + unset ( $this->pInfo[$Url] ); + } + else{ + $toDeletion[$Url] = strval($ProjIn->account_key); + } + } + + /* Attach to project if it isn't marked for detach */ + foreach($this->pInfo as $url => $ProjIn){ + $this->addDebug("noAtt: ".$url); + if(($ProjIn['detach_when_done'] == 0) && ($ProjIn['estado'] < 2)){ + $this->addProject( $ProjIn ); + } + } + + /* Forcefull detach */ + if(!empty($toDeletion)){ + foreach($toDeletion as $url => $auth){ + $eurl = $this->DB->EscapeString($url); + $exist = $this->DB->Consulta("select url_signature from projects where estado < 10 and url='$eurl';"); + if($exist){ + list( $sig ) = $this->DB->SacaTupla(); + $projDel = array(); + $projDel['url'] = $url; + $projDel['url_signature'] = $sig; + $projDel['authenticator'] = $auth; + $projDel['dont_request_more_work'] = 1; + $projDel['abort_not_started'] = 1; + $projDel['detach_when_done'] = 1; + $this->addProject($projDel); + $this->addDebug("ForceDetach: ".$url); + } + else{ + /* unknown project, add to project list to create signature */ + $eauth = $this->DB->EscapeString($auth); + $this->DB->Consulta("insert into projects (nombre,url,url_signature,uid,estado) values('$eurl','$eurl','$eauth',{$conf->conf->adminUid},10);"); + $this->addDebug("unkProj: ".$url); + } + } + } + } + + function addProject($projectArray){ + if(!isset($projectArray['url'])) + return false; + if(!isset($projectArray['url_signature'])) + return false; + + $account = $this->xmlOut->createElement('account'); + $this->xmlAcc->appendChild($account); + + $elementos = array('url','url_signature','authenticator','resource_share','suspend','detach_when_done','dont_request_more_work','abort_not_started','detach'); + + foreach($elementos as $elemento){ + if(isset($projectArray[$elemento])){ + $element = $this->xmlOut->createElement($elemento,$projectArray[$elemento]); + $account->appendChild($element); + } + } + return true; + } + + function addOpaque(){ + $opaque = $this->xmlOut->createElement('opaque'); + $this->xmlAcc->appendChild($opaque); + + $hostid = $this->xmlOut->createElement('dazzlerid',$this->hInfo['id']); + $opaque->appendChild($hostid); + } + function addError($msg = ""){ + $this->addMsg("Error: ".$msg); + } + function addDebug($msg = ""){ + $element = $this->xmlOut->createElement('message', $msg); + $this->debugXml->appendChild($element); + } + function addMsg($msg = ""){ + $element = $this->xmlOut->createElement('message', $msg); + $this->xmlAcc->appendChild($element); + } + function getXml(){ + return $this->xmlOut->saveXML(); + } + +} +?> diff --git a/BAM/lib/class/XmlRequest.inc.php b/BAM/lib/class/XmlRequest.inc.php new file mode 100644 index 0000000..bb29b8d --- /dev/null +++ b/BAM/lib/class/XmlRequest.inc.php @@ -0,0 +1,254 @@ +. + * +*/ + +//require_once $_SERVER['DOCUMENT_ROOT'].'/BAM/lib/class/Db.inc.php'; + +class XmlRequest{ + + public $ProjectId; + public $ProjectUrl; + public $XmlUrl; + + public $ProjectData; + public $ProjectConfig; + + + public $hInfo; + public $pInfo; + + public $Valido; + public $Online; + public $ErrNum; + + public $Msg; + public $Timestamp; + public $Error; + + protected $DB; + function __construct(){ + global $conf; + $this->DB = new Db($conf->db->name, $conf->db->host, $conf->db->user, $conf->db->password, 'pg'); + +//- $this->DB->MostrarConsultas = 1; + $this->ProjectId = 0; + $this->ProjectUrl = ''; + $this->Valido = false; + $this->Online = false; + $this->Msg = array(); + $this->timeStamp = time(); + $this->dayStamp = intval($this->timeStamp/86400); //- days since unix epoch! + } + + function currentRAC($avg, $avg_time){ //- push avg to current timestamp +//- static $M_LN2 = 0.693147180559945309417; +//- static $credit_half_life = 86400 * 7; + + $diff = $avg_time - $this->timeStamp; + if($diff > 0) $diff = 0; + $avg *= exp($diff * 1.146076687e-6 ); + + return round($avg); + } + function setProject($Id){ + $this->Online = false; + $this->Valido = false; + $Id = intval($Id); + $n = $this->DB->Consulta("select id,url from projects where id = $Id;"); + if($n == 1){ + list( $this->ProjectId, $this->ProjectUrl ) = $this->DB->SacaTupla(); + $this->Valido = true; + $this->ProjectConfig = simplexml_load_string( file_get_contents( $this->ProjectUrl.'get_project_config.php' ) ); + + if(!$this->ProjectConfig){/* Html / Xml error... project down ?*/ + $this->Msg[] = $this->Error = "[Project Config] Respuesta del proyecto '{$this->ProjectUrl}' invalida."; + $this->ErrNum = -1; + } +// else if(!empty($this->ProjectConfig->client_account_creation_disabled) || !empty($this->ProjectConfig->account_creation_disabled)){ +// $this->Msg[] = "El proyecto '{$this->ProjectUrl}' no permite la creacion de cuentas."; +// } + else if(!empty($this->ProjectConfig->account_manager)){/* not a project ?*/ + $this->Msg[] = $this->Error = "[Project Config] La dirección '{$this->ProjectUrl}' no contiene un proyecto BOINC."; + $this->ErrNum = -2; + } + else if(!empty($this->ProjectConfig->error_num)){/* Project has problems ?*/ + $this->Msg[] = $this->Error = "[Project Config] El proyecto '{$this->ProjectUrl}' dio el error {$projectConfig->error_num}."; + $this->ErrNum = $this->ProjectConfig->error_num; + } + else{/* No problem, can continue */ + if(!empty($this->ProjectConfig->rpc_prefix)) + $this->XmlUrl = $this->ProjectConfig->rpc_prefix; + else + $this->XmlUrl = $this->ProjectUrl; + + $this->Online = true; + $this->ErrNum = 0; + } + } + else{ + $this->ProjectId = 0; + $this->ProjectUrl = ''; + $this->Valido = false; + $this->Online = false; + } + } + + function getStats(){ /* User/Host Statistic retrieval */ + if(!$this->Online) + return 1; + + $users = array();/* get all users with account in this project */ + $this->DB->Consulta("select uid, authenticator, opaque from authenticators where authenticator notnull and pid = {$this->ProjectId}; "); + while($temp = $this->DB->SacaTupla()) + $users[$temp['uid']] = $temp; + + $lastweek = $this->timeStamp - 7 * 86400; + foreach($users as $uid => $user){ + + $hosts = array(); + $groups = array(); /* get all active host of the user */ + $this->DB->Consulta("select id,gid,xcpid,cpus,mips,flops from hosts where last_contact > $lastweek and gid in (select id from groups where uid = $uid);"); + while($temp = $this->DB->SacaTupla()){ + $hosts[$temp['xcpid']] = $temp; + $groups[] = $temp['gid']; + } + $groups = array_unique($groups); + + $gCount = 0; + foreach($groups as $gid){/* check if there is a "active" host in this project */ + $n = $this->DB->Consulta("select id from statistics where dia={$this->dayStamp} and gid=$gid and pid={$this->ProjectId};"); + if($n == 0) + $gCount++; + } + + if($gCount){ + if(!empty($user['opaque'])) + $Query = '?auth=' . urlencode($user['authenticator']). '&opaque_auth=' . urlencode($user['opaque']).'&format=xml'; + else + $Query = '?auth=' . urlencode($user['authenticator']). '&format=xml'; + + $projectResponse = simplexml_load_string( file_get_contents( $this->XmlUrl.'/show_user.php'.$Query ) ); + + if(!$projectResponse){ + $this->Msg[] = "[getStats] Respuesta del proyecto '{$this->ProjectUrl}' invalida."; + } + else if(!empty($projectResponse->error_num)){ + $this->Msg[] = "[getStats] El proyecto '{$this->ProjectUrl}' dio el error {$projectResponse->error_num}."; + } + else{/* parse stat response */ + $statInfo = array(); + + foreach($projectResponse->host as $rHost){ + $host_cpid = strval($rHost->host_cpid); + $hGroup = intval($hosts[$host_cpid]['gid']); + + if($hGroup == 0) //-host is not active + continue; + $totalCredit = round($rHost->total_credit); + $expavgCredit = floatval($rHost->expavg_credit); + $expavgTime = floatval($rHost->expavg_time); + + $avg = $this->currentRAC($expavgCredit, $expavgTime); + + $statInfo[$hGroup]['expavg_credit'] += $avg; + $statInfo[$hGroup]['total_credit'] += $totalCredit; + + $statInfo[$hGroup]['hosts'] += 1; + $statInfo[$hGroup]['cpus'] += $hosts[$host_cpid]['cpus']; + $statInfo[$hGroup]['mips'] += $hosts[$host_cpid]['cpus']*$hosts[$host_cpid]['mips']; + $statInfo[$hGroup]['flops'] += $hosts[$host_cpid]['cpus']*$hosts[$host_cpid]['flops']; + } + foreach($statInfo as $gid => $stat){ + $this->DB->Consulta("insert into statistics(dia,gid,pid,hosts,cpus,mips,flops,total_credit,expavg_credit,expavg_time) values({$this->dayStamp},$gid, {$this->ProjectId},{$stat['hosts']},{$stat['cpus']},{$stat['mips']},{$stat['flops']},{$stat['total_credit']},{$stat['expavg_credit']},{$this->timeStamp});"); + } + } + } + } + } + function createAccounts(){ /* Project Account Creation */ + if(!$this->Online) + return 1; + + $Users = array(); + $this->DB->Consulta("select uid, nombre, correo, weakhash from (authenticators left join users on (authenticators.uid = users.id) left join usuarios on (authenticators.uid = usuarios.id)) where authenticator isnull and authenticators.pid = {$this->ProjectId}; "); + while($info = $this->DB->SacaTupla()) + $Users[$info['uid']] = $info; + + foreach($Users as $Uid => $User){ + $Query = '?email_addr=' . urlencode($User['correo']) . '&passwd_hash=' . urlencode($User['weakhash']). '&user_name=' . urlencode($User['nombre']); + $projectResponse = simplexml_load_string( file_get_contents( $this->XmlUrl.'/create_account.php'.$Query ) ); + + if(!$projectResponse){ + $this->Msg[] = "[Create User] Respuesta del proyecto '{$this->ProjectUrl}' invalida."; + } + else if(!empty($projectResponse->error_num)){ + $this->Msg[] = "[Create User] El proyecto '{$this->ProjectUrl}' dio el error {$projectResponse->error_num}."; + } + else{ + $Auth = $DB->EscapeString($projectResponse->authenticator); + + if(!empty($projectResponse->opaque_auth)){ + $Opaque = $DB->EscapeString($projectResponse->opaque_auth); + $Query = '?account_key=' . urlencode($projectResponse->authenticator) . '&opaque_auth=' . urlencode($projectResponse->opaque_auth); + } + else{ + $Opaque = ''; + $Query = '?account_key=' . urlencode($projectResponse->authenticator); + } + + $projectResponse = simplexml_load_string( file_get_contents( $this->XmlUrl.'/am_get_info.php'.$Query ) ); + + if(!$projectResponse){ + $this->Msg[] = "[Get Weak] Respuesta del proyecto '{$this->ProjectUrl}' invalida."; + $Weak = ''; + } + else if(!empty($projectResponse->error_num)){ + $this->Msg[] = "[Get Weak] El proyecto '{$this->ProjectUrl}' dio el error {$projectResponse->error_num}."; + $Weak = ''; + } + elseif(!empty($projectResponse->weak_auth)){ + $Weak = $DB->EscapeString($projectResponse->weak_auth); + } + else{ + $Weak = ''; + } + + $this->DB->Consulta("update authenticators set authenticator='$Auth', opaque='$Opaque', weak='$Weak' where pid={$this->ProjectId} and uid=$Uid; "); + } + } + + return 0; + } + /* delete project awaiting for detach */ + function deleteDetaching(){ + if(!$this->Valid) + return 1; + + $this->DB->Consulta("delete from configprojects where pid = {$this->ProjectId} and detach_when_done>0 and detach_when_done<{$this->timeStamp};"); + } + + function saveStatus(){ + if(!$this->Valid) + return 1; + + $this->DB->Consulta("update projects set status={$this->ErrNum} where id = {$this->ProjectId};"); + } + } + +?> diff --git a/BAM/lib/db_base.sql b/BAM/lib/db_base.sql new file mode 100644 index 0000000..4d05a59 --- /dev/null +++ b/BAM/lib/db_base.sql @@ -0,0 +1,115 @@ +CREATE TABLE contenido ( + id BIGSERIAL PRIMARY KEY , + pid BIGINT NOT NULL, + pos SMALLINT, + tipo SMALLINT, + hijos SMALLINT DEFAULT 0, + nombre VARCHAR(50), + icon VARCHAR(32), + contenido TEXT, + FOREIGN KEY (pid) REFERENCES contenido(id) ON DELETE CASCADE ON UPDATE CASCADE +) ; + +CREATE TABLE usuarios ( + id BIGSERIAL PRIMARY KEY , + login VARCHAR(50) not null unique, + clave VARCHAR(50) not null, + sesion BIGINT default null, + + activo smallint default 1, + + nombre VARCHAR(50), + correo VARCHAR(50) +) ; + +CREATE TABLE sesiones ( + id BIGSERIAL PRIMARY KEY , + inicio BIGINT not null, + fin BIGINT not null, + usuario BIGINT not null, + + estado SMALLINT default 0, + + ip INTEGER, + useragent VARCHAR(200), + so SMALLINT, + navegador SMALLINT, + pais SMALLINT, + p INTEGER, + w SMALLINT +) ; + + +CREATE TABLE grupos ( + id BIGSERIAL PRIMARY KEY , + nombre VARCHAR(50) + +) ; + +CREATE TABLE gcontenido ( + gid BIGINT not null, + cid BIGINT not null, + + PRIMARY KEY(gid,cid), + + FOREIGN KEY (gid) REFERENCES grupos(id) ON DELETE CASCADE ON UPDATE CASCADE, + FOREIGN KEY (cid) REFERENCES contenido(id) ON DELETE CASCADE ON UPDATE CASCADE +) ; + +CREATE TABLE gusuarios ( + gid BIGINT not null, + uid BIGINT not null, + + PRIMARY KEY(gid,uid), + + FOREIGN KEY (gid) REFERENCES grupos(id) ON DELETE CASCADE ON UPDATE CASCADE, + FOREIGN KEY (uid) REFERENCES usuarios(id) ON DELETE CASCADE ON UPDATE CASCADE +) ; + +-- sequencias +ALTER SEQUENCE contenido_id_seq INCREMENT 1 MINVALUE 1 MAXVALUE 9223372036854775807 RESTART 1001 CACHE 1 NO CYCLE; +ALTER SEQUENCE usuarios_id_seq INCREMENT 1 MINVALUE 1 MAXVALUE 9223372036854775807 RESTART 1001 CACHE 1 NO CYCLE; +ALTER SEQUENCE grupos_id_seq INCREMENT 1 MINVALUE 1 MAXVALUE 9223372036854775807 RESTART 1001 CACHE 1 NO CYCLE; + +-- system base +insert into contenido(id,pid,pos,tipo,nombre,icon,contenido) values(1,1,0,0,'app-root','folder',''); + + +-- grupos +--insert into grupos(id,nombre) values(1,'User Admin'); +--insert into grupos(id,nombre) values(2,'Web Admin'); +--insert into grupos(id,nombre) values(3,'Group Admin'); +--insert into grupos(id,nombre) values(10,'Basic User'); + + +-- App Admin +--insert into contenido(id,pid,pos,tipo,nombre,hijos,icon,contenido) values(10,1,1,0,'Administracion del sistema',1,'folder',''); +--insert into gcontenido(gid,cid) values(1,10); +--insert into gcontenido(gid,cid) values(2,10); +--insert into gcontenido(gid,cid) values(3,10); + +--insert into contenido(id,pid,pos,tipo,nombre,icon,contenido) values(11,10,1,2,'Usuarios','user','Dazzler.admin.user.js'); +--insert into gcontenido(gid,cid) values(1,11); + +--insert into contenido(id,pid,pos,tipo,nombre,icon,contenido) values(12,10,2,2,'Aplicacion','application_edit','Dazzler.admin.content.js'); +--insert into gcontenido(gid,cid) values(2,12); + +--insert into contenido(id,pid,pos,tipo,nombre,icon,contenido) values(13,10,3,2,'Grupos','application_edit','Dazzler.admin.group.js'); +--insert into gcontenido(gid,cid) values(3,13); + + +-- Admin user +--insert into usuarios(id,login,clave,activo,nombre,correo) values(100,'admin','webadmin',1,'Admin Account','root@localhost'); +-- Permisos Admin +--insert into gusuarios(gid,uid) values(1,100); +--insert into gusuarios(gid,uid) values(2,100); +--insert into gusuarios(gid,uid) values(3,100); +--insert into gusuarios(gid,uid) values(10,100); + +-- Basic User +--insert into usuarios(id,login,clave,activo,nombre,correo) values(101,'user','pass',1,'User Account','user@localhost'); +-- Permisos basicos +--insert into gusuarios(gid,uid) values(10,101); + + + diff --git a/BAM/lib/db_dazzler.sql b/BAM/lib/db_dazzler.sql new file mode 100644 index 0000000..1693d47 --- /dev/null +++ b/BAM/lib/db_dazzler.sql @@ -0,0 +1 @@ +---------DB DAZZLER------------ CREATE TABLE users ( -- acct_mgr_login id BIGINT PRIMARY KEY, weakhash varchar, -- random password for weak auth AcctManager (not Dazzler) group_default BIGINT, tipo integer, FOREIGN KEY (id) REFERENCES usuarios(id) ON DELETE CASCADE ON UPDATE CASCADE ); CREATE TABLE projects ( id BIGSERIAL PRIMARY KEY, uid BIGINT, name VARCHAR not null, url VARCHAR not null, url_signature VARCHAR not null, estado INTEGER, UNIQUE (url), FOREIGN KEY (uid) REFERENCES users(id) ON DELETE RESTRICT ON UPDATE CASCADE ); CREATE TABLE authenticators ( uid BIGINT not null, pid BIGINT not null, weak varchar, authenticator varchar, opaque varchar, FOREIGN KEY (pid) REFERENCES projects(id) ON DELETE RESTRICT ON UPDATE CASCADE , FOREIGN KEY (uid) REFERENCES users(id) ON DELETE RESTRICT ON UPDATE CASCADE , PRIMARY KEY (uid,pid) ); CREATE VIEW myprojects (authenticator, weak, uid, id, name, url, url_signature, estado) AS SELECT authenticator, weak, authenticators.uid, id, name, url, url_signature, estado FROM (authenticators LEFT JOIN projects ON (authenticators.pid = projects.id)); CREATE TABLE groups ( id BIGSERIAL PRIMARY KEY , uid BIGINT, name VARCHAR not null , info VARCHAR not null , -- Confuiguracion de preferencias del grupo mod_time INT DEFAULT '0' , -- 0 allways run start_hour float not null DEFAULT '0.00' , end_hour float not null DEFAULT '0.00' , cpu_usage_limit INT not null DEFAULT '100' , run_if_user_active smallint not null default 1, idle_time_to_run INT not null DEFAULT 1 ,--trabaja despues de un minuto de inactiv FOREIGN KEY (uid) REFERENCES users(id) ON DELETE RESTRICT ON UPDATE CASCADE ); CREATE TABLE hosts ( id BIGSERIAL PRIMARY KEY , gid BIGINT not null , name varchar, -- informacion de identificacion adicional. cpid char(32) not null , xcpid char(32) not null , -- informacion con fines estadisticos cpus integer, mips integer, flops integer, ipaddr integer, -- informacion de contactos hits BIGINT DEFAULT 1, first_contact int not null , last_contact int not null , last_request varchar , UNIQUE (cpid), FOREIGN KEY (gid) REFERENCES groups(id) ON DELETE RESTRICT ON UPDATE CASCADE ); CREATE TABLE configprojects ( pid BIGINT not null , gid BIGINT not null , resource_share INTEGER DEFAULT 100 , suspend INTEGER DEFAULT 0 , detach_when_done INTEGER not null DEFAULT 0, mod_time INTEGER DEFAULT 0 , FOREIGN KEY (pid) REFERENCES projects(id) ON DELETE RESTRICT ON UPDATE CASCADE , FOREIGN KEY (gid) REFERENCES groups(id) ON DELETE CASCADE ON UPDATE CASCADE , PRIMARY KEY (pid,gid) ); CREATE TABLE statistics ( id BIGSERIAL PRIMARY KEY , pid BIGINT not null , gid BIGINT not null , dia INTEGER not null, --datos estaditicos hosts INTEGER, cpus INTEGER, mips INTEGER, flops INTEGER, --datos estaditicos total_credit BIGINT, expavg_credit BIGINT, expavg_time BIGINT, -- indices UNIQUE (dia,pid,gid) ); -- sequencias ALTER SEQUENCE contenido_id_seq INCREMENT 1 MINVALUE 1 MAXVALUE 9223372036854775807 RESTART 1101 CACHE 1 NO CYCLE; ALTER SEQUENCE usuarios_id_seq INCREMENT 1 MINVALUE 1 MAXVALUE 9223372036854775807 RESTART 1002 CACHE 1 NO CYCLE; ALTER SEQUENCE grupos_id_seq INCREMENT 1 MINVALUE 1 MAXVALUE 9223372036854775807 RESTART 1004 CACHE 1 NO CYCLE; ALTER SEQUENCE groups_id_seq INCREMENT 1 MINVALUE 1 MAXVALUE 9223372036854775807 RESTART 3 CACHE 1 NO CYCLE; -- Grupos / Categorias insert into grupos(id,nombre) values(1001,'SCV Manager'); insert into grupos(id,nombre) values(1002,'SCV Provider'); insert into grupos(id,nombre) values(1003,'SCV Researcher'); -- Sitio insert into contenido(id,pid,pos,tipo,nombre,icon,contenido) values(1000,1,2,2,'SCV','application_home','Dazzler.apphome.js'); insert into gcontenido(gid,cid) values(1001,1000); insert into gcontenido(gid,cid) values(1002,1000); insert into gcontenido(gid,cid) values(1003,1000); insert into contenido(id,pid,pos,tipo,nombre,hijos,icon,contenido) values(1001,1,3,0,'Manager',1,'folder',''); insert into gcontenido(gid,cid) values(1001,1001); insert into contenido(id,pid,pos,tipo,nombre,hijos,icon,contenido) values(1002,1,4,0,'Proveedor',1,'folder',''); insert into gcontenido(gid,cid) values(1002,1002); insert into contenido(id,pid,pos,tipo,nombre,hijos,icon,contenido) values(1003,1,5,0,'Investigador',1,'folder',''); insert into gcontenido(gid,cid) values(1003,1003); insert into contenido(id,pid,pos,tipo,nombre,icon,contenido) values(1010,1001,0,2,'Usuarios','user_earth','Dazzler.manager.users.js'); insert into gcontenido(gid,cid) values(1001,1010); insert into contenido(id,pid,pos,tipo,nombre,icon,contenido) values(1011,1001,1,2,'Proyectos','world','Dazzler.manager.projects.js'); insert into gcontenido(gid,cid) values(1001,1011); insert into contenido(id,pid,pos,tipo,nombre,icon,contenido) values(1012,1001,2,2,'Hosts','computer_wrench','Dazzler.manager.hosts.js'); insert into gcontenido(gid,cid) values(1001,1012); insert into contenido(id,pid,pos,tipo,nombre,icon,contenido) values(1020,1002,0,2,'Resumen','table','Dazzler.proveedor.resumen.js'); insert into gcontenido(gid,cid) values(1002,1020); insert into contenido(id,pid,pos,tipo,nombre,icon,contenido) values(1021,1002,1,2,'Grupos','server','Dazzler.proveedor.group.js'); insert into gcontenido(gid,cid) values(1002,1021); insert into contenido(id,pid,pos,tipo,nombre,icon,contenido) values(1023,1002,2,2,'Instalacion','bricks','Dazzler.proveedor.install.js'); insert into gcontenido(gid,cid) values(1002,1023); -- Usuario Administrador insert into usuarios( id,login,clave,activo,nombre,correo) values (1001,'bamadmin','dazzler',2,'Admin Account','root@localhost'); insert into users ( id,weakhash,group_default,tipo ) values(1001,'11625ce7ca73b92f95c0d1adb75b8382',2,7); insert into groups ( id,uid,name,info ) values (1,1001,'lost+found','Grupo de maquinas perdidas'); insert into groups ( id,uid,name,info ) values (2,1001,'Default','Grupo por defecto del Usuario'); insert into gusuarios(gid,uid) values(1001,1001); insert into gusuarios(gid,uid) values(1002,1001); insert into gusuarios(gid,uid) values(1003,1001); \ No newline at end of file diff --git a/BAM/pics/block-bottom.gif b/BAM/pics/block-bottom.gif new file mode 100644 index 0000000..c0570c5 Binary files /dev/null and b/BAM/pics/block-bottom.gif differ diff --git a/BAM/pics/block-top.gif b/BAM/pics/block-top.gif new file mode 100644 index 0000000..cf3fb24 Binary files /dev/null and b/BAM/pics/block-top.gif differ diff --git a/BAM/pics/hd-bg.gif b/BAM/pics/hd-bg.gif new file mode 100644 index 0000000..310102a Binary files /dev/null and b/BAM/pics/hd-bg.gif differ diff --git a/BAM/pics/nologo.png b/BAM/pics/nologo.png new file mode 100644 index 0000000..b6ee821 Binary files /dev/null and b/BAM/pics/nologo.png differ diff --git a/BAM/rpc.php b/BAM/rpc.php new file mode 100644 index 0000000..acdb31c --- /dev/null +++ b/BAM/rpc.php @@ -0,0 +1,55 @@ +. + * +*/ + +$conf = simplexml_load_file("lib/Dazzler.conf"); +require_once $_SERVER['DOCUMENT_ROOT'].'/BAM/lib/class/XmlReply.inc.php'; + +/* ********************************************************************************************* */ +/* **************************** Create Reply Object ******************************************** */ +/* ********************************************************************************************* */ +$XmlReply = new XmlReply(); + +/* ********************************************************************************************* */ +/* **************************** Check for valid RPC (XML Request) ****************************** */ +/* ********************************************************************************************* */ +if(!$XmlReply->loadXml( file_get_contents('php://input') )){ + die( $XmlReply->getXml() ); + } +/* ********************************************************************************************* */ +/* **************************** Check for host/user account ************************************ */ +/* ********************************************************************************************* */ +$XmlReply->checkHost(); + +/* ********************************************************************************************* */ +/* *********************************** Building response *************************************** */ +/* ********************************************************************************************* */ + +/* ******************************* global preferences ************************************ */ +$XmlReply->addPreferences(); + +/* **************************** projects related reply *********************************** */ +$XmlReply->addProjects(); + +/* ************************************* opaque ****************************************** */ +$XmlReply->addOpaque(); + + +echo $XmlReply->getXml(); +?> diff --git a/COPYING b/COPYING new file mode 100644 index 0000000..e963df8 --- /dev/null +++ b/COPYING @@ -0,0 +1,622 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + diff --git a/COPYRIGHT b/COPYRIGHT new file mode 100644 index 0000000..c3e07fc --- /dev/null +++ b/COPYRIGHT @@ -0,0 +1,21 @@ +Copyright(c) 2011 Israel Figueroa , USI - Universidad de Concepcion + +This file is part of Dazzler + +Dazzler is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +Dazzler is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with Dazzler. If not, see . + + +GeoIp library + Copyright (C) 2007 MaxMind LLC + diff --git a/INSTALL b/INSTALL new file mode 100644 index 0000000..455580a --- /dev/null +++ b/INSTALL @@ -0,0 +1,42 @@ +Dazzler +======= +This document describes the process to install and configure Dazzler. + + +Requirements +============ +The following software/library are required to work with Dazzler: + +* Apache +* PHP 5+ +* PHP-psql +* Postgres + +* Ext-JS 3 (3.3.0) +* Ext-JS UX +* TDGi.iconMgr +* famfam icons + +Preparing the server +==================== + +* You should first determine wich will be your *BAM_URL* (http://BAM_URL/). This value is important because the signing keys are linked to it, and it cannot be modified once started attaching hosts. +* Setup a site (or a virtualhost), for the BAM_URL. +* Create a postgres database +* Create a pair of keys for the BAM. (see bamadmin http://boinc.berkeley.edu/trac/wiki/KeySetup ) + +NOTE: Dazzler it's preset to operate in /BAM, so the BAM url is really http://BAM_URL/BAM. This allow the admin, to create content for the BAM manually or using a content management system (like Wordpress). But if you dont like that, the easier way is to redirect traffic from / to /BAM. + + +Installation process +==================== + +* Download dazzler source code. And copy/unzip/link it to the prepared site root. a BAM directory should be present in the root. +* Download and setup the libraries. A prepared package can be found at ext.tar.bz2. If you choose to use it, unzip it *in* the BAM directory. +* Setup the database. First BAM/conf/db_base.sql and then BAM/conf/db_dazzler.sql. +* Edit the sample configuration file to suit your needs. Ext/library related info don't need modification if the prepared package was used. +* Login to the BAM with your web browser in: http://BAM_URL/BAM . Default admin account it's bamadmin:dazzler . This account shouldn't be used for managing hosts, and for *OBVIOUS* reasons the password must be changued inmediatly. +* Setup the periodic task : 0 * * * * /path/to/dazzler/BAM/cron/crontasks.sh + + +More info at the wiki. diff --git a/LICENSE.txt b/LICENSE.txt new file mode 100644 index 0000000..e963df8 --- /dev/null +++ b/LICENSE.txt @@ -0,0 +1,622 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + diff --git a/README b/README new file mode 100644 index 0000000..c9981e0 --- /dev/null +++ b/README @@ -0,0 +1,24 @@ +Dazzler +=== +A BOINC Account manager, for managing groups of hosts as a single farm. It is not thought as a replacement for a common BAM, but a way to ease the managament of medium/large groups of hosts working in several projects, managed by their owners. + +Inspired from: http://boinc.berkeley.edu/trac/wiki/VirtualCampusSupercomputerCenter + + +Acknowledgments +================ +- BOINC-dev mailing list for all it's support. +- jarifa project, for a lot of ideas. +- Universidad of Concepcion, Unidad de Servicios Informaticos (Chile). +- University of California (USA). + +Installation +============ + +See the 'INSTALL' file for more detailed directions. + +Todo +==== + +A lot, this it's just a functional beginning. See TODO for a list. + diff --git a/TODO b/TODO new file mode 100644 index 0000000..857a3c2 --- /dev/null +++ b/TODO @@ -0,0 +1,23 @@ +TODO list +========== + +This list is somehow sorted to reflect the priorty of the thing to do. + +- Statistical interface, to se how the farms go. +- Full preferences setup. +- Better color scheme, for dead hosts. +- Don't use plantext passwords (client passwords encode). + +- Language support +- Project manager interfase. +- Table renaming, for a more intuitive one. +- Upgrade interface to use Ext 4 +- Better, easier install procedure. +- User manual. + +- A better, and more complete TODO list. +- Mysql support. +- Fix bugs? + + +Any suggestion will be considered.