php array function in class - php

I cant get this script to work, $users should hold the array data we take out of the database but it doesnt seem to work. Can anyone tell us what we are doing wrong? i posted the script bellow.
added
$users has to stay static becaus it gets used again later on in the script (this is just a small part)
$user1 does get the right data it just doesnt get passed on to $users
added
this is the intire script hope that helps
<?php
class SingleSignOn_Server
{
public $links_path;
protected $started=false;
protected static $brokers = array(
'FGPostbus' => array('secret'=>"FGPostbus123"),
);
protected static $users = array();
public function query_personen(){
mysql_connect('host','user','pass') or die("Kan helaas geen verbinding maken" . mysql_error());
mysql_select_db('db') or die("Kan geen database selecteren");
$sql = mysql_query('select p_gebruikersnaam, p_wachtwoord, p_id, p_md5 FROM personen');
while ($row_user = mysql_fetch_assoc($sql)) {
self::$users[] = $row_user;
}
}
protected $broker = null;
public function __construct()
{
if (!function_exists('symlink')) $this->links_path = sys_get_temp_dir();
}
protected function sessionStart()
{
if ($this->started) return;
$this->started = true;
$matches = null;
if (isset($_REQUEST[session_name()]) && preg_match('/^SSO-(\w*+)-(\w*+)-([a-z0-9]*+)$/', $_REQUEST[session_name()], $matches)) {
$sid = $_REQUEST[session_name()];
if (isset($this->links_path) && file_exists("{$this->links_path}/$sid")) {
session_id(file_get_contents("{$this->links_path}/$sid"));
session_start();
setcookie(session_name(), "", 1);
} else {
session_start();
}
if (!isset($_SESSION['client_addr'])) {
session_destroy();
$this->fail("Not attached");
}
if ($this->generateSessionId($matches[1], $matches[2], $_SESSION['client_addr']) != $sid) {
session_destroy();
$this->fail("Invalid session id");
}
$this->broker = $matches[1];
return;
}
session_start();
if (isset($_SESSION['client_addr']) && $_SESSION['client_addr'] != $_SERVER['REMOTE_ADDR']) session_regenerate_id(true);
if (!isset($_SESSION['client_addr'])) $_SESSION['client_addr'] = $_SERVER['REMOTE_ADDR'];
}
protected function generateSessionId($broker, $token, $client_addr=null)
{
if (!isset(self::$brokers[$broker])) return null;
if (!isset($client_addr)) $client_addr = $_SERVER['REMOTE_ADDR'];
return "SSO-{$broker}-{$token}-" . md5('session' . $token . $client_addr . self::$brokers[$broker]['secret']);
}
protected function generateAttachChecksum($broker, $token)
{
if (!isset(self::$brokers[$broker])) return null;
return md5('attach' . $token . $_SERVER['REMOTE_ADDR'] . self::$brokers[$broker]['secret']);
}
public function login()
{
$this->sessionStart();
if (empty($_POST['p_gebruikersnaam'])) $this->failLogin("No user specified");
if (empty($_POST['p_wachtwoord'])) $this->failLogin("No password specified");
if (!isset(self::$users[$_POST['p_gebruikersnaam']]) || self::$users[$_POST['p_gebruikersnaam']]['p_wachtwoord'] != md5($_POST['p_wachtwoord'])) $this->failLogin("Incorrect credentials");
$_SESSION['user'] = $_POST['p_gebruikersnaam'];
$this->info();
}
public function logout()
{
$this->sessionStart();
unset($_SESSION['user']);
echo 1;
}
public function attach()
{
$this->sessionStart();
if (empty($_REQUEST['broker'])) $this->fail("No broker specified");
if (empty($_REQUEST['token'])) $this->fail("No token specified");
if (empty($_REQUEST['checksum']) || $this->generateAttachChecksum($_REQUEST['broker'], $_REQUEST['token']) != $_REQUEST['checksum']) $this->fail("Invalid checksum");
if (!isset($this->links_path)) {
$link = (session_save_path() ? session_save_path() : sys_get_temp_dir()) . "/sess_" . $this->generateSessionId($_REQUEST['broker'], $_REQUEST['token']);
if (!file_exists($link)) $attached = symlink('sess_' . session_id(), $link);
if (!$attached) trigger_error("Failed to attach; Symlink wasn't created.", E_USER_ERROR);
} else {
$link = "{$this->links_path}/" . $this->generateSessionId($_REQUEST['broker'], $_REQUEST['token']);
if (!file_exists($link)) $attached = file_put_contents($link, session_id());
if (!$attached) trigger_error("Failed to attach; Link file wasn't created.", E_USER_ERROR);
}
if (isset($_REQUEST['redirect'])) {
header("Location: " . $_REQUEST['redirect'], true, 307);
exit;
}
header("Content-Type: image/png");
readfile("empty.png");
}
public function info()
{
$this->sessionStart();
if (!isset($_SESSION['user'])) $this->failLogin("Not logged in");
header('Content-type: text/xml; charset=UTF-8');
echo '<?xml version="1.0" encoding="UTF-8" ?>', "\n";
echo '<user identity="' . htmlspecialchars($_SESSION['user'], ENT_COMPAT, 'UTF-8') . '">';
echo ' <p_id>' . htmlspecialchars(self::$users[$_SESSION['user']]['p_id'], ENT_COMPAT, 'UTF-8') . '</p_id>';
echo ' <p_md5>' . htmlspecialchars(self::$users[$_SESSION['user']]['p_md5'], ENT_COMPAT, 'UTF-8') . '</p_md5>';
echo '</user>';
}
protected function fail($message)
{
header("HTTP/1.1 406 Not Acceptable");
echo $message;
exit;
}
protected function failLogin($message)
{
header("HTTP/1.1 401 Unauthorized");
echo $message;
exit;
}
}
if (realpath($_SERVER["SCRIPT_FILENAME"]) == realpath(__FILE__) && isset($_GET['cmd'])) {
$ctl = new SingleSignOn_Server();
$ctl->$_GET['cmd']();
}

