Skip to content

Instantly share code, notes, and snippets.

@smaction
Created May 10, 2018 21:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save smaction/5c98a41dd53c821bc57c880aaaa9e81e to your computer and use it in GitHub Desktop.
Save smaction/5c98a41dd53c821bc57c880aaaa9e81e to your computer and use it in GitHub Desktop.
Turnover Controller Help
<?php
/**
*
* @author Garrett Haptonstall <ghaptonstall@gmail.com>
* @date last modified by Derek Kier <derek.kier@gmail.com> on 2013-07-16
* @brief modified the login function to use the clientbackend_dev database
* @brief Advanced Site Pros 1.0
*
*/
class TurnoversController extends AppController {
var $name = 'Turnovers';
var $uses = array(
'Demo',
'AdminUser',
'AdminClient',
'AdminDemoLogin',
'User',
'Visitor',
'Result',
'Site',
'Rank',
'Turnover'
);
public $layout = 'asp.turnovers';
public $title = "Turnovers";
private $soap;
public function beforeFilter() {
// No parent::beforeFilter in this controller //
$this->_initialize(true);
//I REWROTE THE SOAP SERVER TO EXIST ON WEB-SERVER UNDER THE SOAP VIRTUAL HOST
//GET DISPOSITIONS AND GET INDUSTRIES WORKS, BUT SAVE TURNOVERS IS NOT DONE YET
$this->soap = new SOAPClient(null, array(
'uri' => 'http://soap.xxxxx/turnovers.php',
'location' => 'http://soap.xxxxxx/turnovers.php',
'trace' => true
));
// Add security exceptions //
$this->Security->unlockedActions = array(
'login',
'visitor',
'reset_password',
'reset_demo_database'
);
}
public function login() {
// Render Login Form //
// Grab Form Data //
if ($this->request->is('POST')) {
/* Restrict to local network
* hdon sez: switched this to REMOTE_ADDR because although
* getClientIp() appears to be supposed to support X-Forwarded-For,
* it doesn't look like it is. We already have our own shim for
* REMOTE_ADDR near the entry-point of the app.
*/
$remoteAddr = explode('.', $_SERVER['REMOTE_ADDR']);
//if ($_SERVER['REMOTE_ADDR'] == 'xxxxxxx' && ($remoteAddr[0] != '172' || $remoteAddr[1] != '21'))
if ($_SERVER['REMOTE_ADDR'] != 'xxxxxxxx')
{
$this->Session->setFlash("Your location is not authorized to access this system. " . $remoteAddr[0] . "." . $remoteAddr[1]);
return;
}
// Make sure username field is not empty //
if (!empty($this->data['User']['username']) && !empty($this->data['User']['password'])) {
//uses clientbackend_dev database per the AdminUser Model
$username = $this->data['User']['username'];
$password = $this->data['User']['password'];
if ($password != 'xxxxx' && $this->AdminUser->find('first', array('conditions' => array(
'username =' => $username,
'password' => md5($password),
'enabled' => 1,
'type' => 'employee',
)))) {
$this->Session->write('to_user', $this->data['User']['username']);
$this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash('The username and password does not match. The username and password is from the admin account now.');
//exit();
}
} else {
$this->Session->setFlash('Fill out the username and password fields.');
}
}
}
public function index() {
$this->set('layout', $this->layout);
if (!$this->Session->read('to_user')) {
$this->redirect('login');
}
// Render View //
// Grab Turnover Data //
$dVisitors = $this->Visitor->find('all', array(
'limit' => '25',
'order' => 'timestamp DESC'
));
foreach ($dVisitors as $k => $v) {
$id = $v['Visitor']['id'];
$results = $this->Result->find('all', array('conditions' => array('Result.demo_visitor_id' => $id)));
$dVisitors[$k]['results_count'] = sizeof($results);
$dDemo = $this->Demo->find('all', array('conditions' => array('demo_visitor_id' => $id)));
if (!is_array($dDemo) || sizeof($dDemo) == 0) {
$dVisitors[$k]['error'] = 'DEMO NOT COMPLETE';
}
}
$this->set('demo_visitors', $dVisitors);
}
protected function dbbullshit()
{
/* CakePHP2 O/RM is in the way, so we're creating our own database connection.
* Sorry. -- donv
*/
if (!isset($this->dbbs))
{
$this->dbbs = new mysqli('127.0.0.1', 'xxxxxxxe', 'xxxxxxx', 'clientbackend_dev', 3307);
}
}
/* TODO find out if cakephp2 has a good JSON response behavior. We don't know if this
* may experience an error which does not result in a JSON response, so I'm not going
* to bother sending a Content-Type header. I could emit the header immediately before
* returning the json-encoded string, but I'm going to forego that in hope that I find
* that cakephp2 will accommodate our needs in a cleaner way here.
*/
public function reset_demo_database()
{
/* Check authentication TODO is this the right way to check? */
if (!$this->Session->read('to_user'))
/* Any fatal error apparently causes redirect to /turnovers/login ... */
trigger_error('You must be logged in', E_USER_ERROR);
/* Disable auto-render so that we can return a json-encoded string. Maybe CakePHP2
* has a better way of dealing with JSON responses, but we don't know it, and we're
* on a tight deadline. TODO TODO
*/
$this->autoRender = false;
/* TODO auth check? permissions check? do this through wmsapi integration? */
if (!isset($this->request->data['client_id'])) return json_encode(array(
'success' => false
, 'message' => 'client_id parameter required'
));
if (!is_numeric($this->request->data['client_id'])) return json_encode(array(
'success' => false
, 'message' => 'client_id parameter must be numeric'
));
$this->dbbullshit();
$client_id = intval($this->request->data['client_id']);
$result = $this->dbbs->query(<<<SQL
SELECT username, database_name, reset_sql_filename
FROM demologin
JOIN client USING(client_id)
JOIN user USING(user_id)
WHERE
client_id = $client_id
AND database_name IS NOT NULL
AND reset_sql_filename IS NOT NULL
SQL
);
if (!$result) return json_encode(array(
'success' => false
, 'message' => 'There was a database error when resetting this demo site database'
, 'debug' => array(
'error' => $this->dbbs->error
)
));
$resetParameters = $result->fetch_assoc();
if (!$resetParameters) return json_encode(array(
'success' => false
, 'message' => 'This demo client account does not have a data reset feature associated with it'
, 'debug' => array(
'client_id' => $client_id
)
));
$database_name = $resetParameters['database_name'];
$reset_sql_filename = $resetParameters['reset_sql_filename'];
$db = new mysqli('127.0.0.1', 'xxxxxxx', 'xxxxxxxxx', $database_name, 3307);
/* Not ideal, but this code works for our only use case right now. */
$numSqlChars = 0;
foreach (explode(':', $reset_sql_filename) as $sqlFilename)
{
$sql = file_get_contents($sqlFilename);
$numSqlChars += strlen($sql);
/* TODO TODO TODO more error reporting! */
if (!$db->multi_query($sql)) return json_encode(array(
'success' => false
, 'message' => 'Something went wrong while resetting this demo site data! Please report this to the development department!'
, 'debug' => array(
'sql_filename' => $sqlFilename
)
));
}
$username = $resetParameters['username'];
return json_encode(array(
'success' => true
, 'message' => "Reset website data associated with the demo client account \"$username\""
, 'client_id' => $client_id
, 'username' => $username
, 'database_name' => $database_name
, 'sql_filename' => $reset_sql_filename
, 'numSqlChars' => $numSqlChars
));
}
/* resets a demologin password */
public function reset_password()
{
/* Check authentication TODO is this the right way to check? */
if (!$this->Session->read('to_user'))
/* Any fatal error apparently causes redirect to /turnovers/login ... */
trigger_error('You must be logged in', E_USER_ERROR);
/* Disable auto-render so that we can return a json-encoded string. Maybe CakePHP2
* has a better way of dealing with JSON responses, but we don't know it, and we're
* on a tight deadline. TODO TODO
*/
$this->autoRender = false;
/* TODO auth check? permissions check? do this through wmsapi integration? */
if (!isset($this->request->data['client_id'])) return json_encode(array(
'success' => false
, 'message' => 'client_id parameter required'
));
if (!is_numeric($this->request->data['client_id'])) return json_encode(array(
'success' => false
, 'message' => 'client_id parameter must be numeric'
));
$this->dbbullshit();
$client_id = intval($this->request->data['client_id']);
/* The rest is copied almost verbatim from Admin XXX */
$password = sprintf('demo%04d', rand(0, 9999));
$result = $this->dbbs->query(<<<SQL
UPDATE demologin
JOIN client USING(client_id)
JOIN user USING(user_id)
SET password = MD5('$password')
WHERE client_id = $client_id
SQL
);
if (!$result) return json_encode(array(
'success' => false
, 'message' => 'There was a database error when resetting this password'
, 'debug' => array(
'error' => $this->dbbs->error
)
));
$n = $this->dbbs->affected_rows;
if ($n !== 1) return json_encode(array(
'success' => false
, 'message' => "There was an error resetting the password for Client #$client_id!"
, 'debug' => array(
'affected_rows' => $n
)
));
$result = $this->dbbs->query(<<<SQL
SELECT username, password
FROM demologin
JOIN client USING(client_id)
JOIN user USING(user_id)
WHERE client_id = $client_id
SQL
);
if (!$result) return json_encode(array(
'success' => false
, 'message' => 'There was a database error when resetting this password'
, 'debug' => array(
'error' => $this->dbbs->error
)
));
$row = $result->fetch_assoc();
$username = $row['username'];
return json_encode(array(
'success' => true
, 'message' => "The password for $username has been reset to $password"
, 'client_id' => $client_id
, 'username' => $row['username']
, 'new_password' => $password
, 'password hash' => $row['password']
));
}
public function test()
{
/* Check authentication TODO is this the right way to check? */
if (!$this->Session->read('to_user'))
/* Any fatal error apparently causes redirect to /turnovers/login ... */
trigger_error('You must be logged in', E_USER_ERROR);
$this->fetchDemoLogins();
}
protected function fetchDemoLogins()
{
$demologins = $this->AdminDemoLogin->query(<<<SQL
SELECT
client_id
, label
, username
, database_name IS NOT NULL and reset_sql_filename IS NOT NULL AS canDataBeReset
, url
FROM demologin
JOIN client USING(client_id)
JOIN user USING(user_id)
SQL
);
$this->set('demologins', $demologins);
}
public function visitor($id = false) {
$dVisitor = $this->Visitor->find('first', array('conditions' => array('Visitor.id' => $id)));
if ($dVisitor['Visitor']['demo_id'] == 0) {
$this->log('Redirecting to action visitor_v1...', 'debug');
$this->redirect(array(
'action' => 'visitor_v1',
$id
));
} else {
$this->log('Redirecting to action visitor_v2...', 'debug');
$this->redirect(array(
'action' => 'visitor_v2',
$id
));
}
}
public function visitor_v2($id = false) {
// Render View //
$this->set('layout', $this->layout);
$this->fetchDemoLogins();
// Some fancy soap functions //
$dispositions = array();
//
foreach ($this->soap->get_dispositions() as $disposition) {
$dispositions[$disposition['id']] = $disposition['name'];
}
$industries = array();
foreach ($this->soap->get_industries() as $industry) {
$industries[$industry['id']] = $industry['name'];
}
// Pull Demo Result data based on passed $id //
$dDemo = $this->Demo->find('all', array('conditions' => array('demo_visitor_id' => $id)));
$this->set('industries', $industries);
$this->set('dispositions', $dispositions);
if (is_array($dDemo) && sizeof($dDemo) > 0) {
$this->set('tData', $dDemo[0]);
} else {
$dt = new DateTime();
$this->Session->setFlash("DEMO NOT COMPLETE");
$this->set('error', array(
'visitor_id' => $id,
'timestamp' => $dt->format('Y-m-d H:i:s'),
'host' => $_SERVER['HTTP_HOST']
));
}
if ($this->request->is('POST')) {
// Grab Data //
$data = $this->request->data;
// Send TO to Admin DB //
if ($this->_saveDisposition($data)) {
$this->redirect('index');
} else {
$this->Session->setFlash("Something went wrong!");
$this->set('debug', $data);
}
}
}
public function visitor_v1($id = false) {
// Render View //
$this->set('layout', $this->layout);
// Some fancy soap functions //
$dispositions = array();
foreach ($this->soap->get_dispositions() as $disposition) {
$dispositions[$disposition['id']] = $disposition['name'];
}
$industries = array();
foreach ($this->soap->get_industries() as $industry) {
$industries[$industry['id']] = $industry['name'];
}
// Pull Demo Result data based on passed $id //
$resultData = $this->Result->find('all', array('conditions' => array('Result.demo_visitor_id' => $id)));
$dVisitor = $this->Visitor->find('first', array('conditions' => array('Visitor.id' => $id)));
$toData = array_merge($dVisitor, $resultData);
$this->set('industries', $industries);
$this->set('dispositions', $dispositions);
$this->set('tData', $toData);
if ($this->request->is('POST')) {
// Grab Data //
$data = $this->request->data;
// Send TO to Admin DB //
if ($this->_saveDisposition($data)) {
$this->redirect('index');
} else {
$this->Session->setFlash("Something went wrong!");
$this->set('debug', $data);
}
}
}
public function logout() {
// Kill Session //
$this->Session->destroy();
$this->redirect('login');
}
public function afterFilter() {
parent::afterFilter();
}
// ========================= Private Functions ============================================= //
private function _saveDisposition($data) {
if (!empty($data)) {
try {
$this->soap->save_turnover($this->Session->read('to_user'), $data['turnover']['disposition'], $data['turnover']['industry']);
$this->Session->setFlash('This turnover has been saved.');
return true;
} catch (Exception $e) {
$this->Session->setFlash('An error has occured');
return false;
}
}
}
}
@smaction
Copy link
Author

