Example #1
2
/**
 * Authentication & authorization middleware for routes
 *
 * Checks if User is signed in & has required privileges. Otherwise redirects to login page
 *
 * @param int $minRole  Minimum required User role
 *
 * @return callable
 */
function authForRole($minRole)
{
    return function () use($minRole) {
        $app = Slim\Slim::getInstance();
        $auth = new Auth();
        $signedIn = $auth->checkSession();
        if (!$signedIn) {
            $app->flash('error', 'Sign in required');
            $app->redirect('/signin');
        } else {
            $user = unserialize($_SESSION['User']);
            switch ($minRole) {
                case User::ADMIN:
                    if (in_array($user['role'], [User::ADMIN])) {
                        return;
                    }
                    break;
                case User::EXTENDED:
                    if (in_array($user['role'], [User::ADMIN, User::EXTENDED])) {
                        return;
                    }
                    break;
                case User::NORMAL:
                    if (in_array($user['role'], [User::ADMIN, User::EXTENDED, User::NORMAL])) {
                        return;
                    }
                    break;
            }
            $app->flash('error', 'You are not authorized to view this page');
            $app->redirect('/signin');
        }
    };
}
Example #2
0
 public function getLinkAttribute()
 {
     $name = 'shw' . substr($this->attributes['contenible_type'], 0, 7);
     $attr = ['id' . substr($this->attributes['contenible_type'], 0, 3) => $this->attributes['contenible_id']];
     $app = Slim\Slim::getInstance();
     return $app->request->getUrl() . $app->urlFor($name, $attr);
 }
function updateGroup($id)
{
    $app = Slim\Slim::getInstance();
    $json = decodeJsonOrFail($app->request->getBody());
    $group = Group::findOrFail($id);
    $group->update($json);
    echo $group->toJson();
}
function createUser()
{
    $app = Slim\Slim::getInstance();
    $json = decodeJsonOrFail($app->request->getBody());
    $user = new User($json);
    $user->save();
    echo $user->toJson();
}
function showError(Exception $e)
{
    $app = Slim\Slim::getInstance();
    if (is_a($e, 'Illuminate\\Database\\Eloquent\\ModelNotFoundException')) {
        $app->halt(404, json_encode(array('message' => 'Not found')));
    }
    $app->halt(500, json_encode(array('message' => $e->getMessage())));
}
Example #6
0
function get_slug($id = 0)
{
    if ($id == 0) {
        $app = Slim\Slim::getInstance();
        return $app->request()->getResourceUri();
    }
    $page = api\Controller\PageController::getPage($id);
    return $page->slug;
}
Example #7
0
function addBook()
{
    $request = Slim\Slim::getInstance()->request();
    $body = $request->getBody();
    $newBook = json_decode($body);
    $db = getConnection();
    $books = $db->books;
    $books->insert($newBook);
}
Example #8
0
 public function getObjetoLinkAttribute()
 {
     if ($this->attributes['objeto_id']) {
         $name = 'shw' . substr($this->attributes['objeto_type'], 0, 7);
         $attr = ['id' . substr($this->attributes['objeto_type'], 0, 3) => $this->attributes['objeto_id']];
         $app = Slim\Slim::getInstance();
         return $app->request->getUrl() . $app->urlFor($name, $attr);
     } else {
         return '';
     }
 }
Example #9
0
 public function avatarUrlFunction($type, $hash, $size)
 {
     switch ($type) {
         case 1:
             return 'http://www.gravatar.com/avatar/' . $hash . '?d=identicon&s=' . $size;
         case 2:
             return 'http://graph.facebook.com/' . $hash . '/picture?width=' . $size;
         default:
             return Slim\Slim::getInstance()->request()->getRootUri() . '/img/usuario/' . $hash . '/' . $size . '.png';
     }
 }