At the very least you probably want to:
self::$users[] = $users1[$row_user['p_gebruikersnaam']] = $row_user;
Since as is you where replacing the record every time and keeping only one.

You're building an array as a property of an object, but not using an instance of the object. You need to build a new instance ($usersObject = new ObjectName;), drop the static keywords, and instead of self::, use $this->. You also need square brackets after self::$users, like this: self::$users[].

Shouldn't this self::$users = $users1[$row_user['p_gebruikersnaam']] = $row_user; be:
array_push($this->users, $row_user)

You could put directly the result into the array:
while (false === ($row_user = mysql_fetch_array($sql, MYSQL_ASSOC)))
self::$users[$row_user['p_gebruikersnaam']] = $row_user;

Related

I am trying to get some content from s3 bucket AWS and upon requesting data It takes much longer than I can afford around 15 to 20 seconds

heres my api.php file code in try body else case is taking too much time
<?php
require_once(dirname(__FILE__) . "/constants.php");
includeMonstaConfig();
session_start();
require_once(dirname(__FILE__) . '/lib/helpers.php');
require_once(dirname(__FILE__) . '/lib/response_helpers.php');
require_once(dirname(__FILE__) . '/request_processor/RequestMarshaller.php');
if (file_exists(dirname(__FILE__) . '/../../mftp_extensions.php')) {
include_once(dirname(__FILE__) . '/../../mftp_extensions.php');
}
dieIfNotPOST();
require_once(dirname(__FILE__) . '/lib/access_check.php');
$marshaller = new RequestMarshaller();
try {
$request = json_decode($_POST['request'], true);
if ($request['actionName'] == 'fetchFile' || $request['actionName'] == 'downloadMultipleFiles') {
switch ($request['actionName']) {
case 'fetchFile':
$outputPath = $marshaller->prepareFileForFetch($request);
$outputFileName = monstaBasename($request['context']['remotePath']);
break;
case 'downloadMultipleFiles':
$outputResponse = $marshaller->marshallRequest($request, false, true);
$outputPath = $outputResponse["data"];
$outputFileName = "mftp_zip_" . date("Y_m_d_H_i_s") . ".zip";
}
$fileKey = generateRandomString(16);
$_SESSION[MFTP_SESSION_KEY_PREFIX . $fileKey] = array(
"path" => $outputPath,
"fileName" => $outputFileName
);
$response = array(
"success" => true,
"fileKey" => $fileKey
);
print json_encode($response);
} else {
$skipConfigurationActions = array('checkSavedAuthExists', 'writeSavedAuth', 'readSavedAuth',
'readLicense', 'getSystemVars', 'resetPassword', 'forgotPassword', 'validateSavedAuthPassword',
'downloadLatestVersionArchive', 'installLatestVersion');
$skipConfiguration = in_array($request['actionName'], $skipConfigurationActions);
$serializedResponse = $marshaller->marshallRequest($request, $skipConfiguration);
print $serializedResponse;
}
} catch (Exception $e) {
$marshaller->disconnect();
handleExceptionInRequest($e);
}
$marshaller->disconnect();
here is the RequestMarshaller.php code showing only the request code
<?php
require_once(dirname(__FILE__) . '/RequestDispatcher.php');
require_once(dirname(__FILE__) . "/../lib/helpers.php");
require_once(dirname(__FILE__) . "/../system/ApplicationSettings.php");
class RequestMarshaller {
/**
* #var RequestDispatcher
*/
private $requestDispatcher;
private function initRequestDispatcher($request, $skipConfiguration = false) {
if(!$skipConfiguration)
$request['configuration'] = $this->applyConnectionRestrictions($request['connectionType'],
$request['configuration']);
if (is_null($this->requestDispatcher))
$this->requestDispatcher = new RequestDispatcher($request['connectionType'], $request['configuration'],
null, null, $skipConfiguration);
}
public function marshallRequest($request, $skipConfiguration = false, $skipEncode = false) {
$this->initRequestDispatcher($request, $skipConfiguration);
$response = array();
if ($request['actionName'] == 'putFileContents')
$response = $this->putFileContents($request);
else if ($request['actionName'] == 'getFileContents')
$response = $this->getFileContents($request);
else {
$context = array_key_exists('context', $request) ? $request['context'] : null;
$responseData = $this->requestDispatcher->dispatchRequest($request['actionName'], $context);
$response['success'] = true;
if(is_object($responseData)) {
$response['data'] = method_exists($responseData, 'legacyJsonSerialize') ?
$responseData->legacyJsonSerialize() : $responseData;
} else
$response['data'] = $responseData;
}
if ($skipEncode)
return $response;
return json_encode($response);
}
}
}
and here is my RequestDispatcher.php code
<?php
class RequestDispatcher {
/**
* #var ConnectionBase
*/
private $connection;
/**
* #var string
*/
private $connectionType;
/**
* #var array
*/
private $rawConfiguration;
public $username;
public function getusername(){
$configuration = $this->connection->getConfiguration();
$this->username=$configuration->getRemoteUsername();
return $this->username;
}
public function __construct($connectionType, $rawConfiguration, $configurationFactory = null,
$connectionFactory = null, $skipConfiguration = false) {
$this->connectionType = $connectionType;
/* allow factory objects to be passed in for testing with mocks */
if ($skipConfiguration) {
$this->connection = null;
} else {
$this->rawConfiguration = $rawConfiguration;
$configurationFactory = is_null($configurationFactory) ? new ConfigurationFactory() : $configurationFactory;
$connectionFactory = is_null($connectionFactory) ? new ConnectionFactory() : $connectionFactory;
$configuration = $configurationFactory->getConfiguration($connectionType, $rawConfiguration);
$this->connection = $connectionFactory->getConnection($connectionType, $configuration);
}
}
public function dispatchRequest($actionName, $context = null) {
if (in_array($actionName, array(
'listDirectory',
'downloadFile',
'uploadFile',
'deleteFile',
'makeDirectory',
'deleteDirectory',
'rename',
'changePermissions',
'copy',
'testConnectAndAuthenticate',
'checkSavedAuthExists',
'writeSavedAuth',
'readSavedAuth',
'readLicense',
'getSystemVars',
'fetchRemoteFile',
'uploadFileToNewDirectory',
'downloadMultipleFiles',
'createZip',
'setApplicationSettings',
'deleteMultiple',
'extractArchive',
'updateLicense',
'reserveUploadContext',
'transferUploadToRemote',
'getRemoteFileSize',
'getDefaultPath',
'downloadForExtract',
'cleanUpExtract',
'resetPassword',
'forgotPassword',
'validateSavedAuthPassword',
'downloadLatestVersionArchive',
'installLatestVersion'
))) {
if (!is_null($context))
return $this->$actionName($context);
else
return $this->$actionName();
}
throw new InvalidArgumentException("Unknown action $actionName");
}
public function getConnection() {
return $this->connection;
}
private function connectAndAuthenticate($isTest = false) {
$sessionNeedsStarting = false;
if (function_exists("session_status")) {
if (session_status() == PHP_SESSION_NONE) {
$sessionNeedsStarting = true;
}
} else {
$sessionNeedsStarting = session_id() == "";
}
$configuration = $this->connection->getConfiguration();
$this->username=$configuration->getRemoteUsername();
if ($sessionNeedsStarting && !defined("MONSTA_UNIT_TEST_MODE")) { // TODO: pass in this as parameter to avoid global state
session_start();
$_SESSION["RemoteUsername"]=$configuration->getRemoteUsername();
}
$maxFailures = defined("MFTP_MAX_LOGIN_FAILURES") ? MFTP_MAX_LOGIN_FAILURES : 0;
$loginFailureResetTimeSeconds = defined("MFTP_LOGIN_FAILURES_RESET_TIME_MINUTES")
? MFTP_LOGIN_FAILURES_RESET_TIME_MINUTES * 60 : 0;
if (!isset($_SESSION["MFTP_LOGIN_FAILURES"]))
$_SESSION["MFTP_LOGIN_FAILURES"] = array();
$banManager = new UserBanManager($maxFailures, $loginFailureResetTimeSeconds,
$_SESSION["MFTP_LOGIN_FAILURES"]);
if ($banManager->hostAndUserBanned($configuration->getHost(), $configuration->getRemoteUsername())) {
mftpActionLog("Log in", $this->connection, "", "", "Login and user has exceed maximum failures.");
throw new FileSourceAuthenticationException("Login and user has exceed maximum failures.",
LocalizableExceptionDefinition::$LOGIN_FAILURE_EXCEEDED_ERROR, array(
"banTimeMinutes" => MFTP_LOGIN_FAILURES_RESET_TIME_MINUTES
));
}
try {
$this->connection->connect();
} catch (Exception $e) {
mftpActionLog("Log in", $this->connection, "", "", $e->getMessage());
throw $e;
}
try {
$this->connection->authenticate();
} catch (Exception $e) {
mftpActionLog("Log in", $this->connection, "", "", $e->getMessage());
$banManager->recordHostAndUserLoginFailure($configuration->getHost(),
$configuration->getRemoteUsername());
$_SESSION["MFTP_LOGIN_FAILURES"] = $banManager->getStore();
throw $e;
}
$banManager->resetHostUserLoginFailure($configuration->getHost(), $configuration->getRemoteUsername());
$_SESSION["MFTP_LOGIN_FAILURES"] = $banManager->getStore();
if ($isTest) {
// only log success if it is the first connect from the user
mftpActionLog("Log in", $this->connection, "", "", "");
}
if ($configuration->getInitialDirectory() === "" || is_null($configuration->getInitialDirectory())) {
return $this->connection->getCurrentDirectory();
}
return null;
}
public function disconnect() {
if ($this->connection != null && $this->connection->isConnected())
$this->connection->disconnect();
}
public function listDirectory($context) {
$this->connectAndAuthenticate();
$directoryList = $this->connection->listDirectory($context['path'], $context['showHidden']);
$this->disconnect();
return $directoryList;
}
public function downloadFile($context, $skipLog = false) {
$this->connectAndAuthenticate();
$transferOp = TransferOperationFactory::getTransferOperation($this->connectionType, $context);
$this->connection->downloadFile($transferOp);
if (!$skipLog) {
// e.g. if editing a file don't log that it was also downloaded
mftpActionLog("Download file", $this->connection, dirname($transferOp->getRemotePath()), monstaBasename($transferOp->getRemotePath()), "");
}
$this->disconnect();
}
public function downloadMultipleFiles($context) {
$this->connectAndAuthenticate();
$fileFinder = new RecursiveFileFinder($this->connection, $context['baseDirectory']);
$foundFiles = $fileFinder->findFilesInPaths($context['items']);
foreach ($foundFiles as $foundFile) {
$fullPath = PathOperations::join($context['baseDirectory'], $foundFile);
mftpActionLog("Download file", $this->connection, dirname($fullPath), monstaBasename($fullPath), "");
}
$zipBuilder = new ZipBuilder($this->connection, $context['baseDirectory']);
$zipPath = $zipBuilder->buildZip($foundFiles);
$this->disconnect();
return $zipPath;
}
public function createZip($context) {
$this->connectAndAuthenticate();
$fileFinder = new RecursiveFileFinder($this->connection, $context['baseDirectory']);
$foundFiles = $fileFinder->findFilesInPaths($context['items']);
foreach ($foundFiles as $foundFile) {
$fullPath = PathOperations::join($context['baseDirectory'], $foundFile);
mftpActionLog("Download file", $this->connection, dirname($fullPath), monstaBasename($fullPath), "");
}
$zipBuilder = new ZipBuilder($this->connection, $context['baseDirectory']);
$destPath = PathOperations::join($context['baseDirectory'], $context['dest']);
$zipPath = $zipBuilder->buildLocalZip($foundFiles, $destPath);
$this->connection->uploadFile(new FTPTransferOperation($zipPath, $destPath, FTP_BINARY));
$this->disconnect();
return $zipPath;
}
public function uploadFile($context, $preserveRemotePermissions = false, $skipLog = false) {
$this->connectAndAuthenticate();
$transferOp = TransferOperationFactory::getTransferOperation($this->connectionType, $context);
$this->connection->uploadFile($transferOp, $preserveRemotePermissions);
if (!$skipLog) {
// e.g. if editing a file don't log that it was also uploaded
mftpActionLog("Upload file", $this->connection, dirname($transferOp->getRemotePath()), monstaBasename($transferOp->getRemotePath()), "");
}
$this->disconnect();
}
public function uploadFileToNewDirectory($context) {
// This will first create the target directory if it doesn't exist and then upload to that directory
$this->connectAndAuthenticate();
$transferOp = TransferOperationFactory::getTransferOperation($this->connectionType, $context);
$this->connection->uploadFileToNewDirectory($transferOp);
mftpActionLog("Upload file", $this->connection, dirname($transferOp->getRemotePath()), monstaBasename($transferOp->getRemotePath()), "");
$this->disconnect();
}
public function deleteFile($context) {
$this->connectAndAuthenticate();
$this->connection->deleteFile($context['remotePath']);
mftpActionLog("Delete file", $this->connection, dirname($context['remotePath']), monstaBasename($context['remotePath']), "");
$this->disconnect();
}
public function makeDirectory($context) {
$this->connectAndAuthenticate();
$this->connection->makeDirectory($context['remotePath']);
$this->disconnect();
}
public function deleteDirectory($context) {
$this->connectAndAuthenticate();
$this->connection->deleteDirectory($context['remotePath']);
$this->disconnect();
}
public function rename($context) {
$this->connectAndAuthenticate();
if(array_key_exists('action', $context) && $context['action'] == 'move') {
$action = 'Move';
} else {
$action = 'Rename';
}
$itemType = $this->connection->isDirectory($context['source']) ? 'folder' : 'file';
$this->connection->rename($context['source'], $context['destination']);
if ($action == 'Move') {
mftpActionLog($action . " " . $itemType, $this->connection, dirname($context['source']),
monstaBasename($context['source']) . " to " . $context['destination'],
"");
}
if ($action == 'Rename') {
mftpActionLog($action . " " . $itemType, $this->connection, dirname($context['source']),
monstaBasename($context['source']) . " to " . monstaBasename($context['destination']),
"");
}
$this->disconnect();
}
public function changePermissions($context) {
$this->connectAndAuthenticate();
$itemType = $this->connection->isDirectory($context['remotePath']) ? 'folder' : 'file';
$this->connection->changePermissions($context['mode'], $context['remotePath']);
mftpActionLog("CHMOD " . $itemType, $this->connection, dirname($context['remotePath']),
monstaBasename($context['remotePath']) . " to " . decoct($context['mode']), "");
$this->disconnect();
}
public function copy($context) {
$this->connectAndAuthenticate();
$this->connection->copy($context['source'], $context['destination']);
$this->disconnect();
}
public function testConnectAndAuthenticate($context, $isInitalLogin = true) {
$initialDirectory = $this->connectAndAuthenticate($isInitalLogin);
$serverCapabilities = array("initialDirectory" => $initialDirectory);
if (isset($context['getServerCapabilities']) && $context['getServerCapabilities']) {
$serverCapabilities["changePermissions"] = $this->connection->supportsPermissionChange();
}
clearOldTransfers();
return array("serverCapabilities" => $serverCapabilities);
}
public function checkSavedAuthExists() {
if ($this->readLicense() == null)
return false;
return AuthenticationStorage::configurationExists(AUTHENTICATION_FILE_PATH);
}
public function writeSavedAuth($context) {
if ($this->readLicense() == null)
return;
AuthenticationStorage::saveConfiguration(AUTHENTICATION_FILE_PATH, $context['password'],
$context['authData']);
}
public function readSavedAuth($context) {
if ($this->readLicense() == null)
return array();
return AuthenticationStorage::loadConfiguration(AUTHENTICATION_FILE_PATH, $context['password']);
}
public function readLicense() {
$keyPairSuite = new KeyPairSuite(PUBKEY_PATH);
$licenseReader = new LicenseReader($keyPairSuite);
$license = $licenseReader->readLicense(MONSTA_LICENSE_PATH);
if (is_null($license))
return $license;
$publicLicenseKeys = array("expiryDate", "version", "isTrial", "licenseVersion", "productEdition");
$publicLicense = array();
foreach ($publicLicenseKeys as $publicLicenseKey) {
if (isset($license[$publicLicenseKey]))
$publicLicense[$publicLicenseKey] = $license[$publicLicenseKey];
}
return $publicLicense;
}
private function recordAffiliateSource($licenseEmail) {
$affiliateChecker = new AffiliateChecker();
$installUrl = getMonstaInstallUrl();
$affiliateId = defined("MFTP_AFFILIATE_ID") ? MFTP_AFFILIATE_ID : "";
return $affiliateChecker->recordAffiliateSource($affiliateId, $licenseEmail, $installUrl);
}
public function getSystemVars() {
$systemVars = SystemVars::getSystemVarsArray();
$applicationSettings = new ApplicationSettings(APPLICATION_SETTINGS_PATH);
$systemVars['applicationSettings'] = $applicationSettings->getSettingsArray();
return $systemVars;
}
public function setApplicationSettings($context) {
$applicationSettings = new ApplicationSettings(APPLICATION_SETTINGS_PATH);
$applicationSettings->setFromArray($context['applicationSettings']);
$applicationSettings->save();
}
public function validateSavedAuthPassword($context) {
return AuthenticationStorage::validateAuthenticationPassword(AUTHENTICATION_FILE_PATH, $context["password"]);
}
}
i am not that much experienced in this field i am a beginner and got this task to find out the cause of the delay and resolve it . kindly help me in this regard i have tried many things as i thought that json_encoding(response) might be the cause but just 10 items are returning in response