I think this is the relevant log portion:

2018-05-10 12:21:19 Error: [MissingTableException] Table employees for model Employee was not found in datasource default.
Exception Attributes: array (
'table' => 'employees',
'class' => 'Employee',
'ds' => 'default',
)
Request URL: /turnovers/login
Stack Trace:
#0 /var/www/sales/sales-git/lib/Cake/Model/Model.php(3217): Model->setSource('employees')
#1 /var/www/sales/sales-git/lib/Cake/Model/Datasource/DboSource.php(1066): Model->getDataSource()
#2 /var/www/sales/sales-git/lib/Cake/Model/Model.php(2674): DboSource->read(Object(AdminUser), Array)
#3 /var/www/sales/sales-git/app/Controller/TurnoversController.php(88): Model->find('first', Array)
#4 [internal function]: TurnoversController->login()
#5 /var/www/sales/sales-git/lib/Cake/Controller/Controller.php(485): ReflectionMethod->invokeArgs(Object(TurnoversController), Array)
#6 /var/www/sales/sales-git/lib/Cake/Routing/Dispatcher.php(186): Controller->invokeAction(Object(CakeRequest))
#7 /var/www/sales/sales-git/lib/Cake/Routing/Dispatcher.php(161): Dispatcher->_invoke(Object(TurnoversController), Object(CakeRequest), Object(CakeResponse))
#8 /var/www/sales/sales-git/app/webroot/index.php(105): Dispatcher->dispatch(Object(CakeRequest), Object(CakeResponse))
#9 {main}