function error()
{
    $app = Slim\Slim::getInstance();
    dbConn::close_connection();
    // Close the connection to the MySQL database
    mongoConn::close_connection();
    // Close the connection to the NoSQL database
    // remove all session variables
    session_unset();
    // destroy the session
    session_destroy();
    // Show the error
    $error = array("error" => "Unauthorised Access. Please Login to use this site.");
    $app->render('../api/resources/error.php', array('myerror' => $error));
}
function sendMessageToGroup($id)
{
    $app = Slim\Slim::getInstance();
    $group = Group::findOrFail($id);
    $json = decodeJsonOrFail($app->request->getBody());
    if (!isset($json['from'])) {
        $json['from'] = null;
    }
    if (!isset($json['from_user_id'])) {
        $json['from_user_id'] = null;
    }
    $message = new Message($json);
    $message->group()->associate($group);
    $message->save();
    echo $message->toJson();
}
Example #12
0
 public function __construct()
 {
     $this->app = Slim\Slim::getInstance();
     $this->data = array();
     /** default title */
     $this->data['title'] = '';
     /** meta tag and information */
     $this->data['meta'] = array();
     /** queued css files */
     $this->data['css'] = array('internal' => array(), 'external' => array());
     /** queued js files */
     $this->data['js'] = array('internal' => array(), 'external' => array());
     /** prepared message info */
     $this->data['message'] = array('error' => array(), 'info' => array(), 'debug' => array());
     /** global javascript var */
     $this->data['global'] = array();
     /** base dir for asset file */
     $this->data['baseUrl'] = $this->baseUrl();
     $this->data['assetUrl'] = $this->data['baseUrl'] . 'assets/';
     $this->loadBaseCss();
     $this->loadBaseJs();
 }
function resetPassword()
{
    // Globals:
    global $db;
    global $noerrors;
    global $user;
    // Errors:
    if ($noerrors != 0) {
        echo json_encode(array("result" => "failed", "message" => "Database Connection"));
        return;
    }
    $request = Slim\Slim::getInstance()->request();
    $body = $request->getBody();
    $jsonData = json_decode($request->getBody());
    $hashcode = '';
    $newPassword = '';
    if (isset($jsonData->hashcode)) {
        $hashcode = $jsonData->hashcode;
    }
    if (isset($jsonData->newPassword)) {
        $newPassword = $jsonData->newPassword;
    }
    // Is email valid
    // Server Side Validation
    $errors = array();
    if ($hashcode == '') {
        $errors[] = "Hashcode Required";
    }
    if ($newPassword == '') {
        $errors[] = "Password Required";
    }
    if (strlen($newPassword) < 6) {
        $errors[] = "Password must be at least 6 characters";
    }
    // If validation errors exist - display errors
    if (COUNT($errors) > 0) {
        $errorMessage = array();
        $errorMessage["result"] = 'Failed';
        $errorMessage["message"] = 'validation';
        $errorMessage["errorsFound"] = COUNT($errors);
        $errorMessage["errors"] = array();
        foreach ($errors as $error) {
            $errorMessage["errors"][] = $error;
        }
        echo json_encode($errorMessage);
        return;
    }
    // Find account
    $findAccount = $db->prepare("SELECT * FROM `users` a INNER JOIN `hash_codes` b ON b.userID = a.userID WHERE b.code = :hashcode AND b.type= 'password'");
    $findAccount->bindParam(":hashcode", $hashcode);
    $findAccount->execute();
    // If account does not exist
    if ($findAccount->rowCount() != 1) {
        echo json_encode(array("result" => "failed", "message" => "Account doesn't exist"));
        return;
    }
    // Create hash code
    $fetchAccount = $findAccount->fetch();
    $userID = $fetchAccount['userID'];
    $password = $newPassword;
    $salt = bin2hex(openssl_random_pseudo_bytes(24, $cstrong));
    $securePassword = hash('sha256', $salt . $password, false);
    // Update account and delete hashcodes
    $db->beginTransaction();
    $sqlErrors = 0;
    // Update User
    $updateAccount = $db->prepare("UPDATE `users` SET `password`= :password, `salt` = :salt WHERE `userID` = :userID");
    $updateAccount->bindParam(":password", $securePassword);
    $updateAccount->bindParam(":salt", $salt);
    $updateAccount->bindParam(":userID", $userID);
    if (!$updateAccount->execute()) {
        $sqlErrors++;
    }
    //Remove hashcodes password only
    $removeCodes = $db->prepare("DELETE FROM `hash_codes` WHERE `userID` = :userID AND `type` ='password'");
    $removeCodes->bindParam(":userID", $userID);
    if (!$removeCodes->execute()) {
        $sqlErrors++;
    }
    if ($sqlErrors == 0) {
        $db->commit();
        echo json_encode(array("result" => "Successful"));
        return;
    } else {
        $db->rollBack();
        echo json_encode(array("result" => "Failed", "message" => "Database Error"));
        return;
    }
}
<?php