Need to identify an administrator with PHP and PDO

I do a project of an classified advertisements website, with PHP, Twig, SQL and PDO.
I want to put an elseif in the main.php (last part of code) during the users identification, and check if the user is an admin or not. My Admins value is a boolean in my table. I don't know how to do this checking.
First my user class :
<?php
class Utilisateur
{
private $ID_UTILISATEUR;
private $MDP_UTILISATEUR;
private $MAIL_UTILISATEUR;
private $NOM_UTILISATEUR;
private $PRENOM_UTILISATEUR;
private $ADMINS;
//CONSTRUCTEUR
public function __construct($id_user = -1, $user_pass = null, string $user_mail = null, string $nom = null, string $prenom = null, $admins = null)
{
$this->ID_UTILISATEUR = $id_user;
$this->MDP_UTILISATEUR = $user_pass;
$this->MAIL_UTILISATEUR = $user_mail;
$this->NOM_UTILISATEUR = $nom;
$this->PRENOM_UTILISATEUR = $prenom;
$this->ADMINS = $admins;
}
//GETTERS
public function getID_UTILISATEUR()
{
return $this->ID_UTILISATEUR;
}
public function getMDP_UTILISATEUR()
{
return $this->MDP_UTILISATEUR;
}
public function getMAIL_UTILISATEUR()
{
return $this->MAIL_UTILISATEUR;
}
public function getNOM_UTILISATEUR()
{
return $this->NOM_UTILISATEUR;
}
public function getPRENOM_UTILISATEUR()
{
return $this->PRENOM_UTILISATEUR;
}
public function getADMINS()
{
return $this->ADMINS;
}
//SETTERS
public function setID_UTILISATEUR($ID_UTILISATEUR)
{
$this->ID_UTILISATEUR = $ID_UTILISATEUR;
}
public function setMDP_UTILISATEUR($MDP_UTILISATEUR)
{
$this->MDP_UTILISATEUR = $MDP_UTILISATEUR;
}
public function setMAIL_UTILISATEUR($MAIL_UTILISATEUR)
{
$this->MAIL_UTILISATEUR = $MAIL_UTILISATEUR;
}
public function setNOM_UTILISATEUR($NOM_UTILISATEUR)
{
$this->NOM_UTILISATEUR = $NOM_UTILISATEUR;
}
public function setPRENOM_UTILISATEUR($PRENOM_UTILISATEUR)
{
$this->PRENOM_UTILISATEUR = $PRENOM_UTILISATEUR;
}
public function setADMINS($ADMINS)
{
$this->ADMINS = $ADMINS;
}
//FONCTION stringID
public function stringID()
{
return "[" . $this->ID_UTILISATEUR . "]";
}
//FONCTION __toString
public function __toString()
{
return $this->ID_UTILISATEUR . ", " . $this->NOM_UTILISATEUR . ", " . $this->MAIL_UTILISATEUR;
}
}
Then my DAO for getting the data of a user :
public function identifier(Utilisateur $u)
{
try
{
$n = $u->getMAIL_UTILISATEUR();
$p = $u->getMDP_UTILISATEUR();
$requete = $this->cnx->prepare("SELECT ID_UTILISATEUR, MDP_UTILISATEUR, MAIL_UTILISATEUR, ADMINS FROM utilisateur WHERE MAIL_UTILISATEUR=:mail and MDP_UTILISATEUR=SHA2(:pass,224)");
$requete->bindParam(':mail', $n);
$requete->bindParam(':pass', $p);
$requete->setFetchMode(PDO::FETCH_CLASS|PDO::FETCH_PROPS_LATE, 'Utilisateur');
// exécution et récupération des résultats
$data2 = $requete->execute();
$data2 = $requete->fetchAll(PDO::FETCH_CLASS|PDO::FETCH_PROPS_LATE, 'Utilisateur');
return $data2;
}
catch (PDOException $e)
{
throw new BDDException ("Impossible d'identifier les données", 201);
}
}
and the main.php function identify users :
function identifierUtilisateur()
{
require_once dirname(__DIR__) . "/DAO/MySQLUtilisateurDAO.php";
require_once dirname(__DIR__) . "/views/VueLogin.php";
$login = new MySQLUtilisateurDAO();
$login1 = new Utilisateur("", $_POST['mdp'], $_POST['mail'], "", "", "");
$l = $login->identifier($login1);
if (empty($l)) {
echo 'utilisateur non identifié';
$url = $_SERVER["PHP_SELF"];
echo ('<a href=' . $url . '>return</a>');
}
else {
$_SESSION['identification'] = $l;
$mail = $_POST['mail'];
$mdp = $_POST['mdp'];
setcookie("MAIL_UTILISATEUR", $mail, time() + 864000, '/'); // expire après 10 jours
setcookie("MDP_UTILISATEUR", $mdp, time() + 864000, '/');
$url = $_SERVER["PHP_SELF"];
afficherAnnoncesUtilisateur();
}
}