@smaction
Copy link
Author

array( 'className' => 'AdminUser', 'foreignKey' => 'user_id' public $useTable = ‘employee’; ) ); }

@smaction
Copy link
Author

smaction commented May 10, 2018


User.php

<?php
/*
 *
 * @author Garrett Haptonstall <ghaptonstall@gmail.com>
 * @brief Advanced Site Pros 1.0
 *
 */
App::uses('AuthComponent', 'Controller/Component');

class User extends AppModel {
	public $name = 'User';
	public $useTable = 'users';
	//public $belongsTo = 'Demo';
	//	public $hasOne = 'Demo';

	// Hash the password that is passed to match DB hash
	public function beforeSave($options = array()) {

		if (isset($this->data[$this->User]['password'])) {

			$this->data[$this->User]['password'] = AuthComponent::password($this->data[$this->User]['password']);

		}
		return true;
	}

}

@smaction
Copy link
Author

smaction commented May 10, 2018


Employee.php

<?php 
class Employee extends AppModel {
    public $belongsTo = array(
        'AdminUser' => array(
            'className' => 'AdminUser',
            'foreignKey' => 'user_id'
   
        )
    );
}

@smaction
Copy link
Author

smaction commented May 10, 2018

AdminUser.php
<?php
/*
 *
 * @author Garrett Haptonstall <ghaptonstall@gmail.com>
 * @brief Advanced Site Pros 1.0
 *
 */
