Example #1
0
 public function getEntitlementsForPrincipalToService(Principal $p, Service $s)
 {
     $user = sfContext::getInstance()->getUser();
     $eids = array();
     $rps = Doctrine::getTable('RolePrincipal')->findByPrincipalId($p->getId());
     foreach ($rps as $rp) {
         $res = Doctrine::getTable('RoleEntitlement')->findByRoleId($rp->getRoleId());
         foreach ($res as $re) {
             $eids[] = $re->getEntitlementId();
         }
     }
     $ueids = array_unique($eids);
     foreach ($ueids as $ueid) {
         $e = Doctrine::getTable('Entitlement')->find($ueid);
         // $tmp .= $e->getName()." ".$e->getService()." ".$s->getName()."<br>";
         if ($s->isValidated()) {
             if ($e->getServiceId() == $s->getId()) {
                 $es[] = $e;
             }
         }
     }
     if (isset($es)) {
         return $es;
     } else {
         //var_dump(array($tmp));exit;
         return NULL;
     }
 }
/**
* Check the username / password against the PAM system
*/
function SQUID_PAM_check($username, $password)
{
    global $c;
    $script = $c->authenticate_hook['config']['script'];
    if (empty($script)) {
        $script = $c->authenticate_hook['config']['path'];
    }
    $cmd = sprintf('echo %s %s | %s -n common-auth', escapeshellarg($username), escapeshellarg($password), $script);
    $auth_result = exec($cmd);
    if ($auth_result == "OK") {
        dbg_error_log('pwauth', 'User %s successfully authenticated', $username);
        $principal = new Principal('username', $username);
        if (!$principal->Exists()) {
            dbg_error_log('pwauth', 'User %s does not exist in local db, creating', $username);
            $pwent = posix_getpwnam($username);
            $gecos = explode(',', $pwent['gecos']);
            $fullname = $gecos[0];
            $principal->Create(array('username' => $username, 'user_active' => 't', 'email' => sprintf('%s@%s', $username, $email_base), 'fullname' => $fullname));
            if (!$principal->Exists()) {
                dbg_error_log("PAM", "Unable to create local principal for '%s'", $username);
                return false;
            }
            CreateHomeCalendar($username);
        }
        return $principal;
    } else {
        dbg_error_log("PAM", "User %s is not a valid username (or password was wrong)", $username);
        return false;
    }
}
Example #3
0
 /**
  * Executes index action
  *
  * @param sfRequest $request A request object
  */
 public function executeIndex(sfWebRequest $request)
 {
     if (!$request->getParameter('sf_culture')) {
         $ssaml = new SimpleSAML_Auth_Simple('default-sp');
         $attributes = $ssaml->getAttributes();
         if ($this->getUser()->isFirstRequest()) {
             if (array_key_exists('preferredLanguage', $attributes)) {
                 $culture = $attributes['preferredLanguage'];
                 if ($culture != 'hu' && $culture != 'en') {
                     $culture = $request->getPreferredCulture(array('en', 'hu'));
                 }
             } else {
                 $culture = $request->getPreferredCulture(array('en', 'hu'));
             }
             $this->getUser()->setCulture($culture);
             $this->getUser()->isFirstRequest(false);
         } else {
             $culture = $this->getUser()->getCulture();
         }
         $this->redirect('localized_homepage');
     }
     $p = Doctrine::getTable('Principal')->findOneByFedid($this->getUser()->getUsername());
     if ($p) {
         $oos = $p->getOrganization();
         $ros = $p->getRelatedOrganizations(TRUE);
     } else {
         $p = new Principal();
         $p->setFedid($this->getUser()->getUsername());
         $p->save();
     }
     $this->oos = $oos;
     $this->ros = $ros;
 }
Example #4
0
/**
* Check the username / password against the IMAP server
*/
function RIMAP_check($username, $password)
{
    global $c;
    $imap_username = $username;
    if (function_exists('mb_convert_encoding')) {
        $imap_username = mb_convert_encoding($imap_username, "UTF7-IMAP", mb_detect_encoding($imap_username));
    } else {
        $imap_username = imap_utf7_encode($imap_username);
    }
    //$imap_url = '{localhost:143/imap/notls}';
    //$imap_url = '{localhost:993/imap/ssl/novalidate-cert}';
    $imap_url = $c->authenticate_hook['config']['imap_url'];
    $auth_result = "ERR";
    $imap_stream = @imap_open($imap_url, $imap_username, $password, OP_HALFOPEN);
    //print_r(imap_errors());
    if ($imap_stream) {
        // disconnect
        imap_close($imap_stream);
        // login ok
        $auth_result = "OK";
    }
    if ($auth_result == "OK") {
        $principal = new Principal('username', $username);
        if (!$principal->Exists()) {
            dbg_error_log("PAM", "Principal '%s' doesn't exist in local DB, we need to create it", $username);
            if (strstr($username, '@')) {
                $name_arr = explode('@', $username);
                $fullname = ucfirst(strtolower($name_arr[0]));
                $email = $username;
            } else {
                $fullname = ucfirst(strtolower($username));
                $email = $username . "@" . $c->authenticate_hook['config']['email_base'];
            }
            $principal->Create(array('username' => $username, 'user_active' => true, 'email' => $email, 'fullname' => ucfirst($fullname)));
            if (!$principal->Exists()) {
                dbg_error_log("PAM", "Unable to create local principal for '%s'", $username);
                return false;
            }
            CreateHomeCollections($username);
        }
        return $principal;
    } else {
        dbg_error_log("PAM", "User %s is not a valid username (or password was wrong)", $username);
        return false;
    }
}
Example #5
0
 function __construct($user_no = null)
 {
     if (empty($user_no)) {
         $this->user_no = -1;
         $this->principal_id = -1;
         $this->logged_in = false;
         return;
     }
     $this->user_no = $user_no;
     $principal = new Principal('user_no', $user_no);
     // Assign each field in the selected record to the object
     foreach ($principal as $k => $v) {
         $this->{$k} = $v;
     }
     $this->username = $principal->username();
     $this->principal_id = $principal->principal_id();
     $this->email = $principal->email();
     $this->dav_name = $principal->dav_name();
     $this->principal = $principal;
     $this->logged_in = true;
 }
 public function Header()
 {
     $this->SetFont('Helvetica', 'B', 13);
     $this->Cell(0, 10, 'EJEMPLO', 0, 1, 'C', 0, '', 1);
     $header = array('Country', 'Capital', 'Area (sq km)', 'Pop. (thousands)');
     Principal::SetColors();
     $w = array(40, 35, 40, 45);
     //Ancho de las columnas
     $num_headers = count($header);
     for ($i = 0; $i < $num_headers; $i++) {
         $this->Cell($w[$i], 7, $header[$i], 1, 0, 'C', 1);
     }
 }