Passing variables from one class to an other in PhP

Hello I am trying to build my first restful web service and im using the instruction from lorna jane mitchell blog.
If the req comes through this Url : http://localhost:8888/lorna/index.php/tree/getpath?node_id=75
i call the function getpath passing node_id
The function get path looks like this :
class NestedSet
{
public function getPath($id) {
$sql = "SELECT p." . $this->pk . ", p." . $this->name . " FROM ". $this->table . " n, " . $this->table . " p WHERE n.lft BETWEEN p.lft AND p.rgt AND n." . $this->pk ." = " . $id . " ORDER BY p.lft;";
$result = $this->db->query($sql);
if ($result->num_rows == 0) {
return $this->error(1, true);
}
$path = array();
$i = 0;
while ($row = $result->fetch_assoc()) {
$path[$i] = $row;
$i++;
}
return $path;
}
}
Now i want to pass this variable $path to the class JsonView that looks like this :
class JsonView extends ApiView {
public function render($path) {
header('Content-Type: application/json; charset=utf8');
echo json_encode($path);
return true;
}
}
class ApiView {
protected function addCount($data) {
if(!empty($data)) {
// do nothing, this is added earlier
} else {
$data['meta']['count'] = 0;
}
return $data;
}
}
Any Idea on how can I pass the variable $path or any other variable through this JsonView Class.
Thank you very much for your time :)
UPDATE This is the code for creating the nested class object
public function getAction($request) {
$data = $request->parameters;
if(isset($request->url_elements[2])) {
switch ($request->url_elements[2]) {
case 'getpath':
$id = $data['node_id'];
$nested = new NestedSet();
$nested->getPath($id);
$api = new JsonView();
$api->render($path);
break;
default:
# code...
break;
}
} else {
$nested = new NestedSet();
echo $nested->treeAsHtml();
}
}
Just create object of JsonView and then call the function render using that object.
$api = new JsonView;
$api->render($path);

