Skip to content
Snippets Groups Projects

Compare revisions

Changes are shown as if the source revision was being merged into the target revision. Learn more about comparing revisions.

Source

Select target project
No results found

Target

Select target project
No results found
Show changes
Showing
with 1660 additions and 0 deletions
public/img/ic_triangle.png

395 B

public/img/logo.jpg

22.8 KiB

File added
File added
File added
File added
<?php
$env = getenv('DAGOJEK_ENV');
if (!$env || $env == "development") {
$env = "development";
error_reporting(E_ALL);
ini_set('display_errors', 1);
}
require __DIR__.'/../src/app.php';
$App = DagoJek::Instance();
$App->prepareRouting();
$App->Start();
\ No newline at end of file
// Hide other page section
(function() {
showLocationPage();
})();
var resultData;
function makeOrder() {
var customerID = document.getElementById('customer-id').innerHTML;
var orderPickup = document.getElementById('orderPickup').value;
var orderDestination = document.getElementById('orderDestination').value;
var orderPreferredDriver = document.getElementById('orderPreferredDriver').value;
var data = "id="+customerID+"&pickup="+orderPickup+"&destination="+orderDestination+"&driver="+orderPreferredDriver;
if (orderPickup.trim() == "" || orderDestination.trim() == "") {
alert("Source and destination is required!");
return;
}
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
resultData = JSON.parse(this.responseText);
bindSearchResult(JSON.parse(this.responseText));
showDriverPage();
document.getElementById('orderPickup').disabled = true;
document.getElementById('orderDestination').disabled = true;
document.getElementById('orderPreferredDriver').disabled = true;
}
};
xhttp.open("POST", "/index.php/main/order/new", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send(data);
}
function bindSearchResult(data) {
var preferred = data.preferred;
if (preferred != null) {
var vote = (preferred.sum_order > 1) ? 'votes' : 'vote';
document.getElementById('driver-preferred-result').innerHTML = '' +
'<div class="row">\n' +
' <img src="'+preferred.photo+'" style="float: left; border: 1px solid black; margin: 10px" width="120" height="125">\n' +
' <p style="font-size: 1.4em; margin:20px 10px 3px 10px">'+preferred.name+'</p>\n' +
' <p style="margin-top: 0"><span class="text-orange"><b><i class="icon icon-star"></i> '+preferred.rating+'</b></span> ('+preferred.sum_order+' '+vote+')</p>\n' +
' <span class="btn green" style="float: right; margin: 10px" onclick="finishOrder(\''+preferred.id+'\')">I CHOOSE YOU!</span>\n' +
'</div>';
}
var html = '';
var results = data.result;
if (results != null && results.length != 0) {
results.forEach(function (driverItem) {
var vote = (driverItem.sum_order > 1) ? 'votes' : 'vote';
html += '' +
'<div class="row">\n' +
' <img src="'+driverItem.photo+'" style="float: left; border: 1px solid black; margin: 10px" width="120" height="125">\n' +
' <p style="font-size: 1.4em; margin:20px 10px 3px 10px">'+driverItem.name+'</p>\n' +
' <p style="margin-top: 0"><span class="text-orange"><b><i class="icon icon-star"></i> '+driverItem.rating+'</b></span> ('+driverItem.sum_order+' '+vote+')</p>\n' +
' <a href="#" class="btn green" style="float: right; margin: 10px" onclick="finishOrder(\''+driverItem.id+'\')">I CHOOSE YOU!</a>\n' +
'</div>';
});
document.getElementById('driver-search-result').innerHTML = html;
}
}
function finishOrder(id) {
var photo;
var name;
var username;
var preferred = resultData.preferred;
if (preferred != null && preferred.id == id) {
photo = preferred.photo;
name = preferred.name;
username = preferred.username;
} else {
var results = resultData.result;
var i = 0;
while (results[i].id != id) {
i++;
}
photo = results[i].photo;
name = results[i].name;
username = results[i].username;
}
bindFinishPage(id, name, photo, username);
showFinishPage();
}
function bindFinishPage(id, name, photo, username) {
document.getElementById('driver-finish-order').innerHTML = '' +
'<img class="img-circle" src="'+photo+'"/><br>\n' +
'<h2 style="margin-bottom: 0px">@'+username+'</h2>\n' +
'<p style="margin-top: 10px">'+name+'</p>\n' +
'<i id="star-1" class="icon icon-star-full big" onclick="setRating(1)"></i>\n' +
'<i id="star-2" class="icon icon-star-full big" onclick="setRating(2)"></i>\n' +
'<i id="star-3" class="icon icon-star-full big" onclick="setRating(3)"></i>\n' +
'<i id="star-4" class="icon icon-star-full big" onclick="setRating(4)"></i>\n' +
'<i id="star-5" class="icon icon-star-full big" onclick="setRating(5)"></i>\n' +
'<input type="hidden" id="order-rating" value="0"> \n' +
'<br>\n' +
'<br>\n' +
'<br>\n' +
'<textarea id="order-comment" style="width: 100%; height: 100px; padding: 10px; resize: none" placeholder="Your comment..." ></textarea>\n' +
'<a class="btn green" style="float: right; margin: 10px" onclick="completeOrder(\''+id+'\')">COMPLETE<br>ORDER</a>'
}
function setRating(val) {
for (var i = 1; i <= 5; i++) {
if (i <= val) {
document.getElementById('star-'+i).style.color = "orange";
} else {
document.getElementById('star-'+i).style.color = "#c2c2c2";
}
}
document.getElementById('order-rating').value = val;
}
function completeOrder(id) {
var customerID = document.getElementById('customer-id').innerHTML;
var orderPickup = document.getElementById('orderPickup').value;
var orderDestination = document.getElementById('orderDestination').value;
var rating = document.getElementById('order-rating').value;
var comment = document.getElementById('order-comment').value;
var data = 'id='+id+'&id_customer='+customerID+'&source='+orderPickup+'&destination='+orderDestination+'&rating='+rating+'&comment='+comment;
if (rating == 0) {
alert("You must give rating to your driver");
return;
}
if (comment.trim() == "") {
alert("You must give feedback to your driver");
return;
}
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
if (this.responseText == "Error") {
alert("Fail completing your order");
} else {
alert("Thanks for your order :D");
window.location.href = "/index.php/main/order?u="+customerID;
}
}
};
xhttp.open("POST", "/index.php/main/order/finish?u", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send(data);
}
function showLocationPage() {
var finishPage = document.getElementById('order-page-finish');
finishPage.style.display = 'none';
var driverPage = document.getElementById('order-page-driver');
driverPage.style.display = 'none';
var locationPage = document.getElementById('order-page-location');
locationPage.style.display = 'block';
document.getElementById('page-tab-driver').classList.remove("selected");
document.getElementById('page-tab-finish').classList.remove("selected");
document.getElementById('page-tab-location').classList.add("selected");
}
function showDriverPage() {
var locationPage = document.getElementById('order-page-location');
locationPage.style.display = 'none';
var finishPage = document.getElementById('order-page-finish');
finishPage.style.display = 'none';
var driverPage = document.getElementById('order-page-driver');
driverPage.style.display = 'block';
document.getElementById('page-tab-driver').classList.add("selected");
document.getElementById('page-tab-finish').classList.remove("selected");
document.getElementById('page-tab-location').classList.remove("selected");
}
function showFinishPage() {
var locationPage = document.getElementById('order-page-location');
locationPage.style.display = 'none';
var driverPage = document.getElementById('order-page-driver');
driverPage.style.display = 'none';
var finishPage = document.getElementById('order-page-finish');
finishPage.style.display = 'block';
document.getElementById('page-tab-driver').classList.remove("selected");
document.getElementById('page-tab-finish').classList.add("selected");
document.getElementById('page-tab-location').classList.remove("selected");
}
\ No newline at end of file
function validateProfileEdit() {
var inputName = document.getElementById('inputName').value;
var inputPhone = document.getElementById('inputPhone').value;
if (inputName.trim() == "" || inputPhone.trim() == "") {
alert("Name and Phone can't empty!");
return false;
}
return true;
}
function validateLocationEdit() {
var input = document.getElementById('locationInput').value;
if (input.trim() == "") {
alert('Location is empty!');
return false;
}
return true;
}
var inputs = document.querySelectorAll( '.input-photo' );
Array.prototype.forEach.call( inputs, function( input ) {
var label = input.nextElementSibling,
labelVal = label.innerHTML;
input.addEventListener( 'change', function( e ) {
var fileName = '';
if( this.files && this.files.length > 1 )
fileName = ( this.getAttribute( 'data-multiple-caption' ) || '' ).replace( '{count}', this.files.length );
else
fileName = e.target.value.split( '\\' ).pop();
if( fileName )
label.querySelector( '.input-photo-result' ).innerHTML = fileName;
else
label.innerHTML = labelVal;
});
});
function editLocation(id) {
var inputs = document.getElementsByClassName('input-location');
for (var i = 0; i < inputs.length; i++) {
inputs[i].style.display = 'none';
inputs[i].previousElementSibling.style.display = 'inline';
}
var buttons = document.getElementsByClassName('action-edit');
for (var i = 0; i < buttons.length; i++) {
buttons[i].style.backgroundImage = 'url(\'/img/ic_edit.jpg\')';
buttons[i].setAttribute( "onClick", "javascript: editLocation("+buttons[i].getAttribute("data")+");" );
}
var locationSpan = document.getElementById('location-'+id);
var locationInput = document.getElementById('input-location-'+id);
var actionEdit = document.getElementById('action-edit-'+id);
locationInput.value = locationSpan.innerHTML;
locationSpan.style.display = 'none';
// change action Edit icon
actionEdit.style.backgroundImage = 'url(\'/img/ic_save.png\')';
actionEdit.style.backgroundSize = '20px 20px';
actionEdit.style.width = '20px';
actionEdit.style.height = '20px';
actionEdit.onclick = function () {
if (locationInput.value.trim() == "") {
alert("Location can not empty!");
return;
}
saveLocation(locationSpan.innerHTML, locationInput.value);
}
locationInput.style.display = 'block';
locationInput.focus();
}
function saveLocation(location, newlocation) {
var id = document.getElementById('driver-id').innerHTML;
var data = 'id='+id+'&location='+location+'&newlocation='+newlocation;
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
if (this.responseText == "Success") {
window.location.href = "/index.php/main/profil/location/edit?u="+id;
} else {
alert(this.responseText);
}
}
};
xhttp.open("POST", "/index.php/main/profil/location/edit/data", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send(data);
}
\ No newline at end of file
function checkAvailability(string, elmtID, dataCollection) {
var field = document.getElementById(elmtID);
if (string.length === 0) {
field.classList.remove("available");
field.classList.remove("unavailable");
return;
} else {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
if (this.readyState === 4 && this.status === 200) {
if (this.responseText === "available") {
field.classList.remove("unavailable");
field.classList.add("available");
document.getElementById(elmtID+'-status').src = '/img/ic_check.png';
} else {
field.classList.remove("available");
field.classList.add("unavailable");
document.getElementById(elmtID+'-status').src = '/img/ic_close.png';
}
}
};
xmlhttp.open("GET", dataCollection + "?q=" + string, true);
xmlhttp.send();
}
}
function checkRequiredField(elmtID) {
var field = document.getElementById(elmtID);
if (field.value === "") {
field.classList.add("empty-required");
return false;
} else {
field.classList.remove("empty-required");
return true;
}
}
var isNameFilled = false;
var isUsernameFilled = false;
var isPasswordFilled = false;
var isEmailFilled = false;
var isPhoneFilled = false;
var isPasswordMatch = false;
var isUsernameAvailable = false;
var isEmailAvailable = false;
document.getElementById("confirm-password").onkeyup = function () {
var confirmField = document.getElementById("confirm-password");
var passwordField = document.getElementById("password");
if (confirmField.value !== passwordField.value) {
confirmField.classList.add("not-match");
passwordField.classList.add("not-match");
isPasswordMatch = false;
} else {
confirmField.classList.remove("not-match");
passwordField.classList.remove("not-match");
isPasswordMatch = true;
}
};
document.getElementById("name").onkeyup = function () {
isNameFilled = checkRequiredField("name");
};
document.getElementById("username").onkeyup = function () {
isUsernameFilled = checkRequiredField("username");
checkAvailability(this.value, "username", '/index.php/register/validate/username');
isUsernameAvailable = this.classList.contains("available");
};
document.getElementById("password").onkeyup = function () {
isPasswordFilled = checkRequiredField("password");
};
document.getElementById("email").onkeyup = function () {
isEmailFilled = checkRequiredField("email");
checkAvailability(this.value, "email", '/index.php/register/validate/email');
isEmailAvailable = this.classList.contains("available");
};
document.getElementById("phone").onkeyup = function () {
isPhoneFilled = checkRequiredField("phone");
};
document.getElementById("register-form").onkeyup = function () {
var submitBtn = document.getElementById("sign-up-btn");
if (isNameFilled &&
isUsernameFilled &&
isPasswordFilled &&
isEmailFilled &&
isPhoneFilled &&
isPasswordMatch &&
isUsernameAvailable &&
isEmailAvailable) {
submitBtn.removeAttribute("disabled");
} else {
submitBtn.setAttribute("disabled", "true");
}
};
\ No newline at end of file
/* ------------------------- GENERAL -------------------------*/
body {
background-color: #F5F5F5;
font-family: KacstOffice, sans-serif;
}
.container {
width: 80%;
max-width: 700px;
margin: 50px auto;
background-color: white;
padding: 20px;
border-radius: 5px;
}
.row:before,
.row:after {
content: "";
display: table;
clear: both;
}
[class*='col-'] {
float: left;
min-height: 1px;
width: 16.66%;
}
.col-1 {
width: 16.66%;
}
.col-2 {
width: 33.33%;
}
.col-3 {
width: 50%;
}
.col-4 {
width: 66.66%;
}
.col-5 {
width: 83.33%;
}
.col-6 {
width: 100%;
}
.text-left {
text-align: left;
}
.text-right {
text-align: right;
}
.text-center {
text-align: center;
}
.text-orange {
color: orange;
}
.btn {
border-radius: 5px;
border: 1px solid black;
padding: 5px 15px;
color: black;
text-decoration: none;
font-size: medium;
}
.red {
background-color: #DA0000;
}
.green {
background-color: #58F100;
}
.line-height-medium {
line-height: 30px;
}
/* ------------------------- HEADER -------------------------*/
.logo:after {
background-image: url('/img/logo.jpg');
background-size: 210px 40px;
display: inline-block;
width: 210px;
height: 40px;
content: "";
margin-bottom: 5px;
}
.user-action {
margin-top: 0px;
}
.tab {
outline: 1px solid #004D40;
padding-top: 15px;
padding-bottom: 15px;
font-weight: 900;
color: black;
text-decoration: none;
}
.tab.active {
background-color: #426344;
color: #FAFAFA;
}
.tab:hover {
background-color: #426344;
color: #FAFAFA;
}
/* ------------------------- ICON -------------------------*/
@font-face {
font-family: 'icon';
src: url("/font/typicons.eot");
src: url("/font/typicons.eot?#iefix") format('embedded-opentype'),
url("/font/typicons.woff") format('woff'),
url("/font/typicons.ttf") format('truetype'),
url("/font/typicons.svg#typicons") format('svg');
font-weight: normal;
font-style: normal;
}
.icon:before {
font-family: 'icon';
font-style: normal;
font-weight: normal;
speak: none;
display: inline-block;
text-decoration: inherit;
width: 1em;
height: 1em;
font-size: 1em;
text-align: center;
-webkit-font-smoothing: antialiased;
font-smoothing: antialiased;
text-rendering: optimizeLegibility
}
.icon.big {
font-size: 3em;
color: #c2c2c2;
}
.icon.icon-mail:before {
content: '\e0a5'
}
.icon.icon-phone:before {
content: '\e0c5'
}
.icon.icon-star:before {
content: '\e108'
}
.icon.icon-star-full:before{
content:'\e105'
}
/* ------------------------- PROFIL -------------------------*/
.img-circle {
width: 170px;
height: 170px;
border-radius: 50%;
border: 3px solid black;
}
.img-profile {
width: 130px;
height: 130px;
outline: 3px solid black;
}
.profil > p {
line-height: 50%;
}
.location-list {
line-height: 1.9em;
list-style-image: url('/img/ic_triangle.png');
}
.edit:after {
background-image: url('/img/ic_edit.jpg');
background-size: 45px 45px;
display: inline-block;
width: 45px;
height: 45px;
content: "";
}
a.edit:after {
margin: 15px;
}
table {
border-collapse: collapse;
}
table, th, td {
border: 1px solid #c2c2c2;
}
.action-edit {
background-image: url('/img/ic_edit.jpg');
background-size: 25px 25px;
display: inline-block;
width: 25px;
height: 20px;
content: "";
margin-right: 10px;
cursor: pointer;
}
.action-save {
background-image: url('/img/ic_edit.jpg');
background-size: 25px 25px;
display: inline-block;
width: 25px;
height: 20px;
content: "";
margin-right: 10px;
cursor: pointer;
}
.action-delete {
background-image: url('/img/ic_close.png');
background-size: 17px 17px;
display: inline-block;
width: 17px;
height: 17px;
content: "";
}
/* The switch - the box around the slider */
.switch {
position: relative;
display: inline-block;
width: 40px;
height: 22px;
}
/* Hide default HTML checkbox */
.switch input {display:none;}
.slider {
position: absolute;
cursor: pointer;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: #ccc;
-webkit-transition: .4s;
transition: .4s;
}
.slider:before {
position: absolute;
content: "";
height: 15px;
width: 15px;
left: 4px;
bottom: 4px;
background-color: white;
-webkit-transition: .4s;
transition: .4s;
}
input:checked + .slider {
background-color: #008C14;
}
input:focus + .slider {
box-shadow: 0 0 1px #008C14;
}
input:checked + .slider:before {
-webkit-transform: translateX(17px);
-ms-transform: translateX(17px);
transform: translateX(17px);
}
.slider.round {
border-radius: 22px;
}
.slider.round:before {
border-radius: 50%;
}
.input-photo {
width: 0.1px;
height: 0.1px;
opacity: 0;
overflow: hidden;
position: absolute;
z-index: -1;
}
.input-photo + label {
display: inline-block;
cursor: pointer;
width: 100%;
line-height: 33px;
}
.input-photo + label > .input-photo-button {
color: black;
float: right;
font-size: 0.75em;
width: 27%;
background-color: #ccc;
text-align: center;
}
.input-photo + label > .input-photo-result {
float: left;
font-size: 0.75em;
width: 70%;
height: 32px;
padding-left: 5px;
border: solid 1px black;
margin-right: 2px;
}
.input-photo:focus + label > .input-photo-button,
.input-photo + label > .input-photo-button:hover {
background-color: #999aa3;
}
.input-photo:focus + label > .input-photo-button {
outline: 1px dotted #000;
outline: -webkit-focus-ring-color auto 5px;
}
/* ------------------------- ORDER -------------------------*/
.small-circle {
width: 30px;
height: 30px;
border-radius: 50%;
background-color: #c2c2c2;
font-size: large;
vertical-align: middle;
margin: 0;
}
.page-tab {
width: 180px;
height: 50px;
border: 1px solid black;
margin: 0 auto;
display: table;
box-sizing: border-box;
vertical-align: middle;
}
.page-tab.selected {
background-color: #f4fe96;
}
.page-tab > .page-tab-image {
float: left;
width: 30%;
height:100%;
text-align: center;
position: relative;
display: flex;
flex-direction: column;
justify-content: center;
}
.page-tab >.page-tab-image >.circle {
border-radius: 50%;
width: 40px;
height: 40px;
margin: auto;
background-color: #d7d7d7;
padding: auto;
text-align: center;
display: flex;
flex-direction: column;
justify-content: center;
}
.page-tab > .page-tab-content {
float: right;
width: 70%;
height:100%;
display: inline-block;
display: flex;
flex-direction: column;
justify-content: center;
}
/* Login Page */
.login-input {
margin: 5px 0 5px 0;
}
.login-link {
float: right;
margin-top: 10px;
}
.login-button {
padding: 10px 20px;
background-color: #58f100;
}
.login-container {
width: 60%;
max-width: 300px;
margin: 50px auto;
background-color: #74d034;
padding-left: 30px;
padding-right: 30px;
border-radius: 50px;
border: solid 10px #007c30;
color: #007c30;
}
/* Register Page */
#sign-up-btn {
float: right;
}
.register-link {
float: left;
margin-top: 8px;
}
.checkbox {
margin: 10px 0 10px 0;
}
.available {
background-color: greenyellow;
}
.unavailable, .empty-required, .not-match {
background-color: orangered;
}
.not-match::-webkit-input-placeholder, .empty-required::-webkit-input-placeholder, .unavailable::-webkit-input-placeholder {
color: whitesmoke;
}
\ No newline at end of file
<?php
/**
* DagoJek is a singleton class that representing DagoJek application
*/
class DagoJek {
private $routingTable = array();
private function __construct() {
// empty constructor
}
public static function Instance() {
static $instance = null;
if ($instance === null) {
$instance = new DagoJek();
}
$instance->includeAllController();
return $instance;
}
private function includeAllController() {
foreach (scandir(dirname(__FILE__)."/controller") as $filename) {
$path = dirname(__FILE__)."/controller" . '/' . $filename;
if (is_file($path)) {
require_once $path;
}
}
}
public function prepareRouting() {
require __DIR__.'/route.php';
}
private function getCurrentUri() {
$basepath = implode('/', array_slice(explode('/', $_SERVER['SCRIPT_NAME']), 0, -1)) . '/';
$uri = substr($_SERVER['REQUEST_URI'], strlen($basepath));
if (strstr($uri, '?')) $uri = substr($uri, 0, strpos($uri, '?'));
$uri = '/' . trim($uri, '/');
return $uri;
}
public function addRoute($route, $function) {
$data = array(
$route => $function,
);
$this->routingTable += $data;
}
public function Start() {
$base_url = $this->getCurrentUri();
$base_url = $this->trimIndexDotPHP($base_url);
if (array_key_exists ($base_url, $this->routingTable)) {
$this->routingTable[$base_url]();
} else {
die ("404 Page not Found");
}
}
private function trimIndexDotPHP($string) {
$unnecessaryChars = "/index.php";
if (strpos($string, $unnecessaryChars) === 0) {
$result = substr($string, strlen($unnecessaryChars));
return $result;
} else {
return $string;
}
}
}
<?php
// ----------------------- Setting Up Global Connection -----------------------------------
class DB {
private $_db;
static $_instance;
private function __construct() {
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = 'superadmin';
$dbname = 'db_dagojek';
try {
$this->_db = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass);
$this->_db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$this->_db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
} catch (PDOException $e) {
echo "Connection fail :".$e->getMessage();
}
}
private function __clone(){}
public static function getInstance() {
if (!(self::$_instance instanceof self)) {
self::$_instance = new self();
}
return self::$_instance->_db;
}
}
// ------------------------------ Helper Function ----------------------------------------
function simpleCrypt( $string, $action = 'e' ) {
$secret_key = 'dagojek_key';
$secret_iv = 'dagojek_iv';
$output = false;
$encrypt_method = "AES-256-CBC";
$key = hash( 'sha256', $secret_key );
$iv = substr( hash( 'sha256', $secret_iv ), 0, 16 );
if( $action == 'e' ) {
$output = base64_encode( openssl_encrypt( $string, $encrypt_method, $key, 0, $iv ) );
}
else if( $action == 'd' ){
$output = openssl_decrypt( base64_decode( $string ), $encrypt_method, $key, 0, $iv );
}
return $output;
}
<?php
/**
* Created by PhpStorm.
* User: iqbal
* Date: 07/10/17
* Time: 21:42
*/
require_once __DIR__.'/../model/Order.php';
require_once __DIR__.'/../model/User.php';
class HistoryController
{
public static function HistoryHandler() {
// Getting user id from url
if (!isset($_GET['u']) || $_GET['u'] == "") {
echo "Invalid parameter!";
return;
}
$id = $_GET['u'];
// Decrypt user id
$uid = simpleCrypt($id, 'd');
// Getting driver profile
$dbconn = DB::getInstance();
$user = Driver::Create($uid, $dbconn);
if (!$user) {
echo "User not found!";
return;
}
require __DIR__.'/../view/history.php';
}
public static function HistoryAsCustomerHandler() {
$id = simpleCrypt($_GET['u'], 'd');
$pdo = DB::getInstance();
$historyCustomer = Order::GetAllOrderBy('id_customer', $id, $pdo);
$driverNames = array();
foreach ($historyCustomer as $driver) {
$driverId = $driver['id_driver'];
$driverNames[$driverId] = User::GetUserBy('id', $driverId, $pdo);
}
//$historyDriver = Order::GetAllOrderBy('id_driver', '4', $pdo);
echo json_encode(array('history'=>$historyCustomer, 'driverNames'=>$driverNames));
}
public static function HistoryAsDriverHandler() {
$id = simpleCrypt($_GET['u'], 'd');
$pdo = DB::getInstance();
$historyDriver = Order::GetAllOrderBy('id_driver', $id, $pdo);
$customerNames = array();
foreach ($historyDriver as $driver) {
$driverId = $driver['id_driver'];
$customerNames[$driverId] = User::GetUserBy('id', $driverId, $pdo);
}
//$historyDriver = Order::GetAllOrderBy('id_driver', '4', $pdo);
echo json_encode(array('history'=>$historyDriver, 'customerNames'=>$customerNames));
}
}
\ No newline at end of file
<?php
/**
* Created by PhpStorm.
* User: iqbal
* Date: 06/10/17
* Time: 13:22
*/
require_once __DIR__.'/../model/User.php';
class LoginController
{
public static function LoginHandler()
{
session_start();
$userData = null;
if (isset($_POST['username'])) {
$username = $_POST['username'];
$password = md5($_POST['password']);
$pdo = DB::getInstance();
$userData = User::GetUserBy('username', $username, $pdo);
}
if (isset($_GET['logout'])) {
$_SESSION['username'] = "";
header("Location: /");
exit;
}
if ($userData !== null && $userData instanceof User) {
if ($userData->password === $password) {
$_SESSION['username'] = $username;
$userPage = simpleCrypt($userData->id);
header("Location: /index.php/main/profil?u=$userPage");
//echo "<script type='application/javascript'> alert('Login berhasil'); </script>";
} else {
echo "<script type='application/javascript'> alert('Password salah.'); </script>";
}
} else if ($userData !== null) {
echo "<script type='application/javascript'> alert('Username tidak terdaftar.'); </script>";
}
require __DIR__ . "/../view/login.php";
}
}
\ No newline at end of file
<?php
class MainController {
public static function LoginHandler() {
LoginController::LoginHandler();
}
public static function DefaultHandler() {
echo "This is default handler";
}
}
\ No newline at end of file
<?php
class OrderController {
public static function OrderHandler() {
// Getting user id from url
if (!isset($_GET['u']) || $_GET['u'] == "") {
echo "Invalid parameter!";
return;
}
$id = $_GET['u'];
// Decrypt user id
$uid = simpleCrypt($id, 'd');
// Getting driver profile
$dbconn = DB::getInstance();
$user = Driver::Create($uid, $dbconn);
if (!$user) {
echo "User not found!";
return;
}
require __DIR__.'/../view/order.php';
}
public static function MakeOrderHandler() {
$id = simpleCrypt($_POST['id'], 'd');
$pickup = $_POST['pickup'];
$destination = $_POST['destination'];
$driver = $_POST['driver'];
// Get driver
$results = array();
$dbconn = DB::getInstance();
$stmt = $dbconn->prepare(
'SELECT
user.id AS id, name, username, photo, rating, sum_order
FROM user NATURAL JOIN driver
WHERE user.id IN (
SELECT DISTINCT id_driver
FROM prefered_location
WHERE (location = ? OR location = ?) AND user.id <> ?
)'
);
$stmt->execute(array($pickup, $destination, $id));
if ($stmt === false) {
echo "Error";
return;
}
$results += $stmt->fetchAll();
foreach ($results as $key => $field) {
$results[$key]['id'] = simpleCrypt($results[$key]['id'], 'e');
}
// get preferred driver
$preferred_driver = null;
if ($driver != "") {
$dbconn = DB::getInstance();
$stmt = $dbconn->prepare(
'SELECT
user.id AS id, name, username, photo, rating, sum_order
FROM user NATURAL JOIN driver
WHERE username = ? AND user.id <> ?'
);
$stmt->execute(array($driver, $id));
if ($stmt === false) {
echo "Error";
return;
}
$preferred_driver = $stmt->fetchObject();
if ($preferred_driver == false) {
$preferred_driver = null;
} else {
$preferred_driver->id = simpleCrypt($preferred_driver->id, 'e');
}
}
echo json_encode(array('preferred'=>$preferred_driver , 'result' => $results));
}
public static function FinishOrderHandler() {
var_dump($_POST);
$id = simpleCrypt($_POST['id'], 'd');
$id_customer = simpleCrypt($_POST['id_customer'], 'd');
$source = $_POST['source'];
$destination = $_POST['destination'];
$rating = $_POST['rating'];
$comment = $_POST['comment'];
$dbconn = DB::getInstance();
$stmt = $dbconn->prepare(
'INSERT INTO user_order
(id_driver, id_customer, source, destination, rating, comment)
VALUES
(?, ?, ?, ?, ?, ?)'
);
// Write finished order to db
$stmt->execute(array($id, $id_customer, $source, $destination, $rating, $comment));
if ($stmt === false) {
echo "Error";
return;
}
// Setup driver rating
$dbconn = DB::getInstance();
$stmt = $dbconn->prepare(
'UPDATE driver
SET rating=IF(rating=0, ? , ((rating + ?)/2)), sum_order=(sum_order+1)
WHERE
id = ?'
);
$stmt->execute(array($rating, $rating, $id));
if ($stmt === false) {
echo "Error";
return;
}
echo "Success";
}
}
<?php
require_once __DIR__.'/../model/User.php';
require_once __DIR__.'/../model/Driver.php';
class ProfilController {
public static function ProfilHandler() {
// Getting user id from url
if (!isset($_GET['u']) || $_GET['u'] == "") {
echo "Invalid parameter!";
return;
}
$id = $_GET['u'];
// Decrypt user id
$uid = simpleCrypt($id, 'd');
// Getting driver profile
$dbconn = DB::getInstance();
$user = Driver::Create($uid, $dbconn);
if (!$user) {
echo "User not found! (".$uid.")";
return;
}
// Get location
$location = array();
if ($user->isDriver) {
$dbconn = DB::getInstance();
$stmt = $dbconn->prepare(
'SELECT * FROM prefered_location WHERE id_driver = ?'
);
$stmt->execute(array($uid));
$location_result = $stmt->fetchAll();
$location += $location_result;
}
$location_count = sizeof($location);
require __DIR__.'/../view/profil.php';
}
public static function EditHandler() {
// Getting user id from url
if (!isset($_GET['u']) || $_GET['u'] == "") {
echo "Invalid parameter!";
return;
}
$id = $_GET['u'];
// Decrypt user id
$uid = simpleCrypt($id, 'd');
// Getting driver profile
$dbconn = DB::getInstance();
$user = Driver::Create($uid, $dbconn);
if (!$user) {
echo "User not found!";
return;
}
require __DIR__.'/../view/profil_edit.php';
}
public static function SaveProfil() {
// Check sending data
if (!isset($_POST["name"]) || !isset($_POST["phone"]) || !isset($_GET['u'])) {
echo "Invalid data";
return;
}
$isPhotoUploaded = false;
if (isset($_FILES["photo"]) && strlen($_FILES["photo"]["name"]) != 0) {
$isPhotoUploaded = true;
if ($_FILES['photo']['error']) {
echo "File upload error ".$_FILES['photo']['error'];
return;
}
}
$conn = DB::getInstance();
var_dump($_POST);
$user_id = simpleCrypt($_GET['u'], 'd');
$user_name = $_POST["name"];
$user_phone = $_POST["phone"];
$user_driver = isset($_POST["isDriver"]) ? 1 : 0;
$user_photo = isset($_FILES["photo"]) ? $_FILES["photo"]["name"] : null;
// Saving image if available
$stmt = $isPhotoUploaded ?
$conn->prepare('
UPDATE user
SET
name = :name,
phone = :phone,
is_driver = :isDriver,
photo = :photo
WHERE
id = :id
') :
$conn->prepare('
UPDATE user
SET
name = :name,
phone = :phone,
is_driver = :isDriver
WHERE
id = :id
');
if (!$stmt) {
print_r($conn->errorInfo());
}
$data = array(
':name' => $user_name,
':phone' => $user_phone,
':isDriver' => $user_driver,
':id' => $user_id,
);
if ($isPhotoUploaded) {
$photo_name = $_GET['u'];
$data += array(
':photo' => '/img/profile/'.$photo_name,
);
$target = __DIR__.'/../../public/img/profile/'.$photo_name;
if (!move_uploaded_file($_FILES['photo']['tmp_name'], $target)) {
echo "Fail uploading file to ".$target;
return;
}
}
$stmt->execute($data);
if ($stmt === false) {
echo "Fail :";
echo $stmt->errorCode(). "<br>";
print_r($stmt->errorInfo());
} else {
header('Location: /main/profil?u='.$_GET['u']);
}
// Close connection
$stmt = null;
$conn = null;
}
public static function EditLocationHandler() {
// Getting user id from url
if (!isset($_GET['u']) || $_GET['u'] == "") {
echo "Invalid parameter!";
return;
}
$id = $_GET['u'];
// Decrypt user id
$uid = simpleCrypt($id, 'd');
// Get location
$location = array();
$dbconn = DB::getInstance();
$stmt = $dbconn->prepare(
'SELECT * FROM prefered_location WHERE id_driver = ?'
);
$stmt->execute(array($uid));
$location_result = $stmt->fetchAll();
$location += $location_result;
$location_count = sizeof($location);
require __DIR__.'/../view/profil_edit_location.php';
}
public static function AddLocationHandler() {
// Getting user id from url
if (!isset($_GET['u']) || $_GET['u'] == "") {
echo "Invalid parameter!";
return;
}
$id = $_GET['u'];
// Decrypt user id
$uid = simpleCrypt($id, 'd');
$location = $_POST['location'];
// Access database
$dbconn = DB::getInstance();
$stmt = $dbconn->prepare(
'INSERT INTO prefered_location
(id_driver, location)
VALUES
(?,?)'
);
$stmt->execute(array($uid, $location));
if ($stmt === false) {
echo "Fail :";
echo $stmt->errorCode(). "<br>";
print_r($stmt->errorInfo());
} else {
header('Location: /main/profil/location/edit?u='.$_GET['u']);
}
}
public static function DeleteLocationHandler() {
// Getting user id from url
if (!isset($_GET['u']) || $_GET['u'] == "" || !isset($_GET['name']) || $_GET['name'] == "") {
echo "Invalid parameter!";
return;
}
$id = $_GET['u'];
// Decrypt user id
$uid = simpleCrypt($id, 'd');
$name = $_GET['name'];
// Access database
$dbconn = DB::getInstance();
$stmt = $dbconn->prepare(
'DELETE FROM prefered_location
WHERE
id_driver = ? AND
location = ?'
);
$stmt->execute(array($uid,$name));
if ($stmt === false) {
echo "Fail :";
echo $stmt->errorCode(). "<br>";
print_r($stmt->errorInfo());
} else {
header('Location: /main/profil/location/edit?u='.$_GET['u']);
}
}
public static function EditDataLocationHandler() {
if (!isset($_POST['id']) || !isset($_POST['location']) || !isset($_POST['newlocation'])) {
echo "Invalid parameter!";
return;
}
$uid = simpleCrypt($_POST['id'], 'd');
$location = $_POST['location'];
$newlocation = $_POST['newlocation'];
// Access database
$dbconn = DB::getInstance();
$stmt = $dbconn->prepare(
'UPDATE prefered_location
SET
location = :newlocation
WHERE
id_driver = :id AND location = :location'
);
$stmt->bindParam(":newlocation", $newlocation, PDO::PARAM_STR);
$stmt->bindParam(":id", $uid, PDO::PARAM_INT);
$stmt->bindParam(":location", $location, PDO::PARAM_STR);
$stmt->execute();
if (!$stmt->rowCount()) {
echo "Fail :";
echo $stmt->errorInfo();
} else {
echo "Success";
}
}
}
<?php
/**
* Created by PhpStorm.
* User: iqbal
* Date: 07/10/17
* Time: 0:40
*/
require_once __DIR__.'/../model/User.php';
class RegisterController
{
public static function RegisterHandler()
{
if (isset($_POST['username'])) {
$hashedPassword = md5($_POST['password']);
$newUser = array(
"name" => $_POST['name'],
"username" => $_POST['username'],
"email" => $_POST['email'],
"password" => $hashedPassword,
"phone" => $_POST['phone'],
"photo" => "/img/empty_profile.png",
"is_driver" => 0
);
if (isset($_POST['is_driver'])) {
$newUser['is_driver'] = 1;
}
$pdo = DB::getInstance();
$id = User::InsertUser($newUser, $pdo);
$id = simpleCrypt($id, 'e');
//header untuk redirect
if ($newUser['is_driver']) {
header('Location: /main/profil?u='.$id);
} else {
header('Location: /main/order?u='.$id);
}
return;
}
require __DIR__."/../view/register.php";
}
public static function UsernameValidationHandler()
{
$usernameInput = $_REQUEST['q'];
$pdo = DB::getInstance();
if ($usernameInput !== "") {
if (User::GetUserBy("username", $usernameInput, $pdo)) {
echo "unavailable";
} else {
echo "available";
}
}
}
public static function EmailValidationHandler()
{
$emailInput = $_REQUEST['q'];
$pdo = DB::getInstance();
if ($emailInput !== "") {
if (filter_var($emailInput, FILTER_VALIDATE_EMAIL)) {
if (User::GetUserBy("email", $emailInput, $pdo)) {
echo "unavailable";
} else {
echo "available";
}
} else {
echo "unavailable";
}
}
}
}
\ No newline at end of file
<?php
class Driver extends User {
public $rating;
public $sumOrder;
public static function Create($id, PDO $dbconn) {
try {
$stmt = $dbconn->prepare("
SELECT id, name, username, email, phone, rating, is_driver AS isDriver, sum_order AS sumOrder, photo
FROM user NATURAL JOIN driver
WHERE id =:id"
);
$stmt->execute(array('id'=>$id));
$stmt->setFetchMode(PDO::FETCH_ASSOC);
$result = $stmt->fetchObject('Driver');
return $result;
} catch (PDOException $e) {
echo "Error : ".$e->getMessage();
return false;
}
}
public static function InsertNewDriver(PDO $dbconn) {
$lastUser = $dbconn->query("SELECT * FROM user ORDER BY id DESC LIMIT 1")->fetch(PDO::FETCH_ASSOC);
$newId = $lastUser['id'];
$dbconn->prepare("INSERT INTO driver VALUES ($newId, 0, 0)")->execute();
return $newId;
}
}
\ No newline at end of file