$app = Slim\Slim::getInstance();
if (isset($_SESSION['role'])) {
    if ($_SESSION['role'] == 1) {
        $pagename = "Reports - Top Region";
        include 'view/header_dash.php';
        ?>
<!doctype html>
<body>
		<header id="header">
			<hgroup>
				<h1 class="site_title">Bank of Rory - <a href="../../dashboard/admin/<?php 
        echo $_SESSION['user_id'];
        ?>
">Dashboard</a></h1>
				<h2 class="section_title">&nbsp;</h2><div class="btn_view_site"><a href="../../dashboard/user_details/<?php 
        echo $_SESSION['user_id'];
        ?>
"><?php 
        echo $_SESSION['fname'] . ' ' . $_SESSION['lname'];
        ?>
</a></div>
				</h2><div class="btn_view_site"><a href="../../logout">Log Out</a></div>
			</hgroup>
		</header> <!-- end of header bar -->
		
		<section id="secondary_bar">
			<div class="user">
			</div>
			<div class="breadcrumbs_container">
Example #15
0
<?php

include 'db.php';
require 'vendor/autoload.php';
$app = new \Slim\Slim();
$app->get('/hello/:name', function ($name) {
    echo "Hello, {$name}";
});
$app->post("/insertUser", function () use($app) {
    $request = Slim\Slim::getInstance()->request();
    $data = $request->params();
    insertUser($data);
    $response['status'] = "success";
    $response['message'] = "Record Inserted Successfully";
    echo json_encode($response);
});
function insertUser($data)
{
    $name = $data['name'];
    $mobile = $data['mobile'];
    $email = $data['email'];
    $message = $data['message'];
    $sql = "INSERT INTO user (name, mobile, email, message) VALUES ('{$name}','{$mobile}','{$email}','{$message}')";
    try {
        $db = getDB();
        $stmt = $db->prepare($sql);
        $stmt->bindParam("name", $name);
        $stmt->bindParam("mobile", $mobile);
        $stmt->bindParam("email", $email);
        $stmt->bindParam("message", $message);
        $stmt->execute();
function postDelete($value)
{
    $app = Slim\Slim::getInstance();
    $db = dbConn::getConnection();
    $user_details = getAccount($value);
    $request = $app->request();
    $ticket_id = $request->post('ticket_id');
    $db_mongo_coll = mongoConn::getConnection();
    // remove a ticket with a chosen id
    $db_mongo_coll->remove(array('_id' => new MongoId($ticket_id)), true);
    $user_tickets = $db_mongo_coll->find()->sort(array('_id' => -1));
    $app->render('../api/resources/view_all_tickets.php', array('user' => $user_details, 'tickets' => $user_tickets));
}
Example #17
0
function getSlimRequest()
{
    $app = Slim\Slim::getInstance();
    $util = new web_util();
    $value = $util->readContentFormRequest($app->request());
    return $value;
}
Example #18
0
function addUser()
{
    global $db;
    global $noerrors;
    // If database connect details are incorrect
    if ($noerrors != 0) {
        echo json_encode(array("result" => "Failed", "error" => "No connection"));
        return;
    }
    $request = Slim\Slim::getInstance()->request();
    $body = $request->getBody();
    $jsonData = json_decode($request->getBody());
    // Store values from JSON OBject
    if (isset($jsonData->first_name)) {
        $firstName = $jsonData->first_name;
    } else {
        $firstName = '';
    }
    if (isset($jsonData->last_name)) {
        $lastName = $jsonData->last_name;
    } else {
        $lastName = '';
    }
    if (isset($jsonData->email)) {
        $email = $jsonData->email;
    } else {
        $email = '';
    }
    if (isset($jsonData->username)) {
        $username = $jsonData->username;
    } else {
        $username = '';
    }
    if (isset($jsonData->password)) {
        $password = $jsonData->password;
    } else {
        $password = '';
    }
    // Server Side Validation
    $errors = array();
    if ($firstName == '') {
        $errors[] = "First Name Required";
    }
    if ($lastName == '') {
        $errors[] = "Last Name Required";
    }
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $errors[] = "Valid Email Required";
    }
    if ($username == '') {
        $errors[] = "Username Required";
    }
    if ($password == '') {
        $errors[] = "Password Required";
    }
    // If validation errors exist - display errors
    if (COUNT($errors) > 0) {
        $errorMessage = array();
        $errorMessage["result"] = "Failed";
        $errorMessage["message"] = "Failed validation";
        $errorMessage["errorsFound"] = COUNT($errors);
        $errorMessage["errors"] = array();
        foreach ($errors as $error) {
            $errorMessage["errors"][] = $error;
        }
        echo json_encode($errorMessage);
        return;
    }
    // Check if email already exists
    $emailQ = $db->prepare("SELECT * FROM `users` WHERE `email` = :email");
    $emailQ->bindParam(':email', $email);
    $emailQ->execute();
    if ($emailQ->rowCount() > 0) {
        echo json_encode(array("result" => "Failed", "message" => "Email already exists"));
        return;
    }
    // Check if username already exists
    $usernameQ = $db->prepare("SELECT * FROM `users` WHERE `username` = :username");
    $usernameQ->bindParam(':username', $username);
    $usernameQ->execute();
    if ($usernameQ->rowCount() > 0) {
        echo json_encode(array("result" => "Failed", "message" => "Username already exists"));
        return;
    }
    /* ALL VALIDATION HAS PASSED*/
    // Generate Salt and Hash Password
    $insecurepassword = $jsonData->password;
    $salt = bin2hex(openssl_random_pseudo_bytes(24, $cstrong));
    $password = hash('sha256', $salt . $insecurepassword, false);
    // INSERT SQL STATEMENT
    $insertQuery = "INSERT INTO `users`(`dateJoined`, `first_name`, `last_name`, `email`, `username`, `password`, `salt`) VALUES (CURDATE(), :first_name, :last_name, :email, :username, :password, :salt)";
    $q = $db->prepare($insertQuery);
    $q->bindParam(':first_name', $firstName);
    $q->bindParam(':last_name', $lastName);
    $q->bindParam(':email', $email);
    $q->bindParam(':username', $username);
    $q->bindParam(':password', $password);
    $q->bindParam(':salt', $salt);
    // JSON Message Array
    $jsonMessage = array();
    // If insert execute is successful
    if ($q->execute()) {
        // Get Last Insert ID
        $userID = $db->lastInsertId();
        /* Create and store hash code and email activation link to new user*/
        // Create Hash code and store in hash_codes Table
        $hashcode = bin2hex(openssl_random_pseudo_bytes(16, $cstrong));
        $h = $db->prepare("INSERT INTO `hash_codes`(`type`, `code`, `userID`) VALUES ('activation',:code,:userID)");
        $h->bindParam(':userID', $userID);
        $h->bindParam(':code', $hashcode);
        $h->execute();
        $subject = 'Activate your account';
        /* Body of Email */
        $body = "<p>Dear " . $firstName . "</p><p>Thank you for signing up for Managers Companion. Before you get started you will need to confirm your email. To do this click the link below.</p>";
        $body .= '<p><a href="https://192.169.1.2/scripts/activate/' . $hashcode . '">Activate My Account</a></p>';
        $body .= '<p>All the best and good luck<br><br>Managers Companion</p>';
        // Send Activation Email
        //$html = generateEmailHTML($subject,$subject,$body);
        sendEmail($jsonData->email, $subject, $body);
        // Return Success Message
        $jsonMessage["result"] = "successful";
        $jsonMessage["userID"] = $userID;
        // SET SESSION STORAGE
        $_SESSION['userID'] = $userID;
    } else {
        // Return unsuccessful json message
        $jsonMessage["result"] = "Failed";
        $jsonMessage["message"] = "Database Failed";
    }
    // echo JSON Message
    echo json_encode($jsonMessage);
}
 /**
  * Initialize with Slim framework instance
  */
 public function __construct()
 {
     $this->slim = Slim\Slim::getInstance();
 }
Example #20
0
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="<?php 
echo Slim\Slim::getInstance()->getName();
?>
">
<meta name="author" content="Sarfraz Ahmed">

<title><?php 
echo $title;
?>
</title>

<link rel="shortcut icon" href="/favicon.ico"/>
<link rel="shortcut icon" href="<?php 
echo $root;
?>
/favicon.ico"/>

<link href="<?php 
echo $root;
?>
/assets/css/bootstrap.min.css" rel="stylesheet">
<link href="<?php 
echo $root;
?>
/assets/font-awesome-4.1.0/css/font-awesome.min.css" rel="stylesheet">
<link href="<?php 
echo $root;
?>
function updateWashingTime($car_id, $id)
{
    $request = Slim\Slim::getInstance()->request();
    $washing_time = WashingTime::find($id);
    $washing_time_getbody = json_decode($request->getBody());
    $washing_time->dateWT = $washing_time_getbody->dateWT;
    $washing_time->timeWT = $washing_time_getbody->timeWT;
    $washing_time->locationWT = $washing_time_getbody->locationWT;
    $washing_time->statusWT = $washing_time_getbody->statusWT;
    $washing_time->washing_categories_idWC = $washing_time_getbody->washing_categories_idWC;
    $washing_time->cars_idC = $washing_time_getbody->cars_idC;
    $washing_time->save();
    echo $washing_time;
}
Example #22
0
function dmdHeaderRDF(){
	$app = Slim\Slim::getInstance();
	ob_start();
	$project = $_SESSION['project'];
	$format = $_SESSION['format'];
	$mimeType = array(
		'xml' => 'text/xml',
		'rdfxml' => 'application/rdf+xml',
		'jsonld' => 'application/ld+json',
		'turtle' => 'text/turtle',
		'ntriples' => 'application/n-triples'
	);
	if(!array_key_exists($format, $mimeType)){
		$app->flash('error', '指定された出力形式が不正です。');
		throw new RuntimeException('指定された出力形式が不正です。');
	}

	$created = getYmd($project['dct:created']);
	if(!empty($project['dct:license'])){
		$license_uri = getLincenseURI($project['dct:license'], $app->config('license'));
	}else{
		$license_uri = '';
	}
	$dataName = 'convertedData.' . $format;
	$dataType = $mimeType[$format];
	?>
@prefix owl: <http://www.w3.org/2002/07/owl#>.
@prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>.
@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#>.
@prefix xsd: <http://www.w3.org/2001/XMLSchema#>.
@prefix dcterms: <http://purl.org/dc/terms/>.
@prefix adms: <http://www.w3.org/ns/adms#>.
@prefix dcat: <http://www.w3.org/ns/dcat#>.
@prefix dmd: <http://imi.ipa.go.jp/ns/dmd#>.

<http://example.org/imins/<?php echo $project['_id']; ?>> a adms:Asset ;
dcterms:type dmd:DataModelDescription ;
dcterms:issued "<?php echo $created; ?>"^^xsd:date ;
dcterms:description "<?php if(!empty($project['dct:description'])){ echo htmlspecialchars($project['dct:description']); }?>"@ja ;
dcterms:publisher "<?php echo htmlspecialchars($project['dct:creator']); ?>"@ja ;
dcterms:title "<?php echo htmlspecialchars($project['rdfs:label']); ?>"@ja ;

dcterms:license <<?php echo $license_uri; ?>> ;
dcat:distribution <header.ttl> ;
dcat:distribution <header.xml> ;
dcat:distribution <schema.xsd> ;
dcat:distribution <mapping.json> ;
dcat:distribution <<?php echo $dataName; ?>> .

<header.ttl> a adms:AssetDistribution ;
	dcat:mediaType "text/turtle" .

<header.xml> a adms:AssetDistribution ;
	dcat:mediaType "text/xml" .

<schema.xsd> a adms:AssetDistribution ;
	dcat:mediaType "text/xml" .

<mapping.json> a adms:AssetDistribution ;
	dcat:mediaType "application.json" .

<<?php echo $dataName; ?>> a adms:AssetDistribution ;
	dcat:mediaType "<?php echo $dataType; ?>" .

	<?php
	$rdf = ob_get_contents();
	ob_end_clean();
	return $rdf;
}
Example #23
0
function wakeWatchdog($url)
{
    $parts = parse_url($url);
    $fp = fsockopen($parts['host'], isset($parts['port']) ? $parts['port'] : 80, $errno, $errstr, 30);
    if ($fp == 0) {
        $app = Slim\Slim::getInstance();
        $log = $app->getLog();
        $log->warn("Couldn't open a socket to " . $url);
        return;
    }
    $out = "GET " . $parts['path'] . " HTTP/1.1\r\n";
    $out .= "Host: " . $parts['host'] . "\r\n";
    $out .= "Content-Type: application/json\r\n";
    $out .= "Connection: Close\r\n\r\n";
    //$log->info("Sending " . $out);
    fwrite($fp, $out);
    fclose($fp);
}
Example #24
0
function removeFromFavourite($id)
{
    $request = Slim\Slim::getInstance()->request();
    $id = intval($id);
    $contact = array(CONTACTS::IS_FAVOURITE => false);
    $query = new QueryHandler();
    $response = $query->updateContact($id, $contact);
    echoRespnse($response);
}