Session data changed in php

This is my code
class WcfClient {
public $wcfClient = null;
public $user = null;
public function __construct(){
if(isset($_SESSION['APIClient']) && $_SESSION['APIClient'] != null){
$this->wcfClient = $_SESSION['APIClient'];
}
}
public function __destruct(){
}
// Authanticate
private function Authenticate(){
global $_sogh_soapUrl, $_isDebug, $_sogh_header;
$wcargs = array();
$consumerAuthTicket = null;
if($this->wcfClient == null){
$args = array(
'clubname'=>'Wellness Institute at Seven Oaks',
'consumerName'=>'api',
'consumerPassword'=>'api'
);
try{
$wcargs = array(
'soap_version'=>SOAP_1_2
);
if($_isDebug){
$wcargs = array(
'soap_version'=>SOAP_1_2,
'proxy_host'=>"192.168.0.1",
'proxy_port'=>8080
);
}
// Connect to the API with soapclient
$soapAPIClient = new SoapClient($_sogh_soapUrl, $wcargs);
$response = $soapAPIClient->AuthenticateClubConsumer($args);
if(isset($response->AuthenticateClubConsumerResult)){
if(isset($response->AuthenticateClubConsumerResult->IsException) && $response->AuthenticateClubConsumerResult->IsException == true){
// some error occur
$this->wcfClient = null;
$_SESSION['APIClient'] = $this->wcfClient;
} else{
// set consumer ticket
$consumerAuthTicket = $response->AuthenticateClubConsumerResult->Value->AuthTicket;
// $loginData = $responseCode->ReturnValueOfConsumerLoginData;
$headers = array();
$headers[] = new SoapHeader($_sogh_header, "ConsumerAuthTicket", $consumerAuthTicket);
$soapAPIClient->__setSoapHeaders($headers);
// add to session
$this->wcfClient = $soapAPIClient;
$_SESSION['APIClient'] = $this->wcfClient;
}
}
} catch(SoapFault $fault){
$this->error('Fault: ' . $fault->faultcode . ' - ' . $fault->faultstring);
} catch(Exception $e){
$this->error('Error: ' . $e->getMessage());
}
}
return $this->wcfClient;
}
I store the soap client object in $_SESSION['APIClient'], but second times when run some data has been changed in session, I am use this class in drupal 7, I want to save the time using session, because authenticating takes long time.
Please help
Thank in advance

How to use sessions

http://dev."xxxxxyyyyy".com/xxxxx-community/register.html?&invite=5000
I need to store this id ($invite=5000) in a variable called $fromid using session.There are two functions in /components/com_community/controllers/register.php
Where should I call this and how??
class CommunityRegisterController extends CommunityBaseController
{
public function register()
{
}
another one
public function register_save()
{
$mainframe =& JFactory::getApplication();
$modelRegister = CFactory::getModel('register');
// Check for request forgeries
$mySess =& JFactory::getSession();
if(! $mySess->has('JS_REG_TOKEN'))
{
echo '<div class="error-box">' . JText::_('COM_COMMUNITY_INVALID_SESSION') . '</div>';
return;
}
$token = $mySess->get('JS_REG_TOKEN','');
$ipAddress = isset($_SERVER['HTTP_X_FORWARDED_FOR']) ? $_SERVER['HTTP_X_FORWARDED_FOR'] : $_SERVER['REMOTE_ADDR'];
$authKey = $modelRegister->getAssignedAuthKey($token, $ipAddress);
$formToken = JRequest::getVar( 'authkey', '', 'REQUEST');
if(empty($formToken) || empty($authKey) || ($formToken != $authKey))
{
//echo $formToken .'|'. $authKey;
echo '<div class="error-box">' . JText::_('COM_COMMUNITY_INVALID_TOKEN') . '</div>';
return;
}
//update the auth key life span to another 180 sec.
$modelRegister->updateAuthKey ($token, $authKey, $ipAddress);
// Get required system objects
$config = CFactory::getConfig();
$post = JRequest::get('post');
// If user registration is not allowed, show 403 not authorized.
$usersConfig = &JComponentHelper::getParams( 'com_users' );
if ($usersConfig->get('allowUserRegistration') == '0')
{
//show warning message
$view =& $this->getView('register');
$view->addWarning(JText::_( 'COM_COMMUNITY_REGISTRATION_DISABLED' ));
echo $view->get('register');
return;
}
Can i access that $fromid in components/com_users/controllers/registration.php that uses the class
class UsersControllerRegistration extends UsersController
{
}
You can use GET method to get the value , then store it in session variable,
Eg:
$_SESSION['fromid'] = $_GET['invite'];
$fromid = $_SESSION['fromid'];

Categories