Example #7
0
 /**
  * The constructor, which just calls the actual type configured
  */
 function PublicSession()
 {
     global $c;
     $principal = new Principal('username', 'unauthenticated');
     // Assign each field in the selected record to the object
     foreach ($principal as $k => $v) {
         $this->{$k} = $v;
     }
     $this->username = $principal->username();
     $this->user_no = $principal->user_no();
     $this->principal_id = $principal->principal_id();
     $this->email = $principal->email();
     $this->dav_name = $principal->dav_name();
     $this->principal = $principal;
     if (function_exists("awl_set_locale") && isset($this->locale) && $this->locale != "") {
         awl_set_locale($this->locale);
     }
     $this->groups = isset($c->public_groups) ? $c->public_groups : array();
     $this->roles = array('Public' => true);
     $this->logged_in = false;
 }
Example #8
0
/**
* Authenticate against a different PostgreSQL database which contains a usr table in
* the AWL format.
*
* Use this as in the following example config snippet:
*
* require_once('auth-functions.php');
*  $c->authenticate_hook = array(
*      'call'   => 'AuthExternalAwl',
*      'config' => array(
*           // A PgSQL database connection string for the database containing user records
*          'connection[]' => 'dbname=wrms host=otherhost port=5433 user=general',
*           // Which columns should be fetched from the database
*          'columns'    => "user_no, active, email_ok, joined, last_update AS updated, last_used, username, password, fullname, email",
*           // a WHERE clause to limit the records returned.
*          'where'    => "active AND org_code=7"
*      )
*  );
*
*/
function AuthExternalAWL($username, $password)
{
    global $c;
    $persistent = isset($c->authenticate_hook['config']['use_persistent']) && $c->authenticate_hook['config']['use_persistent'];
    if (isset($c->authenticate_hook['config']['columns'])) {
        $cols = $c->authenticate_hook['config']['columns'];
    } else {
        $cols = '*';
    }
    if (isset($c->authenticate_hook['config']['where'])) {
        $andwhere = ' AND ' . $c->authenticate_hook['config']['where'];
    } else {
        $andwhere = '';
    }
    $qry = new AwlQuery('SELECT ' . $cols . ' FROM usr WHERE lower(username) = :username ' . $andwhere, array(':username' => strtolower($username)));
    $authconn = $qry->SetConnection($c->authenticate_hook['config']['connection'], $persistent ? array(PDO::ATTR_PERSISTENT => true) : null);
    if (!$authconn) {
        echo <<<EOERRMSG
  <html><head><title>Database Connection Failure</title></head><body>
  <h1>Database Error</h1>
  <h3>Could not connect to PostgreSQL database</h3>
  </body>
  </html>
EOERRMSG;
        @ob_flush();
        exit(1);
    }
    if ($qry->Exec('Login', __LINE__, __FILE__) && $qry->rows() == 1) {
        $usr = $qry->Fetch();
        if (session_validate_password($password, $usr->password)) {
            $principal = new Principal('username', $username);
            if ($principal->Exists()) {
                if ($principal->modified <= $usr->updated) {
                    $principal->Update($usr);
                }
            } else {
                $principal->Create($usr);
                CreateHomeCollections($username);
            }
            /**
             * We disallow login by inactive users _after_ we have updated the local copy
             */
            if (isset($usr->active) && $usr->active == 'f') {
                return false;
            }
            return $principal;
        }
    }
    return false;
}
/**
* Create/Update the scheduling requests for this resource.  This includes updating
* the scheduled user's default calendar.
* @param vComponent $resource The VEVENT/VTODO/... resource we are scheduling
* @param boolean $create true if the scheduling requests are being created.
* @return true If there was any scheduling action
*/
function do_scheduling_requests(vCalendar $resource, $create, $old_data = null, $remoteAttendee = false)
{
    global $request, $c;
    if (!isset($request) || isset($c->enable_auto_schedule) && !$c->enable_auto_schedule) {
        return false;
    }
    if (!is_object($resource)) {
        trace_bug('do_scheduling_requests called with non-object parameter (%s)', gettype($resource));
        return false;
    }
    $organizer = $resource->GetOrganizer();
    if ($organizer === false || empty($organizer)) {
        dbg_error_log('PUT', 'Event has no organizer - no scheduling required.');
        return false;
    }
    $organizer_email = preg_replace('/^mailto:/i', '', $organizer->Value());
    if ($request->principal->email() != $organizer_email) {
        return do_scheduling_reply($resource, $organizer);
    }
    $schedule_request = clone $resource;
    $schedule_request->AddProperty('METHOD', 'REQUEST');
    $old_attendees = array();
    if (!empty($old_data)) {
        $old_resource = new vCalendar($old_data);
        $old_attendees = $old_resource->GetAttendees();
    }
    $attendees = $resource->GetAttendees();
    if (count($attendees) == 0 && count($old_attendees) == 0) {
        dbg_error_log('PUT', 'Event has no attendees - no scheduling required.', count($attendees));
        return false;
    }
    $removed_attendees = array();
    foreach ($old_attendees as $attendee) {
        $email = preg_replace('/^mailto:/i', '', $attendee->Value());
        if ($email == $request->principal->email()) {
            continue;
        }
        $removed_attendees[$email] = $attendee;
    }
    $uids = $resource->GetPropertiesByPath('/VCALENDAR/*/UID');
    if (count($uids) == 0) {
        dbg_error_log('PUT', 'No UID in VCALENDAR - giving up on REPLY.');
        return false;
    }
    $uid = $uids[0]->Value();
    dbg_error_log('PUT', 'Writing scheduling resources for %d attendees', count($attendees));
    $scheduling_actions = false;
    foreach ($attendees as $attendee) {
        $email = preg_replace('/^mailto:/i', '', $attendee->Value());
        if ($email == $request->principal->email()) {
            dbg_error_log("PUT", "not delivering to owner '%s'", $request->principal->email());
            continue;
        }
        if ($create) {
            $attendee_is_new = true;
        } else {
            $attendee_is_new = !isset($removed_attendees[$email]);
            if (!$attendee_is_new) {
                unset($removed_attendees[$email]);
            }
        }
        $agent = $attendee->GetParameterValue('SCHEDULE-AGENT');
        if ($agent && $agent != 'SERVER') {
            dbg_error_log("PUT", "not delivering to %s, schedule agent set to value other than server", $email);
            continue;
        }
        $schedule_target = new Principal('email', $email);
        $response = '3.7';
        // Attendee was not found on server.
        dbg_error_log('PUT', 'Handling scheduling resources for %s on %s which is %s', $email, $create ? 'create' : 'update', $attendee_is_new ? 'new' : 'an update');
        if ($schedule_target->Exists()) {
            // Instead of always writing to schedule-default-calendar, we first try to
            // find a calendar with an existing instance of the event.
            $sql = 'SELECT caldav_data.dav_name, caldav_data.caldav_data, caldav_data.collection_id FROM caldav_data JOIN calendar_item USING(dav_id) ';
            $sql .= 'WHERE caldav_data.collection_id IN (SELECT collection_id FROM collection WHERE is_calendar AND user_no =?) ';
            $sql .= 'AND uid=? LIMIT 1';
            $qry = new AwlQuery($sql, $schedule_target->user_no(), $uid);
            if (!$qry->Exec('PUT', __LINE__, __FILE__) || $qry->rows() < 1) {
                dbg_error_log('PUT', "Could not find event in attendee's calendars");
                $attendee_calendar = new WritableCollection(array('path' => $schedule_target->internal_url('schedule-default-calendar')));
            } else {
                $row = $qry->Fetch();
                $r = new DAVResource($row);
                $attendee_calendar = new WritableCollection(array('path' => $r->parent_path()));
                if ($attendee_calendar->IsCalendar()) {
                    dbg_error_log('XXX', "found the event in attendee's calendar %s", $attendee_calendar->dav_name());
                } else {
                    dbg_error_log('XXX', 'could not find the event in any calendar, using schedule-default-calendar');
                    $attendee_calendar = new WritableCollection(array('path' => $schedule_target->internal_url('schedule-default-calendar')));
                }
            }
            if (!$attendee_calendar->Exists()) {
                dbg_error_log('ERROR', 'Default calendar at "%s" does not exist for user "%s"', $attendee_calendar->dav_name(), $schedule_target->username());
                $response = '5.2';
                // No scheduling support for user
            } else {
                $attendee_inbox = new WritableCollection(array('path' => $schedule_target->internal_url('schedule-inbox')));
                if (!$attendee_inbox->HavePrivilegeTo('schedule-deliver-invite')) {
                    $response = '3.8';
                    // No authority to deliver invitations to user.
                } else {
                    if ($attendee_inbox->WriteCalendarMember($schedule_request, $attendee_is_new) !== false) {
                        $response = '1.2';
                        // Scheduling invitation delivered successfully
                        if ($attendee_calendar->WriteCalendarMember($resource, $attendee_is_new) === false) {
                            dbg_error_log('ERROR', 'Could not write %s calendar member to %s', $attendee_is_new ? 'new' : 'updated', $attendee_calendar->dav_name(), $attendee_calendar->dav_name(), $schedule_target->username());
                            trace_bug('Failed to write scheduling resource.');
                        }
                    }
                }
            }
        } else {
            if ($remoteAttendee) {
                $attendee->is_remote = true;
                $remote = new iSchedule();
                $answer = $remote->sendRequest($email, 'VEVENT/REQUEST', $schedule_request->Render());
            } else {
                $remote = new iSchedule();
                $answer = $remote->sendRequest($email, 'VEVENT/REQUEST', $schedule_request->Render());
                if ($answer === false) {
                    $response = "3.7;Invalid Calendar User";
                } else {
                    foreach ($answer as $a) {
                        if ($a === false) {
                            $response = "3.7;Invalid Calendar User";
                        } elseif (substr($a, 0, 1) >= 1) {
                            $response = $a;
                        } else {
                            $response = "2.0;Success";
                        }
                    }
                }
            }
        }
        dbg_error_log('PUT', 'Status for attendee <%s> set to "%s"', $attendee->Value(), $response);
        $attendee->SetParameterValue('SCHEDULE-STATUS', $response);
        $scheduling_actions = true;
    }
    if (!$create) {
        foreach ($removed_attendees as $attendee) {
            $schedule_target = new Principal('email', $email);
            if ($schedule_target->Exists()) {
                $attendee_calendar = new WritableCollection(array('path' => $schedule_target->internal_url('schedule-default-calendar')));
            }
        }
    }
    return $scheduling_actions;
}
<?php