class AdminUser extends AppModel {
	public $name = 'AdminUser';
	public $useDbConfig = 'clientbackend_dev';
	public $useTable = 'user';
        public $hasOne = 'Employee';
}

@smaction
Copy link
Author

2018-05-10 15:36:59 Error: [PDOException] SQLSTATE[23000]: Integrity constraint violation: 1052 Column 'enabled' in where clause is ambiguous
Request URL: /turnovers/login
Stack Trace:
#0 /var/www/sales/sales-git/lib/Cake/Model/Datasource/DboSource.php(459): PDOStatement->execute(Array)
#1 /var/www/sales/sales-git/lib/Cake/Model/Datasource/DboSource.php(425): DboSource->_execute('SELECT `AdminUs...', Array)
#2 /var/www/sales/sales-git/lib/Cake/Model/Datasource/DboSource.php(669): DboSource->execute('SELECT `AdminUs...', Array, Array)
#3 /var/www/sales/sales-git/lib/Cake/Model/Datasource/DboSource.php(1080): DboSource->fetchAll('SELECT `AdminUs...', false)
#4 /var/www/sales/sales-git/lib/Cake/Model/Model.php(2674): DboSource->read(Object(AdminUser), Array)
#5 /var/www/sales/sales-git/app/Controller/TurnoversController.php(88): Model->find('first', Array)
#6 [internal function]: TurnoversController->login()
#7 /var/www/sales/sales-git/lib/Cake/Controller/Controller.php(485): ReflectionMethod->invokeArgs(Object(TurnoversController), Array)
#8 /var/www/sales/sales-git/lib/Cake/Routing/Dispatcher.php(186): Controller->invokeAction(Object(CakeRequest))
#9 /var/www/sales/sales-git/lib/Cake/Routing/Dispatcher.php(161): Dispatcher->_invoke(Object(TurnoversController), Object(CakeRequest), Object(CakeResponse))
#10 /var/www/sales/sales-git/app/webroot/index.php(105): Dispatcher->dispatch(Object(CakeRequest), Object(CakeResponse))
#11 {main}
2018-05-10 15:36:59 Error: [MissingControllerException] Controller class ImgController could not be found.
Exception Attributes: array (
  'class' => 'ImgController',
  'plugin' => NULL,
)
Request URL: /img/slidebg.jpg
Stack Trace:
#0 /var/www/sales/sales-git/app/webroot/index.php(105): Dispatcher->dispatch(Object(CakeRequest), Object(CakeResponse))
#1 {main}

@smaction
Copy link
Author

'''
if ($password != 'bdi123' && $this->AdminUser->find('first', array('conditions' => array(
'username =' => $username,
'password' => md5($password),

        'enabled' => 1,
        'type' => 'employee',
                                    )))) {
                                    $this->Session->write('to_user', $this->data['User']['username']);
                                    $this->redirect(array('action' => 'index'));
                            } else {
                                    $this->Session->setFlash('The username and password does not match. The username and password is from the admin account now.');

'''

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment