public function login() { if (empty($_POST)) { HttpHandler::redirect('/'+MODULE+'/login/form'); } else { BM::singleton()->getObject('db')->newConnection(HOST, USER, PASSWORD, DATABASE); $usuario = BM::singleton()->getObject('db')->sanitizeData($_POST['usuario']); $clave = cifrar_RIJNDAEL_256($_POST['clave']); $query = "SELECT * FROM empleado WHERE usuario='{$usuario}' AND clave='{$clave}' AND modulo='terceros';"; BM::singleton()->getObject('db')->executeQuery($query); if (BM::singleton()->getObject('db')->getNumRows() > 0) { $level = 1; while ($data = BM::singleton()->getObject('db')->getResult()->fetch_assoc()) { $level = $data['permiso']; } Session::singleton()->NewSession($usuario, $level); if(!isset($_GET['url'])||empty($_GET['url'])){ HttpHandler::redirect('/'.MODULE.'/login/form'); }else{ HttpHandler::redirect($_GET['url']); } } else { HttpHandler::redirect('/'.MODULE.'/login/form?error_id=2'); } } }
/** * @url POST import */ public function post() { try { $session = Session::singleton(); $allowedRoles = (array) Config::get('allowedRolesForExcelImport', 'excelImport'); if (Config::get('loginEnabled') && !is_null($allowedRoles)) { $ok = false; $sessionRoles = Role::getAllSessionRoles(); foreach ($sessionRoles as $role) { if (in_array($role->label, $allowedRoles)) { $ok = true; } } if (!$ok) { throw new Exception("You do not have access to import excel files", 401); } } if (is_uploaded_file($_FILES['file']['tmp_name'])) { // Parse: $parser = new ImportExcel($_FILES['file']['tmp_name']); $result = $parser->ParseFile(); unlink($_FILES['file']['tmp_name']); } else { Notifications::addError('No file uploaded'); } $result = array('notifications' => $result, 'files' => $_FILES); return $result; } catch (Exception $e) { throw new RestException($e->getCode(), $e->getMessage()); } }
function bloqueo_pantalla() { $usuario = Session::singleton()->getUser(); $query = "SELECT activo FROM empleado WHERE usuario = '{$usuario}'"; data_model()->executeQuery($query); $ret = data_model()->getResult()->fetch_assoc(); echo json_encode($ret); /* if($ret['activo'] == 0 && !empty($usuario)){ echo " <div style=\"position:fixed;width:100%;height:100%;background:#000;top:0px;text-align:center;opacity:0.6\" class=\"metro\"> <br/> <br/> <br/> <br/> <h1 style=\"color:#fff;\">Bloqueado</h1> <br/> <br/> <img src=\"../static/img/candado.png\" /> <br/> <br/> <div class=\"input-control text\" style=\"background:#000;\"> <input style=\"width:300px;border:#D3D3D3;padding:10px;\" type=\"password\" placeholder=\" Password\" /> <button type=\"button\" class=\"large primary\">Desbloquear</button> </div> </div> "; } */ }
public final function __get($index) { switch ($index) { case 'config': $this->config = Config::singleton(); return $this->config; case 'cache': $this->cache = new Cache($this->config->read('framework/cache/driver', Cache::DISABLED), array('host' => $this->config->read('framework/cache/host', null), 'port' => $this->config->read('framework/cache/port', null))); return $this->cache; case 'sql': $this->config->load('db'); $this->sql = new SQL($this->config->read('db/dsn', ''), $this->config->read('db/user', ''), $this->config->read('db/pass', ''), $this->config->read('db/pool', false)); $this->config->unload('db'); return $this->sql; case 'secure': $this->secure = new Secure($this->config->read('framework/secure/seed', 'sampa-framework')); return $this->secure; case 'log': $logfile = __SP_LOG__ . date('Ymd') . '-' . str_replace('_', '-', strtolower(get_class($this))) . '.log'; $this->log = new Log($logfile, $this->config->read('framework/log/level', Log::DISABLED), $this->config->read('framework/log/buffered', true)); return $this->log; case 'session': $this->session = Session::singleton($this->config); return $this->session; default: return null; } }
/** * @url GET run */ public function run() { try { $session = Session::singleton(); $db = Database::singleton(); $allowedRoles = (array) Config::get('allowedRolesForRunFunction', 'execEngine'); if (Config::get('loginEnabled') && !is_null($allowedRoles)) { $ok = false; $sessionRoles = Role::getAllSessionRoles(); foreach ($sessionRoles as $role) { if (in_array($role->label, $allowedRoles)) { $ok = true; } } if (!$ok) { throw new Exception("You do not have access to run the exec engine", 401); } } $session->setRole(); ExecEngine::runAllRules(); $db->closeTransaction('Run completed', false, true, false); $result = array('notifications' => Notifications::getAll()); return $result; } catch (Exception $e) { throw new RestException($e->getCode(), $e->getMessage()); } }
public function imprimir_ticket_cambio($id_cambio){ $queryCambioCabecera = "SELECT caja, fecha, cliente, devolucion.factura FROM devolucion INNER JOIN cambio ON cambio=cambio.id WHERE cambio=$id_cambio"; $cache = array(); data_model()->executeQuery($queryCambioCabecera); if(data_model()->getNumRows()>0){ $res = data_model()->getResult()->fetch_assoc(); $cliente = $res['cliente']; $empresa = $this->model->get_child('system'); $empresa->get(1); list($tieneCaja, $data) = $this->model->get_sibling('factura')->tieneCaja(Session::singleton()->getUser()); $caja = $data['id']; $fecha = $res['fecha']; $empleado = $this->model->get_child('empleado'); $empleado->get(Session::singleton()->getUser()); $id_datos = $empleado->id_datos; $clienteObj = $this->model->get_sibling('cliente'); $clienteObj->get($id_datos); $nombre_empleado = $clienteObj->primer_nombre ." ". $clienteObj->primer_apellido; $queryNombreCliente = "SELECT CONCAT(primer_nombre,' ', segundo_nombre,' ', primer_apellido, ' ', segundo_apellido) as nombre FROM cliente WHERE codigo_afiliado=$cliente"; data_model()->executeQuery($queryNombreCliente); $res = data_model()->getResult()->fetch_assoc(); $nombre_cliente = $res['nombre']; $queryDetalleCambio = "SELECT linea, estilo, color, talla, cantidad, precio FROM devolucion WHERE cambio=$id_cambio"; $detalle = data_model()->cacheQuery($queryDetalleCambio); $this->view->imprimir_ticket_cambio($id_cambio,$caja, $cliente, $fecha, $nombre_cliente, $detalle, $empresa, $nombre_empleado); }else{ echo "Este ticket de cambio está vacío o anulado"; } }
/** * @url GET run * @param array $roleIds */ public function run($roleIds = null) { try { $session = Session::singleton(); $session->activateRoles($roleIds); // Check sessionRoles if allowedRolesForRunFunction is specified $allowedRoles = Config::get('allowedRolesForRunFunction', 'execEngine'); if (!is_null($allowedRoles)) { $ok = false; foreach ($session->getSessionRoles() as $role) { if (in_array($role->label, $allowedRoles)) { $ok = true; } } if (!$ok) { throw new Exception("You do not have access to run the exec engine", 401); } } ExecEngine::run(true); $db = Database::singleton(); $db->closeTransaction('Run completed', false, true, false); $result = array('notifications' => Notifications::getAll()); return $result; } catch (Exception $e) { throw new RestException($e->getCode(), $e->getMessage()); } }
public function View(){ if (!Session::singleton()->ValidateSession()) { HttpHandler::redirect('/warbook/login/form'); } else { $this->view->View(); } }
function updateModules($id = '') { if ($id == '') $str = F_updateModules(Session::singleton()->getUser()); else $str = F_updateModules($id, true); if ($str != "") { $MODULES = unserialize(base64_decode($str)); } }
public function e403() { BM::singleton()->getObject('temp')->buildFromTemplates('template_nofixed.html'); template()->addTemplateBit('content', 'e403.html'); BM::singleton()->getObject('temp')->getPage()->setTitle("Acceso restringido"); BM::singleton()->getObject('temp')->getPage()->addEstigma("username", Session::singleton()->getUser()); BM::singleton()->getObject('temp')->getPage()->addEstigma("TITULO", "Error 403"); BM::singleton()->getObject('temp')->parseExtras(); BM::singleton()->getObject('temp')->parseOutput(); print BM::singleton()->getObject('temp')->getPage()->getContent(); }
public function terceros(){ template()->buildFromTemplates('template_nofixed.html'); page()->setTitle('Registrar proveedor'); template()->addTemplateBit('content', 'terceros/terceros.html'); page()->addEstigma("username", Session::singleton()->getUser()); page()->addEstigma("TITULO", "Mantenimiento a terceros"); page()->addEstigma("back_url", '/'.MODULE.'/terceros/principal'); template()->parseOutput(); template()->parseExtras(); print page()->getContent(); }
public function login() { if (empty($_POST)) { HttpHandler::redirect('/warbook/login/form'); } else { BM::singleton()->getObject('db')->newConnection(HOST, USER, PASSWORD, DATABASE); $usuario = BM::singleton()->getObject('db')->sanitizeData($_POST['usuario']); $clave = md5($_POST['clave']); $query = "SELECT * FROM User WHERE EmailAddress='{$usuario}' AND AccessPassword='******'"; //echo $query; BM::singleton()->getObject('db')->executeQuery($query); if (BM::singleton()->getObject('db')->getNumRows() > 0) { $level = 1; Session::singleton()->NewSession($usuario, $level); HttpHandler::redirect('/warbook/login/form'); } else { HttpHandler::redirect('/warbook/login/form?error_id=2'); } } }
public static function addViolation($rule, $srcAtom, $tgtAtom) { $session = Session::singleton(); $ruleHash = hash('md5', $rule['name']); $ruleMessage = $rule['message'] ? $rule['message'] : "Violation of rule '" . $rule['name'] . "'"; $pairView = RuleEngine::getPairView($srcAtom, $rule['srcConcept'], $tgtAtom, $rule['tgtConcept'], $rule['pairView']); self::$violations[$ruleHash]['ruleMessage'] = $ruleMessage; self::$violations[$ruleHash]['interfaceIds'] = $pairView['interfaceIds']; $violationMessage = empty($pairView['violationMessage']) ? $srcAtom . " - " . $tgtAtom : $pairView['violationMessage']; // Make links to interfaces $links = array(); foreach ($session->getInterfacesToReadConcept($rule['srcConcept']) as $interface) { $links[] = '#/' . $interface->id . '/' . $srcAtom; } foreach ($session->getInterfacesToReadConcept($rule['tgtConcept']) as $interface) { $links[] = '#/' . $interface->id . '/' . $tgtAtom; } $links = array_unique($links); self::$violations[$ruleHash]['tuples'][] = array('violationMessage' => $violationMessage, 'links' => $links); self::addLog($violationMessage . ' - ' . $violationMessage, 'VIOLATION'); }
/** * Handle an authorization request response received from the configured OP. * * @param array $authparams Received parameters. */ protected function handleauthresponse(array $authparams) { global $CFG, $SESSION, $STATEADDITIONALDATA, $USER, $THEME; $is_loggedin = $USER->is_logged_in(); if (!isset($authparams['code'])) { throw new \AuthInstanceException(get_string('errorauthnoauthcode', 'auth.oidc')); } // Validate and expire state. $staterec = get_record('auth_oidc_state', 'state', $authparams['state']); if (empty($staterec)) { throw new \AuthInstanceException(get_string('errorauthunknownstate', 'auth.oidc')); } $orignonce = $staterec->nonce; $additionaldata = array(); if (!empty($staterec->additionaldata)) { $additionaldata = @unserialize($staterec->additionaldata); if (!is_array($additionaldata)) { $additionaldata = array(); } } $STATEADDITIONALDATA = $additionaldata; delete_records('auth_oidc_state', 'id', $staterec->id); // Get token from auth code. $client = $this->get_oidcclient(); $tokenparams = $client->tokenrequest($authparams['code']); if (!isset($tokenparams['id_token'])) { throw new \AuthInstanceException(get_string('errorauthnoidtoken', 'auth.oidc')); } // Decode and verify idtoken. list($oidcuniqid, $idtoken) = $this->process_idtoken($tokenparams['id_token'], $orignonce); require_once $CFG->docroot . '/auth/lib.php'; $SESSION = \Session::singleton(); $USER = new \LiveUser(); $THEME = new \Theme($USER); $instanceid = $this->detect_auth_instance($idtoken); // Can't continue if we didn't find an auth instance. if (empty($instanceid)) { throw new \UserNotFoundException(get_string('errorbadinstitution', 'auth.oidc')); } $auth = new \AuthOidc($instanceid); $can_login = $auth->request_user_authorise($oidcuniqid, $tokenparams, $idtoken); if ($can_login === true) { redirect('/'); } else { // Office 365 uses "upn". $oidcusername = $oidcuniqid; $upn = $idtoken->claim('upn'); if (!empty($upn)) { $oidcusername = $upn; } $SESSION->set('auth_oidc_linkdata', array('authinstance' => $instanceid, 'oidcusername' => $oidcusername)); redirect('/auth/oidc/link.php'); } }
public function closeTransaction($succesMessage = 'Updated', $checkAllConjucts = true, $databaseCommit = false, $setNewContent = true) { $session = Session::singleton(); Hooks::callHooks('preDatabaseCloseTransaction', get_defined_vars()); Notifications::addLog('========================= CLOSING TRANSACTION =========================', 'DATABASE'); if ($checkAllConjucts) { Notifications::addLog("Check all conjuncts", 'DATABASE'); // Evaluate all invariant conjuncts. Conjuncts are cached. $invariantRulesHold = RuleEngine::checkInvariantRules(); // Evaluate all signal conjuncts. Conjuncts are cached RuleEngine::checkProcessRules(); } else { Notifications::addLog("Check all affected conjuncts", 'DATABASE'); // Evaluate all affected invariant conjuncts. Conjuncts are cached. $invariantRulesHold = RuleEngine::checkInvariantRules(RuleEngine::getAffectedInvConjuncts($this->affectedConcepts, $this->affectedRelations), true); // Evaluate all affected signal conjuncts. Conjuncts are cached RuleEngine::checkConjuncts(RuleEngine::getAffectedSigConjuncts($this->affectedConcepts, $this->affectedRelations), true); // Check only those process rules that are relevant for the activate roles RuleEngine::checkProcessRules($session); } unset($this->affectedConcepts, $this->affectedRelations); $this->affectedConcepts = array(); $this->affectedRelations = array(); if ($setNewContent && isset($session->atom)) { $session->atom->setNewContent($session->interface); } // e.g. not needed in Atom::delete() function if ($invariantRulesHold && $databaseCommit) { $this->commitTransaction(); // commit database transaction Notifications::addSuccess($succesMessage); } elseif (Config::get('ignoreInvariantViolations', 'transactions') && COMMIT_INV_VIOLATIONS) { $this->commitTransaction(); Notifications::addError("Transaction committed with invariant violations"); } elseif ($invariantRulesHold) { $this->rollbackTransaction(); // rollback database transaction Notifications::addInfo($succesMessage); } else { $this->rollbackTransaction(); // rollback database transaction } Hooks::callHooks('postDatabaseCloseTransaction', get_defined_vars()); return $invariantRulesHold; }
/** * @url GET notifications/all * @param array $roleIds */ public function getAllNotifications($roleIds = null) { try { $session = Session::singleton(); $session->activateRoles($roleIds); RuleEngine::getProcessViolationsFromDB($session); return Notifications::getAll(); } catch (Exception $e) { throw new RestException($e->getCode(), $e->getMessage()); } }
/** * Méthode principale qui appelle les sous méthodes pour construire, * traiter et afficher le formulaire. * * @access public * @return void */ public function render($template = false) { if ($this->useSession) { $this->includeSessionRequirements(); } $this->session = Session::singleton(); SearchTools::ProlongDataInSession(); $this->auth(); $this->initialize(); if (!$this->parentForm && $this->action == GenericController::FEATURE_DELETE && in_array(GenericController::FEATURE_DELETE, $this->features)) { if (!isset($_REQUEST['confirm_delete'])) { Template::confirmDialog(I_DELETE_ITEMS, $_SERVER['REQUEST_URI'] . '&confirm_delete=1', $this->guessReturnURL()); exit; } $this->delete(); Tools::redirectTo($this->guessReturnURL()); exit(0); } $this->buildForm(); $this->onBeforeDisplay(); if ($this->action == GenericController::FEATURE_VIEW) { $this->form->freeze(); } else { if (isset($_POST['fromAddButton']) && $_POST['fromAddButton'] == '1' || isset($_POST['submitFlag']) && $this->form->validate()) { $values = $this->form->exportValues(); $ret = $this->form->process(array($this, 'handlePostData'), $values); // le script sort ici, car redirigé par la méthode onFinish() // à moins qu'on ait surchargé celle ci. } } if (!$this->parentForm) { $additionalContent = $this->additionalFormContent(); $smarty = $this->template; $smarty->assign('preContent', $this->preContent()); $smarty->assign('form', $this->form->toArray(true)); $smarty->assign('formTitle', empty($this->formTitle) ? ' ' : $this->formTitle); $template = !$template ? GENERIC_ADDEDIT_TEMPLATE : $template; $smarty->assign('additionalContent', $additionalContent); $smarty->assign('postContent', $this->postContent()); $content = $smarty->fetch($template); $method = $this->useAJAX ? 'ajaxPage' : 'page'; Template::$method($this->title, $content, $this->jsRequirements, array(), $this->htmlTemplate); } }
function _clearEditSessionVars($id) { $id = intval($id); $session = Session::singleton(); $session->del("xhelp_editDepartment_{$id}"); $session->del("xhelp_editDepartmentErrors_{$id}"); }
function _clearEditSessionVars($id) { $id = intval($id); $session = Session::singleton(); $session->del("xhelp_editMime_{$id}"); $session->del("xhelp_editMimeErr_{$id}"); }
/** * Logs a message at the given log level. This function should not be called by * any code outside of this module. * * @param string $message The message to display * @param int $loglevel The level to log the message at * @param bool $escape Whether to HTML escape the message * @param bool $backtrace Whether to provide a backtrace if the system is * configured to give backtraces at this level. * @param string $file The file the error occurred in * @param int $line The line number the error occurred on * @param array $trace The backtrace for the error * @access private */ function log_message($message, $loglevel, $escape, $backtrace, $file = null, $line = null, $trace = null) { global $SESSION, $CFG; if (!$SESSION && function_exists('get_config') && $CFG) { require_once get_config('docroot') . 'auth/lib.php'; $SESSION = Session::singleton(); } static $requestprefix = ''; if (!$requestprefix) { $requestprefix = substr(md5(microtime()), 0, 2) . ' '; } static $loglevelnames = array(LOG_LEVEL_ENVIRON => 'environ', LOG_LEVEL_DBG => 'dbg', LOG_LEVEL_INFO => 'info', LOG_LEVEL_WARN => 'warn'); if (!function_exists('get_config') || null === ($targets = get_config('log_' . $loglevelnames[$loglevel] . '_targets'))) { $targets = LOG_TARGET_SCREEN | LOG_TARGET_ERRORLOG; } // Get nice backtrace information if required $trace = $trace ? $trace : debug_backtrace(); // If the last caller was the 'error' function then it came from a PHP warning if (!is_null($file)) { $filename = $file; $linenum = $line; } else { $filename = $trace[1]['file']; $linenum = $trace[1]['line']; } if (!function_exists('get_config') || get_config('log_backtrace_levels') & $loglevel) { list($textbacktrace, $htmlbacktrace) = log_build_backtrace($trace); } else { $textbacktrace = $htmlbacktrace = ''; } if (is_bool($message)) { $loglines = array($message ? 'bool(true)' : 'bool(false)'); } else { if (is_null($message)) { $loglines = array('NULL'); } else { $loglines = explode("\n", print_r($message, true)); } } // Make a prefix for each line, if we are logging a normal debug/info/warn message $prefix = $requestprefix; if ($loglevel != LOG_LEVEL_ENVIRON && function_exists('get_config')) { $docroot = get_config('docroot'); $prefixfilename = substr($filename, 0, strlen($docroot)) == $docroot ? substr($filename, strlen($docroot)) : $filename; $prefix .= '(' . $prefixfilename . ':' . $linenum . ') '; } $prefix = '[' . str_pad(substr(strtoupper($loglevelnames[$loglevel]), 0, 3), 3) . '] ' . $prefix; if ($targets & LOG_TARGET_SCREEN || defined('ADMIN') && $targets & LOG_TARGET_ADMIN) { // Work out which method to call for displaying the message if ($loglevel == LOG_LEVEL_DBG || $loglevel == LOG_LEVEL_INFO) { $method = 'add_info_msg'; } else { $method = 'add_error_msg'; } $message = implode("\n", $loglines); if ($escape) { $message = htmlspecialchars($message, ENT_COMPAT, 'UTF-8'); $message = str_replace(' ', ' ', $message); } $message = nl2br($message); $message = '<div class="backtrace">' . $prefix . $message . "</div>\n"; if (is_a($SESSION, 'Session')) { $SESSION->{$method}($message, false); } else { if (!function_exists('get_config') || get_config('installed')) { // Don't output when we are not installed, since this will cause the // redirect to the install page to fail. echo $message; } } if ($backtrace && $htmlbacktrace) { if (is_a($SESSION, 'Session')) { $SESSION->add_info_msg($htmlbacktrace, false); } else { if (!function_exists('get_config') || get_config('installed')) { echo $htmlbacktrace; } } } } if ($targets & LOG_TARGET_ERRORLOG) { foreach ($loglines as $line) { error_log($prefix . $line); } if ($backtrace && $textbacktrace) { $lines = explode("\n", $textbacktrace); foreach ($lines as $line) { error_log($line); } } } if ($targets & LOG_TARGET_STDOUT) { foreach ($loglines as $line) { echo $prefix . $line . "\n"; } if ($backtrace && $textbacktrace) { echo $textbacktrace; } } if (function_exists('get_config')) { if (!($logfilename = get_config('log_file'))) { $logfilename = get_config('dataroot') . 'error.log'; } if ($targets & LOG_TARGET_FILE && $logfilename) { global $LOGFILE_FH; static $logfile_open_attempted = null; if (!$logfile_open_attempted) { $logfile_open_attempted = true; $LOGFILE_FH = fopen($logfilename, 'wb'); if ($LOGFILE_FH !== false) { function _close_logfile() { global $LOGFILE_FH; fclose($LOGFILE_FH); } register_shutdown_function('_close_logfile'); } else { error_log("Could not open your custom log file ({$logfilename})"); } } if (is_resource($LOGFILE_FH)) { foreach ($loglines as $line) { fwrite($LOGFILE_FH, $prefix . $line . "\n"); } if ($backtrace && $textbacktrace) { $lines = explode("\n", $textbacktrace); foreach ($lines as $line) { fwrite($LOGFILE_FH, $line . "\n"); } } } } } }
public function getContent($interface, $rootElement = true, $tgtAtom = null, $inclLinktoData = false, $arrayType = "assoc", $metaData = true, $recursionAtomArr = array()) { $session = Session::singleton(); if (is_null($tgtAtom)) { $idEsc = $this->database->escape($this->id); $query = "SELECT DISTINCT `tgt` FROM ({$interface->expressionSQL}) AS `results` WHERE `src` = '{$idEsc}' AND `tgt` IS NOT NULL"; $tgtAtoms = array_column($this->database->Exe($query), 'tgt'); } else { // Make sure that atom is in db (not necessarily the case: e.g. new atom) $this->database->addAtomToConcept($this->id, $this->concept); $tgtAtoms[] = $tgtAtom; } foreach ($tgtAtoms as $tgtAtomId) { $tgtAtom = new Atom($tgtAtomId, $interface->tgtConcept, $interface->viewId); // Add @context for JSON-LD to rootElement if ($rootElement) { $content['@context'] = Config::get('serverURL') . Config::get('apiPath') . '/interface/' . $interface->id; } // Leaf if (empty($interface->subInterfaces) && empty($interface->refInterfaceId)) { // Property if ($interface->isProperty && !$interface->isIdent) { $content = !is_null($tgtAtom->id); // convert NULL into false and everything else in true // Object } elseif ($interface->tgtConceptIsObject) { $content = array(); // Add meta data if ($metaData) { // Define interface(s) to navigate to for this tgtAtom $atomInterfaces = array(); if ($interface->isLinkTo && !$inclLinktoData && $session->role->isInterfaceForRole($interface->refInterfaceId)) { $atomInterfaces[] = array('id' => $interface->refInterfaceId, 'label' => $interface->refInterfaceId); } elseif (isset($session->role)) { $atomInterfaces = array_map(function ($o) { return array('id' => $o->id, 'label' => $o->label); }, $session->role->getInterfacesToReadConcept($interface->tgtConcept)); } // Add meta data elements $content = array_merge($content, array('@id' => $tgtAtom->jsonld_id, '@label' => $tgtAtom->label, '@view' => $tgtAtom->view, '@type' => $tgtAtom->jsonld_type, '@interfaces' => $atomInterfaces, '_sortValues_' => array())); } // Add id TODO:can be removed when angular templates use @id instead of id $content = array_merge($content, array('id' => $tgtAtom->id)); // Scalar } else { $content = $this->typeConversion($tgtAtom->id, $interface->tgtConcept); // TODO: now same conversion as to database is used, maybe this must be changed to JSON types (or the json_encode/decode does this automaticaly?) } // Tree } else { $content = array(); // Add meta data if ($metaData) { // Define interface(s) to navigate to for this tgtAtom $atomInterfaces = array(); if ($interface->isLinkTo && !$inclLinktoData && $session->role->isInterfaceForRole($interface->refInterfaceId)) { $atomInterfaces[] = array('id' => $interface->refInterfaceId, 'label' => $interface->refInterfaceId); } elseif (isset($session->role)) { $atomInterfaces = array_map(function ($o) { return array('id' => $o->id, 'label' => $o->label); }, $session->role->getInterfacesToReadConcept($interface->tgtConcept)); } // Add meta data elements $content = array_merge($content, array('@id' => $tgtAtom->jsonld_id, '@label' => $tgtAtom->label, '@view' => $tgtAtom->view, '@type' => $tgtAtom->jsonld_type, '@interfaces' => $atomInterfaces, '_sortValues_' => array())); } // Add id TODO:can be removed when angular templates use @id instead of id $content = array_merge($content, array('id' => $tgtAtom->id)); // Subinterfaces if (!empty($interface->subInterfaces)) { if (!$interface->tgtConceptIsObject) { throw new Exception("TgtConcept of interface: '" . $interface->label . "' is scalar and can not have subinterfaces", 501); } foreach ($interface->subInterfaces as $subinterface) { $otherAtom = $tgtAtom->getContent($subinterface, false, null, $inclLinktoData, $arrayType, $metaData); $content[$subinterface->id] = $otherAtom; // _sortValues_ (if subInterface is uni) if ($subinterface->univalent && $metaData) { // property if (is_bool($otherAtom)) { $content['_sortValues_'][$subinterface->id] = $otherAtom; } elseif ($subinterface->tgtConceptIsObject) { $content['_sortValues_'][$subinterface->id] = current((array) $otherAtom)['@label']; } else { $content['_sortValues_'][$subinterface->id] = $otherAtom; } } } } // Ref subinterfaces (for LINKTO interfaces only when $inclLinktoData = true) if (!empty($interface->refInterfaceId) && (!$interface->isLinkTo || $inclLinktoData) && $recursionAtomArr[$tgtAtom->id] < 2) { if (!$interface->tgtConceptIsObject) { throw new Exception("TgtConcept of interface: '" . $interface->label . "' is scalar and can not have a ref interface defined", 501); } if ($inclLinktoData) { $recursionAtomArr[$tgtAtom->id]++; } $refInterface = new InterfaceObject($interface->refInterfaceId, null); foreach ($refInterface->subInterfaces as $subinterface) { $otherAtom = $tgtAtom->getContent($subinterface, false, null, $inclLinktoData, $arrayType, $metaData, $recursionAtomArr); $content[$subinterface->id] = $otherAtom; // _sortValues_ (if subInterface is uni) if ($subinterface->univalent && $metaData) { // property if (is_bool($otherAtom)) { $content['_sortValues_'][$subinterface->id] = $otherAtom; } elseif ($subinterface->tgtConceptIsObject) { $content['_sortValues_'][$subinterface->id] = current((array) $otherAtom)['@label']; } else { $content['_sortValues_'][$subinterface->id] = $otherAtom; } } } } } // Determine whether value of atom must be inserted as list or as single value // Properties are represented as single value if ($interface->isProperty && !$interface->isIdent && empty($interface->subInterfaces) && empty($interface->refInterfaceId)) { $arr = $content; // Object are always inserted as array } elseif ($interface->tgtConceptIsObject) { switch ($arrayType) { case "num": if ($interface->univalent && !$rootElement) { $arr = $content; } else { $arr[] = $content; } break; case "assoc": default: $arr[$content['id']] = $content; break; } // Non-object UNI results are inserted as single value } elseif ($interface->univalent) { $arr = $content; // Non-object Non-UNI results are inserted as array } else { $arr[] = $content; } unset($content); } return $arr; }
/** * @url GET notifications/all * @param int $roleId */ public function getAllNotifications($roleId = 0) { try { $session = Session::singleton(); $session->setRole($roleId); $session->role->getViolations(); return Notifications::getAll(); } catch (Exception $e) { throw new RestException($e->getCode(), $e->getMessage()); } }
/** * Effectue l'affichage du SearchForm et du Grid. * Note : les méthodes sont séparées pour une éventuelle * personalisation. * * @param string $title titre du grid * @return void */ public function render($title = false, $template = false) { $this->includeSessionRequirements(); $this->session = Session::singleton(); unset($_SESSION['_' . $this->clsname . '_']); $this->auth(); $title = !$title ? $this->title : $title; $template = !$template ? $this->htmlTemplate : $template; if ($this->_withSearhForm) { $this->buildSearchForm(); $this->searchForm->setDisplayForm(!$this->forceGridDisplay); if ($this->searchForm->displayGrid($this->forceGridDisplay)) { if (!empty($this->_checkboxes)) { SearchTools::cleanCheckBoxDataSession($this->_checkboxes); } $filter = $this->getGridFilter(); if (!is_array($filter)) { $filter = array($filter); } // mettre 1 pour préserver les checkbox coché ici empêche de // décoché des checkbox lors que l'on fait plusieurs rechreche // à la suite $filter = array_merge($filter, $this->searchForm->BuildFilterComponentArray($this->preserveGridItems)); $filter = SearchTools::FilterAssembler($filter); $this->buildGrid(); $order = $this->getGridSortOrder(); $this->searchForm->displayResult($this->grid, true, $filter, $order, $title, $this->jsRequirements, $this->additionalContent, 'page'); } else { $content = ''; if (isset($this->additionalContent['beforeForm'])) { $content = $this->additionalContent['beforeForm']; } $content .= $this->searchForm->render() . '</form>'; if (isset($this->additionalContent['between'])) { $content = $this->additionalContent['between']; } Template::page($title, $content, $this->jsRequirements, $this->cssRequirements, $template); } } else { $this->buildGrid(); $filter = $this->getGridFilter(); $order = $this->getGridSortOrder(); Template::pageWithGrid($this->grid, $this->clsname, $title, $filter, $order, $template); } }
public function LoadPostHome(){ $EmailAddress = Session::singleton()->getUser(); $query = "SELECT UserID FROM User WHERE EmailAddress='$EmailAddress'"; data_model()->executeQuery($query); $row = data_model()->getResult()->fetch_assoc(); $UserID = $row['UserID']; $query="SELECT FriendID FROM friendlist WHERE UserID = '$UserID'"; data_model()->executeQuery($query); $response=array(); while($row= data_model()->getResult()->fetch_assoc()): $response[]=$row['FriendID']; endwhile; $users = implode(",", $response); $users .= ",".$UserID; $response = array(); $query = "SELECT PostID, v.UserID as UserID,Content, PostTimeStamp, SupportCount, ProfilePic, CONCAT(FirstName, ' ',LastName) as Name FROM viewuserpost v INNER JOIN User u ON v.UserID = u.UserID WHERE v.UserID IN ($users) ORDER BY PostID DESC "; data_model()->executeQuery($query); while($row = data_model()->getResult()->fetch_assoc()){ $response[] = $row; } echo json_encode($response); }
private function callback($code, $idp) { try { $identityProviders = Config::get('identityProviders', 'OAuthLogin'); if (empty($code)) { throw new Exception("Oops. Someting went wrong during login. Please try again", 401); } $session = Session::singleton(); $db = Database::singleton(); if (!isset($identityProviders[$idp])) { throw new Exception("Unknown identity provider", 500); } $client_id = $identityProviders[$idp]['clientId']; $client_secret = $identityProviders[$idp]['clientSecret']; $redirect_uri = $identityProviders[$idp]['redirectUrl']; $token_url = $identityProviders[$idp]['tokenUrl']; $api_url = $identityProviders[$idp]['apiUrl']; $emailField = $identityProviders[$idp]['emailField']; // instantiate authController $authController = new OAuthLoginController($client_id, $client_secret, $redirect_uri, $token_url); // request token if ($authController->requestToken($code)) { // request data if ($authController->requestData($api_url)) { // Verify email/role here $email = $authController->getData()->{$emailField}; // Get user with $email // Set sessionUser $interface = new InterfaceObject('EmailUser'); $atom = new Atom($email, 'Email'); $users = array_keys((array) $atom->getContent($interface, true)); // create new user if (empty($users)) { $newUser = Concept::createNewAtom('User'); $db->addAtomToConcept($newUser, 'User'); $db->editUpdate('userEmail', false, $newUser, 'User', $email, 'Email'); // add to Organization $domain = explode('@', $email)[1]; $interface = new InterfaceObject('DomainOrgs'); $atom = new Atom($domain, 'Domain'); $orgs = array_keys((array) $atom->getContent($interface, true)); foreach ($orgs as $org) { $db->editUpdate('userOrganization', false, $newUser, 'User', $org, 'Organization'); } $users[] = $newUser; } if (count($users) > 1) { throw new Exception("Multiple users registered with email {$email}", 401); } foreach ($users as $userId) { // Set sessionUser $db->editUpdate('sessionUser', false, session_id(), 'SESSION', $userId, 'User'); // Timestamps $db->editUpdate('userLastLoginTimeStamp', false, $userId, 'User', date(DATE_ISO8601), 'DateTime'); $db->editUpdate('userLoginTimeStamp', false, $userId, 'User', date(DATE_ISO8601), 'DateTime'); } $db->closeTransaction('Login successfull', false, true, false); } } header('Location: ' . Config::get('serverURL')); exit; } catch (Exception $e) { throw new RestException($e->getCode(), $e->getMessage()); } }
public function __construct() { parent::__construct(); $this->SESSION = Session::singleton(); if ($this->SESSION->is_live()) { $this->authenticated = true; while (list($key, ) = each($this->defaults)) { $this->get($key); } } }
<?php namespace Sugi; /** * @package Sugi */ include "common.php"; // Register DB Module::set("db", function () { $db = Module::get("Database", array("type" => "sqlite3", "database" => __DIR__ . "/tmp/test.sqllite3")); $db->query(' CREATE TABLE IF NOT EXISTS sessions ( session_id VARCHAR(40) NOT NULL PRIMARY KEY, session_time INTEGER NOT NULL, session_data TEXT, session_lifetime INTEGER NOT NULL DEFAULT 0 )'); return $db; }); $config = array("type" => Filter::get_str("type", 0, 20, false), "file" => array("path" => __DIR__ . "/tmp/")); // Sugi\Session\Database driver if ($config["type"] == "database") { $config["database"] = array("db" => Module::get("db")); } Session::singleton($config); session_start(); $_SESSION['count'] = isset($_SESSION['count']) ? $_SESSION['count'] + 1 : 0; var_dump($_SESSION['count']);
unset($_SESSION['wantsurl']); } $saml_attributes = $as->getAttributes(); @session_write_close(); // now - let's continue with the session handling that would normally be done // by Maharas init.php // the main thin is that it sets the session cookie name back to what it should be // session_name(get_config('cookieprefix') . 'mahara'); // and starts the session again // *********************************************************************** // copied from original init.php // *********************************************************************** // Only do authentication once we know the page theme, so that the login form // can have the correct theming. require_once dirname(dirname(dirname(__FILE__))) . '/auth/lib.php'; $SESSION = Session::singleton(); $USER = new LiveUser(); $THEME = new Theme($USER); // *********************************************************************** // END of copied stuff from original init.php // *********************************************************************** // restart the session for Mahara @session_start(); if (!$SESSION->get('wantsurl')) { $SESSION->set('wantsurl', preg_replace('/\\&login$/', '', $wantsurl)); } // now start the hunt for the associated authinstance for the organisation attached to the saml_attributes global $instance; $instance = auth_saml_find_authinstance($saml_attributes); // if we don't have an auth instance then this is a serious failure if (!$instance) {
/** * Retourne un singleton Auth * * @access public * @static */ public static function Singleton() { if (!self::$instance) { self::$hasAuth = @(include_once MODELS_DIR . '/UserAccount.php'); Session::singleton(); self::$instance = new Auth(); } return self::$instance; }
private function getSessionInterfaces() { if (Config::get('loginEnabled')) { $session = Session::singleton(); return (array) $session->accessibleInterfaces; } else { return (array) $this->interfaces; } }