include "../classes/Principal.php";
$acao = $_GET['acao'];
$id = $_GET['id'];
$principal = new Principal();
$descricao = "";
if ($acao == "alt") {
    $extra = "WHERE idhistorico=" . $id;
    foreach ($principal->retornaHistoricos($extra) as $historico) {
        $descricao = $historico->getDescricao();
    }
}
?>

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />


<!-- <link rel="stylesheet" href="css/style_forms.css" /> -->
<!-- Incluimos a biblioteca do jquery e as Funçoes -->
<script type="text/javascript"  src="../scripts/jquery-1.4.2.min.js"></script>
<!-- <script type="text/javascript"  src="scripts/funcoes.js"></script> -->

<script type="text/javascript">  
    jQuery(document).ready(function(){  
        jQuery('#formulario').submit(function(){  
            var dados = jQuery( this ).serialize();  
              jQuery.ajax({  
                type: "POST",  
Example #11
0
<?php

//se incluyen las funciones comunes
include_once '../../Comun/FuncionesComunes.php';
include_once '../../Comun/codigoSeguridad.php';
//Se incluye la clase Acceso
include_once '../../Clases/Acceso.php';
//Se incluye la clase de Vista
include_once '../Vistas/V_Principal.php';
//Debemos indicar en la variable correspondiente que estamos en un determinado apartado para
//cuando se cree la vista y muestra el menu lateral correctamente
$_SESSION['PosicionMenuLateral'] = 'B';
//Cargamos el idioma a utilizar en el controlador
$idioma = CargarIdioma();
Acceso::ConPermisos($_SESSION['login'], $_SERVER['SCRIPT_NAME'], '../../Principal/Controladores/Login.php');
//Teniendo permisos a la pagina, se procede a registrar el accceso a la misma por parte del usuario logeado
//Acceso::RegistraAcceso($_SESSION['login'],$_SERVER['SCRIPT_NAME']);
//se instancia la clase Consulta de Usuarios
$princ_view = new Principal();
//se invoca el metodo Display de Clase de Principal
$princ_view->Display($idioma);
Example #12
0
    <script src="http://localhost/web/interfaz/plugins/daterangepicker/daterangepicker.js"></script>
    <!-- datepicker -->
    <script src="http://localhost/web/interfaz/plugins/datepicker/bootstrap-datepicker.js"></script>
    <!-- Bootstrap WYSIHTML5 -->
    <script src="http://localhost/web/interfaz/plugins/bootstrap-wysihtml5/bootstrap3-wysihtml5.all.min.js"></script>
    <!-- Slimscroll -->
    <script src="http://localhost/web/interfaz/plugins/slimScroll/jquery.slimscroll.min.js"></script>
    <!-- FastClick -->
    <script src="http://localhost/web/interfaz/plugins/fastclick/fastclick.min.js"></script>
    <!-- AdminLTE App -->
    <script src="http://localhost/web/interfaz/dist/js/app.min.js"></script>
    <!-- AdminLTE dashboard demo (This is only for demo purposes) -->
    <script src="http://localhost/web/interfaz/dist/js/pages/dashboard.js"></script>
    <!-- AdminLTE for demo purposes -->
    <script src="http://localhost/web/interfaz/dist/js/demo.js"></script>
	</body>
  </html>';
if (isset($_POST)) {
    if ($_POST['submit'] == "datos") {
        Principal::insertarDispositivo($_POST);
        $disp = Area_personal::obtenerDispositivo($_POST['id']);
        echo $disp;
    }
}
BD::desconectar();
?>




Example #13
0
<?php

include 'Principal.class.php';
include 'BD.class.php';
print_r($_GET);
if (isset($_GET)) {
    BD::conectar();
    Principal::insertarMedida($_GET);
    BD::desconectar();
}
<?php

//if(isset($_POST["descricao"])){
$descricao = $_POST["descricao"];
// Verifica se o nome foi preenchido
if (empty($descricao)) {
    echo "Digite a descrição do histórico";
} elseif (strlen($descricao) > 150) {
    echo "Descricao nao pode ser maior que 150 caracteres";
} else {
    // Inserimos no banco de dados
    include "../classes/Principal.php";
    $principal = new Principal();
    $principal->Historicos("", $descricao);
    if ($principal->inserirHistoricos()) {
        echo false;
    } else {
        echo "Problema ao tentar inserir histórico!";
    }
}
Example #15
0
<div id="titulo">DADOS DA EMPRESA</div>

<div  id="box">

<table align="center">
<tr>
<th colspan="2"></font></th>
</tr>

<tr><th colspan="2"><div id="loading"></div></th></tr>

<tr><th colspan="2"><div id='envolve'><div id="aviso"></div></div></th></tr>
<?php 
if (isset($_POST)) {
    include "classes/Principal.php";
    $principal = new Principal();
    foreach ($principal->retornaEmpresa() as $empresa) {
        ?>
<div id="menu">

<!-- function resposta(); -->
<form id="formulario" action="javascript:resposta();" method="post">
<table width="700" border="0">
    <tr>
      <td width="58" bgcolor="#C3D9FF">Razão Social</td>
      <td width="476" bgcolor="#C3D9FF"><input name="razao" type="text" id="razao" size="80" value= "<?php 
        echo $empresa->getRazaosocial();
        ?>
"/></td>
    </tr>
    <tr>
Example #16
0
//$usuario = $_POST['usuario'];
$usuario = $_SESSION['usuario'];
$usuario2 = $_POST['user'];
$pass = $_SESSION['passs'];
// $pass = $_POST['pass'];
// $nombre = $_POST['name'];
//  $latitud = $_POST['latitud'];
// $longitud = $_POST['longitud'];
$latitud = $_SESSION["latitud"];
$longitud = $_SESSION["longitud"];
$susuario = new Usuario($usuario, $nombre, $pass);
$coordenadas = new Coordenadas($latitud, $longitud, $id_usuario);
Principal::mostrarusuario($usuario, $nombre, $pass);
$id_usuario = $_SESSION['id_usuario'];
Principal::insertcoor($id_usuario, $longitud, $latitud);
Principal::selectcoor($id_usuario, $longitud, $latitud);
class Principal
{
    public function mostrarusuario($usuario, $nombre, $pass)
    {
        Usuario::selectusu($usuario, $nombre, $pass);
    }
    public function insertcoor($id_usuario, $longitud, $latitud)
    {
        Coordenadas::insertcoor($id_usuario, $longitud, $latitud);
    }
    public function selectcoor($id_usuario, $longitud, $latitud)
    {
        Coordenadas::selectcoor($id_usuario, $longitud, $latitud);
    }
}
Example #17
0
        <!-- Header Navbar: style can be found in header.less -->
  <nav class="navbar navbar-static-top" role="navigation">

    <!-- Sidebar toggle button-->
    <a href="#" class="sidebar-toggle" data-toggle="offcanvas" role="button"></a>

    <!-- navbar menu -->
    <div class="navbar-custom-menu">
      <ul class="nav navbar-nav">

        <!-- Nombre Usuario  -->
        <li class="dropdown user user-menu">
          <a href="#" class="dropdown-toggle" data-toggle="dropdown">
            <img src="http://localhost/web/interfaz/dist/img/user2-160x160.jpg" class="user-image" alt="User Image">
            <span class="hidden-xs"><?php 
Principal::obtener_nombre($_SESSION['usuario_id']);
?>
</span>
          </a>
          <ul class="dropdown-menu">
            <!-- User image -->
            <li class="user-header">
              <img src="http://localhost/web/interfaz/dist/img/user2-160x160.jpg" class="img-circle" alt="User Image">
              <p>
                Jaime - Desarrollador web
                <small>Miembro desde Dic. 2015</small>
              </p>
            </li>
            <!-- Menu Body -->
            <li class="user-body">
              <div class="col-xs-4 text-center">
Example #18
0
 /**
  * Constructor
  * @param mixed $parameters If null, an empty Principal is created.  If it
  *              is an integer then that ID is read (if possible).  If it is
  *              an array then the Principal matching the supplied elements
  *              is read.  If it is an object then it is expected to be a 'usr'
  *              record that was read elsewhere.
  *
  * @return boolean Whether we actually read data from the DB to initialise the record.
  */
 function __construct($parameters = null)
 {
     global $session, $c;
     $this->exists = null;
     if ($parameters == null) {
         return;
     }
     if (is_object($parameters)) {
         dbg_error_log('principal', 'Principal: record for %s', $parameters->username);
         parent::__construct('username', $parameters->username);
     } else {
         if (is_int($parameters)) {
             dbg_error_log('principal', 'Principal: %d', $parameters);
             parent::__construct('principal_id', $parameters);
         } else {
             if (is_array($parameters)) {
                 if (!isset($parameters['options']['allow_by_email'])) {
                     $parameters['options']['allow_by_email'] = false;
                 }
                 if (isset($parameters['username'])) {
                     parent::__construct('username', $parameters['username']);
                 } else {
                     if (isset($parameters['user_no'])) {
                         parent::__construct('user_no', $parameters['user_no']);
                     } else {
                         if (isset($parameters['principal_id'])) {
                             parent::__construct('principal_id', $parameters['principal_id']);
                         } else {
                             if (isset($parameters['email'])) {
                                 parent::__construct('email', $parameters['email']);
                             } else {
                                 if (isset($parameters['path'])) {
                                     parent::__construct('path', $parameters['path']);
                                 } else {
                                     if (isset($parameters['principal-property-search'])) {
                                         $username = $this->PropertySearch($parameters['principal-property-search']);
                                         parent::__construct('username', $username);
                                     }
                                 }
                             }
                         }
                     }
                 }
             }
         }
     }
     if (!$this->exists) {
         return;
     }
     $this->InitialiseRecord();
 }
/**
 * Check the username / password against the PAM system
 */
function PWAUTH_PAM_check($username, $password)
{
    global $c;
    $program = $c->authenticate_hook['config']['path'];
    $email_base = $c->authenticate_hook['config']['email_base'];
    $pipe = popen(escapeshellarg($program), 'w');
    $authinfo = sprintf("%s\n%s\n", $username, $password);
    $written = fwrite($pipe, $authinfo);
    dbg_error_log('pwauth', 'Bytes written: %d of %d', $written, strlen($authinfo));
    $return_status = pclose($pipe);
    switch ($return_status) {
        case 0:
            // STATUS_OK: Authentication succeeded.
            dbg_error_log('pwauth', 'User %s successfully authenticated', $username);
            $principal = new Principal('username', $username);
            if (!$principal->Exists()) {
                dbg_error_log('pwauth', 'User %s does not exist in local db, creating', $username);
                $pwent = posix_getpwnam($username);
                $gecos = explode(',', $pwent['gecos']);
                $fullname = $gecos[0];
                $principal->Create(array('username' => $username, 'user_active' => 't', 'email' => sprintf('%s@%s', $username, $email_base), 'fullname' => $fullname));
                if (!$principal->Exists()) {
                    dbg_error_log("PAM", "Unable to create local principal for '%s'", $username);
                    return false;
                }
                CreateHomeCalendar($username);
            }
            return $principal;
            break;
            /*
             * Note that for system configurations using PAM instead of
             * reading the password database directly, if PAM is unable to
             * read the password database, pwauth will return status 1.
             */
        /*
         * Note that for system configurations using PAM instead of
         * reading the password database directly, if PAM is unable to
         * read the password database, pwauth will return status 1.
         */
        case 1:
        case 2:
            // (1) STATUS_UNKNOWN: Invalid username or password.
            // (2) STATUS_INVALID: Invalid password.
            dbg_error_log('pwauth', 'Invalid username or password (username: %s)', $username);
            break;
        case 3:
            // STATUS_BLOCKED: UID for username is < pwauth's MIN_UNIX_UID
            dbg_error_log('pwauth', 'UID for username %s is < pwauth MIN_UNIX_UID', $username);
            break;
        case 4:
            // STATUS_EXPIRED: The user account has expired.
            dbg_error_log('pwauth', 'The account for %s has expired', $username);
            break;
        case 5:
            // STATUS_PW_EXPIRED: The user account's password has expired.
            dbg_error_log('pwauth', 'The account password for user %s has expired', $username);
            break;
        case 6:
            // STATUS_NOLOGIN: Logins to the system are administratively disabled.
            dbg_error_log('pwauth', 'Logins administratively disabled (%s)', $username);
            break;
        case 7:
            // STATUS_MANYFAILS: Too many login failures for user account.
            dbg_error_log('pwauth', 'Login rejected for %s, too many failures', $username);
            break;
        case 50:
            // STATUS_INT_USER: Configuration error, Web server cannot use pwauth
            dbg_error_log('pwauth', 'config error: see pwauth man page (%s)', 'STATUS_INT_USER');
            break;
        case 51:
            // STATUS_INT_ARGS: pwauth received no username/passwd to check
            dbg_error_log('pwauth', 'error: pwauth received no username/password');
            break;
        case 52:
            // STATUS_INT_ERR: unknown error
            dbg_error_log('pwauth', 'error: see pwauth man page (%s)', 'STATUS_INT_ERR');
            break;
        case 53:
            // STATUS_INT_NOROOT: pwauth could not read the password database
            dbg_error_log('pwauth', 'config error: cannot read password database (%s)', 'STATUS_INT_NOROOT');
            break;
        default:
            // Unknown error code.
            dbg_error_log('pwauth', 'An unknown error (%d) has occurred', $return_status);
    }
    return FALSE;
}
Example #20
0
    $bairro = $_POST["bairro"];
    $cidade = $_POST["cidade"];
    $uf = $_POST["uf"];
    $cnpj = $_POST["cnpj"];
    $fone = $_POST["fone"];
    $email = $_POST["email"];
    // Verifica se o nome foi preenchido
    if (empty($nome)) {
        echo "Digite o nome da empresa!";
    } elseif (empty($endereco)) {
        echo "Digite o endereço!";
    } elseif (empty($bairro)) {
        echo "Digite o bairro!";
    } elseif (empty($cidade)) {
        echo "Digite a cidade!";
    } elseif (empty($uf)) {
        echo "Digite a sigla do estado!";
    } elseif (strlen($uf) != 2) {
        echo "A sigla do estado deve ter 2 caracteres";
    } else {
        // Inserimos no banco de dados
        include "../classes/Principal.php";
        $principal = new Principal();
        $principal->empresa(1, $nome, $endereco, $bairro, $cidade, $uf, $cnpj, $fone, $email);
        if ($principal->atualizaEmpresa()) {
            echo false;
        } else {
            echo "Nao foi possivel alterar os dados da empresa!";
        }
    }
}
Example #21
0
<?php

if (isset($_POST["nome"])) {
    $nome = $_POST["nome"];
    $senha = $_POST["senha"];
    $senha2 = $_POST["senha2"];
    // Verifica se o nome foi preenchido
    if (empty($nome)) {
        echo "Digite o Usuário!";
    } elseif (empty($senha)) {
        echo "Digite a senha";
    } elseif (strlen($senha) > 8) {
        echo "A senha deve ter no máximo 8 caracteres";
    } elseif ($senha != $senha2) {
        echo "As senhas digitadas não conferem";
    } else {
        // Inserimos no banco de dados
        include "../classes/Principal.php";
        $principal = new Principal();
        $principal->usuarios("", $nome, $senha);
        if ($principal->inserirUsuarios()) {
            echo false;
        } else {
            echo "Nao foi possivel inserir usuario!";
        }
    }
}
Example #22
0
 public function __construct($identity, $password, $name, array $aggregatedPrincipals = [], $privileged = false)
 {
     parent::__construct($identity, $name, $aggregatedPrincipals, $privileged);
     $this->password = (string) $password;
 }
Example #23
0
 public function executeResolve(sfWebRequest $request)
 {
     $i18n = sfContext::getInstance()->getI18N();
     $i = Doctrine::getTable('Invitation')->findOneByUuid($request->getParameter('uuid'));
     /*  Nincs is ilyen meghívó. */
     if (!$i) {
         $m = $i18n->__("Can't find the requested invitation");
         $this->getUser()->setFlash('error', $m);
         $this->redirect("default/error");
     }
     /*  Elfogadta már? */
     if ($i->getStatus() != "pending") {
         $m = $i18n->__('The invitation is no longer pending: %status%', array("%status%" => $i->getStatus()));
         $this->getUser()->setFlash('error', $m);
         $this->redirect("default/error");
     }
     $p = Doctrine::getTable('Principal')->findOneByFedid($this->getUser()->getUsername());
     /* A felhasználó most van itt először. Berakjuk a principal-ba. */
     if (!$p) {
         $p = new Principal();
         $p->setFedid($this->getUser()->getUsername());
         $p->save();
     }
     /* Ugye nincs még benn a szervezetben? */
     $o = $i->getOrganization();
     foreach ($i->getPrincipal() as $prin) {
         if ($prin and $prin->getId() == $this->getUser()->getPrincipalId()) {
             $i->delete();
             $m = $i18n->__('You are already a member of this organization. The invitation has lost its purpose, so we have deleted it.');
             $this->getUser()->setFlash('notice', $m);
             $this->redirect("show/index?id=" . $r->getOrganization()->getId());
         }
     }
     $p_id = $this->getUser()->getPrincipalId();
     $i->setAcceptAt(date('Y-m-d H:i:s'));
     $i->setStatus('accepted');
     $i->setPrincipalId($p_id);
     $i->save();
     $rp = new RolePrincipal();
     $rp->setRoleId($i->getRoleId());
     $rp->setPrincipalId($p_id);
     $rp->save();
     $r = $rp->getRole();
     /* Send email */
     $params = array("o" => $o, "p" => $p, "r" => $r);
     /* szervezők email címei */
     $to = array();
     foreach ($o->getPrincipal() as $manager) {
         $to[] = $manager->getUser()->getEmailAddress();
     }
     $email_params = array("to" => $to, "subject" => $i18n->__('%lname% has accepted the invitation to %organization%', array("%lname%" => $p->getUser()->getLastName(), "%organization%" => $o)), "bodyhtml" => $this->getPartial('invitePrincipal/acceptHtml', $params));
     $this->sendEmail($email_params);
     $this->getUser()->setFlash('notice', $i18n->__('You have been successfully added to %organization% organization.', array("%organization%" => $o)));
     $this->redirect("show/index?id=" . $o->getId());
 }
 /**
  * @ClassDependency: {'model.Principal'}
  */
 public function exeEuler()
 {
     $p_entrada["imax"] = $this->request->getParam('imax');
     $p_entrada["xi"] = $this->request->getParam('xi');
     $p_entrada["yi"] = $this->request->getParam('yi');
     $p_entrada["xf"] = $this->request->getParam('xf');
     $exeFundamento = $this->request->getParam('exeFundamento');
     $exeMetodo = $this->request->getParam('exeMetodo');
     $main = new Principal($p_entrada, $exeFundamento, $exeMetodo);
     $str = $main->getrutaArchivo();
     $split = explode('/', $str);
     $newStr = '';
     $flag = false;
     $foo = 0;
     // Concatena ruta directa al archivo de salida.
     foreach ($split as $i) {
         $foo++;
         if ($i == "src") {
             $flag = true;
         }
         if (!$flag) {
             continue;
         }
         if ($foo == count($split)) {
             $newStr .= $i;
         } else {
             $newStr .= $i . '/';
         }
     }
     $result = array("rutaArchivo" => '../' . $newStr);
     /*=============================================================================*/
     return $result;
 }
Example #25
0
<?php

param_to_global('id', 'int', 'old_id', 'principal_id');
$privilege_names = array('read', 'write-properties', 'write-content', 'unlock', 'read-acl', 'read-current-user-privilege-set', 'bind', 'unbind', 'write-acl', 'read-free-busy', 'schedule-deliver-invite', 'schedule-deliver-reply', 'schedule-query-freebusy', 'schedule-send-invite', 'schedule-send-reply', 'schedule-send-freebusy');
$privilege_xlate = array('all' => translate('All privileges'), 'read' => translate('Read'), 'write-properties' => translate('Write Metadata'), 'write-content' => translate('Write Data'), 'unlock' => translate('Override a Lock'), 'read-acl' => translate('Read Access Controls'), 'read-current-user-privilege-set' => translate('Read Current User\'s Access'), 'bind' => translate('Create Events/Collections'), 'unbind' => translate('Delete Events/Collections'), 'write-acl' => translate('Write Access Controls'), 'read-free-busy' => translate('Read Free/Busy Information'), 'schedule-deliver-invite' => translate('Scheduling: Deliver an Invitation'), 'schedule-deliver-reply' => translate('Scheduling: Deliver a Reply'), 'schedule-query-freebusy' => translate('Scheduling: Query free/busy'), 'schedule-send-invite' => translate('Scheduling: Send an Invitation'), 'schedule-send-reply' => translate('Scheduling: Send a Reply'), 'schedule-send-freebusy' => translate('Scheduling: Send free/busy'), 'write' => translate('Write'), 'schedule-deliver' => translate('Scheduling: Delivery'), 'schedule-send' => translate('Scheduling: Sending'));
$can_write_principal = $session->AllowedTo('Admin') || $session->principal_id == $id;
if (!$can_write_principal && $id > 0) {
    $target_principal = new Principal('principal_id', $id);
    $can_write_principal = $session->HavePrivilegeTo('DAV::write', $target_principal->dav_name());
}
$delete_collection_confirmation_required = null;
$delete_principal_confirmation_required = null;
$delete_ticket_confirmation_required = null;
$delete_bind_in_confirmation_required = null;
$delete_binding_confirmation_required = null;
function handle_subaction($subaction)
{
    global $session, $c, $id, $editor;
    global $delete_collection_confirmation_required;
    global $delete_principal_confirmation_required;
    global $delete_ticket_confirmation_required;
    global $delete_bind_in_confirmation_required;
    global $delete_binding_confirmation_required;
    dbg_error_log('admin-principal-edit', ':handle_action: Action %s', $subaction);
    switch ($subaction) {
        case 'delete_collection':
            dbg_error_log('admin-principal-edit', ':handle_action: Deleting collection %s for principal %d', $_GET['dav_name'], $id);
            if ($session->AllowedTo('Admin') || $id > 0 && $session->principal_id == $id) {
                if ($session->CheckConfirmationHash('GET', 'confirm')) {
                    dbg_error_log('admin-principal-edit', ':handle_action: Allowed to delete collection %s for principal %d', $_GET['dav_name'], $id);
                    $qry = new AwlQuery('DELETE FROM collection WHERE dav_name=?;', $_GET['dav_name']);
Example #26
0
/**
* sync LDAP against the DB
*/
function sync_LDAP()
{
    global $c;
    $ldapDriver = getStaticLdap();
    if (!$ldapDriver->valid) {
        return;
    }
    $mapping = $c->authenticate_hook['config']['mapping_field'];
    $attributes = array_values_mapping($mapping);
    $ldap_users_tmp = $ldapDriver->getAllUsers($attributes);
    if (sizeof($ldap_users_tmp) == 0) {
        return;
    }
    foreach ($ldap_users_tmp as $key => $ldap_user) {
        $ldap_users_info[$ldap_user[$mapping['username']]] = $ldap_user;
        unset($ldap_users_tmp[$key]);
    }
    $qry = new AwlQuery("SELECT username, user_no, modified as updated FROM dav_principal where type_id=1");
    $qry->Exec('sync_LDAP', __LINE__, __FILE__);
    while ($db_user = $qry->Fetch()) {
        $db_users[] = $db_user->username;
        $db_users_info[$db_user->username] = array('user_no' => $db_user->user_no, 'updated' => $db_user->updated);
    }
    // all users from ldap
    $ldap_users = array_keys($ldap_users_info);
    // users only in ldap
    $users_to_create = array_diff($ldap_users, $db_users);
    // users only in db
    $users_to_deactivate = array_diff($db_users, $ldap_users);
    // users present in ldap and in the db
    $users_to_update = array_intersect($db_users, $ldap_users);
    // creation of all users;
    if (sizeof($users_to_create)) {
        $c->messages[] = sprintf(i18n('- creating record for users :  %s'), join(', ', $users_to_create));
        foreach ($users_to_create as $username) {
            $principal = new Principal('username', $username);
            $valid = $ldap_users_info[$username];
            $ldap_timestamp = $valid[$mapping['modified']];
            if (!empty($c->authenticate_hook['config']['format_updated'])) {
                /**
                 * This splits the LDAP timestamp apart and assigns values to $Y $m $d $H $M and $S
                 */
                foreach ($c->authenticate_hook['config']['format_updated'] as $k => $v) {
                    ${$k} = substr($ldap_timestamp, $v[0], $v[1]);
                }
                $ldap_timestamp = $Y . $m . $d . $H . $M . $S;
            } else {
                if (preg_match('{^(\\d{8})(\\d{6})(Z)?$', $ldap_timestamp, $matches)) {
                    $ldap_timestamp = $matches[1] . 'T' . $matches[2] . $matches[3];
                } else {
                    if (empty($ldap_timestamp)) {
                        $ldap_timestamp = date('c');
                    }
                }
            }
            $valid[$mapping['modified']] = $ldap_timestamp;
            sync_user_from_LDAP($principal, $mapping, $valid);
        }
    }
    // deactivating all users
    $params = array();
    $i = 0;
    $paramstring = '';
    foreach ($users_to_deactivate as $v) {
        if (isset($c->do_not_sync_from_ldap) && isset($c->do_not_sync_from_ldap[$v])) {
            continue;
        }
        if ($i > 0) {
            $paramstring .= ',';
        }
        $paramstring .= ':u' . $i . '::text';
        $params[':u' . $i++] = strtolower($v);
    }
    if (count($params) > 0) {
        $c->messages[] = sprintf(i18n('- deactivating users : %s'), join(', ', $users_to_deactivate));
        $qry = new AwlQuery('UPDATE usr SET active = FALSE WHERE lower(username) IN (' . $paramstring . ')', $params);
        $qry->Exec('sync_LDAP', __LINE__, __FILE__);
        Principal::cacheFlush('lower(username) IN (' . $paramstring . ')', $params);
    }
    // updating all users
    if (sizeof($users_to_update)) {
        foreach ($users_to_update as $key => $username) {
            $principal = new Principal('username', $username);
            $valid = $ldap_users_info[$username];
            $ldap_timestamp = $valid[$mapping['modified']];
            $valid['user_no'] = $db_users_info[$username]['user_no'];
            $mapping['user_no'] = 'user_no';
            /**
             * This splits the LDAP timestamp apart and assigns values to $Y $m $d $H $M and $S
             */
            foreach ($c->authenticate_hook['config']['format_updated'] as $k => $v) {
                ${$k} = substr($ldap_timestamp, $v[0], $v[1]);
            }
            $ldap_timestamp = $Y . $m . $d . $H . $M . $S;
            $valid[$mapping['modified']] = "{$Y}-{$m}-{$d} {$H}:{$M}:{$S}";
            $db_timestamp = substr(strtr($db_users_info[$username]['updated'], array(':' => '', ' ' => '', '-' => '')), 0, 14);
            if ($ldap_timestamp > $db_timestamp) {
                sync_user_from_LDAP($principal, $mapping, $valid);
            } else {
                unset($users_to_update[$key]);
                $users_nothing_done[] = $username;
            }
        }
        if (sizeof($users_to_update)) {
            $c->messages[] = sprintf(i18n('- updating user records : %s'), join(', ', $users_to_update));
        }
        if (sizeof($users_nothing_done)) {
            $c->messages[] = sprintf(i18n('- nothing done on : %s'), join(', ', $users_nothing_done));
        }
    }
    $admins = 0;
    $qry = new AwlQuery("SELECT count(*) AS admins FROM usr JOIN role_member USING ( user_no ) JOIN roles USING (role_no) WHERE usr.active=TRUE AND role_name='Admin'");
    $qry->Exec('sync_LDAP', __LINE__, __FILE__);
    while ($db_user = $qry->Fetch()) {
        $admins = $db_user->admins;
    }
    if ($admins == 0) {
        $c->messages[] = sprintf(i18n('Warning: there are no active admin users! You should fix this before logging out.  Consider using the $c->do_not_sync_from_ldap configuration setting.'));
    }
}
Example #27
0
  return false;

  });

});
</script>

</head>
<body>
<div id="titulo">CADASTRO DE USUÁRIOS</div>
<div id="conteudo">

</div>
<?php 
include "classes/Principal.php";
$principal = new Principal();
?>
<div id="aviso"></div>
<div id="menu">
<a href="forms/form_usuario.php"><img src="imagens/adduser.png" width="32" height="32"></a>

<table width="800" border="0">
  <tr bgcolor="#E8EEF7">
  <td width="388" height="41"><b>Usuario</b></td>
  <td width="247"><b>Senha</b></td>
  <td width="66"><b>Opcoes</b></td>
  <td width="81"></td>
  <tr>
  <?php 
$i = 1;
foreach ($principal->retornaUsuarios() as $usuario) {
 /**
  * Assertion helper
  *
  * @param   string pattern
  * @param   security.Principal p
  * @param   string cause
  * @throws  unittest.AssertionFailedError
  */
 protected function assertPrincipal($pattern, Principal $p, $cause)
 {
     if (!preg_match($pattern, $p->getName())) {
         $this->fail($cause . ' did not match', $p->getName(), $pattern);
     }
 }
Example #29
0
            <!-- Main content -->
            <section class="content">
                <div class="row">

                <div class="col-md-12">
                  <div class="box box-primary">
                    <div class="box-header with-border">
                      <h3 class="box-title">Dispositivos</h3>
                    </div><!-- /.box-header -->
                    <div class="box-body no-padding">
                      <div class="table-responsive mailbox-messages">
                        <table class="table table-hover table-striped">
                          <tbody>
                              <?php 
$dispositivos = Principal::obtenerDispositivos();
print_r($dispositivos);
$i = 0;
while ($i < count($dispositivos)) {
    ?>
	                          <tr>
                              <td class="mailbox-name"><a href="edit-dispositivo.php?id=<?php 
    $dispositivos[$i]['id'];
    ?>
"> <?php 
    $dispositivos[$i]['id'];
    ?>
</a></td>
                              <td class="mailbox-subject"> <?php 
    $dispositivos[$i]['descripcion'];
    ?>
Example #30
0
$num_dispositivos = Principal::contarDispositivos();
echo empty($num_dispositivos) ? 0 : $num_dispositivos;
BD::desconectar();
?>
				</small>
              </a>
            </li>

            <!-- Medidas -->
            <li>
              <a href="http://localhost/web/interfaz/pages/medidas/medidas.php">
                <i class="fa fa-envelope"></i> <span style=" font-size:15pt;">Medidas</span>
                <small class="label pull-right bg-green">
					       <?php 
BD::conectar();
$num_medidas_nuevas = Principal::contarNuevasMedidas();
if (empty($num_medidas_nuevas)) {
    echo 0;
} else {
    echo $num_medidas_nuevas['total_count'];
}
BD::desconectar();
?>
				</small>
              </a>
            </li>
          </ul>
        </section>
        <!-- /.sidebar -->
      </aside>