first commit
This commit is contained in:
@@ -0,0 +1,20 @@
|
||||
<?php
|
||||
|
||||
defined('BASEPATH') OR exit('No direct script access allowed');
|
||||
|
||||
if ( ! function_exists('site_url'))
|
||||
{
|
||||
/**
|
||||
* Remove querystring var
|
||||
*
|
||||
* @param string $uri
|
||||
* @param string $key
|
||||
* @return string
|
||||
*/
|
||||
function remove_querystring_var($url, $key) {
|
||||
$url = preg_replace('/(?:&|(\?))' . $key . '=[^&]*(?(1)&|)?/i', "$1", $url);
|
||||
$url = rtrim($url, '?');
|
||||
$url = rtrim($url, '&');
|
||||
return $url;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,163 @@
|
||||
<?php
|
||||
defined('BASEPATH') or exit('No direct script access allowed');
|
||||
|
||||
use GuzzleHttp\Client;
|
||||
use GuzzleHttp\Exception\ClientException;
|
||||
use GuzzleHttp\Exception\ServerException;
|
||||
|
||||
class SQEAPI
|
||||
{
|
||||
private static function handleSQEAPIResponse($response)
|
||||
{
|
||||
$res = json_decode($response->getBody());
|
||||
|
||||
$data = null;
|
||||
$error = null;
|
||||
$success = false;
|
||||
|
||||
if (!isset($res)) {
|
||||
return show_error(500);
|
||||
}
|
||||
|
||||
if (property_exists($res, 'success')) {
|
||||
$success = $res->success;
|
||||
}
|
||||
|
||||
if (property_exists($res, 'message')) {
|
||||
$error = $res->message;
|
||||
}
|
||||
|
||||
if (property_exists($res, 'data')) {
|
||||
$data = $res->data;
|
||||
}
|
||||
|
||||
return array_merge((array) $res, ['data' => $data, 'success' => $success, 'error' => $error]);
|
||||
}
|
||||
|
||||
public static function get($url, $params)
|
||||
{
|
||||
global $savvyext;
|
||||
$token = $savvyext->cfgReadChar('system.oauth2_token');
|
||||
$baseUri = $savvyext->cfgReadChar('system.sqe_api_url');
|
||||
|
||||
$client = new Client(['base_uri' => $baseUri]);
|
||||
$header = ['Authorization' => $token];
|
||||
|
||||
try {
|
||||
$response = $client->request('GET', $url, [
|
||||
'headers' => [
|
||||
'Authorization' => $token,
|
||||
],
|
||||
'query' => $params,
|
||||
]);
|
||||
} catch (ServerException $e) {
|
||||
$response = $e->getResponse();
|
||||
} catch (ClientException $e) {
|
||||
$response = $e->getResponse();
|
||||
}
|
||||
|
||||
return self::handleSQEAPIResponse($response);
|
||||
}
|
||||
|
||||
public static function post($url, $params)
|
||||
{
|
||||
global $savvyext;
|
||||
$token = $savvyext->cfgReadChar('system.oauth2_token');
|
||||
$baseUri = $savvyext->cfgReadChar('system.api_url');
|
||||
|
||||
$client = new Client(['base_uri' => $baseUri]);
|
||||
$header = ['Authorization' => $token, 'Content-Type' => 'application/json'];
|
||||
try {
|
||||
$response = $client->request('POST', $url, [
|
||||
'headers' => $header,
|
||||
'body' => json_encode($params),
|
||||
]);
|
||||
} catch (ServerException $e) {
|
||||
$response = $e->getResponse();
|
||||
} catch (ClientException $e) {
|
||||
$response = $e->getResponse();
|
||||
}
|
||||
|
||||
return self::handleSQEAPIResponse($response);
|
||||
}
|
||||
|
||||
public static function put($url, $params)
|
||||
{
|
||||
global $savvyext;
|
||||
$token = $savvyext->cfgReadChar('system.oauth2_token');
|
||||
$baseUri = $savvyext->cfgReadChar('system.api_url');
|
||||
|
||||
$client = new Client(['base_uri' => $baseUri]);
|
||||
$headers = ['Authorization' => $token, 'Content-Type' => 'text/plain'];
|
||||
|
||||
try {
|
||||
$response = $client->request('PUT', $url, [
|
||||
'headers' => $headers,
|
||||
'body' => $params,
|
||||
]);
|
||||
} catch (ServerException $e) {
|
||||
$response = $e->getResponse();
|
||||
} catch (ClientException $e) {
|
||||
$response = $e->getResponse();
|
||||
}
|
||||
|
||||
return self::handleSQEAPIResponse($response);
|
||||
}
|
||||
|
||||
public static function delete($url)
|
||||
{
|
||||
global $savvyext;
|
||||
$token = $savvyext->cfgReadChar('system.oauth2_token');
|
||||
$baseUri = $savvyext->cfgReadChar('system.api_url');
|
||||
|
||||
$client = new Client(['base_uri' => $baseUri]);
|
||||
$headers = ['Authorization' => $token];
|
||||
|
||||
try {
|
||||
$response = $client->request('DELETE', $url, [
|
||||
'headers' => $headers,
|
||||
]);
|
||||
} catch (ServerException $e) {
|
||||
$response = $e->getResponse();
|
||||
} catch (ClientException $e) {
|
||||
$response = $e->getResponse();
|
||||
}
|
||||
|
||||
return self::handleSQEAPIResponse($response);
|
||||
}
|
||||
|
||||
public static function geocode($addr) {
|
||||
|
||||
global $savvyext;
|
||||
$httpAuthToken = $savvyext->cfgReadChar('system.oauth2_token');
|
||||
$encryptionAlg = $savvyext->cfgReadChar('encryption.algorithm');
|
||||
$encryptionKey = $savvyext->cfgReadChar('encryption.key');
|
||||
$encryptionIV = $savvyext->cfgReadChar('encryption.iv');
|
||||
$api_url = $savvyext->cfgReadChar('system.api_url');
|
||||
|
||||
$url = $api_url . "trips/api/geocode/?address=" . urlencode($addr);
|
||||
|
||||
$ch = curl_init($url);
|
||||
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
|
||||
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
|
||||
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
|
||||
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
|
||||
curl_setopt($ch, CURLOPT_VERBOSE, false);
|
||||
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
|
||||
'Content-Type: application/json',
|
||||
'Authorization: Server-Token ' . $httpAuthToken,
|
||||
"client_id: BackOffice"
|
||||
)
|
||||
);
|
||||
|
||||
$body = curl_exec($ch);
|
||||
$result = json_decode($body, true);
|
||||
|
||||
$payload = openssl_decrypt(
|
||||
hex2bin(
|
||||
$result['payload']
|
||||
), $encryptionAlg, $encryptionKey, OPENSSL_RAW_DATA, $encryptionIV
|
||||
);
|
||||
return json_decode($payload, true);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
<?php
|
||||
defined('BASEPATH') or exit('No direct script access allowed');
|
||||
class AUTHORIZATION
|
||||
{
|
||||
public static function validateTimestamp($token)
|
||||
{
|
||||
$CI = &get_instance();
|
||||
$token = self::validateToken($token);
|
||||
if ($token != false && (now() - $token->timestamp < ($CI->config->item('token_timeout') * 60))) {
|
||||
return $token;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
public static function validateToken($token)
|
||||
{
|
||||
$CI = &get_instance();
|
||||
return JWT::decode($token, $CI->config->item('jwt_key'));
|
||||
}
|
||||
public static function generateToken($data)
|
||||
{
|
||||
$CI = &get_instance();
|
||||
return JWT::encode($data, $CI->config->item('jwt_key'));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,130 @@
|
||||
<?php
|
||||
defined('BASEPATH') or exit('No direct script access allowed');
|
||||
|
||||
use GuzzleHttp\Client;
|
||||
use GuzzleHttp\Exception\ClientException;
|
||||
use GuzzleHttp\Exception\ServerException;
|
||||
|
||||
class AutomaticServerAPI
|
||||
{
|
||||
private static function handleResponse($response)
|
||||
{
|
||||
$res = json_decode($response->getBody());
|
||||
|
||||
$data = null;
|
||||
$error = null;
|
||||
$success = false;
|
||||
|
||||
if (!isset($res)) {
|
||||
return show_error(500);
|
||||
}
|
||||
|
||||
if (property_exists($res, 'success')) {
|
||||
$success = $res->success;
|
||||
}
|
||||
|
||||
if (property_exists($res, 'message')) {
|
||||
$error = $res->message;
|
||||
}
|
||||
|
||||
if (property_exists($res, 'data')) {
|
||||
$data = $res->data;
|
||||
}
|
||||
|
||||
return array_merge((array) $res, ['data' => $data, 'success' => $success, 'error' => $error]);
|
||||
}
|
||||
|
||||
public static function get($url, $params)
|
||||
{
|
||||
$CI = &get_instance();
|
||||
global $savvyext;
|
||||
$token = $savvyext->cfgReadChar('system.automation_api_token');
|
||||
$baseUri = $savvyext->cfgReadChar('system.automation_api_url');
|
||||
|
||||
$client = new Client(['base_uri' => $baseUri]);
|
||||
$headers = ['Authorization' => "Bearer $token"];
|
||||
|
||||
try {
|
||||
$response = $client->request('GET', $url, [
|
||||
'headers' => $headers,
|
||||
'query' => $params,
|
||||
]);
|
||||
} catch (ServerException $e) {
|
||||
$response = $e->getResponse();
|
||||
} catch (ClientException $e) {
|
||||
$response = $e->getResponse();
|
||||
}
|
||||
|
||||
return self::handleResponse($response);
|
||||
}
|
||||
|
||||
public static function post($url, $params)
|
||||
{
|
||||
$CI = &get_instance();
|
||||
global $savvyext;
|
||||
$token = $savvyext->cfgReadChar('system.automation_api_token');
|
||||
$baseUri = $savvyext->cfgReadChar('system.automation_api_url');
|
||||
|
||||
$client = new Client(['base_uri' => $baseUri]);
|
||||
$headers = ['Authorization' => 'Bearer ' . $token, 'Content-Type' => 'application/json'];
|
||||
try {
|
||||
$response = $client->request('POST', $url, [
|
||||
'headers' => $headers,
|
||||
'body' => json_encode($params),
|
||||
]);
|
||||
} catch (ServerException $e) {
|
||||
$response = $e->getResponse();
|
||||
} catch (ClientException $e) {
|
||||
$response = $e->getResponse();
|
||||
}
|
||||
|
||||
return self::handleResponse($response);
|
||||
}
|
||||
|
||||
public static function put($url, $params)
|
||||
{
|
||||
$CI = &get_instance();
|
||||
global $savvyext;
|
||||
$token = $savvyext->cfgReadChar('system.automation_api_token');
|
||||
$baseUri = $savvyext->cfgReadChar('system.automation_api_url');
|
||||
|
||||
$client = new Client(['base_uri' => $baseUri]);
|
||||
$headers = ['Authorization' => 'Bearer ' . $token, 'Content-Type' => 'application/json'];
|
||||
|
||||
try {
|
||||
$response = $client->request('PUT', $url, [
|
||||
'headers' => $headers,
|
||||
'body' => json_encode($params),
|
||||
]);
|
||||
} catch (ServerException $e) {
|
||||
$response = $e->getResponse();
|
||||
} catch (ClientException $e) {
|
||||
$response = $e->getResponse();
|
||||
}
|
||||
|
||||
return self::handleResponse($response);
|
||||
}
|
||||
|
||||
public static function delete($url)
|
||||
{
|
||||
$CI = &get_instance();
|
||||
global $savvyext;
|
||||
$token = $savvyext->cfgReadChar('system.automation_api_token');
|
||||
$baseUri = $savvyext->cfgReadChar('system.automation_api_url');
|
||||
|
||||
$client = new Client(['base_uri' => $baseUri]);
|
||||
$headers = ['Authorization' => 'Bearer ' . $token];
|
||||
|
||||
try {
|
||||
$response = $client->request('DELETE', $url, [
|
||||
'headers' => $headers,
|
||||
]);
|
||||
} catch (ServerException $e) {
|
||||
$response = $e->getResponse();
|
||||
} catch (ClientException $e) {
|
||||
$response = $e->getResponse();
|
||||
}
|
||||
|
||||
return self::handleResponse($response);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,155 @@
|
||||
<?php
|
||||
if (!defined('BASEPATH')) exit('No direct script access allowed');
|
||||
|
||||
/*
|
||||
* CKEditor helper for CodeIgniter
|
||||
*
|
||||
* @author Samuel Sanchez <samuel.sanchez.work@gmail.com> - http://kromack.com/
|
||||
* @package CodeIgniter
|
||||
* @license http://creativecommons.org/licenses/by-nc-sa/3.0/us/
|
||||
* @tutorial http://kromack.com/developpement-php/codeigniter/ckeditor-helper-for-codeigniter/
|
||||
* @see http://codeigniter.com/forums/viewthread/127374/
|
||||
* @version 2010-08-28
|
||||
*
|
||||
*/
|
||||
|
||||
/**
|
||||
* This function adds once the CKEditor's config vars
|
||||
* @author Samuel Sanchez
|
||||
* @access private
|
||||
* @param array $data (default: array())
|
||||
* @return string
|
||||
*/
|
||||
function cke_initialize($data = array())
|
||||
{
|
||||
|
||||
$return = '';
|
||||
|
||||
if (!defined('CI_CKEDITOR_HELPER_LOADED')) {
|
||||
|
||||
define('CI_CKEDITOR_HELPER_LOADED', TRUE);
|
||||
$return = '<script type="text/javascript" src="' . base_url() . $data['path'] . '/ckeditor.js"></script>';
|
||||
$return .= "<script type=\"text/javascript\">CKEDITOR_BASEPATH = '" . base_url() . $data['path'] . "/';</script>";
|
||||
}
|
||||
|
||||
return $return;
|
||||
}
|
||||
|
||||
/**
|
||||
* This function create JavaScript instances of CKEditor
|
||||
* @author Samuel Sanchez
|
||||
* @access private
|
||||
* @param array $data (default: array())
|
||||
* @return string
|
||||
*/
|
||||
function cke_create_instance($data = array())
|
||||
{
|
||||
|
||||
$return = "<script type=\"text/javascript\">
|
||||
CKEDITOR.replace('" . $data['id'] . "', {";
|
||||
|
||||
//Adding config values
|
||||
if (isset($data['config'])) {
|
||||
foreach ($data['config'] as $k => $v) {
|
||||
|
||||
// Support for extra config parameters
|
||||
if (is_array($v)) {
|
||||
$return .= $k . " : [";
|
||||
$return .= config_data($v);
|
||||
$return .= "]";
|
||||
} else {
|
||||
$return .= $k . " : '" . $v . "'";
|
||||
}
|
||||
|
||||
if ($k !== end(array_keys($data['config']))) {
|
||||
$return .= ",";
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
$return .= '});</script>';
|
||||
|
||||
return $return;
|
||||
}
|
||||
|
||||
/**
|
||||
* This function displays an instance of CKEditor inside a view
|
||||
* @author Samuel Sanchez
|
||||
* @access public
|
||||
* @param array $data (default: array())
|
||||
* @return string
|
||||
*/
|
||||
function display_ckeditor($data = array())
|
||||
{
|
||||
// Initialization
|
||||
$return = cke_initialize($data);
|
||||
|
||||
// Creating a Ckeditor instance
|
||||
$return .= cke_create_instance($data);
|
||||
|
||||
|
||||
// Adding styles values
|
||||
if (isset($data['styles'])) {
|
||||
|
||||
$return .= "<script type=\"text/javascript\">CKEDITOR.addStylesSet( 'my_styles_" . $data['id'] . "', [";
|
||||
|
||||
|
||||
foreach ($data['styles'] as $k => $v) {
|
||||
|
||||
$return .= "{ name : '" . $k . "', element : '" . $v['element'] . "', styles : { ";
|
||||
|
||||
if (isset($v['styles'])) {
|
||||
foreach ($v['styles'] as $k2 => $v2) {
|
||||
|
||||
$return .= "'" . $k2 . "' : '" . $v2 . "'";
|
||||
|
||||
if ($k2 !== end(array_keys($v['styles']))) {
|
||||
$return .= ",";
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
$return .= '} }';
|
||||
|
||||
if ($k !== end(array_keys($data['styles']))) {
|
||||
$return .= ',';
|
||||
}
|
||||
}
|
||||
|
||||
$return .= ']);';
|
||||
|
||||
$return .= "CKEDITOR.instances['" . $data['id'] . "'].config.stylesCombo_stylesSet = 'my_styles_" . $data['id'] . "';
|
||||
</script>";
|
||||
}
|
||||
|
||||
return $return;
|
||||
}
|
||||
|
||||
/**
|
||||
* config_data function.
|
||||
* This function look for extra config data
|
||||
*
|
||||
* @author ronan
|
||||
* @link http://kromack.com/developpement-php/codeigniter/ckeditor-helper-for-codeigniter/comment-page-5/#comment-545
|
||||
* @access public
|
||||
* @param array $data. (default: array())
|
||||
* @return String
|
||||
*/
|
||||
function config_data($data = array())
|
||||
{
|
||||
$return = '';
|
||||
foreach ($data as $key) {
|
||||
if (is_array($key)) {
|
||||
$return .= "[";
|
||||
foreach ($key as $string) {
|
||||
$return .= "'" . $string . "'";
|
||||
if ($string != end(array_values($key))) $return .= ",";
|
||||
}
|
||||
$return .= "]";
|
||||
} else {
|
||||
$return .= "'" . $key . "'";
|
||||
}
|
||||
if ($key != end(array_values($data))) $return .= ",";
|
||||
}
|
||||
return $return;
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
<?php
|
||||
defined('BASEPATH') or exit('No direct script access allowed');
|
||||
|
||||
function deleteDir($dirPath)
|
||||
{
|
||||
if (!is_dir($dirPath)) {
|
||||
throw new InvalidArgumentException("$dirPath must be a directory");
|
||||
}
|
||||
if (substr($dirPath, strlen($dirPath) - 1, 1) != '/') {
|
||||
$dirPath .= '/';
|
||||
}
|
||||
$files = glob($dirPath . '*', GLOB_MARK);
|
||||
foreach ($files as $file) {
|
||||
if (is_dir($file)) {
|
||||
deleteDir($file);
|
||||
} else {
|
||||
unlink($file);
|
||||
}
|
||||
}
|
||||
rmdir($dirPath);
|
||||
}
|
||||
|
||||
function zipDir($pathdir, $zipcreated, $extensions = [])
|
||||
{
|
||||
// Create new zip class
|
||||
$zip = new ZipArchive;
|
||||
|
||||
if($zip->open($pathdir . DIRECTORY_SEPARATOR . $zipcreated, (ZipArchive::CREATE)) === TRUE) {
|
||||
|
||||
// Store the path into the variable
|
||||
$dir = opendir($pathdir);
|
||||
|
||||
while($file = readdir($dir)) {
|
||||
$file_parts = pathinfo($pathdir . DIRECTORY_SEPARATOR . $file);
|
||||
if ( ! in_array($file_parts['extension'], $extensions)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if(is_file($pathdir . DIRECTORY_SEPARATOR . $file)) {
|
||||
$zip -> addFile($pathdir . DIRECTORY_SEPARATOR . $file, $file);
|
||||
}
|
||||
}
|
||||
$zip ->close();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
<?php
|
||||
defined('BASEPATH') or exit('No direct script access allowed');
|
||||
|
||||
function export($r, $name = 'download') {
|
||||
set_time_limit(0);
|
||||
$filename = $name . "-" . date("Y-m-d-H-i-s") . ".csv";
|
||||
header('Content-Type: application/vnd.ms-excel');
|
||||
header('Content-Disposition: attachment;filename="' . $filename . '"');
|
||||
header('Cache-Control: max-age=0');
|
||||
|
||||
$i = 0;
|
||||
if (ob_get_contents()) ob_end_clean();
|
||||
$out = fopen('php://output', 'w');
|
||||
while ($row = $r->unbuffered_row()) {
|
||||
$f = (array) $row;
|
||||
if ($i == 0) {
|
||||
fputcsv($out, array_keys($f), ",");
|
||||
}
|
||||
fputcsv($out, array_values($f), ",");
|
||||
$i++;
|
||||
}
|
||||
fclose($out);
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
<?php
|
||||
defined('BASEPATH') or exit('No direct script access allowed');
|
||||
|
||||
function getClassName()
|
||||
{
|
||||
$CI = &get_instance();
|
||||
|
||||
return $CI->router->fetch_class();
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<title>403 Forbidden</title>
|
||||
</head>
|
||||
<body>
|
||||
|
||||
<p>Directory access is forbidden.</p>
|
||||
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,193 @@
|
||||
<?php
|
||||
defined('BASEPATH') or exit('No direct script access allowed');
|
||||
/**
|
||||
* JSON Web Token implementation, based on this spec:
|
||||
* http://tools.ietf.org/html/draft-ietf-oauth-json-web-token-06
|
||||
*
|
||||
* PHP version 5
|
||||
*
|
||||
* @category Authentication
|
||||
* @package Authentication_JWT
|
||||
* @author Neuman Vong <neuman@twilio.com>
|
||||
* @author Anant Narayanan <anant@php.net>
|
||||
* @license http://opensource.org/licenses/BSD-3-Clause 3-clause BSD
|
||||
* @link https://github.com/firebase/php-jwt
|
||||
*/
|
||||
class JWT
|
||||
{
|
||||
/**
|
||||
* Decodes a JWT string into a PHP object.
|
||||
*
|
||||
* @param string $jwt The JWT
|
||||
* @param string|null $key The secret key
|
||||
* @param bool $verify Don't skip verification process
|
||||
*
|
||||
* @return object The JWT's payload as a PHP object
|
||||
* @throws UnexpectedValueException Provided JWT was invalid
|
||||
* @throws DomainException Algorithm was not provided
|
||||
*
|
||||
* @uses jsonDecode
|
||||
* @uses urlsafeB64Decode
|
||||
*/
|
||||
public static function decode($jwt, $key = null, $verify = true)
|
||||
{
|
||||
$tks = explode('.', $jwt);
|
||||
if (count($tks) != 3) {
|
||||
//if you don't want to disclose more details
|
||||
return false;
|
||||
//throw new UnexpectedValueException('Wrong number of segments');
|
||||
}
|
||||
list($headb64, $bodyb64, $cryptob64) = $tks;
|
||||
if (null === ($header = JWT::jsonDecode(JWT::urlsafeB64Decode($headb64)))) {
|
||||
//if you don't want to disclose more details
|
||||
return false;
|
||||
//throw new UnexpectedValueException('Invalid segment encoding');
|
||||
}
|
||||
if (null === $payload = JWT::jsonDecode(JWT::urlsafeB64Decode($bodyb64))) {
|
||||
//if you don't want to disclose more details
|
||||
return false;
|
||||
//throw new UnexpectedValueException('Invalid segment encoding');
|
||||
}
|
||||
$sig = JWT::urlsafeB64Decode($cryptob64);
|
||||
if ($verify) {
|
||||
if (empty($header->alg)) {
|
||||
//if you don't want to disclose more details
|
||||
return false;
|
||||
//throw new DomainException('Empty algorithm');
|
||||
}
|
||||
if ($sig != JWT::sign("$headb64.$bodyb64", $key, $header->alg)) {
|
||||
throw new UnexpectedValueException('Signature verification failed');
|
||||
}
|
||||
}
|
||||
return $payload;
|
||||
}
|
||||
/**
|
||||
* Converts and signs a PHP object or array into a JWT string.
|
||||
*
|
||||
* @param object|array $payload PHP object or array
|
||||
* @param string $key The secret key
|
||||
* @param string $algo The signing algorithm. Supported
|
||||
* algorithms are 'HS256', 'HS384' and 'HS512'
|
||||
*
|
||||
* @return string A signed JWT
|
||||
* @uses jsonEncode
|
||||
* @uses urlsafeB64Encode
|
||||
*/
|
||||
public static function encode($payload, $key, $algo = 'HS256')
|
||||
{
|
||||
$header = array('typ' => 'JWT', 'alg' => $algo);
|
||||
$segments = array();
|
||||
$segments[] = JWT::urlsafeB64Encode(JWT::jsonEncode($header));
|
||||
$segments[] = JWT::urlsafeB64Encode(JWT::jsonEncode($payload));
|
||||
$signing_input = implode('.', $segments);
|
||||
$signature = JWT::sign($signing_input, $key, $algo);
|
||||
$segments[] = JWT::urlsafeB64Encode($signature);
|
||||
return implode('.', $segments);
|
||||
}
|
||||
/**
|
||||
* Sign a string with a given key and algorithm.
|
||||
*
|
||||
* @param string $msg The message to sign
|
||||
* @param string $key The secret key
|
||||
* @param string $method The signing algorithm. Supported
|
||||
* algorithms are 'HS256', 'HS384' and 'HS512'
|
||||
*
|
||||
* @return string An encrypted message
|
||||
* @throws DomainException Unsupported algorithm was specified
|
||||
*/
|
||||
public static function sign($msg, $key, $method = 'HS256')
|
||||
{
|
||||
$methods = array(
|
||||
'HS256' => 'sha256',
|
||||
'HS384' => 'sha384',
|
||||
'HS512' => 'sha512',
|
||||
);
|
||||
if (empty($methods[$method])) {
|
||||
throw new DomainException('Algorithm not supported');
|
||||
}
|
||||
return hash_hmac($methods[$method], $msg, $key, true);
|
||||
}
|
||||
/**
|
||||
* Decode a JSON string into a PHP object.
|
||||
*
|
||||
* @param string $input JSON string
|
||||
*
|
||||
* @return object Object representation of JSON string
|
||||
* @throws DomainException Provided string was invalid JSON
|
||||
*/
|
||||
public static function jsonDecode($input)
|
||||
{
|
||||
$obj = json_decode($input);
|
||||
if (function_exists('json_last_error') && $errno = json_last_error()) {
|
||||
JWT::_handleJsonError($errno);
|
||||
} else if ($obj === null && $input !== 'null') {
|
||||
throw new DomainException('Null result with non-null input');
|
||||
}
|
||||
return $obj;
|
||||
}
|
||||
/**
|
||||
* Encode a PHP object into a JSON string.
|
||||
*
|
||||
* @param object|array $input A PHP object or array
|
||||
*
|
||||
* @return string JSON representation of the PHP object or array
|
||||
* @throws DomainException Provided object could not be encoded to valid JSON
|
||||
*/
|
||||
public static function jsonEncode($input)
|
||||
{
|
||||
$json = json_encode($input);
|
||||
if (function_exists('json_last_error') && $errno = json_last_error()) {
|
||||
JWT::_handleJsonError($errno);
|
||||
} else if ($json === 'null' && $input !== null) {
|
||||
throw new DomainException('Null result with non-null input');
|
||||
}
|
||||
return $json;
|
||||
}
|
||||
/**
|
||||
* Decode a string with URL-safe Base64.
|
||||
*
|
||||
* @param string $input A Base64 encoded string
|
||||
*
|
||||
* @return string A decoded string
|
||||
*/
|
||||
public static function urlsafeB64Decode($input)
|
||||
{
|
||||
$remainder = strlen($input) % 4;
|
||||
if ($remainder) {
|
||||
$padlen = 4 - $remainder;
|
||||
$input .= str_repeat('=', $padlen);
|
||||
}
|
||||
return base64_decode(strtr($input, '-_', '+/'));
|
||||
}
|
||||
/**
|
||||
* Encode a string with URL-safe Base64.
|
||||
*
|
||||
* @param string $input The string you want encoded
|
||||
*
|
||||
* @return string The base64 encode of what you passed in
|
||||
*/
|
||||
public static function urlsafeB64Encode($input)
|
||||
{
|
||||
return str_replace('=', '', strtr(base64_encode($input), '+/', '-_'));
|
||||
}
|
||||
/**
|
||||
* Helper method to create a JSON error.
|
||||
*
|
||||
* @param int $errno An error number from json_last_error()
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
private static function _handleJsonError($errno)
|
||||
{
|
||||
$messages = array(
|
||||
JSON_ERROR_DEPTH => 'Maximum stack depth exceeded',
|
||||
JSON_ERROR_CTRL_CHAR => 'Unexpected control character found',
|
||||
JSON_ERROR_SYNTAX => 'Syntax error, malformed JSON',
|
||||
);
|
||||
throw new DomainException(
|
||||
isset($messages[$errno])
|
||||
? $messages[$errno]
|
||||
: 'Unknown JSON error: ' . $errno
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
<?php
|
||||
defined('BASEPATH') or exit('No direct script access allowed');
|
||||
|
||||
function initPagination($pagePerItem, $totalItems, $selectedPage, $onPageClicked)
|
||||
{
|
||||
$CI = &get_instance();
|
||||
$totalPage = ceil($totalItems / $pagePerItem);
|
||||
$startPage = 1;
|
||||
$endPage = $totalPage;
|
||||
|
||||
if ($selectedPage > 5) {
|
||||
$startPage = $selectedPage - 4;
|
||||
} else {
|
||||
$startPage = 1;
|
||||
}
|
||||
|
||||
if (($selectedPage + 4) < $totalPage) {
|
||||
$endPage = $selectedPage + 4;
|
||||
} else {
|
||||
$endPage = $totalPage;
|
||||
}
|
||||
|
||||
if ($endPage < 10) {
|
||||
$endPage = $totalPage < 10 ? $totalPage : 10;
|
||||
}
|
||||
|
||||
$pagiantionData['pagePerItem'] = $pagePerItem;
|
||||
$paginationData['totalItems'] = $totalItems;
|
||||
$paginationData['totalPage'] = $totalPage;
|
||||
$paginationData['selectedPage'] = $selectedPage;
|
||||
$paginationData['startPage'] = $startPage;
|
||||
$paginationData['endPage'] = $endPage;
|
||||
|
||||
if (strpos($onPageClicked, '?')) {
|
||||
$onPageClicked = $onPageClicked . "&";
|
||||
} else {
|
||||
$onPageClicked = $onPageClicked . "?";
|
||||
}
|
||||
|
||||
$paginationData['handlePagingUrl'] = $onPageClicked;
|
||||
|
||||
return $CI->load->view('shared/pagination', $paginationData, true);
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
<?php
|
||||
defined('BASEPATH') or exit('No direct script access allowed');
|
||||
|
||||
function redirect($url, $statusCode = 303)
|
||||
{
|
||||
header('Location: ' . $url, true, $statusCode);
|
||||
die();
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
<?php
|
||||
defined('BASEPATH') or exit('No direct script access allowed');
|
||||
|
||||
function variation($data, $i, $f, $t, &$dMin, &$dMax, &$tVar, &$tVar0)
|
||||
{
|
||||
$tVar[] = $f['cost'];
|
||||
$trend = $t[$f['time']][2];
|
||||
$delta = $f['cost'] - $trend;
|
||||
$variation = stats_variance($tVar);
|
||||
if ($delta>$dMax) $dMax = $delta;
|
||||
if ($delta<$dMin) $dMin = $delta;
|
||||
$tVar0[$f['time']] = $variation;
|
||||
|
||||
/* {
|
||||
"travel_date":"2020-05-10 14:54:04+00",
|
||||
"cost":"12",
|
||||
"location_start_lat":"1.319292",
|
||||
"location_start_lng":"103.9126091",
|
||||
"location_end_lat":"1.316269",
|
||||
"location_end_lng":"103.977615",
|
||||
"origin":"Central East - Eunos",
|
||||
"destination":"Far East - Changi",
|
||||
"c":"#5555ff"} */
|
||||
//if ($i<5) error_log(json_encode($t));
|
||||
return [$trend, $delta, $variation];
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
<?php
|
||||
defined('BASEPATH') or exit('No direct script access allowed');
|
||||
|
||||
const TEMP_DIRECTORY_UPLOAD = 'application/cache/upload';
|
||||
|
||||
// RESPONSE FUNCTION
|
||||
function verbose($ok = 1, $info = "")
|
||||
{
|
||||
// THROW A 400 ERROR ON FAILURE
|
||||
if ($ok == 0) {
|
||||
http_response_code(400);
|
||||
}
|
||||
die(json_encode(["ok" => $ok, "info" => $info]));
|
||||
}
|
||||
|
||||
function upload_file()
|
||||
{
|
||||
// INVALID UPLOAD
|
||||
if (empty($_FILES) || $_FILES['file']['error']) {
|
||||
verbose(0, "Failed to move uploaded file.");
|
||||
}
|
||||
|
||||
// THE UPLOAD DESITINATION - CHANGE THIS TO YOUR OWN
|
||||
$filePath = $_SERVER['DOCUMENT_ROOT']
|
||||
. DIRECTORY_SEPARATOR
|
||||
. TEMP_DIRECTORY_UPLOAD;
|
||||
if (!file_exists($filePath)) {
|
||||
if (!mkdir($filePath, 0777, true)) {
|
||||
verbose(0, "Failed to create $filePath");
|
||||
}
|
||||
}
|
||||
$fileName = isset($_REQUEST["name"]) ? $_REQUEST["name"] : $_FILES["file"]["name"];
|
||||
$filePath = $filePath . DIRECTORY_SEPARATOR . $fileName;
|
||||
|
||||
// DEAL WITH CHUNKS
|
||||
$chunk = isset($_REQUEST["chunk"]) ? intval($_REQUEST["chunk"]) : 0;
|
||||
$chunks = isset($_REQUEST["chunks"]) ? intval($_REQUEST["chunks"]) : 0;
|
||||
$out = @fopen("{$filePath}.part", $chunk == 0 ? "wb" : "ab");
|
||||
if ($out) {
|
||||
$in = @fopen($_FILES['file']['tmp_name'], "rb");
|
||||
if ($in) {
|
||||
while ($buff = fread($in, 4096)) {
|
||||
fwrite($out, $buff);
|
||||
}
|
||||
} else {
|
||||
verbose(0, "Failed to open input stream");
|
||||
}
|
||||
@fclose($in);
|
||||
@fclose($out);
|
||||
@unlink($_FILES['file']['tmp_name']);
|
||||
} else {
|
||||
verbose(0, "Failed to open output stream");
|
||||
}
|
||||
|
||||
// CHECK IF FILE HAS BEEN UPLOADED
|
||||
if (!$chunks || $chunk == $chunks - 1) {
|
||||
rename("{$filePath}.part", $filePath);
|
||||
}
|
||||
verbose(1, "Upload OK");
|
||||
}
|
||||
Reference in New Issue
Block a user