first commit

This commit is contained in:
dev-chiefworks
2022-05-31 16:21:53 -04:00
commit f76abffdcd
5978 changed files with 1078901 additions and 0 deletions
+6
View File
@@ -0,0 +1,6 @@
<IfModule authz_core_module>
Require all denied
</IfModule>
<IfModule !authz_core_module>
Deny from all
</IfModule>
+11
View File
@@ -0,0 +1,11 @@
<!DOCTYPE html>
<html>
<head>
<title>403 Forbidden</title>
</head>
<body>
<p>Directory access is forbidden.</p>
</body>
</html>
+136
View File
@@ -0,0 +1,136 @@
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
/* SAVVY
| -------------------------------------------------------------------
| AUTO-LOADER
| -------------------------------------------------------------------
| This file specifies which systems should be loaded by default.
|
| In order to keep the framework as light-weight as possible only the
| absolute minimal resources are loaded by default. For example,
| the database is not connected to automatically since no assumption
| is made regarding whether you intend to use it. This file lets
| you globally define which systems you would like loaded with every
| request.
|
| -------------------------------------------------------------------
| Instructions
| -------------------------------------------------------------------
|
| These are the things you can load automatically:
|
| 1. Packages
| 2. Libraries
| 3. Drivers
| 4. Helper files
| 5. Custom config files
| 6. Language files
| 7. Models
|
*/
/*
| -------------------------------------------------------------------
| Auto-load Packages
| -------------------------------------------------------------------
| Prototype:
|
| $autoload['packages'] = array(APPPATH.'third_party', '/usr/local/shared');
|
*/
$autoload['packages'] = array();
/*
| -------------------------------------------------------------------
| Auto-load Libraries
| -------------------------------------------------------------------
| These are the classes located in system/libraries/ or your
| application/libraries/ directory, with the addition of the
| 'database' library, which is somewhat of a special case.
|
| Prototype:
|
| $autoload['libraries'] = array('database', 'email', 'session');
|
| You can also supply an alternative library name to be assigned
| in the controller:
|
| $autoload['libraries'] = array('user_agent' => 'ua');
*/
//$autoload['libraries'] = array();
$autoload['libraries'] = array('database','session','form_validation');
/*
| -------------------------------------------------------------------
| Auto-load Drivers
| -------------------------------------------------------------------
| These classes are located in system/libraries/ or in your
| application/libraries/ directory, but are also placed inside their
| own subdirectory and they extend the CI_Driver_Library class. They
| offer multiple interchangeable driver options.
|
| Prototype:
|
| $autoload['drivers'] = array('cache');
|
| You can also supply an alternative property name to be assigned in
| the controller:
|
| $autoload['drivers'] = array('cache' => 'cch');
|
*/
$autoload['drivers'] = array();
/*
| -------------------------------------------------------------------
| Auto-load Helper Files
| -------------------------------------------------------------------
| Prototype:
|
| $autoload['helper'] = array('url', 'file');
*/
//$autoload['helper'] = array();
//$autoload['helper'] = array('form','url');
$autoload['helper'] = array('form', 'url', 'get_class_name', 'api', 'automatic_server_api');
/*
| -------------------------------------------------------------------
| Auto-load Config files
| -------------------------------------------------------------------
| Prototype:
|
| $autoload['config'] = array('config1', 'config2');
|
| NOTE: This item is intended for use ONLY if you have created custom
| config files. Otherwise, leave it blank.
|
*/
$autoload['config'] = array();
/*
| -------------------------------------------------------------------
| Auto-load Language files
| -------------------------------------------------------------------
| Prototype:
|
| $autoload['language'] = array('lang1', 'lang2');
|
| NOTE: Do not include the "_lang" part of your file. For example
| "codeigniter_lang.php" would be referenced as array('codeigniter');
|
*/
$autoload['language'] = array();
/*
| -------------------------------------------------------------------
| Auto-load Models
| -------------------------------------------------------------------
| Prototype:
|
| $autoload['model'] = array('first_model', 'second_model');
|
| You can also supply an alternative model name to be assigned
| in the controller:
|
| $autoload['model'] = array('first_model' => 'first');
*/
$autoload['model'] = array();
+544
View File
@@ -0,0 +1,544 @@
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
// FLOAT
//function __autoload($classname) {
function my_autoload($classname) {
if (strpos($classname, 'CL_') !== 0) {
$file = APPPATH . 'libraries/' . $classname . '.php';
if (file_exists($file) && is_file($file)) {
@include_once($file);
}
}
}
spl_autoload_register('my_autoload');
/*
|--------------------------------------------------------------------------
| Base Site URL
|--------------------------------------------------------------------------
|
| URL to your CodeIgniter root. Typically this will be your base URL,
| WITH a trailing slash:
|
| http://example.com/
|
| WARNING: You MUST set this value!
|
| If it is not set, then CodeIgniter will try guess the protocol and path
| your installation, but due to security concerns the hostname will be set
| to $_SERVER['SERVER_ADDR'] if available, or localhost otherwise.
| The auto-detection mechanism exists only for convenience during
| development and MUST NOT be used in production!
|
| If you need to allow multiple domains, remember that this file is still
| a PHP script and you can easily do that on your own.
|
*/
//SAVVY
//$config['base_url'] = '';
$config['base_url'] = 'https://'.$_SERVER['SERVER_NAME'].'/';
/*
|--------------------------------------------------------------------------
| Index File
|--------------------------------------------------------------------------
|
| Typically this will be your index.php file, unless you've renamed it to
| something else. If you are using mod_rewrite to remove the page set this
| variable so that it is blank.
|
*/
$config['index_page'] = '';
/*
|--------------------------------------------------------------------------
| URI PROTOCOL
|--------------------------------------------------------------------------
|
| This item determines which server global should be used to retrieve the
| URI string. The default setting of 'REQUEST_URI' works for most servers.
| If your links do not seem to work, try one of the other delicious flavors:
|
| 'REQUEST_URI' Uses $_SERVER['REQUEST_URI']
| 'QUERY_STRING' Uses $_SERVER['QUERY_STRING']
| 'PATH_INFO' Uses $_SERVER['PATH_INFO']
|
| WARNING: If you set this to 'PATH_INFO', URIs will always be URL-decoded!
*/
$config['uri_protocol'] = 'REQUEST_URI';
/*
|--------------------------------------------------------------------------
| URL suffix
|--------------------------------------------------------------------------
|
| This option allows you to add a suffix to all URLs generated by CodeIgniter.
| For more information please see the user guide:
|
| https://codeigniter.com/user_guide/general/urls.html
*/
$config['url_suffix'] = '';
//$config['sess_save_path'] = sys_get_temp_dir();
/*
|--------------------------------------------------------------------------
| Default Language
|--------------------------------------------------------------------------
|
| This determines which set of language files should be used. Make sure
| there is an available translation if you intend to use something other
| than english.
|
*/
$config['language'] = 'english';
/*
|--------------------------------------------------------------------------
| Default Character Set
|--------------------------------------------------------------------------
|
| This determines which character set is used by default in various methods
| that require a character set to be provided.
|
| See http://php.net/htmlspecialchars for a list of supported charsets.
|
*/
$config['charset'] = 'UTF-8';
/*
|--------------------------------------------------------------------------
| Enable/Disable System Hooks
|--------------------------------------------------------------------------
|
| If you would like to use the 'hooks' feature you must enable it by
| setting this variable to TRUE (boolean). See the user guide for details.
|
*/
$config['enable_hooks'] = FALSE;
/*
|--------------------------------------------------------------------------
| Class Extension Prefix
|--------------------------------------------------------------------------
|
| This item allows you to set the filename/classname prefix when extending
| native libraries. For more information please see the user guide:
|
| https://codeigniter.com/user_guide/general/core_classes.html
| https://codeigniter.com/user_guide/general/creating_libraries.html
|
*/
$config['subclass_prefix'] = 'SAV_';
/*
|--------------------------------------------------------------------------
| Composer auto-loading
|--------------------------------------------------------------------------
|
| Enabling this setting will tell CodeIgniter to look for a Composer
| package auto-loader script in application/vendor/autoload.php.
|
| $config['composer_autoload'] = TRUE;
|
| Or if you have your vendor/ directory located somewhere else, you
| can opt to set a specific path as well:
|
| $config['composer_autoload'] = '/path/to/vendor/autoload.php';
|
| For more information about Composer, please visit http://getcomposer.org/
|
| Note: This will NOT disable or override the CodeIgniter-specific
| autoloading (application/config/autoload.php)
*/
//$config['composer_autoload'] = FALSE;
$config['composer_autoload'] = FCPATH . 'vendor/autoload.php';
/*
|--------------------------------------------------------------------------
| Allowed URL Characters
|--------------------------------------------------------------------------
|
| This lets you specify which characters are permitted within your URLs.
| When someone tries to submit a URL with disallowed characters they will
| get a warning message.
|
| As a security measure you are STRONGLY encouraged to restrict URLs to
| as few characters as possible. By default only these are allowed: a-z 0-9~%.:_-
|
| Leave blank to allow all characters -- but only if you are insane.
|
| The configured value is actually a regular expression character group
| and it will be executed as: ! preg_match('/^[<permitted_uri_chars>]+$/i
|
| DO NOT CHANGE THIS UNLESS YOU FULLY UNDERSTAND THE REPERCUSSIONS!!
|
*/
$config['permitted_uri_chars'] = 'a-z 0-9~%.:_\-';
/*
|--------------------------------------------------------------------------
| Enable Query Strings
|--------------------------------------------------------------------------
|
| By default CodeIgniter uses search-engine friendly segment based URLs:
| example.com/who/what/where/
|
| You can optionally enable standard query string based URLs:
| example.com?who=me&what=something&where=here
|
| Options are: TRUE or FALSE (boolean)
|
| The other items let you set the query string 'words' that will
| invoke your controllers and its functions:
| example.com/index.php?c=controller&m=function
|
| Please note that some of the helpers won't work as expected when
| this feature is enabled, since CodeIgniter is designed primarily to
| use segment based URLs.
|
*/
$config['enable_query_strings'] = FALSE;
$config['controller_trigger'] = 'c';
$config['function_trigger'] = 'm';
$config['directory_trigger'] = 'd';
/*
|--------------------------------------------------------------------------
| Allow $_GET array
|--------------------------------------------------------------------------
|
| By default CodeIgniter enables access to the $_GET array. If for some
| reason you would like to disable it, set 'allow_get_array' to FALSE.
|
| WARNING: This feature is DEPRECATED and currently available only
| for backwards compatibility purposes!
|
*/
$config['allow_get_array'] = TRUE;
/*
|--------------------------------------------------------------------------
| Error Logging Threshold
|--------------------------------------------------------------------------
|
| You can enable error logging by setting a threshold over zero. The
| threshold determines what gets logged. Threshold options are:
|
| 0 = Disables logging, Error logging TURNED OFF
| 1 = Error Messages (including PHP errors)
| 2 = Debug Messages
| 3 = Informational Messages
| 4 = All Messages
|
| You can also pass an array with threshold levels to show individual error types
|
| array(2) = Debug Messages, without Error Messages
|
| For a live site you'll usually only enable Errors (1) to be logged otherwise
| your log files will fill up very fast.
|
*/
$config['log_threshold'] = 0;
/*
|--------------------------------------------------------------------------
| Error Logging Directory Path
|--------------------------------------------------------------------------
|
| Leave this BLANK unless you would like to set something other than the default
| application/logs/ directory. Use a full server path with trailing slash.
|
*/
$config['log_path'] = '';
/*
|--------------------------------------------------------------------------
| Log File Extension
|--------------------------------------------------------------------------
|
| The default filename extension for log files. The default 'php' allows for
| protecting the log files via basic scripting, when they are to be stored
| under a publicly accessible directory.
|
| Note: Leaving it blank will default to 'php'.
|
*/
$config['log_file_extension'] = '';
/*
|--------------------------------------------------------------------------
| Log File Permissions
|--------------------------------------------------------------------------
|
| The file system permissions to be applied on newly created log files.
|
| IMPORTANT: This MUST be an integer (no quotes) and you MUST use octal
| integer notation (i.e. 0700, 0644, etc.)
*/
$config['log_file_permissions'] = 0644;
/*
|--------------------------------------------------------------------------
| Date Format for Logs
|--------------------------------------------------------------------------
|
| Each item that is logged has an associated date. You can use PHP date
| codes to set your own date formatting
|
*/
$config['log_date_format'] = 'Y-m-d H:i:s';
/*
|--------------------------------------------------------------------------
| Error Views Directory Path
|--------------------------------------------------------------------------
|
| Leave this BLANK unless you would like to set something other than the default
| application/views/errors/ directory. Use a full server path with trailing slash.
|
*/
$config['error_views_path'] = '';
/*
|--------------------------------------------------------------------------
| Cache Directory Path
|--------------------------------------------------------------------------
|
| Leave this BLANK unless you would like to set something other than the default
| application/cache/ directory. Use a full server path with trailing slash.
|
*/
$config['cache_path'] = '';
/*
|--------------------------------------------------------------------------
| Cache Include Query String
|--------------------------------------------------------------------------
|
| Whether to take the URL query string into consideration when generating
| output cache files. Valid options are:
|
| FALSE = Disabled
| TRUE = Enabled, take all query parameters into account.
| Please be aware that this may result in numerous cache
| files generated for the same page over and over again.
| array('q') = Enabled, but only take into account the specified list
| of query parameters.
|
*/
$config['cache_query_string'] = FALSE;
/*
|--------------------------------------------------------------------------
| Encryption Key
|--------------------------------------------------------------------------
|
| If you use the Encryption class, you must set an encryption key.
| See the user guide for more info.
|
| https://codeigniter.com/user_guide/libraries/encryption.html
|
*/
$config['encryption_key'] = '';
/*
|--------------------------------------------------------------------------
| Session Variables
|--------------------------------------------------------------------------
|
| 'sess_driver'
|
| The storage driver to use: files, database, redis, memcached
|
| 'sess_cookie_name'
|
| The session cookie name, must contain only [0-9a-z_-] characters
|
| 'sess_expiration'
|
| The number of SECONDS you want the session to last.
| Setting to 0 (zero) means expire when the browser is closed.
|
| 'sess_save_path'
|
| The location to save sessions to, driver dependent.
|
| For the 'files' driver, it's a path to a writable directory.
| WARNING: Only absolute paths are supported!
|
| For the 'database' driver, it's a table name.
| Please read up the manual for the format with other session drivers.
|
| IMPORTANT: You are REQUIRED to set a valid save path!
|
| 'sess_match_ip'
|
| Whether to match the user's IP address when reading the session data.
|
| WARNING: If you're using the database driver, don't forget to update
| your session table's PRIMARY KEY when changing this setting.
|
| 'sess_time_to_update'
|
| How many seconds between CI regenerating the session ID.
|
| 'sess_regenerate_destroy'
|
| Whether to destroy session data associated with the old session ID
| when auto-regenerating the session ID. When set to FALSE, the data
| will be later deleted by the garbage collector.
|
| Other session cookie settings are shared with the rest of the application,
| except for 'cookie_prefix' and 'cookie_httponly', which are ignored here.
|
*/
$config['sess_driver'] = 'files';
$config['sess_cookie_name'] = 'ci_session';
$config['sess_expiration'] = 7200;
$config['sess_save_path'] = sys_get_temp_dir();
$config['sess_match_ip'] = FALSE;
$config['sess_time_to_update'] = 300;
$config['sess_regenerate_destroy'] = FALSE;
/*
|--------------------------------------------------------------------------
| Cookie Related Variables
|--------------------------------------------------------------------------
|
| 'cookie_prefix' = Set a cookie name prefix if you need to avoid collisions
| 'cookie_domain' = Set to .your-domain.com for site-wide cookies
| 'cookie_path' = Typically will be a forward slash
| 'cookie_secure' = Cookie will only be set if a secure HTTPS connection exists.
| 'cookie_httponly' = Cookie will only be accessible via HTTP(S) (no javascript)
|
| Note: These settings (with the exception of 'cookie_prefix' and
| 'cookie_httponly') will also affect sessions.
|
*/
$config['cookie_prefix'] = '';
$config['cookie_domain'] = '';
$config['cookie_path'] = '/';
$config['cookie_secure'] = FALSE;
$config['cookie_httponly'] = FALSE;
/*
|--------------------------------------------------------------------------
| Standardize newlines
|--------------------------------------------------------------------------
|
| Determines whether to standardize newline characters in input data,
| meaning to replace \r\n, \r, \n occurrences with the PHP_EOL value.
|
| WARNING: This feature is DEPRECATED and currently available only
| for backwards compatibility purposes!
|
*/
$config['standardize_newlines'] = FALSE;
/*
|--------------------------------------------------------------------------
| Global XSS Filtering
|--------------------------------------------------------------------------
|
| Determines whether the XSS filter is always active when GET, POST or
| COOKIE data is encountered
|
| WARNING: This feature is DEPRECATED and currently available only
| for backwards compatibility purposes!
|
*/
$config['global_xss_filtering'] = FALSE;
/*
|--------------------------------------------------------------------------
| Cross Site Request Forgery
|--------------------------------------------------------------------------
| Enables a CSRF cookie token to be set. When set to TRUE, token will be
| checked on a submitted form. If you are accepting user data, it is strongly
| recommended CSRF protection be enabled.
|
| 'csrf_token_name' = The token name
| 'csrf_cookie_name' = The cookie name
| 'csrf_expire' = The number in seconds the token should expire.
| 'csrf_regenerate' = Regenerate token on every submission
| 'csrf_exclude_uris' = Array of URIs which ignore CSRF checks
*/
$config['csrf_protection'] = FALSE;
$config['csrf_token_name'] = 'csrf_test_name';
$config['csrf_cookie_name'] = 'csrf_cookie_name';
$config['csrf_expire'] = 7200;
$config['csrf_regenerate'] = TRUE;
$config['csrf_exclude_uris'] = array();
/*
|--------------------------------------------------------------------------
| Output Compression
|--------------------------------------------------------------------------
|
| Enables Gzip output compression for faster page loads. When enabled,
| the output class will test whether your server supports Gzip.
| Even if it does, however, not all browsers support compression
| so enable only if you are reasonably sure your visitors can handle it.
|
| Only used if zlib.output_compression is turned off in your php.ini.
| Please do not use it together with httpd-level output compression.
|
| VERY IMPORTANT: If you are getting a blank page when compression is enabled it
| means you are prematurely outputting something to your browser. It could
| even be a line of whitespace at the end of one of your scripts. For
| compression to work, nothing can be sent before the output buffer is called
| by the output class. Do not 'echo' any values with compression enabled.
|
*/
$config['compress_output'] = FALSE;
/*
|--------------------------------------------------------------------------
| Master Time Reference
|--------------------------------------------------------------------------
|
| Options are 'local' or any PHP supported timezone. This preference tells
| the system whether to use your server's local time as the master 'now'
| reference, or convert it to the configured one timezone. See the 'date
| helper' page of the user guide for information regarding date handling.
|
*/
$config['time_reference'] = 'local';
/*
|--------------------------------------------------------------------------
| Rewrite PHP Short Tags
|--------------------------------------------------------------------------
|
| If your PHP installation does not have short tag support enabled CI
| can rewrite the tags on-the-fly, enabling you to utilize that syntax
| in your view files. Options are TRUE or FALSE (boolean)
|
| Note: You need to have eval() enabled for this to work.
|
*/
$config['rewrite_short_tags'] = FALSE;
/*
|--------------------------------------------------------------------------
| Reverse Proxy IPs
|--------------------------------------------------------------------------
|
| If your server is behind a reverse proxy, you must whitelist the proxy
| IP addresses from which CodeIgniter should trust headers such as
| HTTP_X_FORWARDED_FOR and HTTP_CLIENT_IP in order to properly identify
| the visitor's IP address.
|
| You can use both an array or a comma-separated list of proxy addresses,
| as well as specifying whole subnets. Here are a few examples:
|
| Comma-separated: '10.0.1.200,192.168.5.0/24'
| Array: array('10.0.1.200', '192.168.5.0/24')
*/
$config['proxy_ips'] = '';
/*
Other configs
*/
$config['SQE_API_TOKEN'] = 'Server-Token ntSGU51ySIecS5j916rEIAYUqXQSCaVh';
$config['SQE_API_DOMAIN'] = 'https://api.savvy.sqe-dev.float.sg/v1/';
+198
View File
@@ -0,0 +1,198 @@
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
/*
|--------------------------------------------------------------------------
| Display Debug backtrace
|--------------------------------------------------------------------------
|
| If set to TRUE, a backtrace will be displayed along with php errors. If
| error_reporting is disabled, the backtrace will not display, regardless
| of this setting
|
*/
defined('SHOW_DEBUG_BACKTRACE') OR define('SHOW_DEBUG_BACKTRACE', TRUE);
/*
|--------------------------------------------------------------------------
| File and Directory Modes
|--------------------------------------------------------------------------
|
| These prefs are used when checking and setting modes when working
| with the file system. The defaults are fine on servers with proper
| security, but you may wish (or even need) to change the values in
| certain environments (Apache running a separate process for each
| user, PHP under CGI with Apache suEXEC, etc.). Octal values should
| always be used to set the mode correctly.
|
*/
defined('FILE_READ_MODE') OR define('FILE_READ_MODE', 0644);
defined('FILE_WRITE_MODE') OR define('FILE_WRITE_MODE', 0666);
defined('DIR_READ_MODE') OR define('DIR_READ_MODE', 0755);
defined('DIR_WRITE_MODE') OR define('DIR_WRITE_MODE', 0755);
/*
|--------------------------------------------------------------------------
| File Stream Modes
|--------------------------------------------------------------------------
|
| These modes are used when working with fopen()/popen()
|
*/
defined('FOPEN_READ') OR define('FOPEN_READ', 'rb');
defined('FOPEN_READ_WRITE') OR define('FOPEN_READ_WRITE', 'r+b');
defined('FOPEN_WRITE_CREATE_DESTRUCTIVE') OR define('FOPEN_WRITE_CREATE_DESTRUCTIVE', 'wb'); // truncates existing file data, use with care
defined('FOPEN_READ_WRITE_CREATE_DESTRUCTIVE') OR define('FOPEN_READ_WRITE_CREATE_DESTRUCTIVE', 'w+b'); // truncates existing file data, use with care
defined('FOPEN_WRITE_CREATE') OR define('FOPEN_WRITE_CREATE', 'ab');
defined('FOPEN_READ_WRITE_CREATE') OR define('FOPEN_READ_WRITE_CREATE', 'a+b');
defined('FOPEN_WRITE_CREATE_STRICT') OR define('FOPEN_WRITE_CREATE_STRICT', 'xb');
defined('FOPEN_READ_WRITE_CREATE_STRICT') OR define('FOPEN_READ_WRITE_CREATE_STRICT', 'x+b');
/*
|--------------------------------------------------------------------------
| Exit Status Codes
|--------------------------------------------------------------------------
|
| Used to indicate the conditions under which the script is exit()ing.
| While there is no universal standard for error codes, there are some
| broad conventions. Three such conventions are mentioned below, for
| those who wish to make use of them. The CodeIgniter defaults were
| chosen for the least overlap with these conventions, while still
| leaving room for others to be defined in future versions and user
| applications.
|
| The three main conventions used for determining exit status codes
| are as follows:
|
| Standard C/C++ Library (stdlibc):
| http://www.gnu.org/software/libc/manual/html_node/Exit-Status.html
| (This link also contains other GNU-specific conventions)
| BSD sysexits.h:
| http://www.gsp.com/cgi-bin/man.cgi?section=3&topic=sysexits
| Bash scripting:
| http://tldp.org/LDP/abs/html/exitcodes.html
|
*/
defined('EXIT_SUCCESS') OR define('EXIT_SUCCESS', 0); // no errors
defined('EXIT_ERROR') OR define('EXIT_ERROR', 1); // generic error
defined('EXIT_CONFIG') OR define('EXIT_CONFIG', 3); // configuration error
defined('EXIT_UNKNOWN_FILE') OR define('EXIT_UNKNOWN_FILE', 4); // file not found
defined('EXIT_UNKNOWN_CLASS') OR define('EXIT_UNKNOWN_CLASS', 5); // unknown class
defined('EXIT_UNKNOWN_METHOD') OR define('EXIT_UNKNOWN_METHOD', 6); // unknown class member
defined('EXIT_USER_INPUT') OR define('EXIT_USER_INPUT', 7); // invalid user input
defined('EXIT_DATABASE') OR define('EXIT_DATABASE', 8); // database error
defined('EXIT__AUTO_MIN') OR define('EXIT__AUTO_MIN', 9); // lowest automatically-assigned error code
defined('EXIT__AUTO_MAX') OR define('EXIT__AUTO_MAX', 125); // highest automatically-assigned error code
define('SITE_NAME', 'Float');
define('SITE_EMAIL', 'support@float.sg');
define('SITE_PHONE', '+1 911 9110');
define('SITE_FAX', '+1 9FX 9110');
define('PHP_API_OK', 0);
define('MAX_ADMIN_SESSION', 19600);
// SAVVY BACK OFFICE FUNCTION*****************
define('SAVVY_BKO_START', 100000);
define('SAVVY_BKO_LOGIN', 100005);
define('SAVVY_BKO_CREATEUSER', 100010);
define('SAVVY_BKO_EDITUSER', 100011);
define('SAVVY_BKO_UPDATEMEMBER', 100012);
define('SAVVY_BKO_ADDREASON', 100020);
define('SAVVYEXT_BKO_DELETEALLCARDS', 100022);
define('SAVVYEXT_BKO_CARDASSIGNED', 100027);
define('SAVVYEXT_BKO_ADDCARD', 100028);
define('SAVVYEXT_BKO_MOVECARD', 100029);
define('SAVVYEXT_BKO_REFRESHCARD', 100031);
define('SAVVY_BKO_LANGUAGE_STATUS', 100030);
define('SAVVYEXT_BKO_REFRESHGROUP', 100033);
define('SAVVY_BKO_CARPOOL_FRIENDMESSAGE', 100035);
define('SAVVY_BKO_SURVEY_LOGIC', 100041);
define('SAVVY_BKO_GPSTRIGGER_LOGIC', 100042);
define('SAVVY_BKO_PROCESS_POINTS', 100039);
define('SAVVY_BKO_MAINCARD_CREATE', 40200);
define('SAVVY_BKO_MAINCARD_UPDATE', 40210);
define('SAVVY_BKO_USERCARD_ADD', 40220);
define('SAVVY_BKO_USERCARD_DELETE', 40223);
define('SAVVY_BKO_MOVECARD', 40225);
define('SAVVY_BKO_ASSIGN_POINTS', 100047);
//define('FLOAT_SYSTEM_CREATE_DYNAMICCARD', 92026);
//define('SAVVY_BKO_SURVEY_LOGIC', 40230);
define('MIN_INT_2', -32768);
define('MAX_INT_2', 32768);
define('MIN_INT_4', -2147483648);
define('MAX_INT_4', 2147483648);
define("FLOAT_SYSTEM_CREATE_NOTIFICATION", 92025);
define("FLOAT_SYSTEM_EMAIL_NOTIFICATION", 92027);
define('FLOAT_SYSTEM_CREATE_DYNAMICCARD', 92026);
$trigger_card = array(
"ETRG0001" => array(
"active" => 1,
"cat" => 'GOACTIVITY',
"dynamic_key" => "ETRG0001KEY"
),
"ETRG0002" => array(
"active" => 1,
"cat" => 'GOACTIVITY',
"dynamic_key" => "ETRG0002KEY"
),
"ETRG0003" => array(
"active" => 1,
"cat" => 'GOACTIVITY',
"dynamic_key" => "ETRG0003KEY"
),
"ETRG0004" => array(
"active" => 1,
"cat" => 'GOACTIVITY',
"dynamic_key" => "ETRG0004KEY"
),
"ETRG0005" => array(
"active" => 1,
"cat" => 'GOACTIVITY',
"dynamic_key" => "ETRG0005KEY"
),
"ETRG0006" => array(
"active" => 1,
"cat" => 'GOACTIVITY',
"dynamic_key" => "ETRG0006KEY"
),
"ETRG0011" => array(
"active" => 1,
"cat" => 'GOACTIVITY',
"dynamic_key" => "ETRG0011KEY"
),
"ETRG0014" => array(
"active" => 1,
"cat" => 'GOACTIVITY',
"dynamic_key" => "ETRG0014KEY"
),
"ETRG0015" => array(
"active" => 1,
"cat" => 'GOACTIVITY',
"dynamic_key" => "ETRG0015KEY"
),
"ETRG0021" => array(
"active" => 1,
"cat" => 'GOPROFILE',
"dynamic_key" => "ETRG0021KEY"
)
);
+146
View File
@@ -0,0 +1,146 @@
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
/*
| -------------------------------------------------------------------
| DATABASE CONNECTIVITY SETTINGS
| -------------------------------------------------------------------
| This file will contain the settings needed to access your database.
|
| For complete instructions please consult the 'Database Connection'
| page of the User Guide.
|
| -------------------------------------------------------------------
| EXPLANATION OF VARIABLES
| -------------------------------------------------------------------
|
| ['dsn'] The full DSN string describe a connection to the database.
| ['hostname'] The hostname of your database server.
| ['username'] The username used to connect to the database
| ['password'] The password used to connect to the database
| ['database'] The name of the database you want to connect to
| ['dbdriver'] The database driver. e.g.: mysqli.
| Currently supported:
| cubrid, ibase, mssql, mysql, mysqli, oci8,
| odbc, pdo, postgre, sqlite, sqlite3, sqlsrv
| ['dbprefix'] You can add an optional prefix, which will be added
| to the table name when using the Query Builder class
| ['pconnect'] TRUE/FALSE - Whether to use a persistent connection
| ['db_debug'] TRUE/FALSE - Whether database errors should be displayed.
| ['cache_on'] TRUE/FALSE - Enables/disables query caching
| ['cachedir'] The path to the folder where cache files should be stored
| ['char_set'] The character set used in communicating with the database
| ['dbcollat'] The character collation used in communicating with the database
| NOTE: For MySQL and MySQLi databases, this setting is only used
| as a backup if your server is running PHP < 5.2.3 or MySQL < 5.0.7
| (and in table creation queries made with DB Forge).
| There is an incompatibility in PHP with mysql_real_escape_string() which
| can make your site vulnerable to SQL injection if you are using a
| multi-byte character set and are running versions lower than these.
| Sites using Latin-1 or UTF-8 database character set and collation are unaffected.
| ['swap_pre'] A default table prefix that should be swapped with the dbprefix
| ['encrypt'] Whether or not to use an encrypted connection.
|
| 'mysql' (deprecated), 'sqlsrv' and 'pdo/sqlsrv' drivers accept TRUE/FALSE
| 'mysqli' and 'pdo/mysql' drivers accept an array with the following options:
|
| 'ssl_key' - Path to the private key file
| 'ssl_cert' - Path to the public key certificate file
| 'ssl_ca' - Path to the certificate authority file
| 'ssl_capath' - Path to a directory containing trusted CA certificates in PEM format
| 'ssl_cipher' - List of *allowed* ciphers to be used for the encryption, separated by colons (':')
| 'ssl_verify' - TRUE/FALSE; Whether verify the server certificate or not ('mysqli' only)
|
| ['compress'] Whether or not to use client compression (MySQL only)
| ['stricton'] TRUE/FALSE - forces 'Strict Mode' connections
| - good for ensuring strict SQL while developing
| ['ssl_options'] Used to set various SSL options that can be used when making SSL connections.
| ['failover'] array - A array with 0 or more data for connections if the main should fail.
| ['save_queries'] TRUE/FALSE - Whether to "save" all executed queries.
| NOTE: Disabling this will also effectively disable both
| $this->db->last_query() and profiling of DB queries.
| When you run a query, with this setting set to TRUE (default),
| CodeIgniter will store the SQL statement for debugging purposes.
| However, this may cause high memory usage, especially if you run
| a lot of SQL queries ... disable this to avoid that problem.
|
| The $active_group variable lets you choose which connection group to
| make active. By default there is only one group (the 'default' group).
|
| The $query_builder variables lets you determine whether or not to load
| the query builder class.
*/
$active_group = 'default';
$query_builder = TRUE;
global $savvyext;
$db['default'] = array(
'dsn' => '',
'hostname' => $savvyext->cfgReadChar('database.host'), /* '10.142.0.10', */
'username' => $savvyext->cfgReadChar('database.user'), /* 'savvy', */
'password' => $savvyext->cfgReadChar('database.pass'), /* 'savvy001!', */
'database' => $savvyext->cfgReadChar('database.name'), /* 'savvy', */
'port' => $savvyext->cfgReadChar('database.port'), /* '5432', */
'dbdriver' => 'postgre',
'dbprefix' => '',
'pconnect' => FALSE,
'db_debug' => (ENVIRONMENT !== 'production'),
'cache_on' => FALSE,
'cachedir' => '',
'char_set' => 'utf8',
'dbcollat' => 'utf8_general_ci',
'swap_pre' => '',
'encrypt' => FALSE,
'compress' => FALSE,
'stricton' => FALSE,
'failover' => array(),
'save_queries' => TRUE
);
$db['gps'] = array(
'dsn' => '',
'hostname' => $savvyext->cfgReadChar('gpsdatabase.host'), /* '10.142.0.7', */
'username' => $savvyext->cfgReadChar('gpsdatabase.user'), /* 'savvy', */
'password' => $savvyext->cfgReadChar('gpsdatabase.pass'), /* 'savvy001!', */
'database' => $savvyext->cfgReadChar('gpsdatabase.name'), /* 'savvy_gps', */
'port' => $savvyext->cfgReadChar('gpsdatabase.port'), /* '5432', */
'dbdriver' => 'postgre',
'dbprefix' => '',
'pconnect' => FALSE,
'db_debug' => (ENVIRONMENT !== 'production'),
'cache_on' => FALSE,
'cachedir' => '',
'char_set' => 'utf8',
'dbcollat' => 'utf8_general_ci',
'swap_pre' => '',
'encrypt' => FALSE,
'compress' => FALSE,
'stricton' => FALSE,
'failover' => array(),
'save_queries' => TRUE
);
$db['savvy_replica'] = array(
'dsn' => '',
'hostname' => $savvyext->cfgReadChar('database_replica.host'), /* '10.142.0.7', */
'username' => $savvyext->cfgReadChar('database_replica.user'), /* 'savvy', */
'password' => $savvyext->cfgReadChar('database_replica.pass'), /* 'savvy001!', */
'database' => $savvyext->cfgReadChar('database_replica.name'), /* 'savvy_replica', */
'port' => $savvyext->cfgReadChar('database_replica.port'), /* '5432', */
'dbdriver' => 'postgre',
'dbprefix' => '',
'pconnect' => FALSE,
'db_debug' => (ENVIRONMENT !== 'production'),
'cache_on' => FALSE,
'cachedir' => '',
'char_set' => 'utf8',
'dbcollat' => 'utf8_general_ci',
'swap_pre' => '',
'encrypt' => FALSE,
'compress' => FALSE,
'stricton' => FALSE,
'failover' => array(),
'save_queries' => TRUE
);
+24
View File
@@ -0,0 +1,24 @@
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
$_doctypes = array(
'xhtml11' => '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">',
'xhtml1-strict' => '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">',
'xhtml1-trans' => '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">',
'xhtml1-frame' => '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Frameset//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd">',
'xhtml-basic11' => '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML Basic 1.1//EN" "http://www.w3.org/TR/xhtml-basic/xhtml-basic11.dtd">',
'html5' => '<!DOCTYPE html>',
'html4-strict' => '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">',
'html4-trans' => '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">',
'html4-frame' => '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd">',
'mathml1' => '<!DOCTYPE math SYSTEM "http://www.w3.org/Math/DTD/mathml1/mathml.dtd">',
'mathml2' => '<!DOCTYPE math PUBLIC "-//W3C//DTD MathML 2.0//EN" "http://www.w3.org/Math/DTD/mathml2/mathml2.dtd">',
'svg10' => '<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.0//EN" "http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd">',
'svg11' => '<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">',
'svg11-basic' => '<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1 Basic//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11-basic.dtd">',
'svg11-tiny' => '<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1 Tiny//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11-tiny.dtd">',
'xhtml-math-svg-xh' => '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1 plus MathML 2.0 plus SVG 1.1//EN" "http://www.w3.org/2002/04/xhtml-math-svg/xhtml-math-svg.dtd">',
'xhtml-math-svg-sh' => '<!DOCTYPE svg:svg PUBLIC "-//W3C//DTD XHTML 1.1 plus MathML 2.0 plus SVG 1.1//EN" "http://www.w3.org/2002/04/xhtml-math-svg/xhtml-math-svg.dtd">',
'xhtml-rdfa-1' => '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML+RDFa 1.0//EN" "http://www.w3.org/MarkUp/DTD/xhtml-rdfa-1.dtd">',
'xhtml-rdfa-2' => '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML+RDFa 1.1//EN" "http://www.w3.org/MarkUp/DTD/xhtml-rdfa-2.dtd">'
);
+103
View File
@@ -0,0 +1,103 @@
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
/*
| -------------------------------------------------------------------
| Foreign Characters
| -------------------------------------------------------------------
| This file contains an array of foreign characters for transliteration
| conversion used by the Text helper
|
*/
$foreign_characters = array(
'/ä|æ|ǽ/' => 'ae',
'/ö|œ/' => 'oe',
'/ü/' => 'ue',
'/Ä/' => 'Ae',
'/Ü/' => 'Ue',
'/Ö/' => 'Oe',
'/À|Á|Â|Ã|Ä|Å|Ǻ|Ā|Ă|Ą|Ǎ|Α|Ά|Ả|Ạ|Ầ|Ẫ|Ẩ|Ậ|Ằ|Ắ|Ẵ|Ẳ|Ặ|А/' => 'A',
'/à|á|â|ã|å|ǻ|ā|ă|ą|ǎ|ª|α|ά|ả|ạ|ầ|ấ|ẫ|ẩ|ậ|ằ|ắ|ẵ|ẳ|ặ|а/' => 'a',
'/Б/' => 'B',
'/б/' => 'b',
'/Ç|Ć|Ĉ|Ċ|Č/' => 'C',
'/ç|ć|ĉ|ċ|č/' => 'c',
'/Д/' => 'D',
'/д/' => 'd',
'/Ð|Ď|Đ|Δ/' => 'Dj',
'/ð|ď|đ|δ/' => 'dj',
'/È|É|Ê|Ë|Ē|Ĕ|Ė|Ę|Ě|Ε|Έ|Ẽ|Ẻ|Ẹ|Ề|Ế|Ễ|Ể|Ệ|Е|Э/' => 'E',
'/è|é|ê|ë|ē|ĕ|ė|ę|ě|έ|ε|ẽ|ẻ|ẹ|ề|ế|ễ|ể|ệ|е|э/' => 'e',
'/Ф/' => 'F',
'/ф/' => 'f',
'/Ĝ|Ğ|Ġ|Ģ|Γ|Г|Ґ/' => 'G',
'/ĝ|ğ|ġ|ģ|γ|г|ґ/' => 'g',
'/Ĥ|Ħ/' => 'H',
'/ĥ|ħ/' => 'h',
'/Ì|Í|Î|Ï|Ĩ|Ī|Ĭ|Ǐ|Į|İ|Η|Ή|Ί|Ι|Ϊ|Ỉ|Ị|И|Ы/' => 'I',
'/ì|í|î|ï|ĩ|ī|ĭ|ǐ|į|ı|η|ή|ί|ι|ϊ|ỉ|ị|и|ы|ї/' => 'i',
'/Ĵ/' => 'J',
'/ĵ/' => 'j',
'/Ķ|Κ|К/' => 'K',
'/ķ|κ|к/' => 'k',
'/Ĺ|Ļ|Ľ|Ŀ|Ł|Λ|Л/' => 'L',
'/ĺ|ļ|ľ|ŀ|ł|λ|л/' => 'l',
'/М/' => 'M',
'/м/' => 'm',
'/Ñ|Ń|Ņ|Ň|Ν|Н/' => 'N',
'/ñ|ń|ņ|ň|ʼn|ν|н/' => 'n',
'/Ò|Ó|Ô|Õ|Ō|Ŏ|Ǒ|Ő|Ơ|Ø|Ǿ|Ο|Ό|Ω|Ώ|Ỏ|Ọ|Ồ|Ố|Ỗ|Ổ|Ộ|Ờ|Ớ|Ỡ|Ở|Ợ|О/' => 'O',
'/ò|ó|ô|õ|ō|ŏ|ǒ|ő|ơ|ø|ǿ|º|ο|ό|ω|ώ|ỏ|ọ|ồ|ố|ỗ|ổ|ộ|ờ|ớ|ỡ|ở|ợ|о/' => 'o',
'/П/' => 'P',
'/п/' => 'p',
'/Ŕ|Ŗ|Ř|Ρ|Р/' => 'R',
'/ŕ|ŗ|ř|ρ|р/' => 'r',
'/Ś|Ŝ|Ş|Ș|Š|Σ|С/' => 'S',
'/ś|ŝ|ş|ș|š|ſ|σ|ς|с/' => 's',
'/Ț|Ţ|Ť|Ŧ|τ|Т/' => 'T',
'/ț|ţ|ť|ŧ|т/' => 't',
'/Þ|þ/' => 'th',
'/Ù|Ú|Û|Ũ|Ū|Ŭ|Ů|Ű|Ų|Ư|Ǔ|Ǖ|Ǘ|Ǚ|Ǜ|Ũ|Ủ|Ụ|Ừ|Ứ|Ữ|Ử|Ự|У/' => 'U',
'/ù|ú|û|ũ|ū|ŭ|ů|ű|ų|ư|ǔ|ǖ|ǘ|ǚ|ǜ|υ|ύ|ϋ|ủ|ụ|ừ|ứ|ữ|ử|ự|у/' => 'u',
'/Ƴ|Ɏ|Ỵ|Ẏ|Ӳ|Ӯ|Ў|Ý|Ÿ|Ŷ|Υ|Ύ|Ϋ|Ỳ|Ỹ|Ỷ|Ỵ|Й/' => 'Y',
'/ẙ|ʏ|ƴ|ɏ|ỵ|ẏ|ӳ|ӯ|ў|ý|ÿ|ŷ|ỳ|ỹ|ỷ|ỵ|й/' => 'y',
'/В/' => 'V',
'/в/' => 'v',
'/Ŵ/' => 'W',
'/ŵ/' => 'w',
'/Ź|Ż|Ž|Ζ|З/' => 'Z',
'/ź|ż|ž|ζ|з/' => 'z',
'/Æ|Ǽ/' => 'AE',
'/ß/' => 'ss',
'/IJ/' => 'IJ',
'/ij/' => 'ij',
'/Œ/' => 'OE',
'/ƒ/' => 'f',
'/ξ/' => 'ks',
'/π/' => 'p',
'/β/' => 'v',
'/μ/' => 'm',
'/ψ/' => 'ps',
'/Ё/' => 'Yo',
'/ё/' => 'yo',
'/Є/' => 'Ye',
'/є/' => 'ye',
'/Ї/' => 'Yi',
'/Ж/' => 'Zh',
'/ж/' => 'zh',
'/Х/' => 'Kh',
'/х/' => 'kh',
'/Ц/' => 'Ts',
'/ц/' => 'ts',
'/Ч/' => 'Ch',
'/ч/' => 'ch',
'/Ш/' => 'Sh',
'/ш/' => 'sh',
'/Щ/' => 'Shch',
'/щ/' => 'shch',
'/Ъ|ъ|Ь|ь/' => '',
'/Ю/' => 'Yu',
'/ю/' => 'yu',
'/Я/' => 'Ya',
'/я/' => 'ya'
);
+13
View File
@@ -0,0 +1,13 @@
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
/*
| -------------------------------------------------------------------------
| Hooks
| -------------------------------------------------------------------------
| This file lets you define "hooks" to extend CI without hacking the core
| files. Please see the user guide for info:
|
| https://codeigniter.com/user_guide/general/hooks.html
|
*/
+11
View File
@@ -0,0 +1,11 @@
<!DOCTYPE html>
<html>
<head>
<title>403 Forbidden</title>
</head>
<body>
<p>Directory access is forbidden.</p>
</body>
</html>
+19
View File
@@ -0,0 +1,19 @@
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
/*
| -------------------------------------------------------------------------
| Memcached settings
| -------------------------------------------------------------------------
| Your Memcached servers can be specified below.
|
| See: https://codeigniter.com/user_guide/libraries/caching.html#memcached
|
*/
$config = array(
'default' => array(
'hostname' => '127.0.0.1',
'port' => '11211',
'weight' => '1',
),
);
+84
View File
@@ -0,0 +1,84 @@
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
/*
|--------------------------------------------------------------------------
| Enable/Disable Migrations
|--------------------------------------------------------------------------
|
| Migrations are disabled by default for security reasons.
| You should enable migrations whenever you intend to do a schema migration
| and disable it back when you're done.
|
*/
$config['migration_enabled'] = FALSE;
/*
|--------------------------------------------------------------------------
| Migration Type
|--------------------------------------------------------------------------
|
| Migration file names may be based on a sequential identifier or on
| a timestamp. Options are:
|
| 'sequential' = Sequential migration naming (001_add_blog.php)
| 'timestamp' = Timestamp migration naming (20121031104401_add_blog.php)
| Use timestamp format YYYYMMDDHHIISS.
|
| Note: If this configuration value is missing the Migration library
| defaults to 'sequential' for backward compatibility with CI2.
|
*/
$config['migration_type'] = 'timestamp';
/*
|--------------------------------------------------------------------------
| Migrations table
|--------------------------------------------------------------------------
|
| This is the name of the table that will store the current migrations state.
| When migrations runs it will store in a database table which migration
| level the system is at. It then compares the migration level in this
| table to the $config['migration_version'] if they are not the same it
| will migrate up. This must be set.
|
*/
$config['migration_table'] = 'migrations';
/*
|--------------------------------------------------------------------------
| Auto Migrate To Latest
|--------------------------------------------------------------------------
|
| If this is set to TRUE when you load the migrations class and have
| $config['migration_enabled'] set to TRUE the system will auto migrate
| to your latest migration (whatever $config['migration_version'] is
| set to). This way you do not have to call migrations anywhere else
| in your code to have the latest migration.
|
*/
$config['migration_auto_latest'] = FALSE;
/*
|--------------------------------------------------------------------------
| Migrations version
|--------------------------------------------------------------------------
|
| This is used to set migration version that the file system should be on.
| If you run $this->migration->current() this is the version that schema will
| be upgraded / downgraded to.
|
*/
$config['migration_version'] = 0;
/*
|--------------------------------------------------------------------------
| Migrations Path
|--------------------------------------------------------------------------
|
| Path to your migrations folder.
| Typically, it will be within your application path.
| Also, writing permission is required within the migrations path.
|
*/
$config['migration_path'] = APPPATH.'migrations/';
+184
View File
@@ -0,0 +1,184 @@
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
/*
| -------------------------------------------------------------------
| MIME TYPES
| -------------------------------------------------------------------
| This file contains an array of mime types. It is used by the
| Upload class to help identify allowed file types.
|
*/
return array(
'hqx' => array('application/mac-binhex40', 'application/mac-binhex', 'application/x-binhex40', 'application/x-mac-binhex40'),
'cpt' => 'application/mac-compactpro',
'csv' => array('text/x-comma-separated-values', 'text/comma-separated-values', 'application/octet-stream', 'application/vnd.ms-excel', 'application/x-csv', 'text/x-csv', 'text/csv', 'application/csv', 'application/excel', 'application/vnd.msexcel', 'text/plain'),
'bin' => array('application/macbinary', 'application/mac-binary', 'application/octet-stream', 'application/x-binary', 'application/x-macbinary'),
'dms' => 'application/octet-stream',
'lha' => 'application/octet-stream',
'lzh' => 'application/octet-stream',
'exe' => array('application/octet-stream', 'application/x-msdownload'),
'class' => 'application/octet-stream',
'psd' => array('application/x-photoshop', 'image/vnd.adobe.photoshop'),
'so' => 'application/octet-stream',
'sea' => 'application/octet-stream',
'dll' => 'application/octet-stream',
'oda' => 'application/oda',
'pdf' => array('application/pdf', 'application/force-download', 'application/x-download', 'binary/octet-stream'),
'ai' => array('application/pdf', 'application/postscript'),
'eps' => 'application/postscript',
'ps' => 'application/postscript',
'smi' => 'application/smil',
'smil' => 'application/smil',
'mif' => 'application/vnd.mif',
'xls' => array('application/vnd.ms-excel', 'application/msexcel', 'application/x-msexcel', 'application/x-ms-excel', 'application/x-excel', 'application/x-dos_ms_excel', 'application/xls', 'application/x-xls', 'application/excel', 'application/download', 'application/vnd.ms-office', 'application/msword'),
'ppt' => array('application/powerpoint', 'application/vnd.ms-powerpoint', 'application/vnd.ms-office', 'application/msword'),
'pptx' => array('application/vnd.openxmlformats-officedocument.presentationml.presentation', 'application/x-zip', 'application/zip'),
'wbxml' => 'application/wbxml',
'wmlc' => 'application/wmlc',
'dcr' => 'application/x-director',
'dir' => 'application/x-director',
'dxr' => 'application/x-director',
'dvi' => 'application/x-dvi',
'gtar' => 'application/x-gtar',
'gz' => 'application/x-gzip',
'gzip' => 'application/x-gzip',
'php' => array('application/x-httpd-php', 'application/php', 'application/x-php', 'text/php', 'text/x-php', 'application/x-httpd-php-source'),
'php4' => 'application/x-httpd-php',
'php3' => 'application/x-httpd-php',
'phtml' => 'application/x-httpd-php',
'phps' => 'application/x-httpd-php-source',
'js' => array('application/x-javascript', 'text/plain'),
'swf' => 'application/x-shockwave-flash',
'sit' => 'application/x-stuffit',
'tar' => 'application/x-tar',
'tgz' => array('application/x-tar', 'application/x-gzip-compressed'),
'z' => 'application/x-compress',
'xhtml' => 'application/xhtml+xml',
'xht' => 'application/xhtml+xml',
'zip' => array('application/x-zip', 'application/zip', 'application/x-zip-compressed', 'application/s-compressed', 'multipart/x-zip'),
'rar' => array('application/x-rar', 'application/rar', 'application/x-rar-compressed'),
'mid' => 'audio/midi',
'midi' => 'audio/midi',
'mpga' => 'audio/mpeg',
'mp2' => 'audio/mpeg',
'mp3' => array('audio/mpeg', 'audio/mpg', 'audio/mpeg3', 'audio/mp3'),
'aif' => array('audio/x-aiff', 'audio/aiff'),
'aiff' => array('audio/x-aiff', 'audio/aiff'),
'aifc' => 'audio/x-aiff',
'ram' => 'audio/x-pn-realaudio',
'rm' => 'audio/x-pn-realaudio',
'rpm' => 'audio/x-pn-realaudio-plugin',
'ra' => 'audio/x-realaudio',
'rv' => 'video/vnd.rn-realvideo',
'wav' => array('audio/x-wav', 'audio/wave', 'audio/wav'),
'bmp' => array('image/bmp', 'image/x-bmp', 'image/x-bitmap', 'image/x-xbitmap', 'image/x-win-bitmap', 'image/x-windows-bmp', 'image/ms-bmp', 'image/x-ms-bmp', 'application/bmp', 'application/x-bmp', 'application/x-win-bitmap'),
'gif' => 'image/gif',
'jpeg' => array('image/jpeg', 'image/pjpeg'),
'jpg' => array('image/jpeg', 'image/pjpeg'),
'jpe' => array('image/jpeg', 'image/pjpeg'),
'jp2' => array('image/jp2', 'video/mj2', 'image/jpx', 'image/jpm'),
'j2k' => array('image/jp2', 'video/mj2', 'image/jpx', 'image/jpm'),
'jpf' => array('image/jp2', 'video/mj2', 'image/jpx', 'image/jpm'),
'jpg2' => array('image/jp2', 'video/mj2', 'image/jpx', 'image/jpm'),
'jpx' => array('image/jp2', 'video/mj2', 'image/jpx', 'image/jpm'),
'jpm' => array('image/jp2', 'video/mj2', 'image/jpx', 'image/jpm'),
'mj2' => array('image/jp2', 'video/mj2', 'image/jpx', 'image/jpm'),
'mjp2' => array('image/jp2', 'video/mj2', 'image/jpx', 'image/jpm'),
'png' => array('image/png', 'image/x-png'),
'tiff' => 'image/tiff',
'tif' => 'image/tiff',
'css' => array('text/css', 'text/plain'),
'html' => array('text/html', 'text/plain'),
'htm' => array('text/html', 'text/plain'),
'shtml' => array('text/html', 'text/plain'),
'txt' => 'text/plain',
'text' => 'text/plain',
'log' => array('text/plain', 'text/x-log'),
'rtx' => 'text/richtext',
'rtf' => 'text/rtf',
'xml' => array('application/xml', 'text/xml', 'text/plain'),
'xsl' => array('application/xml', 'text/xsl', 'text/xml'),
'mpeg' => 'video/mpeg',
'mpg' => 'video/mpeg',
'mpe' => 'video/mpeg',
'qt' => 'video/quicktime',
'mov' => 'video/quicktime',
'avi' => array('video/x-msvideo', 'video/msvideo', 'video/avi', 'application/x-troff-msvideo'),
'movie' => 'video/x-sgi-movie',
'doc' => array('application/msword', 'application/vnd.ms-office'),
'docx' => array('application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'application/zip', 'application/msword', 'application/x-zip'),
'dot' => array('application/msword', 'application/vnd.ms-office'),
'dotx' => array('application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'application/zip', 'application/msword'),
'xlsx' => array('application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'application/zip', 'application/vnd.ms-excel', 'application/msword', 'application/x-zip'),
'word' => array('application/msword', 'application/octet-stream'),
'xl' => 'application/excel',
'eml' => 'message/rfc822',
'json' => array('application/json', 'text/json'),
'pem' => array('application/x-x509-user-cert', 'application/x-pem-file', 'application/octet-stream'),
'p10' => array('application/x-pkcs10', 'application/pkcs10'),
'p12' => 'application/x-pkcs12',
'p7a' => 'application/x-pkcs7-signature',
'p7c' => array('application/pkcs7-mime', 'application/x-pkcs7-mime'),
'p7m' => array('application/pkcs7-mime', 'application/x-pkcs7-mime'),
'p7r' => 'application/x-pkcs7-certreqresp',
'p7s' => 'application/pkcs7-signature',
'crt' => array('application/x-x509-ca-cert', 'application/x-x509-user-cert', 'application/pkix-cert'),
'crl' => array('application/pkix-crl', 'application/pkcs-crl'),
'der' => 'application/x-x509-ca-cert',
'kdb' => 'application/octet-stream',
'pgp' => 'application/pgp',
'gpg' => 'application/gpg-keys',
'sst' => 'application/octet-stream',
'csr' => 'application/octet-stream',
'rsa' => 'application/x-pkcs7',
'cer' => array('application/pkix-cert', 'application/x-x509-ca-cert'),
'3g2' => 'video/3gpp2',
'3gp' => array('video/3gp', 'video/3gpp'),
'mp4' => 'video/mp4',
'm4a' => 'audio/x-m4a',
'f4v' => array('video/mp4', 'video/x-f4v'),
'flv' => 'video/x-flv',
'webm' => 'video/webm',
'aac' => 'audio/x-acc',
'm4u' => 'application/vnd.mpegurl',
'm3u' => 'text/plain',
'xspf' => 'application/xspf+xml',
'vlc' => 'application/videolan',
'wmv' => array('video/x-ms-wmv', 'video/x-ms-asf'),
'au' => 'audio/x-au',
'ac3' => 'audio/ac3',
'flac' => 'audio/x-flac',
'ogg' => array('audio/ogg', 'video/ogg', 'application/ogg'),
'kmz' => array('application/vnd.google-earth.kmz', 'application/zip', 'application/x-zip'),
'kml' => array('application/vnd.google-earth.kml+xml', 'application/xml', 'text/xml'),
'ics' => 'text/calendar',
'ical' => 'text/calendar',
'zsh' => 'text/x-scriptzsh',
'7z' => array('application/x-7z-compressed', 'application/x-compressed', 'application/x-zip-compressed', 'application/zip', 'multipart/x-zip'),
'7zip' => array('application/x-7z-compressed', 'application/x-compressed', 'application/x-zip-compressed', 'application/zip', 'multipart/x-zip'),
'cdr' => array('application/cdr', 'application/coreldraw', 'application/x-cdr', 'application/x-coreldraw', 'image/cdr', 'image/x-cdr', 'zz-application/zz-winassoc-cdr'),
'wma' => array('audio/x-ms-wma', 'video/x-ms-asf'),
'jar' => array('application/java-archive', 'application/x-java-application', 'application/x-jar', 'application/x-compressed'),
'svg' => array('image/svg+xml', 'application/xml', 'text/xml'),
'vcf' => 'text/x-vcard',
'srt' => array('text/srt', 'text/plain'),
'vtt' => array('text/vtt', 'text/plain'),
'ico' => array('image/x-icon', 'image/x-ico', 'image/vnd.microsoft.icon'),
'odc' => 'application/vnd.oasis.opendocument.chart',
'otc' => 'application/vnd.oasis.opendocument.chart-template',
'odf' => 'application/vnd.oasis.opendocument.formula',
'otf' => 'application/vnd.oasis.opendocument.formula-template',
'odg' => 'application/vnd.oasis.opendocument.graphics',
'otg' => 'application/vnd.oasis.opendocument.graphics-template',
'odi' => 'application/vnd.oasis.opendocument.image',
'oti' => 'application/vnd.oasis.opendocument.image-template',
'odp' => 'application/vnd.oasis.opendocument.presentation',
'otp' => 'application/vnd.oasis.opendocument.presentation-template',
'ods' => 'application/vnd.oasis.opendocument.spreadsheet',
'ots' => 'application/vnd.oasis.opendocument.spreadsheet-template',
'odt' => 'application/vnd.oasis.opendocument.text',
'odm' => 'application/vnd.oasis.opendocument.text-master',
'ott' => 'application/vnd.oasis.opendocument.text-template',
'oth' => 'application/vnd.oasis.opendocument.text-web'
);
+14
View File
@@ -0,0 +1,14 @@
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
/*
| -------------------------------------------------------------------------
| Profiler Sections
| -------------------------------------------------------------------------
| This file lets you determine whether or not various sections of Profiler
| data are displayed when the Profiler is enabled.
| Please see the user guide for info:
|
| https://codeigniter.com/user_guide/general/profiling.html
|
*/
+101
View File
@@ -0,0 +1,101 @@
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
/*
| -------------------------------------------------------------------------
| URI ROUTING
| -------------------------------------------------------------------------
| This file lets you re-map URI requests to specific controller functions.
|
| Typically there is a one-to-one relationship between a URL string
| and its corresponding controller class/method. The segments in a
| URL normally follow this pattern:
|
| example.com/class/method/id/
|
| In some instances, however, you may want to remap this relationship
| so that a different class/function is called than the one
| corresponding to the URL.
|
| Please see the user guide for complete details:
|
| https://codeigniter.com/user_guide/general/routing.html
|
| -------------------------------------------------------------------------
| RESERVED ROUTES
| -------------------------------------------------------------------------
|
| There are three reserved routes:
|
| $route['default_controller'] = 'welcome';
|
| This route indicates which controller class should be loaded if the
| URI contains no data. In the above example, the "welcome" class
| would be loaded.
|
| $route['404_override'] = 'errors/page_missing';
|
| This route will tell the Router which controller/method to use if those
| provided in the URL cannot be matched to a valid route.
|
| $route['translate_uri_dashes'] = FALSE;
|
| This is not exactly a route, but allows you to automatically route
| controller and method names that contain dashes. '-' isn't a valid
| class or method name character, so it requires translation.
| When you set this option to TRUE, it will replace ALL dashes in the
| controller and method URI segments.
|
| Examples: my-controller/index -> my_controller/index
| my-controller/my-method -> my_controller/my_method
*/
$route['default_controller'] = 'welcome';
$route['404_override'] = '';
$route['translate_uri_dashes'] = FALSE;
// geofence_area_country routes
$route['geofence_area_country']['GET'] = 'geofence_area_country/index';
$route['geofence_area_country/create']['GET'] = 'geofence_area_country/create';
$route['geofence_area_country/store']['POST'] = 'geofence_area_country/store';
$route['geofence_area_country/(:num)/edit']['GET'] = 'geofence_area_country/edit/$1';
$route['geofence_area_country/(:num)/update']['POST'] = 'geofence_area_country/update/$1';
$route['geofence_area_country/(:num)/delete']['GET'] = 'geofence_area_country/delete/$1';
// geofence_area_city routes
$route['geofence_area_city']['GET'] = 'geofence_area_city/index';
$route['geofence_area_city/create']['GET'] = 'geofence_area_city/create';
$route['geofence_area_city/store']['POST'] = 'geofence_area_city/store';
$route['geofence_area_city/(:num)/edit']['GET'] = 'geofence_area_city/edit/$1';
$route['geofence_area_city/(:num)/update']['POST'] = 'geofence_area_city/update/$1';
$route['geofence_area_city/(:num)/delete']['GET'] = 'geofence_area_city/delete/$1';
// geofence_area_city_settings routes
$route['geofence_area_city_settings']['GET'] = 'geofence_area_city_settings/index';
$route['geofence_area_city_settings/create']['GET'] = 'geofence_area_city_settings/create';
$route['geofence_area_city_settings/store']['POST'] = 'geofence_area_city_settings/store';
$route['geofence_area_city_settings/(:num)/edit']['GET'] = 'geofence_area_city_settings/edit/$1';
$route['geofence_area_city_settings/(:num)/update']['POST'] = 'geofence_area_city_settings/update/$1';
$route['geofence_area_city_settings/(:num)/delete']['GET'] = 'geofence_area_city_settings/delete/$1';
// geofence_area routes
$route['geofence_area']['GET'] = 'geofence_area/index';
$route['geofence_area/create']['GET'] = 'geofence_area/create';
$route['geofence_area/store']['POST'] = 'geofence_area/store';
$route['geofence_area/(:num)/edit']['GET'] = 'geofence_area/edit/$1';
$route['geofence_area/(:num)/update']['POST'] = 'geofence_area/update/$1';
$route['geofence_area/(:num)/delete']['GET'] = 'geofence_area/delete/$1';
// address routes
$route['addresses/(:num)/edit']['GET']='addresses/addressEdit/$1';
$route['addresses/(:num)/edit']['POST']='addresses/addressEdit/$1';
$route['addresses/(:num)/remove'] = 'addresses/remove/$1';
// logs
$route['logs'] = "logViewerController/index";
// activities
$route['activities/getTripreport/(:num)/(:any)/(:num)'] = 'member/getTripreport/$1/$2/$3';
$route['activities/getTimetravel/(:num)/(:any)/(:num)'] = 'member/getTimetravel/$1/$2/$3';
$route['activities/getSpentCategory/(:num)/(:any)/(:num)'] = 'member/getSpentCategory/$1/$2/0/$3';
$route['activities/getAllSpentCategory/(:num)/(:any)/(:num)'] = 'member/getAllSpentCategory/$1/$2/$3';
$route['activities/getEmissions/(:num)/(:any)/(:num)'] = 'member/getEmissions/$1/$2/$3';
+64
View File
@@ -0,0 +1,64 @@
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
/*
| -------------------------------------------------------------------
| SMILEYS
| -------------------------------------------------------------------
| This file contains an array of smileys for use with the emoticon helper.
| Individual images can be used to replace multiple smileys. For example:
| :-) and :) use the same image replacement.
|
| Please see user guide for more info:
| https://codeigniter.com/user_guide/helpers/smiley_helper.html
|
*/
$smileys = array(
// smiley image name width height alt
':-)' => array('grin.gif', '19', '19', 'grin'),
':lol:' => array('lol.gif', '19', '19', 'LOL'),
':cheese:' => array('cheese.gif', '19', '19', 'cheese'),
':)' => array('smile.gif', '19', '19', 'smile'),
';-)' => array('wink.gif', '19', '19', 'wink'),
';)' => array('wink.gif', '19', '19', 'wink'),
':smirk:' => array('smirk.gif', '19', '19', 'smirk'),
':roll:' => array('rolleyes.gif', '19', '19', 'rolleyes'),
':-S' => array('confused.gif', '19', '19', 'confused'),
':wow:' => array('surprise.gif', '19', '19', 'surprised'),
':bug:' => array('bigsurprise.gif', '19', '19', 'big surprise'),
':-P' => array('tongue_laugh.gif', '19', '19', 'tongue laugh'),
'%-P' => array('tongue_rolleye.gif', '19', '19', 'tongue rolleye'),
';-P' => array('tongue_wink.gif', '19', '19', 'tongue wink'),
':P' => array('raspberry.gif', '19', '19', 'raspberry'),
':blank:' => array('blank.gif', '19', '19', 'blank stare'),
':long:' => array('longface.gif', '19', '19', 'long face'),
':ohh:' => array('ohh.gif', '19', '19', 'ohh'),
':grrr:' => array('grrr.gif', '19', '19', 'grrr'),
':gulp:' => array('gulp.gif', '19', '19', 'gulp'),
'8-/' => array('ohoh.gif', '19', '19', 'oh oh'),
':down:' => array('downer.gif', '19', '19', 'downer'),
':red:' => array('embarrassed.gif', '19', '19', 'red face'),
':sick:' => array('sick.gif', '19', '19', 'sick'),
':shut:' => array('shuteye.gif', '19', '19', 'shut eye'),
':-/' => array('hmm.gif', '19', '19', 'hmmm'),
'>:(' => array('mad.gif', '19', '19', 'mad'),
':mad:' => array('mad.gif', '19', '19', 'mad'),
'>:-(' => array('angry.gif', '19', '19', 'angry'),
':angry:' => array('angry.gif', '19', '19', 'angry'),
':zip:' => array('zip.gif', '19', '19', 'zipper'),
':kiss:' => array('kiss.gif', '19', '19', 'kiss'),
':ahhh:' => array('shock.gif', '19', '19', 'shock'),
':coolsmile:' => array('shade_smile.gif', '19', '19', 'cool smile'),
':coolsmirk:' => array('shade_smirk.gif', '19', '19', 'cool smirk'),
':coolgrin:' => array('shade_grin.gif', '19', '19', 'cool grin'),
':coolhmm:' => array('shade_hmm.gif', '19', '19', 'cool hmm'),
':coolmad:' => array('shade_mad.gif', '19', '19', 'cool mad'),
':coolcheese:' => array('shade_cheese.gif', '19', '19', 'cool cheese'),
':vampire:' => array('vampire.gif', '19', '19', 'vampire'),
':snake:' => array('snake.gif', '19', '19', 'snake'),
':exclaim:' => array('exclaim.gif', '19', '19', 'exclaim'),
':question:' => array('question.gif', '19', '19', 'question')
);
+214
View File
@@ -0,0 +1,214 @@
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
/*
| -------------------------------------------------------------------
| USER AGENT TYPES
| -------------------------------------------------------------------
| This file contains four arrays of user agent data. It is used by the
| User Agent Class to help identify browser, platform, robot, and
| mobile device data. The array keys are used to identify the device
| and the array values are used to set the actual name of the item.
*/
$platforms = array(
'windows nt 10.0' => 'Windows 10',
'windows nt 6.3' => 'Windows 8.1',
'windows nt 6.2' => 'Windows 8',
'windows nt 6.1' => 'Windows 7',
'windows nt 6.0' => 'Windows Vista',
'windows nt 5.2' => 'Windows 2003',
'windows nt 5.1' => 'Windows XP',
'windows nt 5.0' => 'Windows 2000',
'windows nt 4.0' => 'Windows NT 4.0',
'winnt4.0' => 'Windows NT 4.0',
'winnt 4.0' => 'Windows NT',
'winnt' => 'Windows NT',
'windows 98' => 'Windows 98',
'win98' => 'Windows 98',
'windows 95' => 'Windows 95',
'win95' => 'Windows 95',
'windows phone' => 'Windows Phone',
'windows' => 'Unknown Windows OS',
'android' => 'Android',
'blackberry' => 'BlackBerry',
'iphone' => 'iOS',
'ipad' => 'iOS',
'ipod' => 'iOS',
'os x' => 'Mac OS X',
'ppc mac' => 'Power PC Mac',
'freebsd' => 'FreeBSD',
'ppc' => 'Macintosh',
'linux' => 'Linux',
'debian' => 'Debian',
'sunos' => 'Sun Solaris',
'beos' => 'BeOS',
'apachebench' => 'ApacheBench',
'aix' => 'AIX',
'irix' => 'Irix',
'osf' => 'DEC OSF',
'hp-ux' => 'HP-UX',
'netbsd' => 'NetBSD',
'bsdi' => 'BSDi',
'openbsd' => 'OpenBSD',
'gnu' => 'GNU/Linux',
'unix' => 'Unknown Unix OS',
'symbian' => 'Symbian OS'
);
// The order of this array should NOT be changed. Many browsers return
// multiple browser types so we want to identify the sub-type first.
$browsers = array(
'OPR' => 'Opera',
'Flock' => 'Flock',
'Edge' => 'Edge',
'Chrome' => 'Chrome',
// Opera 10+ always reports Opera/9.80 and appends Version/<real version> to the user agent string
'Opera.*?Version' => 'Opera',
'Opera' => 'Opera',
'MSIE' => 'Internet Explorer',
'Internet Explorer' => 'Internet Explorer',
'Trident.* rv' => 'Internet Explorer',
'Shiira' => 'Shiira',
'Firefox' => 'Firefox',
'Chimera' => 'Chimera',
'Phoenix' => 'Phoenix',
'Firebird' => 'Firebird',
'Camino' => 'Camino',
'Netscape' => 'Netscape',
'OmniWeb' => 'OmniWeb',
'Safari' => 'Safari',
'Mozilla' => 'Mozilla',
'Konqueror' => 'Konqueror',
'icab' => 'iCab',
'Lynx' => 'Lynx',
'Links' => 'Links',
'hotjava' => 'HotJava',
'amaya' => 'Amaya',
'IBrowse' => 'IBrowse',
'Maxthon' => 'Maxthon',
'Ubuntu' => 'Ubuntu Web Browser'
);
$mobiles = array(
// legacy array, old values commented out
'mobileexplorer' => 'Mobile Explorer',
// 'openwave' => 'Open Wave',
// 'opera mini' => 'Opera Mini',
// 'operamini' => 'Opera Mini',
// 'elaine' => 'Palm',
'palmsource' => 'Palm',
// 'digital paths' => 'Palm',
// 'avantgo' => 'Avantgo',
// 'xiino' => 'Xiino',
'palmscape' => 'Palmscape',
// 'nokia' => 'Nokia',
// 'ericsson' => 'Ericsson',
// 'blackberry' => 'BlackBerry',
// 'motorola' => 'Motorola'
// Phones and Manufacturers
'motorola' => 'Motorola',
'nokia' => 'Nokia',
'palm' => 'Palm',
'iphone' => 'Apple iPhone',
'ipad' => 'iPad',
'ipod' => 'Apple iPod Touch',
'sony' => 'Sony Ericsson',
'ericsson' => 'Sony Ericsson',
'blackberry' => 'BlackBerry',
'cocoon' => 'O2 Cocoon',
'blazer' => 'Treo',
'lg' => 'LG',
'amoi' => 'Amoi',
'xda' => 'XDA',
'mda' => 'MDA',
'vario' => 'Vario',
'htc' => 'HTC',
'samsung' => 'Samsung',
'sharp' => 'Sharp',
'sie-' => 'Siemens',
'alcatel' => 'Alcatel',
'benq' => 'BenQ',
'ipaq' => 'HP iPaq',
'mot-' => 'Motorola',
'playstation portable' => 'PlayStation Portable',
'playstation 3' => 'PlayStation 3',
'playstation vita' => 'PlayStation Vita',
'hiptop' => 'Danger Hiptop',
'nec-' => 'NEC',
'panasonic' => 'Panasonic',
'philips' => 'Philips',
'sagem' => 'Sagem',
'sanyo' => 'Sanyo',
'spv' => 'SPV',
'zte' => 'ZTE',
'sendo' => 'Sendo',
'nintendo dsi' => 'Nintendo DSi',
'nintendo ds' => 'Nintendo DS',
'nintendo 3ds' => 'Nintendo 3DS',
'wii' => 'Nintendo Wii',
'open web' => 'Open Web',
'openweb' => 'OpenWeb',
// Operating Systems
'android' => 'Android',
'symbian' => 'Symbian',
'SymbianOS' => 'SymbianOS',
'elaine' => 'Palm',
'series60' => 'Symbian S60',
'windows ce' => 'Windows CE',
// Browsers
'obigo' => 'Obigo',
'netfront' => 'Netfront Browser',
'openwave' => 'Openwave Browser',
'mobilexplorer' => 'Mobile Explorer',
'operamini' => 'Opera Mini',
'opera mini' => 'Opera Mini',
'opera mobi' => 'Opera Mobile',
'fennec' => 'Firefox Mobile',
// Other
'digital paths' => 'Digital Paths',
'avantgo' => 'AvantGo',
'xiino' => 'Xiino',
'novarra' => 'Novarra Transcoder',
'vodafone' => 'Vodafone',
'docomo' => 'NTT DoCoMo',
'o2' => 'O2',
// Fallback
'mobile' => 'Generic Mobile',
'wireless' => 'Generic Mobile',
'j2me' => 'Generic Mobile',
'midp' => 'Generic Mobile',
'cldc' => 'Generic Mobile',
'up.link' => 'Generic Mobile',
'up.browser' => 'Generic Mobile',
'smartphone' => 'Generic Mobile',
'cellphone' => 'Generic Mobile'
);
// There are hundreds of bots but these are the most common.
$robots = array(
'googlebot' => 'Googlebot',
'msnbot' => 'MSNBot',
'baiduspider' => 'Baiduspider',
'bingbot' => 'Bing',
'slurp' => 'Inktomi Slurp',
'yahoo' => 'Yahoo',
'ask jeeves' => 'Ask Jeeves',
'fastcrawler' => 'FastCrawler',
'infoseek' => 'InfoSeek Robot 1.0',
'lycos' => 'Lycos',
'yandex' => 'YandexBot',
'mediapartners-google' => 'MediaPartners Google',
'CRAZYWEBCRAWLER' => 'Crazy Webcrawler',
'adsbot-google' => 'AdsBot Google',
'feedfetcher-google' => 'Feedfetcher Google',
'curious george' => 'Curious George',
'ia_archiver' => 'Alexa Crawler',
'MJ12bot' => 'Majestic-12',
'Uptimebot' => 'Uptimebot'
);
+334
View File
@@ -0,0 +1,334 @@
<?php
defined('BASEPATH') or exit('No direct script access allowed');
class Acl extends Admin_Controller {
public $viewData = array();
public function __construct() {
parent::__construct();
$this->load->library('table');
$this->table->set_template($this->template);
$this->load->model('combo_model');
$this->load->model('Acl_model', 'acl');
// Load Pagination library
$this->load->library('pagination');
$controller = ($this->getController());
$options_array = array_combine($controller, $controller);
$this->viewData['controller_name'] = $this->combo_model->getControllerCombo('controller_name', $options_array, '');
$this->viewData['permission_level'] = $this->combo_model->getPermissionLevel('permission_level', '');
// filter
$options_array = array_merge($options_array, ['' => 'Select']);
ksort($options_array);
$this->viewData['card_class_filter'] = $this->combo_model->getControllerCombo('card_class_filter', $options_array, '');
$this->viewData['card_permission_level_filter'] = $this->combo_model->getPermissionLevel('card_permission_level_filter', '');
$this->viewData['msg'] = null;
}
protected function renderToolsPage($page_name, $data) {
$this->load->view('admin/view_admin_header', $data);
$this->load->view('acl/' . $page_name, $data);
$this->load->view('admin/view_admin_footer', $data);
}
private function getController() {
$path = __DIR__;
$controller = array();
$allFiles = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path));
$phpFiles = new RegexIterator($allFiles, '/\.php$/');
foreach ($phpFiles as $phpFile) {
$content = file_get_contents($phpFile->getRealPath());
$tokens = token_get_all($content);
$namespace = '';
for ($index = 0; isset($tokens[$index]); $index++) {
if (!isset($tokens[$index][0])) {
continue;
}
if (T_CLASS === $tokens[$index][0]) {
$index += 2; // Skip class keyword and whitespace
$controller[] = $tokens[$index][1];
}
}
}
sort($controller);
return $controller;
}
public function getMethodsByController() {
$controller = $this->input->post('controller');
$path = __DIR__;
$methods = array();
$phpFile = $path . '/' . $controller . '.php';
$content = file_get_contents($phpFile);
$tokens = token_get_all($content);
$namespace = '';
for ($index = 0; isset($tokens[$index]); $index++) {
if (!isset($tokens[$index][0])) {
continue;
}
if (T_FUNCTION === $tokens[$index][0]) {
$index += 2; // Skip class keyword and whitespace
if (!is_array($tokens[$index])) {
continue;
}
$methods[] = $tokens[$index][1];
}
}
sort($methods);
echo json_encode([
'methods' => $methods,
]);
}
public function index()
{
$this->renderToolsPage("view_acl", $this->viewData);
}
private function setFormRuleCreate()
{
$this->form_validation->set_rules('controller_name', 'Controller', 'required|max_length[50]');
$this->form_validation->set_rules('method_name', 'Method', 'required|max_length[50]');
$this->form_validation->set_rules('permission_level', 'Permission Level', 'required|callback_exists_permission_level|callback_check_duplicate_acl_and_permission_level');
}
private function getFormValue()
{
return [
'controller' => $this->input->post('controller_name'),
'method' => $this->input->post('method_name'),
'plevel' => $this->input->post('permission_level')
];
}
public function create() {
$this->load->helper(array('form', 'url'));
$this->load->database();
$this->load->library('form_validation');
$this->setFormRuleCreate();
$params = $this->getFormValue();
if ($this->form_validation->run() == false) {
$this->viewData['msg'] = validation_errors();
$this->renderToolsPage('view_acl', $this->viewData);
return;
}
$this->db->trans_start();
$this->db->trans_strict(FALSE);
$id = $this->acl->insert_acl($params);
$params = array_merge($params, [ 'bko_acl_id' => $id ]);
$this->acl->insert_acl_permission_level($params);
$this->acl->insert_acl_whitelist($params);
$this->db->trans_complete();
if ($this->db->trans_status() === FALSE) {
$this->db->trans_rollback();
$this->viewData['msg'] = "Insert Failed";
}
else {
$this->db->trans_commit();
$this->viewData['msg'] = "Insert Succesful";
}
$this->renderToolsPage('view_acl', $this->viewData);
}
public function check_duplicate_acl_and_permission_level() {
if ($this->acl->getRecordControllerMethodPlevel([
'controller' => $this->input->post('controller_name'),
'method' => $this->input->post('method_name'),
'plevel' => $this->input->post('permission_level')
])) {
$this->form_validation->set_message('check_duplicate_acl_and_permission_level', 'Oops !!! The value you entered is already in the list');
return FALSE;
} else {
return TRUE;
}
}
public function exists_permission_level() {
$permission_level = $this->input->post('permission_level');
if (!$permission_level) {
$this->form_validation->set_message('exists_permission_level', 'Please enter an existing permission');
return FALSE;
}
if (!$this->acl->getRecordByPermissionLevel([ 'plevel' => $permission_level])) {
$this->form_validation->set_message('exists_permission_level', 'Please enter an existing permission');
return FALSE;
} else {
return TRUE;
}
}
private function setFormRuleUpdate()
{
$this->form_validation->set_rules('id', 'Controller and Method', 'required|callback_exists_bko_acl');
$this->form_validation->set_rules('permission_level', 'Permission Level', 'callback_exists_permission_level');
}
public function exists_bko_acl($id)
{
if (!$id || !is_numeric($id)) {
$this->form_validation->set_message('exists_bko_acl', 'Please enter an existing controller and method');
return FALSE;
}
if (!$this->acl->gerRecordAclById(['id' => $id]))
{
$this->form_validation->set_message('exists_bko_acl', 'Please enter an existing controller and method');
return FALSE;
}
else
{
return TRUE;
}
}
public function update($bko_acl_id) {
$this->load->helper(array('form', 'url'));
$this->load->database();
$this->load->library('form_validation');
$this->form_validation->set_data(['id' => $bko_acl_id]);
$this->setFormRuleUpdate();
$params = $this->getFormValue();
$params = array_merge($params, ['bko_acl_id' => $bko_acl_id]);
if ($this->form_validation->run() == false) {
$this->viewData['msg'] = validation_errors();
$this->renderToolsPage('view_acl', $this->viewData);
return;
}
$this->viewData['msg'] = $this->acl->update_acl_permission_level($params) <> 1
? "Update Failed"
: "Update Successful" ;
$this->renderToolsPage('view_acl', $this->viewData);
}
private function setFormRuleDelete()
{
$this->form_validation->set_rules('id', 'Controller and Method', 'callback_exists_bko_acl');
}
public function destroy($id) {
$this->load->helper(array('form', 'url'));
$this->load->database();
$this->load->library('form_validation');
$this->form_validation->set_data(['id' => $id]);
$this->setFormRuleDelete();
if ($this->form_validation->run() == false) {
$this->viewData['msg'] = validation_errors();
$this->renderToolsPage('view_acl', $this->viewData);
return;
}
$this->viewData['msg'] = !$this->acl->deleteAclById($id)
? "Delete Failed"
: "Delete Successful" ;
$this->renderToolsPage('view_acl', $this->viewData);
}
private function setFormRuleSearchForm()
{
$this->form_validation->set_rules(
'card_permission_level_filter',
'Permission Level',
'numeric'
);
}
public function loadRecord(){
$rowno = $this->input->get('rowno');
parse_str($this->input->get('filters'), $filters);
$filters = array_filter($filters, function($val) {
return $val !== '';
});
$this->form_validation->set_data($filters);
$this->setFormRuleSearchForm();
$errors = [];
if ($this->form_validation->run() == false) {
$errors = $this->form_validation->error_array();
}
$filters = array_diff_key($filters, $errors);
// Row per page
$rowperpage = 10;
$cur_page = $rowno;
// Row position
if($rowno != 0){
$rowno = ($rowno-1) * $rowperpage;
}
// All records count
$allcount = $this->acl->getrecordCount($filters);
// Get records
$users_record = $this->acl->getData($rowno,$rowperpage,$filters);
// Pagination Configuration
$config['base_url'] = '/Acl/loadRecord';
$config['use_page_numbers'] = TRUE;
$config['total_rows'] = $allcount;
$config['per_page'] = $rowperpage;
$config['cur_page'] = $cur_page;
$config['full_tag_open'] = "<ul class='pagination'>";
$config['full_tag_close'] = "</ul>";
$config['num_tag_open'] = '<li>';
$config['num_tag_close'] = '</li>';
$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
$config['next_tag_open'] = "<li>";
$config['next_tagl_close'] = "</li>";
$config['prev_tag_open'] = "<li>";
$config['prev_tagl_close'] = "</li>";
$config['first_tag_open'] = "<li>";
$config['first_tagl_close'] = "</li>";
$config['last_tag_open'] = "<li>";
$config['last_tagl_close'] = "</li>";
// Initialize
$this->pagination->initialize($config);
// Initialize $data Array
$data['pagination'] = $this->pagination->create_links();
$data['result'] = $users_record;
$data['row'] = $rowno;
echo json_encode($data);
}
}
+292
View File
@@ -0,0 +1,292 @@
<?php
defined('BASEPATH') or exit('No direct script access allowed');
class Acl_WhiteList extends Admin_Controller {
public $viewData = [];
private $options_array = [];
public function __construct() {
parent::__construct();
$this->load->library('table');
$this->table->set_template($this->template);
$this->load->model('combo_model');
$this->load->model('Acl_Whitelist_model', 'acl_whitelist');
$this->load->model('Acl_Whitelist_Extra_model', 'acl_whitelist_extra');
// Load Pagination library
$this->load->library('pagination');
$this->options_array = $this->acl_whitelist->getControllerAndMethod();
$this->viewData['class_method'] = $this->combo_model->getControllerCombo('class_method', $this->options_array, '');
$this->viewData['msg'] = null;
// filter
$controller = $this->getController();
$options_array = array_combine($controller, $controller);
$options_array = array_merge($options_array, ['' => 'Select']);
ksort($options_array);
$this->viewData['card_class_filter'] = $this->combo_model->getControllerCombo('card_class_filter', $options_array, '');
$this->viewData['card_permission_level_filter'] = $this->combo_model->getPermissionLevel('card_permission_level_filter', '');
}
private function getController() {
$path = __DIR__;
$controller = array();
$allFiles = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path));
$phpFiles = new RegexIterator($allFiles, '/\.php$/');
foreach ($phpFiles as $phpFile) {
$content = file_get_contents($phpFile->getRealPath());
$tokens = token_get_all($content);
$namespace = '';
for ($index = 0; isset($tokens[$index]); $index++) {
if (!isset($tokens[$index][0])) {
continue;
}
if (T_CLASS === $tokens[$index][0]) {
$index += 2; // Skip class keyword and whitespace
$controller[] = $tokens[$index][1];
}
}
}
sort($controller);
return $controller;
}
protected function renderToolsPage($page_name, $data) {
$this->load->view('admin/view_admin_header', $data);
$this->load->view('acl_whitelist/' . $page_name, $data);
$this->load->view('admin/view_admin_footer', $data);
}
public function index()
{
$this->renderToolsPage("view_acl_whitelist", $this->viewData);
}
private function setFormRuleCreate()
{
$this->form_validation->set_rules('class_method', 'Class and Method', 'required|callback_existsAclWhitelist');
$this->form_validation->set_rules('parameter_name', 'Parameter name', 'required|max_length[50]|callback_checkDuplicateAclWhiltelistExtra');
$this->form_validation->set_rules('parameter_value', 'Parameter value', 'required|max_length[50]');
}
public function existsAclWhitelist() {
$id = $this->input->post('class_method');
if (!$id) {
$this->form_validation->set_message('existsAclWhitelist', 'Please enter an existing class and method');
return FALSE;
}
if (!$this->acl_whitelist->getRecordAclWhitelistById(['id' => $id])) {
$this->form_validation->set_message('existsAclWhitelist', 'Please enter an existing class and method');
return FALSE;
} else {
return TRUE;
}
}
public function checkDuplicateAclWhiltelistExtra() {
if ($this->acl_whitelist_extra->getRecordAclWhiteListExtraByParamNameAndParamValueAndAclWhiteListID($this->getFormValue())) {
$this->form_validation->set_message('checkDuplicateAclWhiltelistExtra', 'Oops !!! The value you entered is already in the list');
return FALSE;
} else {
return TRUE;
}
}
private function getFormValue()
{
return [
'bko_acl_whitelist_id' => $this->input->post('class_method'),
'parameter_name' => $this->input->post('parameter_name'),
'parameter_value' => $this->input->post('parameter_value')
];
}
public function create() {
$this->load->helper(array('form', 'url'));
$this->load->database();
$this->load->library('form_validation');
$this->setFormRuleCreate();
$params = $this->getFormValue();
if ($this->form_validation->run() == false) {
$this->viewData['class_method'] = $this->combo_model->getControllerCombo('class_method', $this->options_array, $params['bko_acl_whitelist_id']);
$this->viewData = array_merge($this->viewData, $params);
$this->viewData['msg'] = validation_errors();
$this->renderToolsPage('view_acl_whitelist', $this->viewData);
return;
}
if (!$this->acl_whitelist_extra->insertAclWhitelistExtra($params)) {
$this->viewData['msg'] = "Insert Failed";
}
else {
$this->viewData['msg'] = "Insert Succesful";
}
$this->renderToolsPage('view_acl_whitelist', $this->viewData);
}
private function setFormRuleSearchForm() {
$this->form_validation->set_rules(
'card_permission_level_filter',
'Permission Level',
'numeric'
);
}
public function loadRecord() {
$rowno = $this->input->get('rowno');
parse_str($this->input->get('filters'), $filters);
$filters = array_filter($filters, function($val) {
return $val !== '';
});
$this->form_validation->set_data($filters);
$this->setFormRuleSearchForm();
$errors = [];
if ($this->form_validation->run() == false) {
$errors = $this->form_validation->error_array();
}
$filters = array_diff_key($filters, $errors);
// Row per page
$rowperpage = 10;
$cur_page = $rowno;
// Row position
if($rowno != 0){
$rowno = ($rowno-1) * $rowperpage;
}
// All records count
$allcount = $this->acl_whitelist->getrecordCount($filters);
// Get records
$users_record = $this->acl_whitelist->getData($rowno,$rowperpage,$filters);
// Pagination Configuration
$config['base_url'] = '/Acl_Whitelist/loadRecord';
$config['use_page_numbers'] = TRUE;
$config['total_rows'] = $allcount;
$config['per_page'] = $rowperpage;
$config['cur_page'] = $cur_page;
$config['full_tag_open'] = "<ul class='pagination'>";
$config['full_tag_close'] = "</ul>";
$config['num_tag_open'] = '<li>';
$config['num_tag_close'] = '</li>';
$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
$config['next_tag_open'] = "<li>";
$config['next_tagl_close'] = "</li>";
$config['prev_tag_open'] = "<li>";
$config['prev_tagl_close'] = "</li>";
$config['first_tag_open'] = "<li>";
$config['first_tagl_close'] = "</li>";
$config['last_tag_open'] = "<li>";
$config['last_tagl_close'] = "</li>";
// Initialize
$this->pagination->initialize($config);
// Initialize $data Array
$data['pagination'] = $this->pagination->create_links();
$data['result'] = $users_record;
$data['row'] = $rowno;
echo json_encode($data);
}
private function setFormRuleUpdate()
{
$this->form_validation->set_rules('id', 'White list Extra', 'required|callback_existsAclWhitelistExtra');
$this->form_validation->set_rules('parameter_name', 'Parameter name', 'required|max_length[50]|callback_checkDuplicateAclWhiltelistExtra');
$this->form_validation->set_rules('parameter_value', 'Parameter value', 'required|max_length[50]');
}
public function existsAclWhitelistExtra($id) {
if (!$id || !is_numeric($id)) {
$this->form_validation->set_message('existsAclWhitelistExtra', 'Please enter an existing white list extra');
return FALSE;
}
if (!$this->acl_whitelist_extra->getRecordAclWhitelistExtraByID(['id' => $id]))
{
$this->form_validation->set_message('existsAclWhitelistExtra', 'Please enter an existing white list extra');
return FALSE;
}
else
{
return TRUE;
}
}
public function update($id) {
$this->load->helper(array('form', 'url'));
$this->load->database();
$this->load->library('form_validation');
$params = $this->getFormValue();
$params = array_merge($params, ['id' => $id]);
$this->form_validation->set_data($params);
$this->setFormRuleUpdate();
if ($this->form_validation->run() == false) {
$this->viewData['class_method'] = $this->combo_model->getControllerCombo('class_method', $this->options_array, $params['bko_acl_whitelist_id']);
$this->viewData = array_merge($this->viewData, $params);
$this->viewData['msg'] = validation_errors();
$this->renderToolsPage('view_acl_whitelist', $this->viewData);
return;
}
$result = $this->acl_whitelist_extra->updateAclWhitelistExtra($params);
$this->viewData['msg'] = $result === 0 ? "Update Failed" : "Update Succesful";
$this->renderToolsPage('view_acl_whitelist', $this->viewData);
}
private function setFormRuleDelete()
{
$this->form_validation->set_rules('id', 'White list Extra', 'required|callback_existsAclWhitelistExtra');
}
public function destroy($id) {
$this->load->helper(array('form', 'url'));
$this->load->database();
$this->load->library('form_validation');
$params = $this->getFormValue();
$this->form_validation->set_data(['id' => $id]);
$this->setFormRuleDelete();
if ($this->form_validation->run() == false) {
$this->viewData['class_method'] = $this->combo_model->getControllerCombo('class_method', $this->options_array, $params['bko_acl_whitelist_id']);
$this->viewData = array_merge($this->viewData, $params);
$this->viewData['msg'] = validation_errors();
$this->renderToolsPage('view_acl_whitelist', $this->viewData);
return;
}
$result = $this->acl_whitelist_extra->deleteAclWhitelistExtra($id);
$this->viewData['msg'] = $result === 0 ? "Delete Failed" : "Delete Successful";
$this->renderToolsPage('view_acl_whitelist', $this->viewData);
}
}
+267
View File
@@ -0,0 +1,267 @@
<?php
defined('BASEPATH') or exit('No direct script access allowed');
class Addresses extends Admin_Controller
{
public $viewData = array();
public $countries = array();
public $pagePerItem = 10;
private $geocode;
public function __construct()
{
parent::__construct();
// Load model
$this->load->model('combo_model');
$this->load->model('address_model', 'address');
$this->load->model('Geofence_area_city_model', 'geofence_area_city');
$this->viewData['selectedTab'] = 'address';
$this->load->helper('pagination');
}
public function index()
{
$page = $this->input->get('page', true);
$params = [];
if ($page) {
$params = ['page' => $page];
};
$this->viewData['city'] = $this->combo_model->getCityCombo('city', trim($this->input->get('city')));
$data = $this->address->getAddresses($params);
$this->viewData['radius_default'] = 'on';
$this->viewData['list'] = $data['list'];
$this->viewData['pagination'] = initPagination($this->pagePerItem, $data['total'], $data['page'], '/addresses');
$this->renderAdminPage('addresses/list', $this->viewData);
}
public function create()
{
$this->load->helper(array('form', 'url'));
$this->load->library('form_validation');
$this->viewData['errMsg'] = null;
$this->setFormRule();
if ($this->form_validation->run() == false) {
$this->renderAdminPage('addresses/create', $this->viewData);
return;
}
$params = $this->getFormValue();
$res = $this->address->createAddress($params);
if ($res['success']) {
$this->session->set_flashdata('success', $res['message']);
redirect('/addresses');
} else {
$this->viewData['errMsg'] = $res['error'];
$this->viewData['address'] = $params;
}
$this->load->view('addresses/create', $this->viewData);
}
public function getParamsRequest()
{
return [
'city' => trim($this->input->get('city_id', true)),
'city_name' => trim($this->input->get('city_name', true)),
'address' => trim($this->input->get('address', true)),
'radius' => trim($this->input->get('radius', true)),
'longitude' => trim($this->input->get('longitude', true)),
'latitude' => trim($this->input->get('latitude', true)),
'radius_default' => $this->input->get('radius_default'),
];
}
public function search()
{
$params = $this->getParamsRequest();
$page = $this->input->get('page', true);
$params = array_filter($params, function ($val) {
return $val !== '';
});
$pagingUrl = '/addresses/search?' . http_build_query($params);
if ($page) {
$params['page'] = $page;
}
$data = $this->address->getAddresses($params);
$this->viewData['city'] = $this->combo_model->getCityCombo('city', $this->input->get('city'));
$this->viewData['list'] = $data['list'];
$this->viewData['pagination'] = initPagination($this->pagePerItem, $data['total'], $data['page'], $pagingUrl);
$this->viewData = array_merge($this->viewData, $params);
$this->renderAdminPage('addresses/list', $this->viewData);
}
public function addressEdit($param)
{
$this->load->helper(array('form', 'url'));
$this->load->library('form_validation');
// Check if user edit the id through browser inspect
$this->viewData['address'] = ['id' => $param];
$id = $this->input->post('id');
if (isset($id) && $id != $param) {
redirect('/addresses');
}
$res = $this->address->getAddressById($param);
$this->viewData['address'] = $res['data'];
if (isset($res['error'])) {
redirect('/addresses');
return;
}
$this->viewData['errMsg'] = null;
$this->setFormRule();
if ($this->form_validation->run() == false) {
$this->viewData['errMsg'] = validation_errors();
$this->renderAdminPage('addresses/edit', $this->viewData);
return;
}
$params = $this->getFormValue();
$updateParams = http_build_query($params);
$res = $this->address->updateAddressById($id, $updateParams);
if ($res['success']) {
$this->session->set_flashdata('success', $res['message']);
redirect('/addresses');
} else {
$this->viewData['errMsg'] = $res['error'];
$this->viewData['address'] = $params;
}
$this->viewData['address'] = $params;
$this->renderAdminPage('addresses/edit', $this->viewData);
}
public function remove($param)
{
$res = $this->address->removeAddressById($param);
if ($res['success']) {
$this->session->set_flashdata('success', $res['message']);
} else {
$this->session->set_flashdata('error', $res['error']);
}
redirect('/addresses');
}
private function setFormRule()
{
$this->form_validation->set_rules('address', 'Address', 'required|callback_isValidAddress');
$this->form_validation->set_rules('geocoding_date', 'Geocoding date', 'required|callback_isDate');
$this->form_validation->set_rules('description', 'Description', 'max_length[100]');
}
protected function renderAdminPage($page_name, $data)
{
$this->load->view('admin/view_admin_header', $data);
$this->load->view($page_name, $data);
$this->load->view('admin/view_admin_footer', $data);
}
private function getFormValue()
{
return [
'address' => trim($this->input->post('address')),
'geocoding_date' => trim($this->input->post('geocoding_date')),
'description' => trim($this->input->post('description')),
'latitude' => $this->geocode['lat'],
'longitude' => $this->geocode['lng'],
'timezone' => $this->geocode['timezone'],
'postal' => $this->geocode['postal'],
'country' => $this->geocode['country'],
'geometry' => $this->convertToGeometry($this->geocode),
'city' => $this->geocode['city_id'],
];
}
public function isDate($date)
{
$matches = [];
$result = preg_match_all("/^([0-9]{4})-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])$/", $date, $matches, PREG_SET_ORDER);
if ($result == 0 || $result == false) {
$this->form_validation->set_message('isDate', 'Geocoding date is invalid');
return false;
}
$day = $matches[0][3];
$month = $matches[0][2];
$year = $matches[0][1];
if (checkdate($month, $day, $year)) {
return true;
} else {
$this->form_validation->set_message('isDate', 'Geocoding date is invalid');
return false;
}
}
public function isValidAddress($address)
{
$this->geocode = SQEAPI::geocode($address)['geocode'];
if (!$this->geocode) {
$this->form_validation->set_message('isValidAddress', 'Address is invalid');
return false;
}
$this->city = $this->geofence_area_city->getCityByCoordindates([
'latitude' => $this->geocode['lat'],
'longitude' => $this->geocode['lng'],
'radius' => 5, // km
]);
if (!$this->city) {
$this->form_validation->set_message('isValidAddress', 'Address is invalid');
return false;
}
$this->geocode['city_id'] = $this->city[0]['id'];
return true;
}
public function getAddressesAjax()
{
if (!$this->input->is_ajax_request()) {
exit('No direct script access allowed');
}
$result = $this->address->getAddressesWithUsingQuery([
'address' => trim($this->input->get('name')),
'page' => $this->input->get('page'),
]);
echo json_encode([
'data' => $result['data'],
'total' => $result['total'],
]);
}
private function convertToGeometry($params)
{
$query = "";
$query = "SELECT(ST_GeomFromText('"
. "POINT(" . $params['lat'] . " "
. $params['lng'] . ")', 4326)) AS geometry";
$rs = $this->read_replica->query($query);
return $rs->row_array()['geometry'];
}
}
+524
View File
@@ -0,0 +1,524 @@
<?php
defined('BASEPATH') or exit('No direct script access allowed');
class Advice extends Admin_Controller
{
const CSV_FIELDS = [
'travel_date', // | 2019-11-19 08:58:00
'duration', // | 26
'cost_raw', // | SGD 13.00
'cost', // | 13.00
'updated', // | 2019-11-19 03:53:48.809183
'distance', // | 10.77
'transport_provider_id', // | 3
'travel_date_end', // | 2019-11-19 09:24:55
'location_start_id', // | 7276
'location_end_id', // | 7277
'location_start_address', // | 65 Jurong West Central 3, Singapore, 648332
'location_start_lat', // | 1.339345
'location_start_lng', // | 103.705984
'location_start_postal', // |
'location_start_country', // | SG
'location_start_description', // |
'location_start_tz', // | Asia/Singapore
'location_end_address', // | 3 Engineering Drive 3, Singapore, 117582
'location_end_lat', // | 1.299255
'location_end_lng', // | 103.772206
'location_end_postal', // |
'location_end_country', // | SG
'location_end_description', // |
'location_end_tz' // | Asia/Singapore
];
public function __construct()
{
parent::__construct();
$this->load->model('advice_model');
$this->load->model('receipt_advice_model');
// Load form validation library
$this->load->library('form_validation');
// Load file helper
$this->load->helper('file');
}
public function index()
{
$data = array();
$this->load->helper('url');
$this->advicelist();
}
protected function renderAdvicePage($page_name, $data)
{
$this->load->view('admin/view_admin_header', $data);
$this->load->view('advice/' . $page_name, $data);
$this->load->view('admin/view_admin_footer', $data);
}
public function advicelist()
{
$data = [];
$data["page_title"] = "Advice List";
$data['advice_list'] = [];
$data['pagination_link'] = [];
$params = [];
$params = $this->input->get();
if (!empty($params)) {
$this->form_validation->set_data($params);
$this->setSearchRules();
if ($this->form_validation->run() == false) {
$this->renderAdvicePage("view_advice", $data);
return;
}
}
$query = $this->advice_model->getAdviceQuery($params);
$tableData = $this->returnAdminTable(
[
'count_query' => $query,
'query' => $query,
],
'advice/advicelist',
[
'per_page' => 100,
'reuse_query_string' => TRUE,
]
);
$data['advice_list'] = $tableData['output_table'];
$data['pagination_link'] = $tableData['links'];
$this->renderAdvicePage("view_advice", $data);
}
public function advicejson()
{
$id = $this->input->get('id');
if ($id == '' || $id < 1) {
echo '{"message":"Invalid ID"}';
return;
}
$q = "SELECT * FROM parsedemail_item WHERE id=" . $id;
$r = $this->read_replica->query($q);
$parsedemail_item = $r->row_array();
$q = "SELECT * FROM parsedemail_item_advice_google WHERE parsedemail_item_id = ${id}";
$r = $this->read_replica->query($q);
$advices = [];
foreach ($r->result() as $f) {
$advices[] = (array) $f;
}
foreach ($advices as $j => $advice) {
$q = "SELECT * FROM google_directions_legs WHERE parsedemail_item_advice_google_id = " . $advice["id"];
$r = $this->read_replica->query($q);
$legs = [];
foreach ($r->result() as $f) {
$legs[] = (array) $f;
}
foreach ($legs as $i => $leg) {
$q = "SELECT a.id AS step_id,a.distance,a.duration,a.travel_mode,a.location_start_lat,a.location_start_lng,a.location_end_lat,a.location_end_lng,a.html_instructions,a.polyline,b.* ";
$q .= ",c.name,c.service,c.board,c.alight,c.distance AS quote_distance,c.fare,c.fare_raw,c.distance_raw";
$q .= " FROM google_directions_leg_steps a LEFT JOIN google_directions_leg_step_details b ON (b.google_directions_leg_step_id=a.id) ";
$q .= " LEFT JOIN leg_step_quote c ON c.google_directions_leg_step_id=a.id ";
$q .= " WHERE a.google_directions_leg_id=" . $leg['id'];
$r = $this->read_replica->query($q);
$steps = [];
foreach ($r->result() as $f) {
$data = (array) $f;
foreach ($data as $key => $val) {
if ($val == NULL || $val == "") {
unset($data[$key]);
}
}
$steps[] = $data;
}
$leg['steps'] = $steps;
$legs[$i] = $leg;
}
$advice["legs"] = $legs;
$advices[$j] = $advice;
}
$parsedemail_item["advices"] = $advices;
echo json_encode($parsedemail_item);
/* echo '{
"id": 224583,
"location_start": "97 Meyer Rd, 93, Singapore 437918",
"location_end": "1 Fusionopolis Way, #01-07 & #02-14, Connexis, Singapore 138632",
"cost_raw": "14.6",
"trackedemail_item_id": 0,
"cost": "14.60",
"transport_provider_id": 4,
"location_start_lat": "1.2970576",
"location_start_lng": "103.8925856",
"location_end_lat": "1.2987049",
"location_end_lng": "103.7875699",
"request_date": "2020-01-09T13:09:00.955Z",
"started": "2020-01-09T13:09:04.203Z",
"complete": "2020-01-09T13:09:04.743Z",
"status": 0,
"message": "android_automation_job_detail",
"attempts": 0,
"automation_id": 206441,
"completed": "2020-01-09T13:09:04.743Z",
"created": "2020-01-09 13:09:01.072305",
"location_start_id": "4426",
"location_end_id": "4386",
"member_id": "13",
"deeplink": "ComfortDelGroTaxi:\/\/\/?action=setBooking&endingLat=1.298705&endingLong=103.787570&startingLat=1.297085&startingLong=103.892571"
}'; // */
}
private function setSearchRules()
{
$config = [
[
'field' => 'travel_date',
'label' => 'Travel date',
'rules' => 'trim',
],
[
'field' => 'duration_from',
'label' => 'Duration from',
'rules' => 'trim|numeric',
],
[
'field' => 'duration_to',
'label' => 'Duration to',
'rules' => 'trim|numeric',
],
[
'field' => 'distance_from',
'label' => 'Distance from',
'rules' => 'trim|numeric',
],
[
'field' => 'distance_to',
'label' => 'Distance to',
'rules' => 'trim|numeric',
],
[
'field' => 'location_start_id',
'label' => 'Location start',
'rules' => 'integer',
],
[
'field' => 'location_start_name',
'label' => 'Location start name',
'rules' => 'trim',
],
[
'field' => 'location_end_id',
'label' => 'Location end',
'rules' => 'integer',
],
[
'field' => 'location_end_name',
'label' => 'Location end name',
'rules' => 'trim',
],
];
$this->form_validation->set_rules($config);
}
public function exportCSV()
{
$this->load->helper('export_csv');
$data = [];
$data["page_title"] = "Advice List";
$data['advice_list'] = [];
$data['pagination_link'] = [];
$params = [];
$params = $this->input->get();
if (!empty($params)) {
$this->form_validation->set_data($params);
$this->setSearchRules();
if ($this->form_validation->run() == false) {
$this->renderAdvicePage("view_advice", $data);
return;
}
}
$params = array_filter($params, function ($val) {
return $val !== '';
});
$query = $this->advice_model->getAdviceQuery($params);
$tableData = $this->returnAdminTable(
[
'count_query' => $query,
'query' => $query,
],
'advice/advicelist',
[
'per_page' => 100,
'reuse_query_string' => TRUE,
]
);
$data['advice_list'] = $tableData['output_table'];
$data['pagination_link'] = $tableData['links'];
$query = $this->advice_model->get_query_parsed_email_quote_records($params);
$r = $this->read_replica->query($query);
if ($r->result_array()[0]['all_count'] === '0') {
$this->session->set_flashdata('error', 'Data not found !!!');
$this->renderAdvicePage("view_advice", $data);
return;
}
$this->read_replica->save_queries = false;
$query = $this->advice_model->get_query_parsed_email_quote_records(
$params,
self::NONE_COUNT_RECORD
);
$r = $this->read_replica->query($query);
export($r);
}
public function upload()
{
$this->load->helper('upload_file');
upload_file();
}
public function importCSV()
{
$this->load->helper('directory');
$row = 0;
$file_path = $_SERVER['DOCUMENT_ROOT']
. DIRECTORY_SEPARATOR
. self::TEMP_DIRECTORY_UPLOAD;
$file_name = scandir($file_path);
if ( ! $file_name) {
echo json_encode([
'code' => '404',
'message' => 'File Not Found !!!'
]);
}
if (($handle = fopen($file_path . '/' . $file_name[2], "r")) !== FALSE) {
deleteDir($file_path);
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$num = count($data);
$f = [];
for ($c=0; $c < $num; $c++) {
$f[self::CSV_FIELDS[$c]] = $data[$c];
}
if ($row>0) {
$this->save_record($f);
}
$row++;
}
fclose($handle);
}
echo json_encode([
'code' => '201',
'message' => 'Imported Successfully !!!'
]);
}
function save_record($f)
{
$member_id = $this->input->post()['member_id'];
$location_start_id = $this->get_address($f, 'start');
$location_end_id = $this->get_address($f, 'end');
if ($location_start_id < 1 || $location_end_id < 1) {
echo "Invalid address\n";
return NULL;
}
$q = "INSERT INTO trackedemail_item (member_id) VALUES(${member_id}) RETURNING id";
$trackedemail_item_id = NULL;
$r = $this->db->query($q);
if (isset($r->result_array()[0]['id'])) {
$trackedemail_item_id = $r->result_array()[0]['id'];
} else {
return NULL;
}
$q = "INSERT INTO parsedemail_item (travel_date,duration,cost_raw,trackedemail_item_id,cost,updated,distance,transport_provider_id,travel_date_end,location_start_id,location_end_id) VALUES (";
$q .= "'" . pg_escape_string($f["travel_date"]) . "',"; // | 2019-11-19 08:58:00
$q .= $f['duration'] == '' ? "NULL," : (((int) $f["duration"]) . ","); // | 26
$q .= "'" . pg_escape_string($f["cost_raw"]) . "',"; // | SGD 13.00
$q .= $trackedemail_item_id == NULL ? "NULL," : (((int) $trackedemail_item_id) . ",");
$q .= $f['cost'] == '' ? "NULL," : (floatval($f["cost"]) . ","); // | 13.00
$q .= $f['updated'] == '' ? "NULL," : ("'" . pg_escape_string($f["travel_date"]) . "',"); // | 2019-11-19 03:53:48.809183
$q .= $f['distance'] == '' ? "NULL," : (floatval($f["distance"]) . ","); // | 10.77
$q .= $f['transport_provider_id'] == '' ? "NULL," : (((int) $f["transport_provider_id"]) . ","); // | 3
$q .= $f['travel_date_end'] == '' ? "NULL," : ("'" . pg_escape_string($f["travel_date_end"]) . "',"); // | 2019-11-19 09:24:55
$q .= $location_start_id . "," . $location_end_id;
$q .= ") RETURNING id";
$r = $this->db->query($q)->result_array();
if (count($r) === 0) {
echo $q . "\n";
if ($trackedemail_item_id > 0) {
$q = "DELETE FROM trackedemail_item WHERE member_id = ${member_id} AND id = ${trackedemail_item_id}";
$this->db->query($q);
}
return NULL;
}
}
private function get_address($f, $what)
{
$tzid = $this->get_timezone($f, $what);
$q = "SELECT * FROM address WHERE lower(address)=lower('" . pg_escape_string($f["location_${what}_address"]) . "') and latitude=";
$q .= floatval($f["location_${what}_lat"]) . " AND longitude=" . floatval($f["location_${what}_lng"]);
$r = $this->read_replica->query($q)->result_array();
if (count($r)) {
return $r[0]['id'];
} else {
echo $q . "\n";
}
$q = "INSERT INTO address (address,latitude,longitude,timezone,geocoding_date,postal,country,geometry,description) VALUES(";
$q .= "'" . pg_escape_string($f["location_${what}_address"]) . "',"; // | 65 Jurong West Central 3, Singapore, 648332
$q .= floatval($f["location_${what}_lat"]) . ","; // | 1.339345
$q .= floatval($f["location_${what}_lng"]) . ","; // | 103.705984
$q .= $tzid . ",NOW(),"; // |
$q .= "'" . pg_escape_string($f["location_${what}_postal"]) . "',"; //
$q .= "'" . pg_escape_string($f["location_${what}_country"]) . "',"; // | SG
$q .= "st_setsrid(st_point(" . $f["location_${what}_lng"] . "," . $f["location_${what}_lat"] . "),4326),";
if ($f["location_${what}_description"] == '') {
$q .= "NULL";
} else {
$q .= "'" . pg_escape_string($f["location_${what}_description"]) . "'"; // |
}
$q .= ") RETURNING id";
$r = $this->db->query($q)->result_array();
if (count($r)) {
return $r[0]['id'];
} else {
echo $q . "\n";
}
return NULL;
}
private function get_timezone($f, $what)
{
$q = "SELECT * FROM address_timezone WHERE lower(timezone)=lower('" . pg_escape_string($f["location_${what}_tz"]) . "')";
$r = $this->read_replica->query($q)->result_array();
if (count($r)) {
return $r[0]['id'];
}
$q = "INSERT INTO address_timezone (timezone) VALUES('" . pg_escape_string($f["location_${what}_tz"]) . "') RETURNING id";
$r = $this->db->query($q)->result_array();
if (count($r)) {
return $r[0]['id'];
}
return NULL;
}
// Receipt Advice
public function receiptadvice()
{
$data = [];
$data["page_title"] = "Receipt Advice";
$data['receipt_advice'] = [];
$data['pagination_link'] = [];
$params = [];
$params = $this->input->get();
if (!empty($params)) {
$this->form_validation->set_data($params);
$this->setSearchRules();
if ($this->form_validation->run() == false) {
$this->renderAdvicePage("view_receipt_advice", $data);
return;
}
}
$query = $this->receipt_advice_model->getAdviceQuery($params);
$tableData = $this->returnAdminTable(
[
'count_query' => $query,
'query' => $query,
],
'advice/receiptadvice',
[
'per_page' => 100,
'reuse_query_string' => TRUE,
]
);
$data['receipt_advice'] = $tableData['output_table'];
$data['pagination_link'] = $tableData['links'];
$this->renderAdvicePage("view_receipt_advice", $data);
}
public function exportCSV_receipt_advice()
{
$this->load->helper('export_csv');
$data = [];
$data["page_title"] = "Advice List";
$data['receipt_advice'] = [];
$data['pagination_link'] = [];
$params = [];
$params = $this->input->get();
if (!empty($params)) {
$this->form_validation->set_data($params);
$this->setSearchRules();
if ($this->form_validation->run() == false) {
$this->renderAdvicePage("view_receipt_advice", $data);
return;
}
}
$params = array_filter($params, function ($val) {
return $val !== '';
});
$query = $this->receipt_advice_model->getAdviceQuery($params);
$tableData = $this->returnAdminTable(
[
'count_query' => $query,
'query' => $query,
],
'advice/receiptadvice',
[
'per_page' => 100,
'reuse_query_string' => TRUE,
]
);
$data['receipt_advice'] = $tableData['output_table'];
$data['pagination_link'] = $tableData['links'];
$query = $this->receipt_advice_model->get_query_parsed_email_quote_records($params);
$r = $this->read_replica->query($query);
if ($r->result_array()[0]['all_count'] === '0') {
$this->session->set_flashdata('error', 'Data not found !!!');
$this->renderAdvicePage("view_receipt_advice", $data);
return;
}
$this->read_replica->save_queries = false;
$query = $this->receipt_advice_model->get_query_parsed_email_quote_records(
$params,
self::NONE_COUNT_RECORD
);
$r = $this->read_replica->query($query);
export($r);
}
}
+90
View File
@@ -0,0 +1,90 @@
<?php
defined('BASEPATH') or exit('No direct script access allowed');
class Ajax extends CI_Controller
{
public function __construct()
{
parent::__construct();
$this->load->model('geofence_area_city_model');
}
public function geocodeReverse($latitude, $longitude)
{
//$this->output(['city' => "Wrocław"]);
global $savvyext;
$httpAuthToken = $savvyext->cfgReadChar('system.oauth2_token');
// Call geocoding service
$url = "http://oauth2.service/api/v1/reverse/?lat=" . $latitude . '&lng=' . $longitude;
$opts = array(
'http' => array(
'method' => "GET",
'timeout' => 60, /* 1 minute */
'header' =>
"Content-Type: application/x-www-form-urlencoded\r\n" .
"Accept: application/json\r\n" .
"Authorization: Server-Token ${httpAuthToken}\r\n",
),
);
$context = stream_context_create($opts);
$body = file_get_contents($url, false, $context);
$geocoded = json_decode($body, true);
if (is_array($geocoded) && is_array($geocoded["data"]) && !isset($geocoded["error"])) {
return $geocoded["data"]['city'];
}
return null;
}
public function updatecity($id, $latitude, $longitude)
{
$error = 1;
$city = $this->geocodeReverse($latitude, $longitude);
if (!empty($city)) {
$inputData = [
'city' => $city,
];
if ($this->geofence_area_city_model->update($id, $inputData) > 0) {
$error = 0;
$this->output(['error' => $error, 'msg' => 'Updated geofence area city successfully.','city'=>$city]);
} else {
$this->output(['error' => $error, 'msg' => 'Updated failed.','city'=>$city]);
}
}
$this->output(['error' => $error, 'msg' => 'Invalid input.','city'=>$city]);
}
public function cleanupCities(){
$duplicateds=$this->geofence_area_city_model->getDuplicatedCities();
$error=0;
foreach($duplicateds as $city){
$city_name =$city->city;
$country =$city->country;
$condition="LOWER(city) ILIKE '" . strtolower(pg_escape_string($city_name)) . "' AND country='" . $country . "'";
$city_ids = $this->geofence_area_city_model->getCities($condition);
$num = count($city_ids);
if ($num > 0) {
$ids=[];
foreach ($city_ids as $info) {
$ids[]=$info->id;
}
if(count($ids)>0){
$city_id = $ids[0];
$data_update = [
'city_id' => $city_id,
];
$condition = "country='" . $country . "' AND city_id IN (" . implode(",", $ids) . ")";
$updated = $this->geofence_area_city_model->updateAddresses($condition, $data_update);
}
}
}
$this->geofence_area_city_model->deleteUnusedCities();
$this->output(['error' => $error, 'msg' => 'Clean up successfully']);
}
private function output($output)
{
echo json_encode($output);exit;
}
}
@@ -0,0 +1,294 @@
<?php
defined('BASEPATH') or exit('No direct script access allowed');
class Android_automation_job_details extends Admin_Controller
{
public $viewData = array();
public $pagePerItem = 50;
public $statusOptions = [
'Inactive' => '0',
'Active' => '1',
];
public function __construct()
{
parent::__construct();
// Load model
$this->load->model('android_automation_job_detail_model', 'android_automation_job_detail');
$this->load->model('transport_provider_model', 'transport_provider');
$this->load->model('automation_job_model', 'automation_job');
$this->load->helper('pagination');
}
public function index()
{
$this->load->helper(array('url'));
//get query string filter
$filterData = $this->input->get();
$queryString = $this->input->server('QUERY_STRING');
$pagingUrl = empty($queryString) ? uri_string() : uri_string() . '?' . $queryString;
$pagingUrl = remove_querystring_var($pagingUrl, 'page');
$data = $this->android_automation_job_detail->getAndroidAutomationJobDetail(
[
'transport_provider_id' => !empty($filterData['transport_provider_id'])
? $filterData['transport_provider_id']
: '',
'job_id' => empty($filterData['job_id'])
? ''
: $filterData['job_id'],
'uuid' => empty($filterData['uuid'])
? ''
: $filterData['uuid'],
'name' => empty($filterData['name'])
? ''
: $filterData['name'],
'service_id' => empty($filterData['service_id'])
? ''
: $filterData['service_id'],
'page' => isset($filterData['page']) ? $filterData['page'] : 1
]
);
$transport_provider = [];
// Change data to array for display
foreach ($data['transport_providers'] as $tp) {
$transport_provider[] = (array) $tp;
}
$this->viewData['transport_provider'] = $transport_provider;
$data['list'] = array_map(function($item) {
$item['quote_date'] = $this->formatDate($item['quote_date']);
return $item;
}, $data['list']);
$this->viewData['list'] = $data['list'];
$this->viewData['statusOptions'] = $this->statusOptions;
$this->viewData['filterData'] = $filterData;
$this->viewData['pagination'] = initPagination($this->pagePerItem, $data['totalItems'], $data['page'], $pagingUrl);
$this->renderAdminPage('android_automation_job_details/list', $this->viewData);
}
public function create()
{
$this->load->helper(array('form', 'url'));
$this->viewData['statusOptions'] = $this->statusOptions;
$this->viewData['android_automation_job_detail'] = null;
$this->renderAdminPage('android_automation_job_details/create', $this->viewData);
}
public function store()
{
$this->load->helper(array('form', 'url'));
$this->load->library('form_validation');
$inputData = $this->getFormData();
$this->viewData['android_automation_job_detail'] = $inputData;
$this->viewData['statusOptions'] = $this->statusOptions;
$this->setAndroidAutomationJobDetailCreationRules();
if ($this->form_validation->run() == false) {
$this->renderAdminPage('android_automation_job_details/create', $this->viewData);
return;
}
$res = $this->android_automation_job_detail->createAndroidAutomationJobDetail($inputData);
if ($res['status'] == 'success') {
$this->session->set_flashdata('success', isset($res['message']) ? $res['message'] : 'Create success.');
redirect('/android_automation_job_details');
} else {
$this->session->set_flashdata('error', isset($res['message']) ? $res['message'] : 'Create fail.');
$this->renderAdminPage('android_automation_job_details/create', $this->viewData);
return;
}
}
private function formatDate($date) {
return (new DateTime($date))->format('Y-m-d');
}
public function edit($id)
{
$this->load->helper(array('form', 'url'));
$res = $this->android_automation_job_detail->getAndroidAutomationJobDetailByID($id);
if ($res['data']) {
$res['data']['quote_date'] = $this->formatDate($res['data']['quote_date']);
}
$this->viewData['android_automation_job_detail'] = isset($res['data']) ? $res['data'] : [];
$this->viewData['statusOptions'] = $this->statusOptions;
$this->viewData['id'] = $id;
$this->renderAdminPage('android_automation_job_details/edit', $this->viewData);
}
public function update($id)
{
$this->load->helper(array('form', 'url'));
$this->load->library('form_validation');
$inputData = $this->getFormData();
$this->viewData['statusOptions'] = $this->statusOptions;
$this->viewData['android_automation_job_detail'] = $inputData;
$this->viewData['id'] = $id;
$this->setAndroidAutomationJobDetailCreationRules();
if ($this->form_validation->run() == false) {
$this->renderAdminPage('android_automation_job_details/edit', $this->viewData);
return;
}
$res = $this->android_automation_job_detail->updateAndroidAutomationJobDetailById($id, $inputData);
if ($res['status'] == 'success') {
$this->session->set_flashdata('success', isset($res['message']) ? $res['message'] : 'Create success');
redirect('/android_automation_job_details');
} else {
$this->session->set_flashdata('error', $res['message']);
$this->renderAdminPage('android_automation_job_details/edit', $this->viewData);
return;
}
}
public function remove($param)
{
$res = $this->android_automation_job_detail->removeAndroidAutomationJobDetailById($param);
if (!$res['success'] != 'success') {
$this->viewData['errMsg'] = isset($res['message']) ? $res['message'] : 'Something went wrong. Please try again later.';
$this->renderAdminPage('android_automation_job_details', $this->viewData);
return;
}
redirect('/android_automation_job_details');
}
protected function renderAdminPage($page_name, $data)
{
$this->load->view('admin/view_admin_header', $data);
$this->load->view($page_name, $data);
$this->load->view('admin/view_admin_footer', $data);
}
private function getFormData()
{
return [
'job_id' => $this->input->post('job_id'),
'icon_info' => $this->input->post('icon_info'),
'name' => $this->input->post('name'),
'icon_url' => $this->input->post('icon_url'),
'descriptor' => $this->input->post('descriptor'),
'warning_message' => $this->input->post('warning_message'),
'uuid' => $this->input->post('uuid'),
'series_id' => $this->input->post('series_id'),
'service_id' => $this->input->post('service_id'),
'additional_booking_fee' => $this->input->post('additional_booking_fee'),
'advance_booking_fee' => $this->input->post('advance_booking_fee'),
'low_estimate' => $this->input->post('low_estimate'),
'high_estimate' => $this->input->post('high_estimate'),
'fixed' => $this->input->post('fixed'),
'quote_date' => $this->input->post('quote_date'),
];
}
private function setAndroidAutomationJobDetailCreationRules()
{
$config = [
[
'field' => 'job_id',
'label' => 'Job ID',
'rules' => 'required',
],
[
'field' => 'icon_info',
'label' => 'Icon Info',
'rules' => 'required',
],
[
'field' => 'name',
'label' => 'Nmae',
'rules' => 'required',
],
[
'field' => 'icon_url',
'label' => 'Icon Url',
'rules' => 'required',
],
[
'field' => 'descriptor',
'label' => 'Descriptor',
'rules' => 'required'
],
[
'field' => 'warning_message',
'label' => 'Warning Message',
'rules' => 'required',
],
[
'field' => 'uuid',
'label' => 'UUID',
'rules' => 'required',
],
[
'field' => 'series_id',
'label' => 'Series ID',
'rules' => 'required',
],
[
'field' => 'service_id',
'label' => 'Service ID',
'rules' => 'required',
],
[
'field' => 'additional_booking_fee',
'label' => 'Additional Booking Fee',
'rules' => 'required',
],
[
'field' => 'advance_booking_fee',
'label' => 'Advance Booking Fee',
'rules' => 'required',
],
[
'field' => 'low_estimate',
'label' => 'Low Estimate',
'rules' => 'required',
],
[
'field' => 'high_estimate',
'label' => 'High Estimate',
'rules' => 'required',
],
[
'field' => 'fixed',
'label' => 'Fixed',
'rules' => 'required',
],
[
'field' => 'quote_date',
'label' => 'Quote Date',
'rules' => 'required',
]
];
$this->form_validation->set_rules($config);
}
public function getTransportProviderByName() {
$name = $this->input->get()['q'];
$res = $this->transport_provider->getTransportProviderByName($name);
echo json_encode($res);
}
}
+225
View File
@@ -0,0 +1,225 @@
<?php
defined('BASEPATH') or exit('No direct script access allowed');
class Automation_jobs extends Admin_Controller
{
public $viewData = array();
public $pagePerItem = 50;
public function __construct()
{
parent::__construct();
// Load model
$this->load->model('automation_job_model', 'automation_job');
$this->load->helper('pagination');
}
public function setOnePastWeek(&$params) {
if (
(empty($params['from_complete']))
&& (empty($params['to_complete']))
) {
$params['from_complete'] = date('Y-m-d', strtotime('-1 week'));
$params['to_complete'] = date('Y-m-d');
}
}
public function index()
{
$this->load->helper(array('url'));
//get query string filter
$filterData = $this->input->get();
$this->setOnePastWeek($filterData);
$filterData['transport_provider_name'] = '';
$queryString = $this->input->server('QUERY_STRING');
// remove empty value
$filterData = array_map(function($ele) {
return trim($ele);
}, $filterData);
$filterData = array_filter($filterData, function ($v, $k) {
return $v !== '';
}, ARRAY_FILTER_USE_BOTH);
$pagingUrl = empty($queryString) ? uri_string() : uri_string() . '?' . $queryString;
$pagingUrl = remove_querystring_var($pagingUrl, 'page');
$data = $this->automation_job->getJobs($filterData);
$this->viewData['list'] = $data['list'];
$this->viewData['filterData'] = $filterData;
$this->viewData['pagination'] = initPagination($this->pagePerItem, $data['totalItems'], $data['page'], $pagingUrl);
$this->viewData = array_merge($this->viewData, $filterData);
$this->renderAdminPage('automation_jobs/list', $this->viewData);
}
public function create()
{
$this->load->helper(array('form', 'url'));
$this->viewData['job'] = null;
$this->renderAdminPage('automation_jobs/create', $this->viewData);
}
public function store()
{
$this->load->helper(array('form', 'url'));
$this->load->library('form_validation');
$this->viewData['job'] = null;
$this->setJobCreationRules();
$inputData = $this->getFormData();
if ($this->form_validation->run() == false) {
$this->viewData['job'] = $this->prepareTransportProviderData();
$this->renderAdminPage('automation_jobs/create', $this->viewData);
return;
}
$res = $this->automation_job->createJob($inputData);
if ($res['status'] == 'success') {
$this->session->set_flashdata('success', isSet($res['message']) ? $res['message'] : 'Create success.');
redirect('/automation_jobs');
} else {
$this->viewData['job'] = $this->prepareTransportProviderData();
$this->session->set_flashdata('error', isSet($res['message']) ? $res['message'] : 'Create fail.');
$this->renderAdminPage('automation_jobs/create', $this->viewData);
return;
}
}
public function edit($id)
{
$this->load->helper(array('form', 'url'));
$res= $this->automation_job->getById($id);
$job = isSet($res['data']) ? $res['data'] : [];
$this->viewData['job'] = $job;
$this->viewData['transport_provider_name'] = isset($job) ? $job['transport_provider_name'] : "";
$this->viewData['jobId'] = $id;
$this->renderAdminPage('automation_jobs/edit', $this->viewData);
}
public function update($id)
{
$this->load->helper(array('form', 'url'));
$this->load->library('form_validation');
$this->viewData['job'] = null;
$this->viewData['jobId'] = $id;
$this->setJobCreationRules();
if ($this->form_validation->run() == false) {
$this->viewData['job'] = $this->prepareTransportProviderData();
$this->renderAdminPage('automation_jobs/edit', $this->viewData);
return;
}
$inputData = $this->getFormData();
$inputData['id'] = (int) $id;
$res = $this->automation_job->updateById($id, $inputData);
if ($res['status'] == 'success') {
$this->session->set_flashdata('success', isSet($res['message']) ? $res['message'] : 'Create success');
redirect('/automation_jobs');
} else {
$this->viewData['job'] = $this->prepareTransportProviderData();
$this->session->set_flashdata('error', $res['message']);
$this->renderAdminPage('automation_jobs/edit', $this->viewData);
return;
}
}
public function remove($param)
{
$res = $this->automation_job->removeById($param);
if (!$res['success'] != 'success') {
$this->viewData['errMsg'] = isSet($res['message']) ? $res['message'] : 'Something went wrong. Please try again later.';
$this->renderAdminPage('automation_jobs', $this->viewData);
return;
}
redirect('/automation_jobs');
}
protected function renderAdminPage($page_name, $data) {
$this->load->view('admin/view_admin_header', $data);
$this->load->view($page_name, $data);
$this->load->view('admin/view_admin_footer', $data);
}
private function getFormData() {
return [
'location_start' => $this->input->post('location_start'),
'location_end' => $this->input->post('location_end'),
'location_start_lat' => $this->input->post('location_start_lat'),
'location_start_lng' => $this->input->post('location_start_lng'),
'location_end_lat' => $this->input->post('location_end_lat'),
'location_end_lng' => $this->input->post('location_end_lng'),
'cost_raw' => $this->input->post('cost_raw'),
'transport_provider_id' => (int) $this->input->post('transport_provider_id'),
'trackedemail_item_id' => $this->input->post('trackedemail_item_id'),
'cost' => $this->input->post('cost'),
'started' => $this->input->post('started'),
'complete' => $this->input->post('complete'),
'status' => $this->input->post('status'),
'message' => $this->input->post('message'),
'attempts' => (int) $this->input->post('attempts'),
];
}
private function setJobCreationRules()
{
$config = [
[
'field' => 'location_start',
'label' => 'Location start',
'rules' => 'required|max_length[200]',
'errors' => array(
'max_length' => 'Max length is 200.'
),
],
[
'field' => 'location_end',
'label' => 'Location end',
'rules' => 'required|max_length[200]',
'errors' => array(
'max_length' => 'Max length is 200.'
)
],
[
'field' => 'trackedemail_item_id',
'label' => 'Trackedemail Item',
'rules' => 'required'
],
[
'field' => 'transport_provider_id',
'label' => 'Transport provider',
'rules' => 'required',
],
];
$this->form_validation->set_rules($config);
}
private function prepareTransportProviderData() {
return [
'transport_provider_id' => (int) $this->input->post('transport_provider_id'),
'transport_provider_name' => $this->input->post('transport_provider_name')
];
}
public function getAndroidAutomationJobsByTransportProvider() {
$transport_provider_id = (int)$this->input->get('transport_provider_id');
$data = $this->automation_job->getJobs(
$transport_provider_id === 0 ? [] : [ 'transport_provider_id' => $transport_provider_id ]
);
echo json_encode([
'android_automation_jobs' => $data['list']
]);
}
}
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+109
View File
@@ -0,0 +1,109 @@
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Blog extends Admin_Controller {
public function index() {
$data['page_title'] = 'Blog';
$this->renderPage('index', $data);
}
public function getBlogs() {
$postData = $this->input->post();
$this->validate($postData, 'filter');
$params = !empty($postData['params']) ? $postData['params'] : null;
$pageNo = !empty($postData['pageNo']) ? $postData['pageNo'] - 1 : 0;
$pageSize = !empty($postData['pageSize']) ? $postData['pageSize'] : 10;
$this->load->model('blog_model');
$data = $this->blog_model->getBlogs($params, $pageNo, $pageSize);
echo json_encode($data);
}
public function store() {
$postData = $this->input->post();
$this->validate($postData);
$this->load->model('blog_model');
// Find record with blog_id
$record = $this->blog_model->getBlogs(['blog_id' => $postData['blog_id']]);
// If we found a record then return errors
if(!empty($record['result'])) {
header('HTTP/1.1 400 Bad Request');
echo json_encode(['errors' => ['message' => 'This Blog ID had been used']]);
return;
}
$this->blog_model->store($postData);
echo json_encode(['message' => 'Added successfully!']);
}
public function update() {
$postData = $this->input->post();
$this->validate($postData);
$this->load->model('blog_model');
// Find record with blog_id
$record = $this->blog_model->getBlogs(['blog_id' => $postData['blog_id']]);
// If we found a record then return errors
if(!empty($record['result']) && $record['result'][0]['id'] != $postData['id']) {
header('HTTP/1.1 400 Bad Request');
echo json_encode(['errors' => ['message' => 'This Blog ID had been used']]);
return;
}
$id = array_shift($postData);
$this->blog_model->update($id, $postData);
echo json_encode(['message' => 'Updated successfully!']);
}
public function delete() {
$postData = $this->input->post();
$this->load->model('blog_model');
$this->blog_model->delete($postData);
echo json_encode(['message' => 'Deleted successfully!']);
}
protected function validate($data, $type = 'saveOrUpdate') {
$this->load->library('form_validation');
$this->form_validation->set_data($data);
$this->setFormRuleForBlog($type);
if ($this->form_validation->run() === FALSE) {
$errors = $this->form_validation->error_array();
header('HTTP/1.1 400 Bad Request');
echo json_encode(['errors' => $errors]);
exit;
}
}
protected function setFormRuleForBlog($type) {
if ($type === 'filter') {
$this->form_validation->set_rules('params[blog_id]', 'Blog ID', 'integer');
$this->form_validation->set_rules('params[status]', 'Status', 'integer');
return;
}
$this->form_validation->set_rules('blog_id', 'Blog ID', 'required|integer');
$this->form_validation->set_rules('description', 'Description', 'required');
$this->form_validation->set_rules('status', 'Status', 'integer');
}
protected function renderPage($page_name, $data) {
$this->load->view('admin/view_admin_header', $data);
$this->load->view('blog/' . $page_name, $data);
$this->load->view('admin/view_admin_footer', $data);
}
}
@@ -0,0 +1,110 @@
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Blog_app_articles extends Admin_Controller {
public function index() {
$data['page_title'] = 'Blog App Articles';
$this->renderPage('index', $data);
}
public function getBlogs() {
$postData = $this->input->post();
$this->validate($postData, 'filter');
$params = !empty($postData['params']) ? $postData['params'] : null;
$pageNo = !empty($postData['pageNo']) ? $postData['pageNo'] - 1 : 0;
$pageSize = !empty($postData['pageSize']) ? $postData['pageSize'] : 10;
$this->load->model('blog_app_article_model');
$data = $this->blog_app_article_model->getBlogs($params, $pageNo, $pageSize);
echo json_encode($data);
}
public function store() {
$postData = $this->input->post();
$this->validate($postData);
$this->load->model('blog_app_article_model');
// Find record with blog_id
$record = $this->blog_app_article_model->getBlogs(['blog_id' => $postData['blog_id']]);
// If we found a record then return errors
if(!empty($record['result'])) {
header('HTTP/1.1 400 Bad Request');
echo json_encode(['errors' => ['message' => 'This Blog ID had been used']]);
return;
}
$this->blog_app_article_model->store($postData);
echo json_encode(['message' => 'Added successfully!']);
}
public function update() {
$postData = $this->input->post();
$this->validate($postData);
$this->load->model('blog_app_article_model');
// Find record with blog_id
$record = $this->blog_app_article_model->getBlogs(['blog_id' => $postData['blog_id']]);
// If we found a record then return errors
if(!empty($record['result']) && $record['result'][0]['id'] != $postData['id']) {
header('HTTP/1.1 400 Bad Request');
echo json_encode(['errors' => ['message' => 'This Blog ID had been used']]);
return;
}
$id = array_shift($postData);
$this->blog_app_article_model->update($id, $postData);
echo json_encode(['message' => 'Updated successfully!']);
}
public function delete() {
$postData = $this->input->post();
$this->load->model('blog_app_article_model');
$this->blog_app_article_model->delete($postData);
echo json_encode(['message' => 'Deleted successfully!']);
}
protected function validate($data, $type = 'saveOrUpdate') {
$this->load->library('form_validation');
$this->form_validation->set_data($data);
$this->setFormRuleForBlog($type);
if ($this->form_validation->run() === FALSE) {
$errors = $this->form_validation->error_array();
header('HTTP/1.1 400 Bad Request');
echo json_encode(['errors' => $errors]);
exit;
}
}
protected function setFormRuleForBlog($type) {
if ($type === 'filter') {
$this->form_validation->set_rules('params[blog_id]', 'Blog ID', 'integer');
$this->form_validation->set_rules('params[description]', 'Description', 'max_length[100]');
$this->form_validation->set_rules('params[status]', 'Status', 'integer');
return;
}
$this->form_validation->set_rules('blog_id', 'Blog ID', 'required|integer');
$this->form_validation->set_rules('description', 'Description', 'required|max_length[100]');
$this->form_validation->set_rules('status', 'Status', 'integer');
}
protected function renderPage($page_name, $data) {
$this->load->view('admin/view_admin_header', $data);
$this->load->view('blog_app_articles/' . $page_name, $data);
$this->load->view('admin/view_admin_footer', $data);
}
}
+62
View File
@@ -0,0 +1,62 @@
<?php
defined('BASEPATH') or exit('No direct script access allowed');
class Booking extends Admin_Controller {
private $params = null;
private $itemPerPage = 10;
public function __construct() {
parent::__construct();
// Load model
$this->load->model('booking_model');
}
public function index() {
$this->summary();
}
public function summary() {
$data['page_title'] = 'Booking';
$this->renderBookingPage('view_booking_summary', $data);
}
public function getReports() {
$postData = $this->input->post();
$this->validate($postData);
$params = !empty($postData['params']) ? $postData['params'] : $this->params;
$pageNo = !empty($postData['pageNo']) ? $postData['pageNo'] - 1 : 0;
$pageSize = !empty($postData['pageSize']) ? $postData['pageSize'] : $this->itemPerPage;
$data = $this->booking_model->getReports($params, $pageNo, $pageSize);
echo json_encode($data);
}
protected function validate($data, $type = 'filter') {
$this->load->library('form_validation');
$this->form_validation->set_data($data);
$this->setFormRuleForBooking($type);
if ($this->form_validation->run() === FALSE) {
$errors = $this->form_validation->error_array();
header('HTTP/1.1 400 Bad Request');
echo json_encode(['errors' => $errors]);
exit;
}
}
protected function setFormRuleForBooking($type) {
$this->form_validation->set_rules('params[id]', 'ID', 'integer');
$this->form_validation->set_rules('params[quote_id]', 'Quote ID', 'integer');
$this->form_validation->set_rules('params[member_id]', 'Member ID', 'integer');
$this->form_validation->set_rules('params[cost]', 'Cost', 'integer');
}
protected function renderBookingPage($page_name, $data) {
$this->load->view('admin/view_admin_header', $data);
$this->load->view('booking/' . $page_name, $data);
$this->load->view('admin/view_admin_footer', $data);
}
}
File diff suppressed because it is too large Load Diff
+100
View File
@@ -0,0 +1,100 @@
<?php
class Ckeditor extends Admin_Controller
{
// extends CI_Controller for CI 2.x users
public $data = array();
public function __construct()
{
//parent::Controller();
parent::__construct();
$this->load->helper('ckeditor');
//Ckeditor's configuration
$this->data['ckeditor'] = array(
//ID of the textarea that will be replaced
'id' => 'content',
'path' => 'js/ckeditor',
//Optionnal values
'config' => array(
'toolbar' => "Full", //Using the Full toolbar
'width' => "100px", //Setting a custom width
'height' => '100px', //Setting a custom height
),
//Replacing styles from the "Styles tool"
'styles' => array(
//Creating a new style named "style 1"
'style 1' => array(
'name' => 'Blue Title',
'element' => 'h2',
'styles' => array(
'color' => 'Blue',
'font-weight' => 'bold'
)
),
//Creating a new style named "style 2"
'style 2' => array(
'name' => 'Red Title',
'element' => 'h2',
'styles' => array(
'color' => 'Red',
'font-weight' => 'bold',
'text-decoration' => 'underline'
)
)
)
);
$this->data['ckeditor_2'] = array(
//ID of the textarea that will be replaced
'id' => 'content_2',
'path' => 'js/ckeditor',
//Optionnal values
'config' => array(
'width' => "550px", //Setting a custom width
'height' => '100px', //Setting a custom height
'toolbar' => array( //Setting a custom toolbar
array('Bold', 'Italic'),
array('Underline', 'Strike', 'FontSize'),
array('Smiley'),
'/'
)
),
//Replacing styles from the "Styles tool"
'styles' => array(
//Creating a new style named "style 1"
'style 3' => array(
'name' => 'Green Title',
'element' => 'h3',
'styles' => array(
'color' => 'Green',
'font-weight' => 'bold'
)
)
)
);
}
public function index()
{
$this->load->view('ckeditor', $this->data);
}
}
@@ -0,0 +1,67 @@
<?php
defined('BASEPATH') or exit('No direct script access allowed');
class Credit_card_benefits extends Admin_Controller
{
public $viewData = array();
public function __construct()
{
parent::__construct();
// Load model
$this->load->model('credit_card_benefit_model');
}
private function getFormValue()
{
return [
'benefit_id' => $this->input->post('benefit_id[]') ?? [],
'benefit' => $this->input->post('benefit[]') ?? [],
'expired_date' => $this->input->post('expired_date[]') ?? [],
];
}
public function update() {
$this->load->helper(array('form', 'url'));
$this->load->library('form_validation');
$params = $this->getFormValue();
$this->form_validation->set_data($params);
$this->setFormRuleUpdate();
if ($this->form_validation->run() == false) {
// Rerender filter if validate fail
echo json_encode([
'code' => '500',
'message' => validation_errors()
]);
return FALSE;
}
$this->credit_card_benefit_model->update($params);
echo json_encode([
'code' => '200',
'message' => 'Updated Successful'
]);
}
public function setFormRuleUpdate()
{
$this->form_validation->set_rules('benefit_id[]', 'ID', 'required');
$this->form_validation->set_rules('benefit[]', 'Benefit', 'required|max_length[256]');
$this->form_validation->set_rules('expired_date[]', 'Expired Date', 'regex_match[/\d{4}-\d{2}-\d{2}/]');
}
public function validateForm(&$params)
{
if ($this->form_validation->run() == false) {
// Rerender filter if validate fail
$this->viewData['msg'] = validation_errors();
return FALSE;
}
return TRUE;
}
}
+305
View File
@@ -0,0 +1,305 @@
<?php
defined('BASEPATH') or exit('No direct script access allowed');
class Credit_cards extends Admin_Controller
{
public $viewData = array();
public function __construct()
{
parent::__construct();
// load library
$this->load->library('session');
// Load model
$this->load->model('bank_model');
$this->load->model('credit_card_model');
$this->load->model('credit_card_benefit_model');
$this->load->library('pagination');
$this->viewData['benefits'] = [];
}
protected function renderToolsPage($page_name, $data)
{
$this->load->view('admin/view_admin_header', $data);
$this->load->view('credit_cards/' . $page_name, $data);
$this->load->view('admin/view_admin_footer', $data);
}
public function index()
{
$this->renderToolsPage("view_credit_cards", $this->viewData);
}
public function loadRecord()
{
$rowno = $this->input->get('rowno');
parse_str($this->input->get('filters'), $filters);
$filters = array_filter($filters, function($val) {
return $val !== '';
});
// Row per page
$rowperpage = 10;
$cur_page = $rowno;
// Row position
if ($rowno != 0) {
$rowno = ($rowno - 1) * $rowperpage;
}
// All records count
$allcount = count($this->credit_card_model->getData($filters));
// Get records
$users_record = $this
->credit_card_model
->getData($filters, $rowperpage, $rowno);
foreach($users_record as &$ele) {
$ele['benefits'] = array_map(function($ele) {
$ele['expired_date'] = empty($ele['expired_date'])
? ''
: $ele['expired_date'];
return $ele;
}, $this
->credit_card_benefit_model
->getBenefitByCardID($ele['credit_card_id']));
}
// Pagination Configuration
$config['base_url'] = '/Credit_cards/loadRecord';
$config['use_page_numbers'] = TRUE;
$config['total_rows'] = $allcount;
$config['per_page'] = $rowperpage;
$config['cur_page'] = $cur_page;
$config['full_tag_open'] = "<ul class='pagination pb-20'>";
$config['full_tag_close'] = "</ul>";
$config['num_tag_open'] = '<li>';
$config['num_tag_close'] = '</li>';
$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
$config['next_tag_open'] = "<li>";
$config['next_tagl_close'] = "</li>";
$config['prev_tag_open'] = "<li>";
$config['prev_tagl_close'] = "</li>";
$config['first_tag_open'] = "<li>";
$config['first_tagl_close'] = "</li>";
$config['last_tag_open'] = "<li>";
$config['last_tagl_close'] = "</li>";
// Initialize
$this->pagination->initialize($config);
// Initialize $data Array
$data['pagination'] = $this->pagination->create_links();
$data['result'] = $users_record;
$data['row'] = $rowno;
echo json_encode($data);
}
public function create()
{
$this->load->helper(array('form', 'url'));
$this->load->library('form_validation');
$this->setFormRuleCreate();
$params = $this->getFormValue();
if ($this->validateForm($params) === FALSE) {
$this->renderToolsPage('view_credit_cards', $this->viewData);
return;
}
if ($this->isExistBankNameAndCardType($params)) {
$this->viewData['msg'] = 'Bank Name and Card Type already input';
$this->renderToolsPage('view_credit_cards', $this->viewData);
return;
}
$this->insert_record($params);
redirect('/credit_cards');
}
public function setFormRuleCreate()
{
$this->form_validation->set_rules('bank_name', 'Bank Name', 'required|max_length[50]');
$this->form_validation->set_rules('card_name', 'Card Type', 'required|max_length[50]');
$this->form_validation->set_rules('benefits[]', 'Benefit', 'max_length[256]');
$this->form_validation->set_rules('expired_date[]', 'Expired Date', 'regex_match[/\d{4}-\d{2}-\d{2}/]');
}
private function getFormValue()
{
return [
'bank_name' => trim($this->input->post('bank_name') ?? ''),
'card_name' => trim($this->input->post('card_name') ?? ''),
'bank_id' => $this->input->post('bank_id'),
'credit_card_id' => $this->input->post('credit_card_id'),
'old_bank_name' => trim($this->input->post('old_bank_name') ?? ''),
'old_card_name' => trim($this->input->post('old_card_name') ?? ''),
'benefits[]' => $this->input->post('benefits[]') ?? [],
'expired_date[]' => $this->input->post('expired_date[]') ?? []
];
}
public function validateForm(&$params)
{
$this->form_validation->set_data($params);
if ($this->form_validation->run() == false) {
$this->viewData = array_merge($this->viewData, $params);
// Rerender filter if validate fail
$this->viewData['msg'] = validation_errors();
return FALSE;
}
return TRUE;
}
private function isExistBankNameAndCardType($data) {
return $this->credit_card_model->countRecordsByBankAndCardName([
'bank_name' => $data['bank_name'],
'card_name' => $data['card_name'],
]) > 0;
}
private function insert_record($params) {
$this->db->trans_start();
$this->db->trans_strict(FALSE);
$params['bank_id'] = $this->bank_model->insert($params);
$params['credit_card_id'] = $this->credit_card_model->insert($params);
$this->credit_card_benefit_model->insert($params);
$this->db->trans_complete();
if ($this->db->trans_status() === FALSE) {
$this->db->trans_rollback();
$this->viewData['msg'] = 'Something went wrong !!!';
return FALSE;
}
else {
$this->db->trans_commit();
return TRUE;
}
}
public function setFormRuleUpdate()
{
$this->form_validation->set_rules('bank_name', 'Bank Name', 'required|max_length[50]');
$this->form_validation->set_rules('card_name', 'Card Type', 'required|max_length[50]');
$this->form_validation->set_rules('benefits[]', 'Benefit', 'max_length[256]');
}
public function update()
{
$this->load->helper(array('form', 'url'));
$this->load->library('form_validation');
$this->setFormRuleUpdate();
$params = $this->getFormValue();
if ($this->validateForm($params) === FALSE) {
// $this->renderToolsPage('view_credit_cards', $this->viewData);
$response = array(
'type' => 'errors',
'message' => validation_errors()
);
return $this->output->set_content_type('application/json')->set_output( json_encode( $response ) );
}
if (
strcmp($params['bank_name'], $params['old_bank_name']) !== 0 ||
strcmp($params['card_name'], $params['old_card_name']) !== 0
) {
if ($this->isExistBankNameAndCardType($params)) {
$this->viewData['msg'] = 'Bank Name and Card Type already input';
$this->renderToolsPage('view_credit_cards', $this->viewData);
return;
}
}
$update = $this->update_record($params);
return $this->output->set_content_type('application/json')->set_output( json_encode( $update ) );
}
private function update_record($params) {
$this->db->trans_start();
$this->db->trans_strict(FALSE);
$params['bank_id'] = $this->bank_model->insert($params);
$this->credit_card_model->update($params);
// delete old records
$this->credit_card_benefit_model->delete($params);
$this->credit_card_benefit_model->insert($params);
$this->db->trans_complete();
if ($this->db->trans_status() === FALSE) {
$this->db->trans_rollback();
$this->viewData['msg'] = 'Something went wrong !!!';
return FALSE;
}
else {
$this->db->trans_commit();
return $params;
}
}
public function destroy() {
$this->load->helper(array('form', 'url'));
$this->load->database();
$params = $this->getFormValue();
$this->setFormRuleDelete();
if ($this->validateForm($params) === FALSE) {
$this->renderToolsPage('view_credit_cards', $this->viewData);
return;
}
$result = $this->delete_record($params);
$this->viewData['msg'] = $result ? "Delete Successful" : "Delete Fail";
$this->renderToolsPage('view_credit_cards', $this->viewData);
}
public function delete_record($params) {
$this->db->trans_start();
$this->db->trans_strict(FALSE);
$this->credit_card_benefit_model->delete($params);
$this->credit_card_model->delete($params);
$this->db->trans_complete();
if ($this->db->trans_status() === FALSE) {
$this->db->trans_rollback();
return FALSE;
}
else {
$this->db->trans_commit();
if ($this->credit_card_model->count_credit_card($params) === '0') {
$this->bank_model->delete($params);
}
return TRUE;
}
}
private function setFormRuleDelete()
{
$this->form_validation->set_rules('credit_card_id', 'Credit', 'required|numeric|exist[credit_cards,id,credit_card_id]');
}
}
+256
View File
@@ -0,0 +1,256 @@
<?php
defined( 'BASEPATH' ) OR exit( 'No direct script access allowed' );
class Dash extends Admin_Controller {
public function index() {
return $this->dashdata();
}
public function memberlist(){
global $bko_users_members_access_list;
$mysql = "SELECT '<a href=\"/member/viewLocateMember?member_id='||id||'\" >Select</a>' AS select, id,username,firstname,lastname, last_login,loc,"
. " '<button style=\"padding:3px;\" type=\"button\" class=\"btn btn-info btn-xs\" onclick=\"viewMember('||id||');\" >View</button>' AS ACT "
. " "
. " FROM members WHERE id>0 ";
if (isset($bko_users_members_access_list) && $bko_users_members_access_list!="") {
$mysql .= " AND id IN (${bko_users_members_access_list})";
}
$mysql.= "ORDER BY id ASC";
$mysql = "SELECT count(*) AS count FROM members WHERE id>0";
if (isset($bko_users_members_access_list) && $bko_users_members_access_list!="") {
$mysql .= " AND id IN (${bko_users_members_access_list})";
}
$r = $this->read_replica->query($mysql);
$f = $r->row_array();
$this->load->library( 'pagination' );
$config = array();
//$query = $this->db->query( $mysql );
$config["total_rows"] = $f['count']; //$query->num_rows();
$config["base_url"] = base_url() . "/dash/memberlist";
$config["per_page"] = 15;
$config["uri_segment"] = 3;
$config["num_links"] = 5;
$config['full_tag_open'] = "<ul class='pagination'>";
$config['full_tag_close'] = "</ul>";
$config['num_tag_open'] = '<li>';
$config['num_tag_close'] = '</li>';
$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
$config['next_tag_open'] = "<li>";
$config['next_tagl_close'] = "</li>";
$config['prev_tag_open'] = "<li>";
$config['prev_tagl_close'] = "</li>";
$config['first_tag_open'] = "<li>";
$config['first_tagl_close'] = "</li>";
$config['last_tag_open'] = "<li>";
$config['last_tagl_close'] = "</li>";
$this->pagination->initialize( $config );
$page = ( $this->uri->segment( 3 ) ) ? $this->uri->segment( 3 ) : 0;
$page = is_numeric( $page ) ? $page : 0;
global $savvyext;
$this->load->helper( 'url' );
$data = array();
$this->load->library( 'table' );
$this->template["table_open"] = "<table class='table table-striped table-hover table-bordered table-condensed' style='padding:0px; background-color:lightgreen;'>";
$this->table->set_template( $this->template );
//coalesce(xx,'')
$mysql = "SELECT '<a href=\"/member/viewLocateMember?member_id='||id||'\" >Select</a>' AS select, id,"
. "username,firstname||' '||lastname AS name,decision_group, last_login,loc,"
. " '<button style=\"padding:3px;\" type=\"button\" class=\"btn btn-info btn-xs\" onclick=\"viewMember('||id||');\" >View</button>&nbsp;' ||"
. " CASE WHEN status = 0 OR login_failures >= 5 THEN '<button style=\"padding:3px; width: 50px;\" type=\"button\" class=\"btn btn-info btn-xs\" onclick=\"unblockMember('||id||');\" >Unblock</button>' "
. " WHEN status = 1 OR login_failures < 5 THEN '<button style=\"padding:3px; width: 50px;\" type=\"button\" class=\"btn btn-danger btn-xs\" onclick=\"blockMember('||id||');\" >Block</button>' "
. " ELSE '' "
. " END "
. " AS ACT "
. " "
. " FROM members WHERE id>0 ";
if (isset($bko_users_members_access_list) && $bko_users_members_access_list!="") {
$mysql .= " AND id IN (${bko_users_members_access_list})";
}
$mysql .= "ORDER BY id ASC LIMIT " . $config["per_page"] . " OFFSET " . $page . " ";
$query = $this->read_replica->query( $mysql );
$this->table->set_heading( array( 'data' => 'Select', 'style' => 'width:40px' ), array( 'data' => 'ID',
'style' => 'width:30px'
), 'Email', 'Personalty','Name', 'Last Login', 'Location', array( 'data' => 'ACT',
'style' => 'width:40px; text-align: center;'
) );
$data['member_table'] = $this->table->generate( $query );
$data["links"] = $this->pagination->create_links();
$data['google_api_key'] = $savvyext->cfgReadChar( 'google.api_key' );
$data["page_title"] = "";
$data["page_link"] = $this->pagination->create_links();
$q = "SELECT count(id) AS dcount ,added::date AS dt FROM members WHERE added + '27 days' > now() GROUP BY added::date ORDER BY added::date LIMIT 7";
$query = $this->read_replica->query($q);
$data['plot_signup'] = $query->result_array();
$q = "SELECT count(id),created::date FROM trackedemail_item GROUP BY created::date ORDER BY created DESC LIMIT 30";
$query = $this->read_replica->query($q);
$data['plot_emaildownload'] = $query->result_array();
$this->renderAdminPage( 'view_memberlist', $data );
// echo 'Ameye Olu';
}
public function dashdata() {
global $bko_users_members_access_list;
$mysql = "SELECT '<a href=\"/member/viewLocateMember?member_id='||id||'\" >Select</a>' AS select, id,username,firstname,lastname, last_login,loc,"
. " '<button style=\"padding:3px;\" type=\"button\" class=\"btn btn-info btn-xs\" onclick=\"viewMember('||id||');\" >View</button>' AS ACT "
. " "
. " FROM members WHERE id>0 ";
if (isset($bko_users_members_access_list) && $bko_users_members_access_list!="") {
$mysql .= " AND id IN (${bko_users_members_access_list})";
}
$mysql.= "ORDER BY id ASC";
$mysql = "SELECT count(*) AS count FROM members WHERE id>0";
if (isset($bko_users_members_access_list) && $bko_users_members_access_list!="") {
$mysql .= " AND id IN (${bko_users_members_access_list})";
}
$r = $this->read_replica->query($mysql);
$f = $r->row_array();
$this->load->library( 'pagination' );
$config = array();
//$query = $this->db->query( $mysql );
$config["total_rows"] = $f['count']; //$query->num_rows();
$config["base_url"] = base_url() . "/dash/dashdata";
$config["per_page"] = 15;
$config["uri_segment"] = 3;
$config["num_links"] = 5;
$config['full_tag_open'] = "<ul class='pagination'>";
$config['full_tag_close'] = "</ul>";
$config['num_tag_open'] = '<li>';
$config['num_tag_close'] = '</li>';
$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
$config['next_tag_open'] = "<li>";
$config['next_tagl_close'] = "</li>";
$config['prev_tag_open'] = "<li>";
$config['prev_tagl_close'] = "</li>";
$config['first_tag_open'] = "<li>";
$config['first_tagl_close'] = "</li>";
$config['last_tag_open'] = "<li>";
$config['last_tagl_close'] = "</li>";
$this->pagination->initialize( $config );
$page = ( $this->uri->segment( 3 ) ) ? $this->uri->segment( 3 ) : 0;
$page = is_numeric( $page ) ? $page : 0;
global $savvyext;
$this->load->helper( 'url' );
$data = array();
$this->load->library( 'table' );
$this->template["table_open"] = "<table class='table table-striped table-hover table-bordered table-condensed' style='padding:0px; background-color:lightgreen;'>";
$this->table->set_template( $this->template );
//coalesce(xx,'')
$mysql = "SELECT '<a href=\"/member/viewLocateMember?member_id='||id||'\" >Select</a>' AS select, id,"
. "username,firstname||' '||lastname AS name,decision_group, last_login,loc,"
. " '<button style=\"padding:3px;\" type=\"button\" class=\"btn btn-info btn-xs\" onclick=\"viewMember('||id||');\" >View</button>&nbsp;' ||"
. " CASE WHEN status = 0 OR login_failures >= 5 THEN '<button style=\"padding:3px; width: 50px;\" type=\"button\" class=\"btn btn-info btn-xs\" onclick=\"unblockMember('||id||');\" >Unblock</button>' "
. " WHEN status = 1 OR login_failures < 5 THEN '<button style=\"padding:3px; width: 50px;\" type=\"button\" class=\"btn btn-danger btn-xs\" onclick=\"blockMember('||id||');\" >Block</button>' "
. " ELSE '' "
. " END "
. " AS ACT "
. " "
. " FROM members WHERE id>0 ";
if (isset($bko_users_members_access_list) && $bko_users_members_access_list!="") {
$mysql .= " AND id IN (${bko_users_members_access_list})";
}
$mysql .= "ORDER BY id ASC LIMIT " . $config["per_page"] . " OFFSET " . $page . " ";
$query = $this->read_replica->query( $mysql );
$this->table->set_heading( array( 'data' => 'Select', 'style' => 'width:40px' ), array( 'data' => 'ID',
'style' => 'width:30px'
), 'Email', 'Personalty','Name', 'Last Login', 'Location', array( 'data' => 'ACT',
'style' => 'width:40px; text-align: center;'
) );
$data['member_table'] = $this->table->generate( $query );
$data["links"] = $this->pagination->create_links();
$data['google_api_key'] = $savvyext->cfgReadChar( 'google.api_key' );
$data["page_title"] = "";
$data["page_link"] = $this->pagination->create_links();
$q = "SELECT count(id) AS dcount ,added::date AS dt FROM members WHERE added + '27 days' > now() GROUP BY added::date ORDER BY added::date LIMIT 7";
$query = $this->read_replica->query($q);
$data['plot_signup'] = $query->result_array();
$q = "SELECT count(id),created::date FROM trackedemail_item GROUP BY created::date ORDER BY created DESC LIMIT 30";
$query = $this->read_replica->query($q);
$data['plot_emaildownload'] = $query->result_array();
//How many Farm records generated daliy - last 10 days [SG & US] - 2 plots
$q = "SELECT a.*,b.total AS success, CASE WHEN a.total>0 THEN ROUND(100.0*b.total/a.total,2) ELSE 0.0 END AS success_rate
FROM (SELECT date_trunc('day',aa.created) AS created,count(*) AS total FROM quotes aa
LEFT JOIN address ab ON ab.id=aa.location_start_id
WHERE aa.created>now()-interval '9 days' AND ab.country='SG' GROUP BY date_trunc('day',aa.created)) AS a
LEFT JOIN (SELECT date_trunc('day',ba.created) AS created,count(*) AS total FROM quotes ba
LEFT JOIN address bb ON bb.id=ba.location_start_id
WHERE ba.created>now()-interval '9 days' AND ba.cost>0 AND bb.country='SG'
GROUP BY date_trunc('day',created)) AS b ON (b.created=a.created) ORDER BY a.created DESC";
$query = $this->read_replica->query( $q );
$data['records_generated_daliy_SG'] = $this->table->generate( $query );
$q = "SELECT a.*,b.total AS success, CASE WHEN a.total>0 THEN ROUND(100.0*b.total/a.total,2) ELSE 0.0 END AS success_rate
FROM (SELECT date_trunc('day',aa.created) AS created,count(*) AS total FROM quotes aa
LEFT JOIN address ab ON ab.id=aa.location_start_id
WHERE aa.created>now()-interval '9 days' AND ab.country='US' GROUP BY date_trunc('day',aa.created)) AS a
LEFT JOIN (SELECT date_trunc('day',ba.created) AS created,count(*) AS total FROM quotes ba
LEFT JOIN address bb ON bb.id=ba.location_start_id
WHERE ba.created>now()-interval '9 days' AND ba.cost>0 AND bb.country='US'
GROUP BY date_trunc('day',created)) AS b ON (b.created=a.created) ORDER BY a.created DESC";
$query = $this->read_replica->query( $q );
$data['records_generated_daliy_US'] = $this->table->generate( $query );
$this->renderAdminPage( 'view_start', $data );
// echo 'Ameye Olu';
}
public function dashpage() {
global $savvyext;
$this->load->helper( 'url' );
$data = array();
$this->load->library( 'table' );
$this->table->set_template( $this->template );
$mysql = "SELECT '<button type=\"button\" class=\"btn btn-primary btn-xs\" onclick=\"viewMember('||id||');\" >View</button>' AS action ,username,firstname,lastname FROM members";
$query = $this->read_replica->query( $mysql );
$this->table->set_heading( array( 'data' => 'ACTION',
'style' => 'width:90px'
), 'USERNAME', 'FIRSTNAME', 'LASTNAME' );
$data['member_table'] = $this->table->generate( $query );
$data['google_api_key'] = $savvyext->cfgReadChar( 'google.api_key' );
//$data['js'] = array('https://maps.googleapis.com/maps/api/js?key=AIzaSyDvjiRTxngOQyBP4zpqFlZuiquc0ROvo9c&callback=initMap');
$this->renderAdminPage( 'view_dash', $data );
// echo 'Ameye Olu';
}
}
+784
View File
@@ -0,0 +1,784 @@
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Descision extends Admin_Controller {
var $template = array(
'table_open' => "<table style='background-color:aliceblue' class='table table-striped table-hover table-bordered table-condensed'>",
'thead_open' => '<thead class=\'bg-teal\'>',
'thead_close' => '</thead>',
'heading_row_start' => '<tr>',
'heading_row_end' => '</tr>',
'heading_cell_start' => '<th>',
'heading_cell_end' => '</th>',
'tbody_open' => '<tbody>',
'tbody_close' => '</tbody>',
'row_start' => '<tr>',
'row_end' => '</tr>',
'cell_start' => '<td>',
'cell_end' => '</td>',
'row_alt_start' => '<tr>',
'row_alt_end' => '</tr>',
'cell_alt_start' => '<td>',
'cell_alt_end' => '</td>',
'table_close' => '</table>'
);
public function index() {
}
protected function renderDescisionPage($page_name, $data) {
$this->load->view('admin/view_admin_header', $data);
$this->load->view('descision/' . $page_name, $data);
$this->load->view('admin/view_admin_footer', $data);
}
public function getValueOfDecisionLogic() {
return [
'logic' => trim($this->input->get('logic')),
'description' => trim($this->input->get('description')),
'status' => trim($this->input->get('card_status')
?? $this->input->get('status') ?? '-1'),
'survey' => trim($this->input->get('card_survey')
?? $this->input->get('survey') ?? '-1'),
'from_weight' => trim($this->input->get('from_weight')),
'to_weight' => trim($this->input->get('to_weight'))
];
}
public function setComboForDecisionLogic($params) {
$this->load->model('combo_model');
$combo['card_status'] = $this->combo_model->getStatusComboWithAll(
'card_status',
$params['status']
);
$combo['card_survey'] = $this->combo_model->getYesNoComboWithAll(
'card_survey',
$params['survey']
);
return $combo;
}
public function validateValueForDecisionLogic($params) {
$this->load->library('form_validation');
$this->form_validation->set_data($params);
$this->setFormRuleForDecisionLogic();
$errors = [];
if ($this->form_validation->run() === FALSE) {
$errors = $this->form_validation->error_array();
}
return $errors;
}
public function setFormRuleForDecisionLogic() {
$this->form_validation->set_rules('survey', 'Survey', 'integer');
$this->form_validation->set_rules('from_weight', 'From Weight', 'integer');
$this->form_validation->set_rules('to_weight', 'To Weight', 'integer');
$this->form_validation->set_rules('status', 'Status', 'integer');
}
public function load_pagination($all_record, $params, $action) {
// pagination
$this->load->library('pagination');
$config["total_rows"] = count($all_record);
$config["base_url"] = base_url() . '/' . get_class($this) . '/' . $action;
$config["per_page"] = 10;
$config["uri_segment"] = 3;
$config["num_links"] = 5;
$config["suffix"] =
"?"
. http_build_query($params);
$config["first_url"] =
"/" . get_class($this) . "/{$action}/0?"
. http_build_query($params);
$config['full_tag_open'] = "<ul class='pagination'>";
$config['full_tag_close'] = "</ul>";
$config['num_tag_open'] = '<li>';
$config['num_tag_close'] = '</li>';
$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
$config['next_tag_open'] = "<li>";
$config['next_tagl_close'] = "</li>";
$config['prev_tag_open'] = "<li>";
$config['prev_tagl_close'] = "</li>";
$config['first_tag_open'] = "<li>";
$config['first_tagl_close'] = "</li>";
$config['last_tag_open'] = "<li>";
$config['last_tagl_close'] = "</li>";
$this->pagination->initialize($config);
$page = ( $this->uri->segment(3) ) ? $this->uri->segment(3) : 0;
$offset = is_numeric($page) ? $page : 0;
return [
'link' => $this->pagination->create_links(),
'offset' => $offset,
'limit' => $config["per_page"]
];
}
public function getValueCombo($val) {
$status_value = range(0, 1);
return in_array($val, $status_value)
? $val
: '';
}
public function descisionlogic() {
$this->load->model('decision_model');
$this->load->library('table');
$this->table->set_template($this->template);
$this->table->set_heading([
'ID',
'Lorder',
'Logic',
'Description',
'Status',
'Survey',
'Weight',
'Update',
]);
$params = $this->getValueOfDecisionLogic();
$data = $this->setComboForDecisionLogic($params);
$data["page_title"] = "Descision Logic";
$params['status'] = $this->getValueCombo($params['status']);
$params['survey'] = $this->getValueCombo($params['survey']);
$params = array_filter($params, function($ele) {
return $ele !== "";
});
$errors = $this->validateValueForDecisionLogic($params);
$params = array_diff_key($params, $errors);
$data = array_merge(
$data,
$params,
$this->load_pagination(
$this->decision_model->get_decision_logic_records($params),
$params,
'descisionlogic'
)
);
$data['pos_table'] = $this->table->generate(
$this->decision_model->get_decision_logic_records(
$params,
$data['limit'],
$data['offset']
)
);
$this->renderDescisionPage('view_descisionlogic', $data);
}
public function updatelogic() {
$setting_value = (int) $this->input->get('setting_value');
$setting_id = (int) $this->input->get('setting_id');
$setting_key = (int) $this->input->get('setting_key');
if ($setting_value > 0 && $setting_id > 0 && $setting_key > 0) {
$q = "UPDATE group_decision_logic SET weight=$setting_value WHERE id = $setting_id AND decision_logic = $setting_key";
$r = $this->db->query($q);
echo 'Updated.';
}
}
public function configurenextaction() {
$data = array();
$this->load->library('table');
$this->table->set_template($this->template_small);
$decision_id = (int) $this->input->get('decision_id');
$id = (int) $this->input->get('id');
$proc = $this->input->get('proc');
$mysql = "SELECT d.id,d.target_key,g.description
FROM decision_group_action d
LEFT JOIN decision_group g ON d.target_key = g.dkey WHERE d.dkey=(SELECT dkey FROM decision_group WHERE id = $decision_id)";
$query = $this->read_replica->query($mysql);
//$this->table->set_heading( array('data' => 'ID', 'style' => 'width:10px'), 'Description', array('data' => 'ADD', 'style' => 'width:50px'));
$data['logic_list'] = $this->table->generate($query);
$data["decision_group_title"] = "A10AA01"; // based on selection
$data["card_category"] = "";
$data["decision_id"] = $decision_id;
$this->load->view('descision/view_next_action', $data);
return 0;
}
public function getValueOfMemberReport() {
return [
'decision_group' => trim($this->input->get('member')['decision_group']),
'description' => trim($this->input->get('member')['description']),
'from_count' => trim($this->input->get('member')['from_count']),
'to_count' => trim($this->input->get('member')['to_count'])
];
}
public function validateValueForMemberReport($params) {
$this->load->library('form_validation');
$this->form_validation->set_data($params);
$this->setFormRuleForMemberReport();
$errors = [];
if ($this->form_validation->run() === FALSE) {
$errors = $this->form_validation->error_array();
}
return $errors;
}
public function setFormRuleForMemberReport() {
$this->form_validation->set_rules('from_count', 'From Count', 'integer');
$this->form_validation->set_rules('to_count', 'To Count', 'integer');
}
public function member_report(&$data) {
$this->load->model('decision_model');
$this->load->library('table');
$this->table->set_template($this->template);
$this->table->set_heading([
'Count',
'Decision_Group',
'Description',
]);
$params = $this->getValueOfMemberReport();
$params = array_filter($params, function($ele) {
return $ele !== "";
});
$errors = $this->validateValueForMemberReport($params);
$params = array_diff_key($params, $errors);
$data = array_merge(
$data,
$params,
$this->load_pagination(
$this->decision_model->get_member_report_records($params),
$params,
'descisionreport'
)
);
$data['member_report'] = $this->table->generate(
$this->decision_model->get_member_report_records(
$params,
$data['limit'],
$data['offset']
)
);
}
public function getValueOfRefreshReport() {
return [
'description' => trim($this->input->get('description')),
'from_count' => trim($this->input->get('from_count')),
'to_count' => trim($this->input->get('to_count'))
];
}
public function validateValueForRefreshReport($params) {
$this->load->library('form_validation');
$this->form_validation->set_data($params);
$this->setFormRuleForfRefreshReport();
$errors = [];
if ($this->form_validation->run() === FALSE) {
$errors = $this->form_validation->error_array();
}
return $errors;
}
public function setFormRuleForfRefreshReport() {
$this->form_validation->set_rules('from_count', 'From Count', 'integer');
$this->form_validation->set_rules('to_count', 'To Count', 'integer');
}
public function refresh_report(&$data) {
$this->load->model('decision_model');
$this->load->library('table');
$this->table->set_template($this->template);
$this->table->set_heading([
'Description',
'Count',
]);
$params = $this->getValueOfRefreshReport();
$params = array_filter($params, function($ele) {
return $ele !== "";
});
$errors = $this->validateValueForRefreshReport($params);
$params = array_diff_key($params, $errors);
// $data = array_merge(
// $data,
// $params,
// $this->load_pagination(
// $this->decision_model->get_refresh_report_records($params),
// $params,
// 'descisionreport'
// )
// );
$data['refresh_report'] = $this->table->generate(
$this->decision_model->get_refresh_report_records(
$params,
$data['limit'],
$data['offset']
)
);
}
public function descisionreport() {
$this->load->library('table');
$this->table->set_template($this->template_small);
$data["page_title"] = "Descision Report";
$this->member_report($data);
$this->refresh_report($data);
$this->renderDescisionPage("view_descisionreport", $data);
}
/*
savvy=> select * from decision_group;
id | lorder | description | dkey | status | personality
----+--------+---------------------------+---------+--------+---------------------------
8 | 0 | New User no Data | A10AA01 | 1 | New User no Data
2 | 99 | Comfort Oriented | A300003 | 0 | Comfort Oriented
3 | 99 | Luxury Lover | A300004 | 0 | Luxury Lover
4 | 99 | Low Budget | A300005 | 0 | Low Budget
5 | 99 | Bike/Scooters Lover | A300006 | 0 | Bike/Scooters Lover
6 | 99 | Eco Friendly | A300007 | 0 | Eco Friendly
7 | 99 | Family/Group | A300008 | 0 | Family/Group
*/
public function updatePersonaltyName() {
// echo 'ameye-001';
///descision/updatePersonaltyName?id=" + id + "&pers_text=" + pers_text_value + "&dkey=" + dkey
$decision_group = $this->input->get('dkey');
$group_id = (int) $this->input->get('id');
$personality = trim($this->input->get('pers_text'));
$offers = (int)$this->input->get('pers_offers');
$update_query = 'UPDATE decision_group SET ';
if ($decision_group == '' || $group_id <= 0) {
echo "Error - Not updated";
return;
} else {
$update_query .= " personality='$personality'";
}
if ($offers <= 0) {
echo "Error - Offers must be a number greater than 0";
return;
} else {
$update_query .= " , offers_count=$offers";
}
$update_query .= " WHERE id=$group_id AND dkey='$decision_group'";
$this->db->query($update_query);
echo "Updated";
}
public function getValueOfPersonaltyCards() {
return [
'dkey' => trim($this->input->get('dkey')),
'description' => trim($this->input->get('description')),
'status' => trim($this->input->get('card_status')
?? $this->input->get('status') ?? '-1'),
'personality' => trim($this->input->get('personality'))
];
}
public function setComboForPersonaltyCards($params) {
$this->load->model('combo_model');
$combo['card_status'] = $this->combo_model->getStatusComboWithAll(
'card_status',
$params['status']
);
return $combo;
}
public function validateValueForPersonaltyCards($params) {
$this->load->library('form_validation');
$this->form_validation->set_data($params);
$this->setFormRuleForPersonaltyCards();
$errors = [];
if ($this->form_validation->run() === FALSE) {
$errors = $this->form_validation->error_array();
}
return $errors;
}
public function setFormRuleForPersonaltyCards() {
$this->form_validation->set_rules('status', 'Status', 'integer');
}
public function personaltycards() {
$this->load->model('decision_model');
$this->load->library('table');
$this->table->set_template($this->template);
$this->table->set_heading([
'ID',
'Lorder',
'Dkey',
'Status',
'Description',
'Personality',
]);
$params = $this->getValueOfPersonaltyCards();
$data = $this->setComboForPersonaltyCards($params);
$data["page_title"] = "Personalty Cards";
$params['status'] = $this->getValueCombo($params['status']);
$params = array_filter($params, function($ele) {
return $ele !== "";
});
$errors = $this->validateValueForPersonaltyCards($params);
$params = array_diff_key($params, $errors);
$data = array_merge(
$data,
$params,
$this->load_pagination(
$this->decision_model->get_personalty_card_records($params),
$params,
'PersonaltyCards'
)
);
$data['pers_data'] =
$this->decision_model->get_personalty_card_records(
$params,
$data['limit'],
$data['offset']
);
$data['pers_data'] = array_map(function($ele) {
$this->table->set_heading(
"Card Title", array('data' => 'Country', 'style' => 'width:50px')
);
$ele['card_list'] =
$this->table->generate($this->decision_model->get_card_list_records($ele));
$this->table->set_heading(
"Card Title", array('data' => 'Country', 'style' => 'width:50px')
);
$ele['card_group'] =
$this->table->generate($this->decision_model->get_card_group_records($ele));
$this->table->set_heading(
"Card Title", array('data' => 'Country', 'style' => 'width:50px')
);
$ele['card_country'] =
$this->table->generate($this->decision_model->get_card_country_records($ele));
return $ele;
}, $data['pers_data']);
$this->renderDescisionPage('view_persnalitycards', $data);
}
function getCardList($dkey) {
$mysql = "SELECT c.name||' <b>'||c.button1_action||'</b><br>'||c.id||' - '|| c.title AS Card,c.card_country FROM decision_cards d LEFT JOIN main_cards c ON c.id=d.card_id WHERE d.decision_id=(SELECT id FROM decision_group WHERE dkey='$dkey') AND d.status=1 ";
$mysql .= " ORDER BY c.id DESC";
$query = $this->read_replica->query($mysql);
$this->table->set_heading( "Card Title", array('data' => 'Country', 'style' => 'width:50px'));
$data["card_list"] = $this->table->generate($query);
$mysql = "SELECT c.button1_action,count(c.id) FROM decision_cards d LEFT JOIN main_cards c ON c.id=d.card_id WHERE d.decision_id=(SELECT id FROM decision_group WHERE dkey='$dkey') AND d.status=1 ";
$mysql .= " GROUP BY c.button1_action";
$query = $this->read_replica->query($mysql);
$this->table->set_heading( "Card Title", array('data' => 'Country', 'style' => 'width:50px'));
$data["card_group"] = $this->table->generate($query);
$mysql = "SELECT c.card_country,count(c.id) FROM decision_cards d LEFT JOIN main_cards c ON c.id=d.card_id WHERE d.decision_id=(SELECT id FROM decision_group WHERE dkey='$dkey') AND d.status=1 ";
$mysql .= " GROUP BY c.card_country";
$query = $this->read_replica->query($mysql);
$this->table->set_heading( "Card Title", array('data' => 'Country', 'style' => 'width:50px'));
$data["card_country"] = $this->table->generate($query);
return $data;
}
public function getValueOfPersonaltyName() {
return [
'dkey' => trim($this->input->get('dkey')),
'description' => trim($this->input->get('description')),
'status' => trim($this->input->get('card_status')
?? $this->input->get('status') ?? '-1'),
'personality' => trim($this->input->get('personality')),
'from_offer' => trim($this->input->get('from_offer')),
'to_offer' => trim($this->input->get('to_offer'))
];
}
public function setComboForPersonaltyName($params) {
$this->load->model('combo_model');
$combo['card_status'] = $this->combo_model->getStatusComboWithAll(
'card_status',
$params['status']
);
return $combo;
}
public function validateValueForPersonaltyName($params) {
$this->load->library('form_validation');
$this->form_validation->set_data($params);
$this->setFormRuleForPersonaltyName();
$errors = [];
if ($this->form_validation->run() === FALSE) {
$errors = $this->form_validation->error_array();
}
return $errors;
}
public function setFormRuleForPersonaltyName() {
$this->form_validation->set_rules('from_offer', 'From Offer', 'integer');
$this->form_validation->set_rules('to_offer', 'To Offer', 'integer');
$this->form_validation->set_rules('status', 'Status', 'integer');
}
public function personaltyname() {
$this->load->model('decision_model');
$this->load->library('table');
$this->table->set_template($this->template);
$this->table->set_heading([
'ID',
'Lorder',
'Dkey',
'Status',
'Description',
'Personality',
'Offers',
'Action'
]);
$params = $this->getValueOfPersonaltyName();
$data = $this->setComboForPersonaltyName($params);
$data["page_title"] = "Personalty Name";
$params['status'] = $this->getValueCombo($params['status']);
$params = array_filter($params, function($ele) {
return $ele !== "";
});
$errors = $this->validateValueForPersonaltyName($params);
$params = array_diff_key($params, $errors);
$data = array_merge(
$data,
$params,
$this->load_pagination(
$this->decision_model->get_personalty_name_records($params),
$params,
'personaltyname'
)
);
$data['pers_table'] = $this->table->generate(
$this->decision_model->get_personalty_name_records(
$params,
$data['limit'],
$data['offset']
)
);
$this->renderDescisionPage('view_persnalityname', $data);
}
public function addGPSTriggerLogic() {
// alert("/descision/addGPSTriggerLogic?decision_group=" + decision_group + "&address_id=" + address_id_value);
$decision_group = $this->input->get('decision_group');
$gps_address_id = (int) $this->input->get('gps_address_id');
if ($decision_group != '' && $gps_address_id != '' && $gps_address_id > 0) {
$in = array();
$in['action'] = SAVVY_BKO_GPSTRIGGER_LOGIC;
$in['decision_group'] = $decision_group;
$in['gps_address_id'] = $gps_address_id;
$out = array();
$ret = $this->savvy_api($in, $out);
$back_message = "<br> Result - " . isset($out["status_message"]) ? $out["status_message"] : '';
} else {
$back_message = "<br> Select address to add.";
}
echo $back_message;
}
public function addSurveyLogic() {
// url: "/descision/addSurveyLogic?decision_group=" + decision_group + "&survey_id_value="+survey_id_value+"&survey_ans_value=" + survey_ans_value
/*
* savvy=> SELECT * FROM group_decision_logic;
id | lorder | group_id | decision_logic | status | added | weight
----+--------+----------+----------------+--------+----------------------------+--------
3 | 0 | 2 | 3 | 1 | 2019-07-02 00:26:55.237707 | 10
1 | 0 | 8 | 1 | 0 | 2019-07-02 00:26:55.231772 | 10
6 | 0 | 8 | 3 | 0 | 2019-07-02 08:38:36.87994 | 10
5 | 0 | 8 | 1 | 0 | 2019-07-02 08:29:29.833282 | 10
*/
$back_message = '';
$decision_group = $this->input->get('decision_group');
$card_id = (int) $this->input->get('survey_id_value');
$survey_ans = $this->input->get('survey_ans_value');
if ($decision_group != '' && $card_id != '' && $survey_ans != '') {
$in = array();
$in['action'] = SAVVY_BKO_SURVEY_LOGIC;
$in['decision_group'] = $decision_group;
$in['card_id'] = $card_id;
$in['survey_ans'] = $survey_ans;
$out = array();
$ret = $this->savvy_api($in, $out);
// print_r($out);
$back_message = "<br> Result - " . isset($out["status_message"]) ? $out["status_message"] : '';
} else {
$back_message = "<br> Select Survey and Set Answer";
}
echo "Input: $decision_group $card_id $survey_ans ]" . $back_message;
}
public function descisiontree() {
$data = array();
// $this->load->library('table');
// $this->table->set_template($this->template);
// $this->load->model('combo_model');
//
// Prepare the head of the tree
$tree_data = array();
$mysql = "SELECT *,dkey AS name FROM decision_group WHERE dkey ='A10AA01'";
$query = $this->read_replica->query($mysql);
$row = $query->row_array();
if (isset($row)) {
$mysql2 = "SELECT *,dkey AS name FROM decision_group WHERE dkey IN ( SELECT target_key FROM decision_group_action WHERE dkey ='A10AA01' )";
$query2 = $this->read_replica->query($mysql2);
$dat['children'] = array();
$icc = 0;
foreach ($query2->result_array() as $row2) {
// echo $row['title'];
// echo $row['name'];
if ($icc == 0) {
$dat['children'] = $row2;
} else {
array_merge($dat['children'], $row2);
}
$icc++;
}
$row["children"] = $dat['children'];
$tree_data['A10AA01'] = $row;
} // if the root works first
$data['tree'] = $tree_data;
// print_r($data);
// foreach ($query->result_array() as $row)
// {
// echo $row['decision_group'];
// echo $row['description'];
// echo $row['body'];
// }
// $this->table->set_heading(array('data' => 'View', 'style' => 'width:50px'), 'Card', array('data' => 'Image', 'style' => 'width:120px'));
// $data["member_report"] = $this->table->generate($query);
$data["page_title"] = "Descision Tree";
$this->renderDescisionPage("view_descisiontree", $data);
}
}
/*
savvy=> SELECT * FROM decision_group WHERE dkey ='dkey';
id | lorder | description | dkey | status
----+--------+-------------+------+--------
(0 rows)
savvy=> SELECT * FROM decision_group WHERE dkey ='A10AA01';
id | lorder | description | dkey | status
----+--------+------------------+---------+--------
8 | 0 | New User no Data | A10AA01 | 1
(1 row)
savvy=> SELECT * FROM decision_group_action WHERE dkey ='A10AA01';
id | dkey | target_key | status | added
----+---------+------------+--------+----------------------------
1 | A10AA01 | A10BB01 | 1 | 2019-10-20 02:01:41.079293
2 | A10AA01 | A100001 | 1 | 2019-10-20 02:01:41.085738
3 | A10AA01 | A1000A1 | 1 | 2019-10-20 02:01:41.95765
(3 rows)
savvy=> SELECT target_key FROM decision_group_action WHERE dkey ='A10AA01';
target_key
------------
A10BB01
A100001
A1000A1
(3 rows)
savvy=> SELECT target_key FROM decision_group_action WHERE dkey ='A10BB01';
target_key
------------
A1000A1
A100001
*/
+173
View File
@@ -0,0 +1,173 @@
<?php
defined( 'BASEPATH' ) OR exit( 'No direct script access allowed' );
class Emission extends Admin_Controller {
public $statusOptions = [
'Active' => 1,
'Inactive' => 0
];
public function __construct() {
parent::__construct();
// load library
$this->load->library('table');
// load model
$this->load->model('Emission_model', 'emission');
$this->load->model('Emission_Average_model', 'emissionAvrg');
// init view layer
$this->view = array();
}
public function index() {
$this->template["table_open"] = "<table class='table table-striped table-hover table-bordered table-condensed' style='padding:0px; background-color:lightgreen;'>";
$this->table->set_template( $this->template );
$emission = $this->getEmission();
$emissionAvrg = $this->getEmissionAvrg();
$data = array();
$data['emission_model'] = $this->table->generate( $emission );
$data['emission_model_item'] = $emissionAvrg;
$this->renderEmissionPage( 'view_emissionmodel', $data );
}
public function getEmission(){
global $bko_users_members_access_list;
//How many Farm records generated daliy - last 10 days [SG & US] - 2 plots
$emission = $this->emission->getData();
return $emission;
// echo 'Ameye Olu';
}
/**
* Get emission avrg result per page and pagination links
* @return array
*/
public function getEmissionAvrg() {
$this->load->helper(array('url'));
$this->load->helper('pagination');
// get pagination params
$page = $this->input->get('page') ? $this->input->get('page') : 1;
$results = $this->emissionAvrg->index($page);
return $results;
}
/**
* Delete emission avrg record by id
* @param itn $id emission avrg id
* @return status code
*/
public function deleteEmissionAvrg($id) {
$affected = $this->emissionAvrg->delete($id);
$this->output->set_content_type('application/json')
->set_output(json_encode($affected));
}
/**
* View form create new emission avrg
* @return view
*/
public function create() {
$this->prepare_form();
$this->renderEmissionPage('create_emission_avrg', $this->view);
}
/**
* View Emission Avrg
* @param int $id emission avrg id
* @return object emission avrg details
*/
public function edit($id) {
$result = $this->emissionAvrg->edit($id);
if (!$result) {
show_404();
}
$this->view['details'] = $result;
$this->prepare_form();
$this->renderEmissionPage('edit_emission_avrg', $this->view);
}
/**
* Store Emission Avrg
* @return bool return true if create success, reverse
*/
public function store() {
$this->load->helper(array('form', 'url'));
$this->load->library('form_validation');
$this->prepare_form();
$this->view['details'] = $this->input->post();
$this->form_validation->set_rules($this->emissionAvrg->rules);
if ($this->form_validation->run() == false) {
$this->renderEmissionPage('create_emission_avrg', $this->view);
return;
}
$create = $this->emissionAvrg->store($this->view['details']);
if ($create) {
$this->session->set_flashdata('success', isSet($create['message']) ? $create['message'] : 'Create success');
redirect('/emission');
}
$this->session->set_flashdata('error', $create['message']);
$this->renderEmissionPage('create_emission_avrg', $this->view);
return;
}
/**
* Update Emission Avrg
* @param int $id emission avrg id
* @return bool return true if update success, reverse
*/
public function update($id) {
$this->load->helper(array('form', 'url'));
$this->load->library('form_validation');
$this->prepare_form();
$this->view['details'] = $this->input->post();
$this->view['details']['id'] = $id;
$this->form_validation->set_rules($this->emissionAvrg->rules);
if ($this->form_validation->run() == false) {
$this->renderEmissionPage('edit_emission_avrg', $this->view);
return;
}
$update = $this->emissionAvrg->update($id, $this->view['details']);
if ($update) {
$this->session->set_flashdata('success', isSet($update['message']) ? $update['message'] : 'Create success');
redirect('/emission');
} else {
$this->session->set_flashdata('error', $update['message']);
$this->renderEmissionPage('edit_emission_avrg', $this->view);
return;
}
}
/**
* Prepare form before actions (create, edit)
* @return array
*/
protected function prepare_form() {
// load mkey from emission model
$mkeyOptions = $this->getEmission()->result();
$mkeyOptions = (isset($mkeyOptions) and !empty($mkeyOptions)) ? array_column($mkeyOptions, 'mkey') : null;
// load country from country model
$this->load->model('Country_model', 'country');
$country = $this->country->getAll();
$country = (isset($country) and !empty($country)) ? array_column($country, 'code') : null;
// load status code
$status = $this->statusOptions;
$this->view['mkeyOptions'] = $mkeyOptions;
$this->view['country'] = $country;
$this->view['statusOptions'] = $status;
}
}
+39
View File
@@ -0,0 +1,39 @@
<?php
defined('BASEPATH') or exit('No direct script access allowed');
class Farm_records extends Admin_Controller
{
public $viewData = [];
public function __construct() {
parent::__construct();
}
public function index() {
$this->load->model('farm_record_model');
$this->load->library('table');
$this->table->set_template($this->template);
$data["page_title"] = "Farm Records";
$data['records_generated_daily_SG'] = $this->table->generate(
$this->farm_record_model->get_farm_records(
['country' => 'SG']
)
);
$data['records_generated_daily_US'] = $this->table->generate(
$this->farm_record_model->get_farm_records(
['country' => 'US']
)
);
$this->renderFarmRecords('view_farm_records', $data);
}
private function renderFarmRecords($page_name, $data) {
$this->load->view('admin/view_admin_header', $data);
$this->load->view('admin/report/' . $page_name, $data);
$this->load->view('admin/view_admin_footer', $data);
}
}
+120
View File
@@ -0,0 +1,120 @@
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Feed extends Admin_Controller {
public function index() {
$this->load->helper('url');
$data = array();
$this->load->library('table');
$this->table->set_template($this->template);
}
public function onboardingsurvey() {
$this->load->library('table');
//$this->table->set_template($this->survey_template);
$this->load->model('onboarding_survey_model');
$cardCats = $this->db->get('card_category');
$data['page_title'] = 'Onboarding Survey';
$data['surveys'] = $this->onboarding_survey_model->getOnboardingSurvey();
$data['card_cats'] = $cardCats->result_array();
$this->renderFeedPage('view_onboardfeed', $data);
}
private function setFormRuleForSurvey() {
$this->form_validation->set_rules('groupKey', 'Group key', 'max_length[10]');
$this->form_validation->set_rules('answersKey', 'Answers key', 'max_length[25]');
$this->form_validation->set_rules('answers', 'Answers', 'max_length[100]');
}
public function getOnboardingSurvey() {
$postData = $this->input->post();
$postData = array_filter($postData, function($ele) {
return $ele !== "" && $ele !== null;
});
$pageNo = !empty($postData['pageNo']) ? $postData['pageNo'] - 1 : 0;
$this->load->library('form_validation');
$this->form_validation->set_data($postData);
$this->setFormRuleForSurvey();
if ($this->form_validation->run() === FALSE) {
$errors = $this->form_validation->error_array();
header('HTTP/1.1 400 Bad Request');
echo json_encode(['errors' => $errors]);
return;
}
$this->load->model('onboarding_survey_model');
$result = $this->onboarding_survey_model->getOnboardingSurvey($postData, $pageNo);
echo json_encode(['data' => $result]);
}
public function getAvailableAndAssignedSurveyCards() {
$postData = $this->input->post();
$this->load->model('onboarding_survey_model');
$result = $this->onboarding_survey_model->getAvailableAndAssignedSurveyCards($postData);
echo json_encode(['result' => $result]);
}
public function assignSurveyCard() {
$postData = $this->input->post();
$this->load->model('onboarding_survey_model');
$this->onboarding_survey_model->assignSurveyCard($postData);
echo json_encode(['message' => 'Assigned!']);
}
public function unassignSurveyCard() {
$postData = $this->input->post();
$this->load->model('onboarding_survey_model');
$this->onboarding_survey_model->unassignSurveyCard($postData);
echo json_encode(['message' => 'Unassigned!']);
}
public function updateSurveyAnswers() {
$postData = $this->input->post();
$this->load->library('form_validation');
$this->form_validation->set_data($postData);
$this->setFormRuleForSurvey();
if ($this->form_validation->run() === FALSE) {
$errors = $this->form_validation->error_array();
header('HTTP/1.1 400 Bad Request');
echo json_encode(['errors' => $errors]);
return;
}
$id = $postData['id'];
$surveyData = [
'answers' => $postData['answers']
];
$this->load->model('onboarding_survey_model');
$this->onboarding_survey_model->updateSurvey($id, $surveyData);
echo json_encode(['message' => 'Updated answers successfully!']);
}
protected function renderFeedPage($page_name, $data) {
$this->load->view('admin/view_admin_header', $data);
$this->load->view('feed/' . $page_name, $data);
$this->load->view('admin/view_admin_footer', $data);
}
}
+103
View File
@@ -0,0 +1,103 @@
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class GeoServices extends Admin_Controller {
public function index() {
$data = array();
$this->load->helper('url');
$this->listobjects();
}
protected function renderGeoServicesPage($page_name, $data) {
$this->load->view('admin/view_admin_header', $data);
$this->load->view('geoservices/' . $page_name, $data);
$this->load->view('admin/view_admin_footer', $data);
}
public function listobjects() {
$data = array();
$this->load->library('table');
$this->table->set_template($this->template);
$data["page_title"] = "List Geofence Objects";
$mysql = "SELECT * FROM geofence_area_country";
$query = $this->read_replica->query($mysql);
$data["geofence_area_country"] = $this->table->generate($query);
$mysql = "SELECT a.id,b.country,a.name, c.name AS transport_provider ";
$mysql.= " FROM country_services a, geofence_area_country b, transport_providers c";
$mysql.= " WHERE b.id=a.country_id AND c.id=a.transport_provider_id";
$query = $this->read_replica->query($mysql);
$data["country_services"] = $this->table->generate($query);
$mysql = "SELECT * FROM geofence_area_city";
$query = $this->read_replica->query($mysql);
$data["geofence_area_city"] = $this->table->generate($query);
$mysql = "SELECT a.id,b.country,b.city,a.name, c.name AS transport_provider ";
$mysql.= " FROM city_services a, geofence_area_city b, transport_providers c";
$mysql.= " WHERE b.id=a.city_id AND c.id=a.transport_provider_id";
$query = $this->read_replica->query($mysql);
$data["city_services"] = $this->table->generate($query);
$this->renderGeoServicesPage("view_listobjects",$data);
}
public function checkgps() {
$data = array();
$this->load->library('table');
$this->table->set_template($this->template);
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');
$data['latitude'] = 37.777412;
$data['longitude'] = -122.472961;
if ($this->input->post()) {
$data['latitude'] = $this->input->post('latitude');
$data['longitude'] = $this->input->post('longitude');
}
$url = $api_url . "/booking/api/options/?latitude=" . $data['latitude'] . "&longitude=" . $data['longitude'];
$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
);
$data["payload"] = json_decode($payload, true);
$data["page_title"] = "Check Services by GPS coordinates";
$this->renderGeoServicesPage("view_checkgps",$data);
}
}
+314
View File
@@ -0,0 +1,314 @@
<?php
defined('BASEPATH') or exit('No direct script access allowed');
class Geofence_area extends Admin_Controller
{
public $viewData = array();
public $pagePerItem = 10;
public function __construct()
{
parent::__construct();
// Load model
$this->load->model('geofence_area_model');
$this->load->model('country_model');
$this->load->helper('pagination');
}
public function index()
{
$this->load->helper(array('form', 'url'));
//get query string filter
$queryString = $this->input->server('QUERY_STRING');
$filterData = $this->input->get();
$page = $this->input->get('page');
// remove empty value
$filterData = array_filter($filterData, function ($v, $k) {
return $v != '';
}, ARRAY_FILTER_USE_BOTH);
$pagingUrl = empty($queryString) ? uri_string() : uri_string() . '?' . $queryString;
$pagingUrl = remove_querystring_var($pagingUrl, 'page');
$data = $this->geofence_area_model->getAllWithPagination($page, $this->pagePerItem, $filterData);
$this->viewData['list'] = $data['data'];
$this->viewData['filterData'] = $filterData;
$this->viewData['pagination'] = initPagination($this->pagePerItem, $data['total'], $page, $pagingUrl);
$this->read_replica->order_by('city', 'ASC');
$this->viewData['cityList'] = $this->read_replica->get('geofence_area_city')->result();
$this->renderAdminPage('geofence_area/list', $this->viewData);
}
public function create()
{
$this->load->helper(array('form', 'url'));
$this->viewData['countryList'] = $this->country_model->getAll();
$this->viewData['cityList'] = $this->read_replica->get('geofence_area_city')->result();
$this->viewData['geofencingAreaTypes'] = Geofence_area_model::GEOFENCING_AREA_TYPES;
$this->viewData['item'] = null;
$this->renderAdminPage('geofence_area/create', $this->viewData);
}
public function store()
{
$this->load->helper(array('form', 'url'));
$this->load->library('form_validation');
$this->viewData['item'] = null;
$this->viewData['countryList'] = $this->country_model->getAll();
$this->viewData['cityList'] = $this->read_replica->get('geofence_area_city')->result();
$this->viewData['geofencingAreaTypes'] = Geofence_area_model::GEOFENCING_AREA_TYPES;
$this->setCreationRules();
if ($this->form_validation->run() == false) {
$this->renderAdminPage('geofence_area/create', $this->viewData);
return;
}
$inputData = [
'name' => $this->input->post('name'),
'area' => $this->input->post('area'),
'city_id' => $this->input->post('city_id'),
'country' => $this->input->post('country_code'),
'latitude' => $this->input->post('latitude'),
'longitude' => $this->input->post('longitude'),
'type' => $this->input->post('type'),
'boundaries' => $this->input->post('boundaries') ?: null
];
$this->geofence_area_model->create($inputData);
$this->session->set_flashdata('success', 'Created geofence area successfully.');
redirect('/geofence_area');
}
public function edit($id)
{
$this->load->helper(array('form', 'url'));
$this->viewData['item'] = $this->geofence_area_model->getItem($id);
$this->viewData['itemId'] = $id;
$this->viewData['countryList'] = $this->country_model->getAll();
$this->viewData['cityList'] = $this->read_replica->get('geofence_area_city')->result();
$this->viewData['geofencingAreaTypes'] = Geofence_area_model::GEOFENCING_AREA_TYPES;
$this->renderAdminPage('geofence_area/edit', $this->viewData);
}
public function update($id)
{
$this->load->helper(array('form', 'url'));
$this->load->library('form_validation');
$this->viewData['item'] = $this->geofence_area_model->getItem($id);
$this->viewData['itemId'] = $id;
$this->viewData['countryList'] = $this->country_model->getAll();
$this->viewData['cityList'] = $this->read_replica->get('geofence_area_city')->result();
$this->viewData['geofencingAreaTypes'] = Geofence_area_model::GEOFENCING_AREA_TYPES;
$this->setCreationRules();
if ($this->form_validation->run() == false) {
$this->renderAdminPage('geofence_area/edit', $this->viewData);
return;
}
$inputData = [
'name' => $this->input->post('name'),
'area' => $this->input->post('area'),
'city_id' => $this->input->post('city_id'),
'country' => $this->input->post('country_code'),
'latitude' => $this->input->post('latitude'),
'longitude' => $this->input->post('longitude'),
'type' => $this->input->post('type'),
'boundaries' => $this->input->post('boundaries') ?: null
];
$this->geofence_area_model->update($id, $inputData);
$this->session->set_flashdata('success', 'Updated geofence area successfully.');
redirect('/geofence_area');
}
public function delete($id)
{
$res = $this->geofence_area_model->delete($id);
$this->session->set_flashdata('success', 'Deleted geofence area successfully.');
redirect('/geofence_area');
}
public function comparePriceBetweenAreas()
{
$filterData = $this->input->get();
$fromAreaId = $filterData['from_area_id'] ?? null;
$toAreaId = $filterData['to_area_id'] ?? null;
$this->viewData['polygons'] = [];
$this->viewData['priceComparison'] = [];
if ($fromAreaId && $toAreaId) {
$priceComparisonData = $this->geofence_area_model->priceComparison($fromAreaId, $toAreaId);
if ($priceComparisonData['success']) {
$startArea = $priceComparisonData['from_area'];
$endArea = $priceComparisonData['to_area'];
$startBoundaries = json_decode($startArea['boundaries'], true);
$endBoundaries = json_decode($endArea['boundaries'], true);
if (isset($startBoundaries['polygon'])) {
$startPolygon = $startBoundaries['polygon'];
}
if (isset($endBoundaries['polygon'])) {
$endPolygon = $endBoundaries['polygon'];
}
$polygons = [
"startPolygon" => !empty($startPolygon) ? $startPolygon : [],
"endPolygon" => !empty($endPolygon) ? $endPolygon : []
];
$this->viewData['polygons'] = json_encode($polygons);
$this->viewData['priceComparison'] = $priceComparisonData;
}
}
$this->read_replica->order_by('city', 'ASC');
$this->viewData['cityList'] = $this->read_replica->get('geofence_area_city')->result();
$this->viewData['areaList'] = $this->geofence_area_model->getAllAreas();
$this->viewData['filterData'] = $filterData;
// add css/js
$this->viewData['extra_styles'] = [
'/assets/css/geofence_area/price_comparison.css'
];
$this->viewData['js'] = [
'https://maps.googleapis.com/maps/api/js?key=AIzaSyDvjiRTxngOQyBP4zpqFlZuiquc0ROvo9c&libraries=geometry'
];
$this->renderAdminPage('geofence_area/price-comparison', $this->viewData);
}
public function getCityListDependOnCountryCodeAjax()
{
$inputData = $this->input->get();
$this->read_replica->where('country', $inputData['country_code']);
$this->read_replica->order_by('city', 'ASC');
$query = $this->read_replica->get('geofence_area_city');
$data = $query->result_array();
$response = [
'success' => true,
'data' => !empty($data) ? $data : []
];
echo json_encode($response);
}
public function getAreaListDependOnCityIdAjax()
{
$inputData = $this->input->get();
$cityId = $inputData['city_id'] ?? null;
if ($cityId) {
$this->read_replica->where('city_id', $cityId);
}
$this->read_replica->order_by('name', 'ASC');
$query = $this->read_replica->get('geofence_area');
$data = $query->result_array();
$response = [
'success' => true,
'data' => !empty($data) ? $data : []
];
echo json_encode($response);
}
protected function renderAdminPage($page_name, $data)
{
$this->load->view('admin/view_admin_header', $data);
$this->load->view($page_name, $data);
$this->load->view('admin/view_admin_footer', $data);
}
private function setCreationRules()
{
$config = [
[
'field' => 'name',
'label' => 'Name',
'rules' => 'required',
],
[
'field' => 'area',
'label' => 'Area name',
'rules' => 'required',
],
[
'field' => 'country_code',
'label' => 'Country',
'rules' => 'required',
],
[
'field' => 'city_id',
'label' => 'City',
'rules' => 'required',
],
[
'field' => 'latitude',
'label' => 'Latitude',
'rules' => 'required|numeric',
],
[
'field' => 'longitude',
'label' => 'Longitude',
'rules' => 'required|numeric',
],
[
'field' => 'type',
'label' => 'Geofencing area types',
'rules' => 'required',
],
[
'field' => 'boundaries',
'label' => 'Boundaries',
'rules' => 'callback_jsonRegex', // The input have to be json format
'errors' => [
'jsonRegex' => 'Please enter a json format.',
],
],
];
$this->form_validation->set_rules($config);
}
public function jsonRegex($input)
{
if (empty(trim($input))) {
return;
}
// json format regex
$pcreRegex = '/
(?(DEFINE)
(?<number> -? (?= [1-9]|0(?!\d) ) \d+ (\.\d+)? ([eE] [+-]? \d+)? )
(?<boolean> true | false | null )
(?<string> " ([^"\n\r\t\\\\]* | \\\\ ["\\\\bfnrt\/] | \\\\ u [0-9a-f]{4} )* " )
(?<array> \[ (?: (?&json) (?: , (?&json) )* )? \s* \] )
(?<pair> \s* (?&string) \s* : (?&json) )
(?<object> \{ (?: (?&pair) (?: , (?&pair) )* )? \s* \} )
(?<json> \s* (?: (?&number) | (?&boolean) | (?&string) | (?&array) | (?&object) ) \s* )
)
\A (?&json) \Z
/six';
if (preg_match($pcreRegex, $input)) {
return true;
} else {
return false;
}
}
}
@@ -0,0 +1,315 @@
<?php
defined('BASEPATH') or exit('No direct script access allowed');
class Geofence_area_anchor extends Admin_Controller
{
public $viewData = [];
public function __construct()
{
parent::__construct();
$this->load->library('table');
$this->table->set_template($this->template);
$this->load->model('combo_model');
$this->load->model('address_model', 'address');
$this->load->model('Geofence_area_anchor_model', 'geofence_area_anchor');
$this->load->model('Geofence_area_model', 'geofence_area');
$this->load->model('Geofence_area_city_model', 'geofence_area_city');
// Load Pagination library
$this->load->library('pagination');
$this->viewData['city_card'] = $this->combo_model->getCityCombo('city_card', $this->input->get('city'));
$this->viewData['geofence_area_city_card'] = $this->combo_model->getCityCombo('geofence_area_city_card', '');
$this->viewData['country_card'] = $this->combo_model->getCountryCombo('country_card', '');
$this->viewData['msg'] = null;
}
protected function renderToolsPage($page_name, $data)
{
$this->load->view('admin/view_admin_header', $data);
$this->load->view('geofence_area_anchor/' . $page_name, $data);
$this->load->view('admin/view_admin_footer', $data);
}
public function index()
{
$this->renderToolsPage("view_geofence_area_anchor", $this->viewData);
}
private function getFormValue()
{
return [
'geofence_area_city_card' => $this->input->post('geofence_area_city_card'),
'geofence_area_id' => $this->input->post('geofence_area_card'),
'address_id' => $this->input->post('address_id'),
'title' => $this->input->post('title'),
'address' => $this->input->post('address'),
'city_filter' => $this->input->post('city_filter'),
'geo_area_filter' => $this->input->post('geo_area_filter'),
'country_filter' => $this->input->post('country_filter'),
];
}
public function create()
{
$this->load->helper(array('form', 'url'));
$this->load->database();
$this->load->library('form_validation');
$this->setFormRuleCreate();
$params = $this->getFormValue();
if ($this->validateForm($params) === FALSE) {
return;
}
if (!$this->geofence_area_anchor->insertGeoAreaAnchor($params)) {
$this->viewData['msg'] = "Insert Failed";
} else {
$this->viewData['msg'] = "Insert Succesful";
}
$this->renderToolsPage('view_geofence_area_anchor', $this->viewData);
}
public function loadRecord()
{
$rowno = $this->input->get('rowno');
$filters = $this->input->get('filters');
$filters = $filters ? $filters : [];
$filters = array_filter($filters, function ($ele) {
return $ele !== '';
});
// Row per page
$rowperpage = 10;
$cur_page = $rowno;
// Row position
if ($rowno != 0) {
$rowno = ($rowno - 1) * $rowperpage;
}
// All records count
$allcount = count($this->geofence_area_anchor->getGeoAreaAnchorRecord($filters));
// Get records
$record = $this->geofence_area_anchor->getGeoAreaAnchorRecord($filters, $rowperpage, $rowno);
// Pagination Configuration
$config['base_url'] = '/Geofence_area_anchor/loadRecord';
$config['use_page_numbers'] = TRUE;
$config['total_rows'] = $allcount;
$config['per_page'] = $rowperpage;
$config['cur_page'] = $cur_page;
$config['suffix'] = '?' . http_build_query($filters);
$config['first_url'] = '/Geofence_area_anchor/loadRecord/0?' . http_build_query($filters);
$config['full_tag_open'] = "<ul class='pagination'>";
$config['full_tag_close'] = "</ul>";
$config['num_tag_open'] = '<li>';
$config['num_tag_close'] = '</li>';
$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
$config['next_tag_open'] = "<li>";
$config['next_tagl_close'] = "</li>";
$config['prev_tag_open'] = "<li>";
$config['prev_tagl_close'] = "</li>";
$config['first_tag_open'] = "<li>";
$config['first_tagl_close'] = "</li>";
$config['last_tag_open'] = "<li>";
$config['last_tagl_close'] = "</li>";
// Initialize
$this->pagination->initialize($config);
// Initialize $data Array
$data['pagination'] = $this->pagination->create_links();
$data['result'] = $record;
$data['row'] = $rowno;
echo json_encode($data);
}
public function update($id)
{
$this->load->helper(array('form', 'url'));
$this->load->database();
$this->load->library('form_validation');
$params = $this->getFormValue();
$params = array_merge($params, [
'id' => $id
]);
$this->setFormRuleUpdate($params);
if ($this->validateForm($params) === FALSE) {
return;
}
if (!$this->geofence_area_anchor->updateGeoAreaAnchor($params)) {
$this->viewData['msg'] = "Update Failed";
} else {
$this->viewData['msg'] = "Updated Succesful";
}
$this->renderToolsPage('view_geofence_area_anchor', $this->viewData);
}
public function validateForm(&$params)
{
$this->form_validation->set_data($params);
if ($this->form_validation->run() == false) {
$this->viewData = array_merge($this->viewData, $params);
$this->viewData['geofence_area_city_card'] = $this->combo_model->getCityCombo('geofence_area_city_card', $params['geofence_area_city_card'] ?? '');
$this->viewData['geofence_area_card'] = $this->combo_model->getGeofenceAreaCombo('geofence_area_card', $params['geofence_area_id'] ?? '');
// Rerender filter if validate fail
$this->viewData['geofence_area_filter_card'] = $this->combo_model->getCityCombo('geofence_area_filter_card', $params['geo_area_filter'] ?? '');
$this->viewData['city_card'] = $this->combo_model->getCityCombo('city_card', $params['city_filter'] ?? '');
$this->viewData['country_card'] = $this->combo_model->getCountryCombo('country_card', $params['country_filter'] ?? '');
$this->viewData['msg'] = validation_errors();
$this->renderToolsPage('view_geofence_area_anchor', $this->viewData);
return FALSE;
}
unset($params['geofence_area_city_card']);
unset($params['address']);
unset($params['city_filter']);
unset($params['geo_area_filter']);
unset($params['country_filter']);
return TRUE;
}
public function setFormRuleCreate()
{
$this->form_validation->set_rules('geofence_area_id', 'Geofence Area', 'required|numeric|callback_isExistsGeofenceArea');
$this->form_validation->set_rules('address_id', 'Address', 'required|numeric|callback_isExistsAddress|callback_isExistsGeoAreaAndAdress');
$this->form_validation->set_rules('title', 'Title', 'max_length[100]');
}
public function setFormRuleUpdate($params)
{
// prevent wrong id of geofene_area_anchor
$this->form_validation->set_rules('id', 'Geofence Area Anchor', 'required|numeric|callback_isExistsGeofenceAreaAnchor');
$this->form_validation->set_rules('geofence_area_id', 'Geofence Area', 'required|numeric|callback_isExistsGeofenceArea');
$this->form_validation->set_rules('title', 'Title', 'max_length[100]');
// prevent duplication of unique key
$old_geo_area_id = $this->input->post('old_geofence_area_id');
$old_address_id = $this->input->post('old_address_id');
if ($old_geo_area_id === $params['geofence_area_id'] && $old_address_id === $params['address_id']) {
$this->form_validation->set_rules('address_id', 'Address', 'required|numeric|callback_isExistsAddress');
} else {
$this->form_validation->set_rules('address_id', 'Address', 'required|numeric|callback_isExistsAddress|callback_isExistsGeoAreaAndAdress');
}
}
private function setFormRuleDelete()
{
$this->form_validation->set_rules('id', 'Geofence Area Anchor', 'required|numeric|callback_isExistsGeofenceAreaAnchor');
}
public function destroy($id = null)
{
$this->load->helper(array('form', 'url'));
$this->load->database();
$this->load->library('form_validation');
$params = ['id' => $id];
$this->setFormRuleDelete();
if ($this->validateForm($params) === FALSE) {
return;
}
if (!$this->geofence_area_anchor->deleteGeoAreaAnchor($id)) {
$this->viewData['msg'] = "Delete Failed";
} else {
$this->viewData['msg'] = "Delete Succesful";
}
$this->renderToolsPage('view_geofence_area_anchor', $this->viewData);
}
public function getLocationByAddress()
{
$location = $this->address->getAddresses([
'address' => $this->input->get('address'),
'page' => $this->input->get('page')
]);
echo json_encode([
'data' => $location['list'],
'total' => $location['total']
]);
}
public function isExistsAddress($id)
{
if (!$this->address->getAddresses(['id' => $id])) {
$this->form_validation->set_message('isExistsAddress', 'Please enter an existing address');
return FALSE;
} else {
return TRUE;
}
}
public function isExistsGeofenceArea($id)
{
if (!$this->geofence_area->getLocationByID($id)) {
$this->form_validation->set_message('isExistsGeofenceArea', 'Please enter an existing geofence area');
return FALSE;
} else {
return TRUE;
}
}
public function isExistsGeofenceAreaAnchor($id)
{
if (!$this->geofence_area_anchor->getLocationByID($id)) {
$this->form_validation->set_message('isExistsGeofenceAreaAnchor', 'Please enter an existing geofence area anchor');
return FALSE;
} else {
return TRUE;
}
}
public function isExistsGeoAreaAndAdress()
{
$geo_area_id = $this->input->post('geofence_area_card');
$address_id = $this->input->post('address_id');
if (!$geo_area_id || !$address_id) {
$this->form_validation->set_message('isExistsGeoAreaAndAdress', '');
return FALSE;
}
if ($this->geofence_area_anchor->getRecordByGeoAreaAndAddress([
'geofence_area_id' => $geo_area_id,
'address_id' => $address_id
])) {
$this->form_validation->set_message('isExistsGeoAreaAndAdress', 'The data already input');
return FALSE;
} else {
return TRUE;
}
}
public function loadGeoAreaByCity($city_id = NULL)
{
if (is_numeric($city_id) === FALSE) {
echo json_encode([]);
return;
}
echo json_encode($this->geofence_area->getLocationByCityID($city_id));
}
public function loadCityByCountry($country_id = NULL) {
$condition="country='" . pg_escape_string($country_id) . "'";
echo json_encode(['contries' => $this->geofence_area_city->getCities($condition)]);
}
}
@@ -0,0 +1,245 @@
<?php
defined('BASEPATH') or exit('No direct script access allowed');
class Geofence_area_city extends Admin_Controller
{
const CSV_FIELDS = [
'id',
'city',
'country',
'latitude',
'longitude',
'location',
'radius',
'status'
];
public $viewData = array();
public $pagePerItem = 10;
public function __construct()
{
parent::__construct();
// Load model
$this->load->model('geofence_area_city_model');
$this->load->model('country_model');
$this->load->helper('pagination');
}
public function index()
{
$this->load->helper(array('form', 'url'));
//get query string filter
$queryString = $this->input->server('QUERY_STRING');
$filterData = $this->input->get();
$page = $this->input->get('page');
// remove empty value
$filterData = array_filter($filterData, function ($v, $k) {
return $v != '';
}, ARRAY_FILTER_USE_BOTH);
$pagingUrl = empty($queryString) ? uri_string() : uri_string() . '?' . $queryString;
$pagingUrl = remove_querystring_var($pagingUrl, 'page');
$data = $this->geofence_area_city_model->getAllWithPagination($page, $this->pagePerItem, $filterData);
$this->viewData['list'] = $data['data'];
$this->viewData['filterData'] = $filterData;
$this->viewData['countryList'] = $this->country_model->getAll();
$this->viewData['cityStatus'] = [
Geofence_area_city_model::ACTIVE_STATUS=>'Active',
Geofence_area_city_model::INACTIVE_STATUS=>'Inactive' ,
];
$this->viewData['pagination'] = initPagination($this->pagePerItem, $data['total'], $page, $pagingUrl);
$this->renderAdminPage('geofence_area_city/list', $this->viewData);
}
public function create()
{
$this->load->helper(array('form', 'url'));
$this->viewData['countryList'] = $this->country_model->getAll();
$this->viewData['cityStatus'] = [
'Active' => Geofence_area_city_model::ACTIVE_STATUS,
'Inactive' => Geofence_area_city_model::INACTIVE_STATUS,
];
$this->viewData['item'] = null;
$this->renderAdminPage('geofence_area_city/create', $this->viewData);
}
public function store()
{
$this->load->helper(array('form', 'url'));
$this->load->library('form_validation');
$this->viewData['item'] = null;
$this->viewData['countryList'] = $this->country_model->getAll();
$this->viewData['cityStatus'] = [
'Active' => Geofence_area_city_model::ACTIVE_STATUS,
'Inactive' => Geofence_area_city_model::INACTIVE_STATUS,
];
$this->setCreationRules();
if ($this->form_validation->run() == false) {
$this->renderAdminPage('geofence_area_city/create', $this->viewData);
return;
}
$inputData = [
'city' => $this->input->post('city'),
'country' => $this->input->post('country_code'),
'latitude' => $this->input->post('latitude'),
'longitude' => $this->input->post('longitude'),
'radius' => $this->input->post('radius'),
'status' => $this->input->post('status'),
];
$this->geofence_area_city_model->create($inputData);
$this->session->set_flashdata('success', 'Created geofence area city successfully.');
redirect('/geofence_area_city');
}
public function edit($id)
{
$this->load->helper(array('form', 'url'));
$this->viewData['item'] = $this->geofence_area_city_model->getItem($id);
$this->viewData['itemId'] = $id;
$this->viewData['countryList'] = $this->country_model->getAll();
$this->viewData['cityStatus'] = [
'Active' => Geofence_area_city_model::ACTIVE_STATUS,
'Inactive' => Geofence_area_city_model::INACTIVE_STATUS,
];
$this->renderAdminPage('geofence_area_city/edit', $this->viewData);
}
public function update($id)
{
$this->load->helper(array('form', 'url'));
$this->load->library('form_validation');
$this->viewData['item'] = $this->geofence_area_city_model->getItem($id);
$this->viewData['itemId'] = $id;
$this->viewData['countryList'] = $this->country_model->getAll();
$this->viewData['cityStatus'] = [
'Active' => Geofence_area_city_model::ACTIVE_STATUS,
'Inactive' => Geofence_area_city_model::INACTIVE_STATUS,
];
$this->setCreationRules();
if ($this->form_validation->run() == false) {
$this->renderAdminPage('geofence_area_city/edit', $this->viewData);
return;
}
$inputData = [
'city' => $this->input->post('city'),
'country' => $this->input->post('country_code'),
'latitude' => $this->input->post('latitude'),
'longitude' => $this->input->post('longitude'),
'radius' => $this->input->post('radius'),
'status' => $this->input->post('status'),
];
$this->geofence_area_city_model->update($id, $inputData);
$this->session->set_flashdata('success', 'Updated geofence area city successfully.');
redirect('/geofence_area_city');
}
public function delete($id)
{
$res = $this->geofence_area_city_model->delete($id);
$this->session->set_flashdata('success', 'Deleted geofence area city successfully.');
redirect('/geofence_area_city');
}
protected function renderAdminPage($page_name, $data)
{
$this->load->view('admin/view_admin_header', $data);
$this->load->view($page_name, $data);
$this->load->view('admin/view_admin_footer', $data);
}
public function getcityAjax()
{
if (!$this->input->is_ajax_request()) {
exit('No direct script access allowed');
}
$result = $this->geofence_area_city_model->getCityWithFilter([
'city_name' => trim($this->input->get('city_name')),
'page' => $this->input->get('page')
]);
echo json_encode([
'data' => $result['data'],
'total' => $result['total']
]);
}
private function setCreationRules()
{
$config = [
[
'field' => 'country_code',
'label' => 'Country',
'rules' => 'required',
],
[
'field' => 'city',
'label' => 'City name',
'rules' => 'required',
],
[
'field' => 'latitude',
'label' => 'Latitude',
'rules' => 'required|numeric',
],
[
'field' => 'longitude',
'label' => 'Longitude',
'rules' => 'required|numeric',
],
[
'field' => 'radius',
'label' => 'Radius',
'rules' => 'required|integer',
],
[
'field' => 'status',
'label' => 'Status',
'rules' => 'required|integer',
],
];
$this->form_validation->set_rules($config);
}
public function getCities() {
//get query string filter
$queryString = $this->input->server('QUERY_STRING');
$filterData = $this->input->get();
$page = $this->input->get('page');
// remove empty value
$filterData = array_filter($filterData, function ($val) {
return $val !== '';
});
$pagingUrl = empty($queryString) ? uri_string() : uri_string() . '?' . $queryString;
$pagingUrl = remove_querystring_var($pagingUrl, 'page');
$result = $this->geofence_area_city_model->getAllWithPagination($page, $this->pagePerItem, $filterData);
echo json_encode(
[
'data' =>$result['data'],
'total' => $result['total'],
]
);
}
}
@@ -0,0 +1,193 @@
<?php
defined('BASEPATH') or exit('No direct script access allowed');
class Geofence_area_city_settings extends Admin_Controller
{
const CSV_FIELDS = [
'id',
'status',
'geofence_area_city',
'image_url',
'is_fectched_data',
'city',
'country',
'latitude',
'longitude'
];
public $viewData = array();
public $pagePerItem = 10;
public function __construct()
{
parent::__construct();
// Load model
$this->load->model('geofence_area_city_settings_model');
$this->load->model('country_model');
$this->load->helper('pagination');
global $savvyext;
$this->viewData['storage'] = $savvyext->cfgReadChar('system.storage_url');
}
public function index()
{
$this->load->helper(array('form', 'url'));
//get query string filter
$queryString = $this->input->server('QUERY_STRING');
$filterData = $this->input->get();
$page = $this->input->get('page') ?? 1;
// remove empty value
$filterData = array_filter($filterData, function ($v, $k) {
return $v != '';
}, ARRAY_FILTER_USE_BOTH);
$pagingUrl = empty($queryString) ? uri_string() : uri_string() . '?' . $queryString;
$pagingUrl = remove_querystring_var($pagingUrl, 'page');
$data = $this->geofence_area_city_settings_model->getAllWithPagination($filterData, ['page' => $page, 'itemPerPage' => $this->pagePerItem]);
$this->viewData['list'] = $data['data'];
$this->viewData['filterData'] = $filterData;
$this->viewData['countryList'] = $this->country_model->getAll();
$this->viewData['cityStatus'] = [
Geofence_area_city_settings_model::ACTIVE_STATUS=>'Active',
Geofence_area_city_settings_model::INACTIVE_STATUS=>'Inactive' ,
];
$this->viewData['pagination'] = initPagination($this->pagePerItem, $data['total'], $page, $pagingUrl);
$this->renderAdminPage('geofence_area_city_settings/list', $this->viewData);
}
public function create()
{
$this->load->helper(array('form', 'url'));
$this->viewData['cityStatus'] = [
'Active' => Geofence_area_city_settings_model::ACTIVE_STATUS,
'Inactive' => Geofence_area_city_settings_model::INACTIVE_STATUS,
];
$this->viewData['item'] = null;
$this->renderAdminPage('geofence_area_city_settings/create', $this->viewData);
}
public function store()
{
$this->load->helper(array('form', 'url'));
$this->load->library('form_validation');
$this->viewData['item'] = null;
$this->viewData['countryList'] = $this->country_model->getAll();
$this->viewData['cityStatus'] = [
'Active' => Geofence_area_city_settings_model::ACTIVE_STATUS,
'Inactive' => Geofence_area_city_settings_model::INACTIVE_STATUS,
];
$this->setCreationRules();
if ($this->form_validation->run() == false) {
$this->renderAdminPage('geofence_area_city_settings/create', $this->viewData);
return;
}
$inputData = [
'geofence_area_city' => $this->input->post('city'),
'status' => intval($this->input->post('status')),
'image_url' => $this->input->post('image_url') ?? '',
];
$this->geofence_area_city_settings_model->create($inputData);
$this->session->set_flashdata('success', 'Created geofence area city successfully.');
redirect('/geofence_area_city_settings');
}
public function edit($id)
{
$this->load->helper(array('form', 'url'));
$this->viewData['item'] = $this->geofence_area_city_settings_model->getItem($id);
$this->viewData['itemId'] = $id;
$this->viewData['editing'] = true;
$this->viewData['cityStatus'] = [
'Active' => Geofence_area_city_settings_model::ACTIVE_STATUS,
'Inactive' => Geofence_area_city_settings_model::INACTIVE_STATUS,
];
$this->renderAdminPage('geofence_area_city_settings/edit', $this->viewData);
}
public function update($id)
{
$this->load->helper(array('form', 'url'));
$this->load->library('form_validation');
$this->viewData['item'] = $this->geofence_area_city_settings_model->getItem($id);
$this->viewData['itemId'] = $id;
$this->viewData['cityStatus'] = [
'Active' => Geofence_area_city_settings_model::ACTIVE_STATUS,
'Inactive' => Geofence_area_city_settings_model::INACTIVE_STATUS,
];
$this->setEditRules();
if ($this->form_validation->run() == false) {
$this->renderAdminPage('geofence_area_city_settings/edit', $this->viewData);
return;
}
$inputData = [
'status' => $this->input->post('status'),
'image_url' => $this->input->post('image_url') ?? '',
];
$this->geofence_area_city_settings_model->update($id, $inputData);
$this->session->set_flashdata('success', 'Updated geofence area city settings successfully.');
redirect('/geofence_area_city_settings');
}
public function delete($id)
{
$res = $this->geofence_area_city_settings_model->delete($id);
$this->session->set_flashdata('success', 'Deleted geofence area city settings successfully.');
redirect('/geofence_area_city_settings');
}
protected function renderAdminPage($page_name, $data)
{
$this->load->view('admin/view_admin_header', $data);
$this->load->view($page_name, $data);
$this->load->view('admin/view_admin_footer', $data);
}
private function setCreationRules()
{
$config = [
[
'field' => 'city',
'label' => 'City',
'rules' => 'required',
],
[
'field' => 'status',
'label' => 'Status',
'rules' => 'required|integer',
],
];
$this->form_validation->set_rules($config);
}
private function setEditRules()
{
$config = [
[
'field' => 'status',
'label' => 'Status',
'rules' => 'required|integer',
],
];
$this->form_validation->set_rules($config);
}
}
@@ -0,0 +1,151 @@
<?php
defined('BASEPATH') or exit('No direct script access allowed');
class Geofence_area_country extends Admin_Controller
{
public $viewData = array();
public $pagePerItem = 10;
public function __construct()
{
parent::__construct();
// Load model
$this->load->model('geofence_area_country_model');
$this->load->model('country_model');
$this->load->helper('pagination');
}
public function index()
{
$this->load->helper(array('form', 'url'));
$page = $this->input->get('page');
//get query string filter
$queryString = $this->input->server('QUERY_STRING');
$pagingUrl = empty($queryString) ? uri_string() : uri_string() . '?' . $queryString;
$pagingUrl = remove_querystring_var($pagingUrl, 'page');
$data = $this->geofence_area_country_model->getAllWithPagination($page, $this->pagePerItem);
$this->viewData['list'] = $data['data'];
$this->viewData['pagination'] = initPagination($this->pagePerItem, $data['total'], $page, $pagingUrl);
$this->renderAdminPage('geofence_area_country/list', $this->viewData);
}
public function create()
{
$this->load->helper(array('form', 'url'));
$this->viewData['countryList'] = $this->country_model->getAll();
$this->viewData['item'] = null;
$this->renderAdminPage('geofence_area_country/create', $this->viewData);
}
public function store()
{
$this->load->helper(array('form', 'url'));
$this->load->library('form_validation');
$this->viewData['item'] = null;
$this->viewData['countryList'] = $this->country_model->getAll();
$this->setCreationRules();
if ($this->form_validation->run() == false) {
$this->renderAdminPage('geofence_area_country/create', $this->viewData);
return;
}
$inputData = [
'country' => $this->input->post('country_code'),
'latitude' => $this->input->post('latitude'),
'longitude' => $this->input->post('longitude'),
'radius' => $this->input->post('radius'),
];
$this->geofence_area_country_model->create($inputData);
$this->session->set_flashdata('success', 'Created geofence area country successfully.');
redirect('/geofence_area_country');
}
public function edit($id)
{
$this->load->helper(array('form', 'url'));
$this->viewData['item'] = $this->geofence_area_country_model->getItem($id);
$this->viewData['itemId'] = $id;
$this->viewData['countryList'] = $this->country_model->getAll();
$this->renderAdminPage('geofence_area_country/edit', $this->viewData);
}
public function update($id)
{
$this->load->helper(array('form', 'url'));
$this->load->library('form_validation');
$this->viewData['item'] = $this->geofence_area_country_model->getItem($id);
$this->viewData['itemId'] = $id;
$this->viewData['countryList'] = $this->country_model->getAll();
$this->setCreationRules();
if ($this->form_validation->run() == false) {
$this->renderAdminPage('geofence_area_country/edit', $this->viewData);
return;
}
$inputData = [
'country' => $this->input->post('country_code'),
'latitude' => $this->input->post('latitude'),
'longitude' => $this->input->post('longitude'),
'radius' => $this->input->post('radius'),
];
$this->geofence_area_country_model->update($id, $inputData);
$this->session->set_flashdata('success', 'Updated geofence area country successfully.');
redirect('/geofence_area_country');
}
public function delete($id)
{
$res = $this->geofence_area_country_model->delete($id);
$this->session->set_flashdata('success', 'Deleted geofence area country successfully.');
redirect('/geofence_area_country');
}
protected function renderAdminPage($page_name, $data)
{
$this->load->view('admin/view_admin_header', $data);
$this->load->view($page_name, $data);
$this->load->view('admin/view_admin_footer', $data);
}
private function setCreationRules()
{
$config = [
[
'field' => 'country_code',
'label' => 'Country',
'rules' => 'required',
],
[
'field' => 'latitude',
'label' => 'Latitude',
'rules' => 'required|numeric',
],
[
'field' => 'longitude',
'label' => 'Longitude',
'rules' => 'required|numeric',
],
[
'field' => 'radius',
'label' => 'Radius',
'rules' => 'required|integer',
]
];
$this->form_validation->set_rules($config);
}
}
+225
View File
@@ -0,0 +1,225 @@
<?php
defined('BASEPATH') or exit('No direct script access allowed');
class Global_settings extends Admin_Controller {
public $viewData = [];
public function __construct() {
parent::__construct();
$this->load->library('table');
$this->table->set_template($this->template);
$this->load->model('combo_model');
$this->load->model('Global_setting_model', 'global_setting');
// Load Pagination library
$this->load->library('pagination');
$this->viewData['card_status'] = $this->combo_model->getStatusCombo('card_status', $this->getFormValue()['status']);
$this->viewData['card_status_filter'] = $this->combo_model->getStatusCombo('card_status_filter', '');
$this->viewData['msg'] = null;
}
private function renderToolsPage($page_name, $data) {
$this->load->view('admin/view_admin_header', $data);
$this->load->view('global_setting/' . $page_name, $data);
$this->load->view('admin/view_admin_footer', $data);
}
public function index() {
$this->renderToolsPage("view_global_setting", $this->viewData);
}
private function setFormRuleSearchForm()
{
$this->form_validation->set_rules(
'card_status_filters',
'Status',
'numeric'
);
}
public function loadRecord(){
$rowno = $this->input->get('rowno');
parse_str($this->input->get('filters'), $filters);
$filters = array_filter($filters, function($val) {
return $val !== '';
});
$this->form_validation->set_data($filters);
$this->setFormRuleSearchForm();
$errors = [];
if ($this->form_validation->run() == false) {
$errors = $this->form_validation->error_array();
}
$filters = array_diff_key($filters, $errors);
// Row per page
$rowperpage = 10;
$cur_page = $rowno;
// Row position
if($rowno != 0){
$rowno = ($rowno-1) * $rowperpage;
}
// All records count
$allcount = $this->global_setting->getrecordCount($filters);
// Get records
$users_record = $this->global_setting->getData($rowno, $rowperpage, $filters);
// Pagination Configuration
$config['base_url'] = '/Global_settings/loadRecord';
$config['use_page_numbers'] = TRUE;
$config['total_rows'] = $allcount;
$config['per_page'] = $rowperpage;
$config['cur_page'] = $cur_page;
$config['full_tag_open'] = "<ul class='pagination'>";
$config['full_tag_close'] = "</ul>";
$config['num_tag_open'] = '<li>';
$config['num_tag_close'] = '</li>';
$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
$config['next_tag_open'] = "<li>";
$config['next_tagl_close'] = "</li>";
$config['prev_tag_open'] = "<li>";
$config['prev_tagl_close'] = "</li>";
$config['first_tag_open'] = "<li>";
$config['first_tagl_close'] = "</li>";
$config['last_tag_open'] = "<li>";
$config['last_tagl_close'] = "</li>";
// Initialize
$this->pagination->initialize($config);
// Initialize $data Array
$data['pagination'] = $this->pagination->create_links();
$data['result'] = $users_record;
$data['row'] = $rowno;
echo json_encode($data);
}
public function create() {
$this->load->helper(array('form', 'url'));
$this->load->database();
$this->load->library('form_validation');
$this->setFormRule();
$params = $this->getFormValue();
if ($this->form_validation->run() == false) {
$this->viewData = array_merge($this->viewData, $params);
$this->viewData['msg'] = validation_errors();
$this->renderToolsPage('view_global_setting', $this->viewData);
return;
}
if (!$this->global_setting->insertGlobalSetting($params)) {
$this->viewData['msg'] = "Insert Failed";
}
else {
$this->viewData['msg'] = "Insert Succesful";
}
$this->renderToolsPage('view_global_setting', $this->viewData);
}
public function update($id) {
$this->load->helper(array('form', 'url'));
$this->load->database();
$this->load->library('form_validation');
$this->setFormRule();
$params = $this->getFormValue();
if (strcmp($params['key'], $params['old_key']) === 0) {
$this->form_validation->set_rules('key', 'Key', 'required|max_length[50]');
}
if ($this->form_validation->run() == false) {
$this->viewData = array_merge($this->viewData, $params);
$this->viewData['msg'] = validation_errors();
$this->renderToolsPage('view_global_setting', $this->viewData);
return;
}
if (!$this->global_setting->updateGlobalSetting($id, $params)) {
$this->viewData['msg'] = "Update Failed";
}
else {
$this->viewData['msg'] = "Update Succesful";
}
$this->renderToolsPage('view_global_setting', $this->viewData);
}
private function setFormRule()
{
$this->form_validation->set_rules('key', 'Key', 'trim|required|max_length[50]|is_unique[global_settings.key]');
$this->form_validation->set_rules('value', 'Value', 'trim|required|max_length[50]');
$this->form_validation->set_rules('description', 'description', 'trim|required|max_length[350]');
$this->form_validation->set_rules('card_status', 'Status', 'trim|required|numeric|callback_isValidStatus');
$this->form_validation->set_message('isOutOfRangeInt4', 'The %s field is out of range');
}
public function isValidStatus($status) {
if (preg_match('/^[0-1]{1}$/', $status)) {
return TRUE;
} else {
$this->form_validation->set_message('isValidStatus', 'The Status is invalid');
return FALSE;
}
}
private function getFormValue()
{
return [
'key' => trim($this->input->post('key')),
'value' => trim($this->input->post('value')),
'old_key' => trim($this->input->post('old_key')),
'description' => trim($this->input->post('description')),
'status' => trim($this->input->post('card_status')),
];
}
public function destroy($id) {
$this->load->helper(array('form', 'url'));
$this->load->database();
$this->load->library('form_validation');
$this->form_validation->set_data(['id' => $id]);
$this->setFormRuleDelete();
if ($this->form_validation->run() == false) {
$this->viewData['msg'] = validation_errors();
$this->renderToolsPage('view_global_setting', $this->viewData);
return;
}
$this->viewData['msg'] = !$this->global_setting->deleteGlobalSettingById(['id' => $id])
? "Delete Failed"
: "Delete Successful" ;
$this->renderToolsPage('view_global_setting', $this->viewData);
}
private function setFormRuleDelete()
{
$this->form_validation->set_rules('id', 'Global Settings', 'required|numeric|callback_existsGlobalSetting');
}
public function existsGlobalSetting($id) {
if (!$this->global_setting->getGlobalSettingsByID(['id' => $id]))
{
$this->form_validation->set_message('existsGlobalSetting', 'Please choose an existing global settings');
return FALSE;
}
else
{
return TRUE;
}
}
}
+173
View File
@@ -0,0 +1,173 @@
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Gps extends Admin_Controller {
public function index() {
}
protected function renderGpsPage($page_name, $data) {
$this->load->view('admin/view_admin_header', $data);
$this->load->view('gps/' . $page_name, $data);
$this->load->view('admin/view_admin_footer', $data);
}
public function tracking() {
$data = array();
$data["members"] = [];
$data["member_id"] = $this->input->get('member_id');
$gps = $this->load->database('gps', TRUE);
$q = "SELECT member_id,count(*) AS count FROM members_tracking GROUP BY member_id ORDER BY member_id";
$r = $gps->query($q);
if ($r->num_rows()) {
foreach ($r->result() as $row) {
$data["members"][] = (array)$row;
}
}
$data["tracking_links"] = "";
$data["tracking_table"] = "";
$data["tracking_trips_table"] = "";
if ($data["member_id"]>0) {
// id member_id traked_group speed lat lng gps ttime loc created device_id previous_id distance duration
$q = "SELECT id,duration,distance,round(speed,2) as speed,date_trunc('second',ttime) as ttime,device_id,loc,traked_group FROM members_tracking WHERE member_id=".$data["member_id"];
$r = $gps->query($q);
if ($r->num_rows()) {
$this->load->library('pagination');
$config = array();
$config["total_rows"] = $r->num_rows();
$config["base_url"] = base_url() . "/gps/tracking";
$config["per_page"] = 20;
$config["uri_segment"] = 3;
$config["num_links"] = 7;
$config['attributes'] = array('onclick' => 'document.location=this.href+\'?member_id='.$data["member_id"].'\';return false;');
$config['full_tag_open'] = "<ul class='pagination'>";
$config['full_tag_close'] = "</ul>";
$config['num_tag_open'] = '<li>';
$config['num_tag_close'] = '</li>';
$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
$config['next_tag_open'] = "<li>";
$config['next_tagl_close'] = "</li>";
$config['prev_tag_open'] = "<li>";
$config['prev_tagl_close'] = "</li>";
$config['first_tag_open'] = "<li>";
$config['first_tagl_close'] = "</li>";
$config['last_tag_open'] = "<li>";
$config['last_tagl_close'] = "</li>";
$this->pagination->initialize($config);
$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
$page = is_numeric($page) ? $page : 0;
$q.= " ORDER BY ttime DESC LIMIT " . $config["per_page"] . " OFFSET " . $page;
$query = $gps->query($q);
$this->load->helper('url');
$this->load->library('table');
$this->table->set_template($this->template);
// id duration distance speed ttime device_id loc traked_group
$this->table->set_heading(
array('data' => 'ID', 'style' => 'width:80px'),
array('data' => 'Duration', 'style' => 'width:80px'),
array('data' => 'Distance', 'style' => 'width:80px'),
array('data' => 'Speed', 'style' => 'width:80px'),
array('data' => 'Time', 'style' => 'width:160px'),
array('data' => 'Device ID', 'style' => 'width:80px'),
array('data' => 'IP Address', 'style' => 'width:80px'),
array('data' => 'Tracked Group', 'style' => 'width:80px')
);
$data["tracking_table"] = $this->table->generate($query);
$data["tracking_links"] = $this->pagination->create_links();
}
$q = "SELECT '<button id=\"trip'||id||'\" type=\"button\" class=\"btn btn-primary btn-xs\" block onclick=\"viewTrip('||id||');\">View</button>',";
$q.= "ROUND(a.duration,0) AS duration,ROUND(a.distance,2) AS distance,ROUND(a.speed,2) AS speed, ROUND(a.avg_speed,2) AS avg_speed ";
$q.= "FROM members_tracking_trips a WHERE a.member_id=".$data["member_id"];
$q.= " AND a.distance>15 AND a.duration>15";
$r = $gps->query($q);
$this->table->set_heading(
array('data' => 'ID', 'style' => 'width:30px'),
array('data' => 'Duration', 'style' => 'width:40px'),
array('data' => 'Distance', 'style' => 'width:40px'),
array('data' => 'Speed', 'style' => 'width:40px'),
array('data' => 'Avg.Speed', 'style' => 'width:40px')
);
$data["tracking_trips_table"] = $this->table->generate($r);
}
$data["page_title"] = "GPS Tracking";
$this->renderGpsPage("view_tracking", $data);
}
public function trip() {
global $savvyext;
$data = array();
$data["members"] = [];
$data["member_id"] = (int)$this->input->get('member_id');
$data["id"] = (int)$this->input->get('id');
if ($data["id"]<1 || $data["member_id"]<1) {
redirect('gps/tracking?member_id='.$data["member_id"]);
return;
}
$gps = $this->load->database('gps', TRUE);
$q = "SELECT a.id, a.device_id, ROUND(a.duration,0) AS duration, ";
$q.= "ROUND(a.distance,2) AS distance,ROUND(a.speed,2) AS speed, ";
$q.= "ROUND(a.avg_speed,2) AS avg_speed, a.location_start, a.location_end, ";
$q.= "b.lat AS start_lat, b.lng AS start_lng, ";
$q.= "c.lat AS end_lat, c.lng AS end_lng, ";
$q.= "b.ttime AS start_time, c.ttime AS end_time ";
$q.= "FROM members_tracking_trips a ";
$q.= "LEFT JOIN members_tracking b ON (b.id=a.location_start) ";
$q.= "LEFT JOIN members_tracking c ON (c.id=a.location_end) ";
$q.= "WHERE a.member_id=".$data["member_id"]." AND a.id=".$data["id"];
$r = $gps->query($q);
$f = $r->row_array();
$data = array_merge($data, $f);
$q = "SELECT date_trunc('second',ttime) AS ttime,lat,lng,speed,distance,duration ";
$q.= "FROM members_tracking WHERE member_id=".$data["member_id"]." ";
$q.= "AND id>=".$data["location_start"]." AND id<=".$data["location_end"]." ";
$q.= ($data["device_id"]>0?("AND device_id=".$data["device_id"]):" AND device_id IS NULL");
$q.= " ORDER BY ttime";
$r = $gps->query($q);
$this->load->library('table');
$this->table->set_template($this->template);
$this->table->set_heading(
array('data' => 'Time', 'style' => 'width:30px'),
array('data' => 'Lat', 'style' => 'width:30px'),
array('data' => 'Lng', 'style' => 'width:30px'),
array('data' => 'Speed', 'style' => 'width:40px'),
array('data' => 'Distance', 'style' => 'width:40px'),
array('data' => 'Duration', 'style' => 'width:40px')
);
$data["tracking_trips_table"] = $this->table->generate($r);
$min_lat = PHP_INT_MAX;
$min_lng = PHP_INT_MAX;
$max_lat = PHP_INT_MIN;
$max_lng = PHP_INT_MIN;
$center_lat = 0;
$center_lng = 0;
foreach ($r->result() as $row) {
$f = (array) $row;
$data["items"][] = $f;
if ($f["lat"]<$min_lat) $min_lat = $f["lat"];
if ($f["lng"]<$min_lng) $min_lng = $f["lng"];
if ($f["lat"]>$max_lat) $max_lat = $f["lat"];
if ($f["lng"]>$max_lng) $max_lng = $f["lng"];
}
$data["center_lat"] = ($min_lat+$max_lat)/2;
$data["center_lng"] = ($min_lng+$max_lng)/2;
$data['google_api_key'] = $savvyext->cfgReadChar('google.api_key');
$this->renderGpsPage("view_trip", $data);
}
}
@@ -0,0 +1,19 @@
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
require 'vendor/autoload.php';
class LogViewerController extends CI_Controller {
public function __construct() {
parent::__construct();
$this->logViewer = new \CILogViewer\CILogViewer();
//...
}
public function index()
{
echo $this->logViewer->showLogs();
return;
}
}
+15
View File
@@ -0,0 +1,15 @@
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Logout extends CI_Controller {
public function index() {
$data = array();
$_SESSION['firstname'] = $_SESSION['username'] = $_SESSION['sessionid'] = $_SESSION['session_id'] = "";
$data['action_message'] = '';
unset($_SESSION);
redirect('welcome');
}
}
File diff suppressed because it is too large Load Diff
+167
View File
@@ -0,0 +1,167 @@
<?php
defined('BASEPATH') or exit('No direct script access allowed');
class Myfloat_version extends Admin_Controller
{
public function index()
{
$this->load->model('myfloat_version_model');
$platform_id = "";
$validated = true;
$data = [
"platform_id" => "",
"name" => "",
"released" => "",
"notes" => "",
"rev_count" => "",
"short_hash" => "",
"url" => "",
"form_button" => "Create",
];
$data['message'] = "";
$query = "SELECT id,platform
FROM members_device_platforms
WHERE platform != ''";
$platforms = $this->read_replica->query($query);
$platforms = $platforms->result_array();
try {
if ($_POST) {
$data['id'] = $this->input->post('id') ? trim($this->input->post('id')) : "";
$platform_id = trim($this->input->post('platform_id'));
$data['platform_id'] = $platform_id;
$data['name'] = trim($this->input->post('name'));
$data['released'] = trim($this->input->post('released'));
$data['notes'] = trim($this->input->post('notes'));
$data['rev_count'] = trim($this->input->post('rev_count'));
$data['short_hash'] = trim($this->input->post('short_hash'));
$data['url'] = trim($this->input->post('url'));
// Validate
if (empty($data['platform_id'])) {
$data['message'] .= "<br/>Invalid platform id";
$validated = false;
}
if (empty($data['name']) || strlen($data['name']) > 50) {
$data['message'] .= "<br/>Invalid name";
$validated = false;
}
if (empty($data['released'])) {
$data['message'] .= "<br/>Invalid released";
$validated = false;
}
if ($validated == true) {
// Upsert
$q = "INSERT INTO myfloat_version
(
platform_id,
name,
released,
notes,
rev_count,
short_hash,
url
)
VALUES
(
'" . pg_escape_string($data['platform_id']) . "',
'" . pg_escape_string($data['name']) . "',
'" . pg_escape_string($data['released']) . "',
'" . pg_escape_string($data['notes']) . "',
" . ($data['rev_count'] ?: 0) . ",
'" . pg_escape_string($data['short_hash']) . "',
'" . pg_escape_string($data['url']) . "'
) ON CONFLICT (platform_id,name) DO UPDATE SET
platform_id = '" . pg_escape_string($data['platform_id']) . "',
name = '" . pg_escape_string($data['name']) . "',
released = '" . pg_escape_string($data['released']) . "',
notes = '" . pg_escape_string($data['notes']) . "',
short_hash = '" . pg_escape_string($data['short_hash']) . "',
rev_count = " . ($data['rev_count'] ?: 0) . ",
url = '" . pg_escape_string($data['url']) . "'
RETURNING *,
CASE WHEN xmax::text::int > 0
THEN 'updated' else 'inserted' END AS act";
if ($data['message'] == "") {
$r = $this->db->query($q);
$f = $r->row_array();
$act = $f["act"];
if ($f != null && isset($act)) {
$data['message'] = 'My float version ' . $act . '!';
$data["form_button"] = $act == 'inserted' ? 'Insert' : 'Update';
} else {
$data['message'] = 'Failed to ' . $act . ' my float version!';
}
}
}
}
$params = [];
$params = $this->input->get();
$query = $this->myfloat_version_model->getVersionQuery($params);
$tableData = $this->returnAdminTable(
[
'count_query' => $query,
'query' => $query,
],
'/myfloat_version/index',
[
'per_page' => 20,
'reuse_query_string' => TRUE,
]
);
$data['links'] = $tableData['links'];
$data['crashlog_table'] = $tableData['output_table'];
$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
$data['filterData'] = $params;
$data = array_merge($data, [
"versions" => $tableData['limited_data'],
"page" => $page,
"platforms" => $platforms,
]);
} catch (Exception $e) {
$data["message"] = $e->getMessage();
}
$this->renderAdminPage('view_myfloat_version', $data);
}
public function deleteVersion()
{
$data = [];
$id = (int) $this->input->get('id');
header('Content-Type: application/json');
if ($id > 0) {
$q = "DELETE FROM myfloat_version WHERE id=${id}";
$r = $this->db->query($q);
if ($r) {
echo json_encode([
'state' => 'successful',
'message' => 'My Float Version is deleted',
'id' => $id,
]);
} else {
echo json_encode([
'state' => 'failure',
'message' => 'Delete failed',
]);
}
} else {
echo json_encode([
'state' => 'failure',
'message' => 'Invalid ID',
]);
}
}
}
+553
View File
@@ -0,0 +1,553 @@
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Notifications extends Admin_Controller {
public function __construct() {
parent::__construct();
$this->load->model('Notification_model', 'notification');
$this->load->model('Members_notification_model', 'members_notification');
}
public function index() {
$this->noticelist();
}
public function noticelist() {
$data = [];
$data['page_title'] = "Members Notifications";
$params = [];
if ($this->input->method(TRUE) === 'GET') {
$params = $this->input->get();
}
$query = $this->members_notification->getNotifications($params);
$data['params'] = $params;
$tableData = $this->returnAdminTable([
'count_query' => $query,
'query' => $query,
], remove_querystring_var($_SERVER['REQUEST_URI'], 'page'), [
'per_page' => 100,
'enable_query_strings'=>TRUE,
'page_query_string'=>TRUE,
'use_page_numbers'=>TRUE,
'reuse_query_string'=>FALSE,
'query_string_segment'=>'page',
]);
$data['notification_table'] = $tableData['output_table'];
$data['pagination_link'] = $tableData['links'];
$this->table->set_heading(
['data' => 'Member', 'style' => 'width:50px'], ['data' => 'Account Email', 'style' => 'width:150px'], ['data' => 'Notify', 'style' => 'width:50px'], ['data' => 'trigger_key', 'style' => 'width:50px'], ['data' => 'Email-Msg', 'style' => 'width:50px'], ['data' => 'M-Type', 'style' => 'width:90px'], 'Message', ['data' => 'Status', 'style' => 'width:50px'], ['data' => 'Add Date', 'style' => 'width:95px'], ['data' => 'Mode', 'style' => 'width:75px'], ['data' => 'Action', 'style' => 'width:40px']
);
$data['notificationStatus'] = [
Members_notification_model::PENDING_STATUS => 'Pending',
Members_notification_model::CANCELLED_STATUS => 'Cancelled',
Members_notification_model::COMPLETED_STATUS => 'Completed',
Members_notification_model::EXPIRED_STATUS => 'Expired',
];
// get notification types list
$notificationTypesQuery = $this->read_replica->get('notification_types');
$data['notificationTypes'] = $notificationTypesQuery->result();
$this->renderNotificationPage('view_noticelist', $data);
}
/*
* member_id | integer |
| character varying(10) |
| text |
status | integer | default 1
added | timestamp without time zone | default now()
| character varying(20) | not null
trigger_key
*/
public function load_ckeditor() {
$this->load->library('ckeditor');
$this->ckeditor->basePath = base_url() . 'assets/ckeditor/';
$this->ckeditor->config['toolbar'] = [
[
'Source',
'-',
'Bold',
'Italic',
'Underline',
'-',
'Cut',
'Copy',
'Paste',
'PasteText',
'PasteFromWord',
'-',
'Undo',
'Redo',
'-',
'NumberedList',
'BulletedList'
]
];
$this->ckeditor->config['width'] = 'auto';
$this->ckeditor->config['height'] = '200px';
}
public function load_pagination($all_record, $params) {
// pagination
$this->load->library('pagination');
$config["total_rows"] = count($all_record);
$config["base_url"] = base_url() . "/notifications/emailtrigger";
$config["suffix"] = '?' . http_build_query($params);
$config["first_url"] = '/notifications/emailtrigger/0?' . http_build_query($params);
$config["per_page"] = 10;
$config["uri_segment"] = 3;
$config["num_links"] = 5;
$config['full_tag_open'] = "<ul class='pagination'>";
$config['full_tag_close'] = "</ul>";
$config['num_tag_open'] = '<li>';
$config['num_tag_close'] = '</li>';
$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
$config['next_tag_open'] = "<li>";
$config['next_tagl_close'] = "</li>";
$config['prev_tag_open'] = "<li>";
$config['prev_tagl_close'] = "</li>";
$config['first_tag_open'] = "<li>";
$config['first_tagl_close'] = "</li>";
$config['last_tag_open'] = "<li>";
$config['last_tagl_close'] = "</li>";
$this->pagination->initialize($config);
$page = ( $this->uri->segment(3) ) ? $this->uri->segment(3) : 0;
$offset = is_numeric($page) ? $page : 0;
return [
'link' => $this->pagination->create_links(),
'offset' => $offset,
'limit' => $config["per_page"]
];
}
public function setValueCombo($val) {
$yes_no_value = [0, 1];
return in_array($val, $yes_no_value) ? $val : '';
}
public function setComboForEmailTrigger($params) {
$this->load->model('combo_model');
$combo['card_send_notification'] = $this->combo_model->getYesNoComboWithAll(
'card_send_notification', $params['send_notification']
);
$combo['card_send_mail'] = $this->combo_model->getYesNoComboWithAll(
'card_send_mail', $params['send_mail']
);
$combo['card_status'] = $this->combo_model->getStatusComboWithAll(
'card_status', $params['status']
);
return $combo;
}
public function triggerreport() {
$this->load->library('table');
$this->table->set_template($this->template);
$data = [];
$data["page_title"] = "Trigger Items Aggregate Report";
$mysql = "SELECT count(n.member_id),m.country from members_notification n LEFT JOIN members m ON m.id = n.member_id GROUP By m.country";
$query = $this->read_replica->query($mysql);
$this->table->set_heading(array('data' => 'Count', 'style' => 'width:10px'), 'Country');
$data['country_report'] = $this->table->generate($query);
$mysql = "SELECT count(n.member_id),m.country from members_notification n LEFT JOIN members m ON m.id = n.member_id AND n.status = 1 GROUP By m.country";
$query = $this->read_replica->query($mysql);
$this->table->set_heading(array('data' => 'Count', 'style' => 'width:10px'), 'Country');
$data['trigger_report_table'] = $this->table->generate($query);
$mysql = "SELECT count(n.member_id),m.country from members_notification n LEFT JOIN members m ON m.id = n.member_id AND n.status = 5 AND n.date_sent > now()+ '-1 days' GROUP By m.country";
$query = $this->read_replica->query($mysql);
$this->table->set_heading(array('data' => 'Count', 'style' => 'width:10px'), 'Country');
$data['completed_report_table'] = $this->table->generate($query);
$mysql = "SELECT count(id),trigger_key FROM members_notification GROUP BY trigger_key";
$query = $this->read_replica->query($mysql);
$this->table->set_heading(array('data' => 'Count', 'style' => 'width:10px'), 'Country');
$data['insight_report_table'] = $this->table->generate($query);
$mysql = "SELECT count(id),trigger_key FROM members_notification WHERE status = 1 GROUP BY trigger_key";
$query = $this->read_replica->query($mysql);
$this->table->set_heading(array('data' => 'Count', 'style' => 'width:10px'), 'Country');
$data['insight_pending_report_table'] = $this->table->generate($query);
$mysql = "SELECT count(id),trigger_key FROM members_notification WHERE status = 5 GROUP BY trigger_key";
$query = $this->read_replica->query($mysql);
$this->table->set_heading(array('data' => 'Count', 'style' => 'width:10px'), 'Country');
$data['insight_completed_report_table'] = $this->table->generate($query);
$this->renderNotificationPage('view_trigger_report', $data);
}
public function emailtrigger() {
$this->load->model('email_trigger_model');
$this->load->helper('url');
$this->load_ckeditor();
$params = $this->getValueOfEmailTriggerForm();
$data = $this->setComboForEmailTrigger($params);
$params['send_notification'] = $this->setValueCombo($params['send_notification']);
$params['send_mail'] = $this->setValueCombo($params['send_mail']);
$params['status'] = $this->setValueCombo($params['status']);
$params = array_filter($params, function($ele) {
return $ele !== "";
});
$errors = $this->validateValueForEmailTriggerForm($params);
$params = array_diff_key($params, $errors);
$data = array_merge($data, $params);
$data['page_title'] = "Email Trigger";
$data = array_merge(
$data, $this->load_pagination(
$this->email_trigger_model->get_email_trigger_records($params), $params
)
);
$data['trigger_table'] = $this->email_trigger_model->get_email_trigger_records(
$params, $data['limit'], $data['offset']
);
$this->renderNotificationPage('view_emailtrigger', $data);
}
public function getValueOfEmailTriggerForm() {
return [
'trigger_id' => trim($this->input->get('trigger_id') ?? ''),
'next_action' => trim($this->input->get('next_action') ?? ''),
'card_key' => trim($this->input->get('card_key') ?? ''),
'email_template' => trim($this->input->get('email_template') ?? ''),
'send_mail' => trim($this->input->get('card_send_mail') ?? -1),
'send_notification' => trim($this->input->get('card_send_notification') ?? -1),
'status' => trim($this->input->get('card_status') ?? -1),
'icon' => trim($this->input->get('icon') ?? ''),
];
}
public function validateValueForEmailTriggerForm($params) {
$this->load->library('form_validation');
$this->form_validation->set_data($params);
$this->setFormRuleForEmailTriggerForm();
$errors = [];
if ($this->form_validation->run() === FALSE) {
$errors = $this->form_validation->error_array();
}
return $errors;
}
public function setFormRuleForEmailTriggerForm() {
$yes_no_pattern = 'regex_match[/^(?:[0-1])$/]';
$this->form_validation->set_rules('send_mail', 'Send email', $yes_no_pattern);
$this->form_validation->set_rules('send_notification', 'Send Notification', $yes_no_pattern);
$this->form_validation->set_rules('status', 'Status', $yes_no_pattern);
}
public function generateCard() {
$out = array();
$notice_id = (int) $this->input->get('notice_id');
$member_id = (int) $this->input->get('member_id');
$message = "";
global $trigger_card;
// print_r($trigger_card);
$trigger_key = "";
$dynamic_key = "";
$status_msg = '';
$cat = '';
if ($notice_id != '' && $member_id != '') {
$mysql = "SELECT * FROM members_notification WHERE id=$notice_id AND member_id=$member_id";
$query = $this->read_replica->query($mysql);
$row = $query->row();
if (isset($row)) {
$trigger_key = $row->trigger_key;
$message = $row->msg;
}
$card_allowded = false;
if (array_key_exists($trigger_key, $trigger_card)) {
$status_msg = "The $trigger_key is in the array";
// print_r( $trigger_card[$trigger_key] );
$dynamic_key = $trigger_card[$trigger_key]["dynamic_key"];
$mysql = "SELECT category FROM email_trigger WHERE e_trigger='".$trigger_key."' LIMIT 1";
$query = $this->read_replica->query($mysql);
$row = $query->row();
if (isset($row)) {
$cat = $row->category;
}else{
$cat = $trigger_card[$trigger_key]["cat"];
}
$card_allowded = true;
} else {
$status_msg = "The $trigger_key not set up for cards";
}
if (true == $card_allowded && $message != '' && $trigger_key != '' && $dynamic_key != '') {
$in = array();
$in["dynamic_key"] = $dynamic_key;
$in["member_id"] = $member_id;
$in["trigger_key"] = $trigger_key;
$in["message"] = $message;
$in["notice_id"] = $notice_id;
$in["cat"] = $cat;
$in['action'] = FLOAT_SYSTEM_CREATE_DYNAMICCARD;
$ret = $this->savvy_api($in, $out);
echo "---------------------## ------------------------";
print_r($out);
if ($ret == PHP_API_OK) {
$message = 'Completed!';
} else {
$message = 'Failed to Create';
}
}
}
echo $status_msg;
}
public function sendnotification() {
//notice_id='+notice_id+'&member_id=' + member_id
// echo 'Ameye';
$out = array();
$message = "";
$notice_id = (int) $this->input->get('notice_id');
$member_id = (int) $this->input->get('member_id');
if ($notice_id != '' && $member_id != '') {
// get the message
/*
* savvy=> SELECT * FROM members_notification WHERE member_id =1 AND id = 4967;;
id | member_id | notice_type | msg | status | added | mmode | trigger_key
------+-----------+-------------+---------------------------------------------+--------+---------------------------+-------+-------------
4967 | 1 | GENALERT | You are spending too much. Let's save money | 1 | 2020-02-23 04:00:03.58477 | AUTO | ETRG0003
(1 row)
*/
$mysql = "SELECT * FROM members_notification WHERE member_id = ${member_id} AND id = ${notice_id}"; //SELECT * FROM members_devices WHERE member_id=${member_id}";
$query = $this->read_replica->query($mysql);
$row = $query->row();
if (isset($row)) {
$message = $row->msg;
}
//echo $message;
$device_count = 0;
$q = "SELECT * FROM members_devices WHERE member_id=${member_id}";
$r = $this->read_replica->query($q);
foreach ($r->result() as $row) {
$data["devices"][] = $row->player_id;
$device_count++;
}
// $data["devices"] = ['a','b','c'];
$arrayData = array("NEXTSCREEN" => "bar");
if ($device_count > 0 && $message != '') {
$this->load->model('onesignal_model');
// print_r($data["devices"]);
$out = $this->onesignal_model->sendmemberMessage($member_id, $data["devices"], $message, $arrayData);
// print_r($out);
}
}
}
protected function renderNotificationPage($page_name, $data) {
$this->load->view('admin/view_admin_header', $data);
$this->load->view('notifications/' . $page_name, $data);
$this->load->view('admin/view_admin_footer', $data);
}
public function update() {
$result = $this->notification->updateDescription([
'id' => $this->input->post('id'),
'description' => $this->input->post('description'),
]);
echo json_encode([
'message' => $result ? "Updated" : "Failed",
'code' => $result ? 1 : 0
]);
}
public function before_update_trigger(){
$e_trigger = $this->input->get('e_trigger');//
$card_settings = $this->input->get('card_settings');//
//check card is used
$mysql = "SELECT m.id AS card_id, m.dynamic_key, e.e_trigger, e.action_detail FROM main_cards m LEFT JOIN email_trigger e ON m.dynamic_key = e.dynamic_key WHERE m.id='".$card_settings."'";
$query = $this->read_replica->query($mysql);
$mr = $query->row_array();
$message ='';
$used = false;
if(!empty($mr)){
$used_trigger = $mr["e_trigger"];
$dynamic_key = $mr["dynamic_key"];
if(!empty($dynamic_key) && $used_trigger!=$e_trigger){//used
$used = true;
$message= "Action card is used by ".$used_trigger.". Do you want to update?";
}
}
echo json_encode([
'message' => $message,
'used' => $used
]);exit;
}
public function update_trigger() {
// echo "updateTriggerItem Ameye";
// url: "/notifications/updateTriggerItem?category_settings=" + category_settings + "&e_trigger=" + e_trigger
$data = array();
$this->load->model('combo_model');
$points_settings_value = '';
$message_card = "";
if ($this->input->post()) {
$category_settings = $this->input->post('category_settings');
$e_trigger = $this->input->post('e_trigger');
$card_settings = $this->input->post('card_settings');
$override_text = $this->input->post('override_text');
$expiration = $this->input->post('expiration');
$icon = $this->input->post('icon');
$notify_title = pg_escape_string($this->input->post('notify_title')??'');
$frequency = $this->input->post('frequency') ?: null;
$send_day = $this->input->post('send_day') ?: null;
$send_time = $this->input->post('send_time') ?: null;
if ($e_trigger != '' && $category_settings != '' && $card_settings != '') {
// update email trigger
$this->db->set('category', $category_settings);
$this->db->set('override_text', $override_text);
$this->db->set('expiration', $expiration);
$this->db->set('icon', $icon);
$this->db->set('notify_title', $notify_title);
$this->db->set('frequency', $frequency);
$this->db->set('send_day', $send_day);
$this->db->set('send_time', $send_time);
//where condition
$this->db->where('e_trigger', $e_trigger);
//update
$query = $this->db->update('email_trigger');
//$mysql = "UPDATE email_trigger SET category='$category_settings',override_text=$override_text,expiration='$expiration', icon='$icon', notify_title = '$notify_title' WHERE e_trigger='$e_trigger'";
// $query = $this->db->query($mysql);
$q = "SELECT e.dynamic_key, m.description as action_detail,m.id AS card_id FROM email_trigger e LEFT JOIN main_cards m ON m.dynamic_key = e.dynamic_key WHERE e.e_trigger='".$e_trigger."'";
$query = $this->read_replica->query($q);
$mr = $query->row_array();
$dynamic_key = $mr["dynamic_key"];
$action_detail = $mr["action_detail"];
$card_id = $mr["card_id"];
$mysql ="";
if(!empty($card_id)){
$mysql.= "UPDATE main_cards SET dynamic_key=null WHERE id='$card_id';";
}
$mysql .= "UPDATE main_cards SET dynamic_key='$dynamic_key' WHERE id = '".$card_settings."'";
$this->db->query($mysql);
$message = "Updated ";
// Override Card Text Copy Description
if($override_text == 1 && !empty($e_trigger)){
$description = trim(preg_replace('/\s+/', ' ', strip_tags($action_detail)));
$mysql = "UPDATE email_trigger SET action_detail = '".pg_escape_string($description)."' WHERE e_trigger='$e_trigger'";
$this->db->query($mysql);
$message = "Updated and Overriding";
}
echo $message;
}
}
}
public function editTrigger() {
$data = array();
$this->load->model('combo_model');
$points_settings_value = '';
if ($this->input->get()) {
$trigger_id = $this->input->get('trigger_id');
/*
id | e_trigger | category | action_detail | template_name | status | added | updated | dynamic_key | message | send_mail | send_notification
----+-----------+------------+------------------------------------------+---------------+--------+----------------------------+----------------------------+-------------+-------------------------------+-----------+-------------------
2 | ETRG0002 | GOACTIVITY | <p>Good Job, you&#39;re saving money</p>+| etrg0002.html | 1 | 2020-02-18 15:06:46.721542 | 2020-02-18 15:06:46.721542 | ETRG0002KEY | Good Job, you're saving money | 0 | 1
| | | | | | | | | | |
(1 row)
*/
if ($trigger_id != '') {
$mysql = "SELECT e.*,m.id AS card_id FROM email_trigger e LEFT JOIN main_cards m ON m.dynamic_key = e.dynamic_key WHERE e.e_trigger='$trigger_id'";
$query = $this->read_replica->query($mysql);
$mr = $query->row_array();
// print_r($mr);
$data["e_trigger"] = $mr["e_trigger"];
$data["category"] = $mr["category"];
$data["dynamic_key"] = $mr["dynamic_key"];
$data["card_id"] = $mr["card_id"];
$data["override_text"] = $mr["override_text"];
$data["expiration"] = $mr["expiration"];
$data["icon"] = $mr["icon"];
$data["notify_title"] = $mr["notify_title"]??'';
$data["frequency"] = $mr["frequency"]??'';
$data["send_day"] = $mr["send_day"]??'';
$data["send_time"] = $mr["send_time"]??'';
// $this->memberPointsItems($member_id, $data);
$data["category_settings"] = $this->combo_model->getCardCategoryCombo("category_settings", $data["category"], '', 'CARDDYNAMIC');
// $data['member_id'] = $member_id;
$data['card_settings'] = $this->combo_model->getTriggerCardsCombo("card_settings", $data["card_id"]);
$data["override_text_combo"] = $this->combo_model->getYesNoCombo("override_text", $data["override_text"]);
$data["expiration_combo"] = $this->combo_model->getTriggerExpirationCombo("expiration", $data["expiration"]);
$data["frequency_combo"] = $this->combo_model->getTriggerFrequency("frequency", $data["frequency"]);
$data["send_day_combo"] = $this->combo_model->getTriggerSendDay("send_day", $data["send_day"]);
$data["send_time_combo"] = $this->combo_model->getTriggerSendTime("send_time", $data["send_time"]);
$this->load->view('notifications/extra/notifications_extra', $data);
}
}
}
}
@@ -0,0 +1,518 @@
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Notifications extends Admin_Controller {
public function __construct() {
parent::__construct();
$this->load->model('Notification_model', 'notification');
$this->load->model('Members_notification_model', 'members_notification');
}
public function index() {
$this->noticelist();
}
public function noticelist() {
$data = [];
$data['page_title'] = "Members Notifications";
$params = [];
if ($this->input->method(TRUE) === 'GET') {
$params = $this->input->get();
}
$query = $this->members_notification->getNotifications($params);
$data['params'] = $params;
$tableData = $this->returnAdminTable([
'count_query' => $query,
'query' => $query,
], remove_querystring_var($_SERVER['REQUEST_URI'], 'page'), [
'per_page' => 100,
'enable_query_strings'=>TRUE,
'page_query_string'=>TRUE,
'use_page_numbers'=>TRUE,
'reuse_query_string'=>FALSE,
'query_string_segment'=>'page',
]);
$data['notification_table'] = $tableData['output_table'];
$data['pagination_link'] = $tableData['links'];
$this->table->set_heading(
['data' => 'Member', 'style' => 'width:50px'], ['data' => 'Account Email', 'style' => 'width:150px'], ['data' => 'Notify', 'style' => 'width:50px'], ['data' => 'trigger_key', 'style' => 'width:50px'], ['data' => 'Email-Msg', 'style' => 'width:50px'], ['data' => 'M-Type', 'style' => 'width:90px'], 'Message', ['data' => 'Status', 'style' => 'width:50px'], ['data' => 'Add Date', 'style' => 'width:95px'], ['data' => 'Mode', 'style' => 'width:75px'], ['data' => 'Action', 'style' => 'width:40px']
);
$data['notificationStatus'] = [
Members_notification_model::PENDING_STATUS => 'Pending',
Members_notification_model::CANCELLED_STATUS => 'Cancelled',
Members_notification_model::COMPLETED_STATUS => 'Completed',
Members_notification_model::EXPIRED_STATUS => 'Expired',
];
// get notification types list
$notificationTypesQuery = $this->read_replica->get('notification_types');
$data['notificationTypes'] = $notificationTypesQuery->result();
$this->renderNotificationPage('view_noticelist', $data);
}
/*
* member_id | integer |
| character varying(10) |
| text |
status | integer | default 1
added | timestamp without time zone | default now()
| character varying(20) | not null
trigger_key
*/
public function load_ckeditor() {
$this->load->library('ckeditor');
$this->ckeditor->basePath = base_url() . 'assets/ckeditor/';
$this->ckeditor->config['toolbar'] = [
[
'Source',
'-',
'Bold',
'Italic',
'Underline',
'-',
'Cut',
'Copy',
'Paste',
'PasteText',
'PasteFromWord',
'-',
'Undo',
'Redo',
'-',
'NumberedList',
'BulletedList'
]
];
$this->ckeditor->config['width'] = 'auto';
$this->ckeditor->config['height'] = '200px';
}
public function load_pagination($all_record, $params) {
// pagination
$this->load->library('pagination');
$config["total_rows"] = count($all_record);
$config["base_url"] = base_url() . "/notifications/emailtrigger";
$config["suffix"] = '?' . http_build_query($params);
$config["first_url"] = '/notifications/emailtrigger/0?' . http_build_query($params);
$config["per_page"] = 10;
$config["uri_segment"] = 3;
$config["num_links"] = 5;
$config['full_tag_open'] = "<ul class='pagination'>";
$config['full_tag_close'] = "</ul>";
$config['num_tag_open'] = '<li>';
$config['num_tag_close'] = '</li>';
$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
$config['next_tag_open'] = "<li>";
$config['next_tagl_close'] = "</li>";
$config['prev_tag_open'] = "<li>";
$config['prev_tagl_close'] = "</li>";
$config['first_tag_open'] = "<li>";
$config['first_tagl_close'] = "</li>";
$config['last_tag_open'] = "<li>";
$config['last_tagl_close'] = "</li>";
$this->pagination->initialize($config);
$page = ( $this->uri->segment(3) ) ? $this->uri->segment(3) : 0;
$offset = is_numeric($page) ? $page : 0;
return [
'link' => $this->pagination->create_links(),
'offset' => $offset,
'limit' => $config["per_page"]
];
}
public function setValueCombo($val) {
$yes_no_value = [0, 1];
return in_array($val, $yes_no_value) ? $val : '';
}
public function setComboForEmailTrigger($params) {
$this->load->model('combo_model');
$combo['card_send_notification'] = $this->combo_model->getYesNoComboWithAll(
'card_send_notification', $params['send_notification']
);
$combo['card_send_mail'] = $this->combo_model->getYesNoComboWithAll(
'card_send_mail', $params['send_mail']
);
$combo['card_status'] = $this->combo_model->getStatusComboWithAll(
'card_status', $params['status']
);
return $combo;
}
public function triggerreport() {
$this->load->library('table');
$this->table->set_template($this->template);
$data = [];
$data["page_title"] = "Trigger Items Aggregate Report";
$mysql = "SELECT count(n.member_id),m.country from members_notification n LEFT JOIN members m ON m.id = n.member_id GROUP By m.country";
$query = $this->read_replica->query($mysql);
$this->table->set_heading(array('data' => 'Count', 'style' => 'width:10px'), 'Country');
$data['country_report'] = $this->table->generate($query);
$mysql = "SELECT count(n.member_id),m.country from members_notification n LEFT JOIN members m ON m.id = n.member_id AND n.status = 1 GROUP By m.country";
$query = $this->read_replica->query($mysql);
$this->table->set_heading(array('data' => 'Count', 'style' => 'width:10px'), 'Country');
$data['trigger_report_table'] = $this->table->generate($query);
$mysql = "SELECT count(n.member_id),m.country from members_notification n LEFT JOIN members m ON m.id = n.member_id AND n.status = 5 AND n.date_sent > now()+ '-1 days' GROUP By m.country";
$query = $this->read_replica->query($mysql);
$this->table->set_heading(array('data' => 'Count', 'style' => 'width:10px'), 'Country');
$data['completed_report_table'] = $this->table->generate($query);
$mysql = "SELECT count(id),trigger_key FROM members_notification GROUP BY trigger_key";
$query = $this->read_replica->query($mysql);
$this->table->set_heading(array('data' => 'Count', 'style' => 'width:10px'), 'Country');
$data['insight_report_table'] = $this->table->generate($query);
$mysql = "SELECT count(id),trigger_key FROM members_notification WHERE status = 1 GROUP BY trigger_key";
$query = $this->read_replica->query($mysql);
$this->table->set_heading(array('data' => 'Count', 'style' => 'width:10px'), 'Country');
$data['insight_pending_report_table'] = $this->table->generate($query);
$mysql = "SELECT count(id),trigger_key FROM members_notification WHERE status = 5 GROUP BY trigger_key";
$query = $this->read_replica->query($mysql);
$this->table->set_heading(array('data' => 'Count', 'style' => 'width:10px'), 'Country');
$data['insight_completed_report_table'] = $this->table->generate($query);
$this->renderNotificationPage('view_trigger_report', $data);
}
public function emailtrigger() {
$this->load->model('email_trigger_model');
$this->load->helper('url');
$this->load_ckeditor();
$params = $this->getValueOfEmailTriggerForm();
$data = $this->setComboForEmailTrigger($params);
$params['send_notification'] = $this->setValueCombo($params['send_notification']);
$params['send_mail'] = $this->setValueCombo($params['send_mail']);
$params['status'] = $this->setValueCombo($params['status']);
$params = array_filter($params, function($ele) {
return $ele !== "";
});
$errors = $this->validateValueForEmailTriggerForm($params);
$params = array_diff_key($params, $errors);
$data = array_merge($data, $params);
$data['page_title'] = "Email Trigger";
$data = array_merge(
$data, $this->load_pagination(
$this->email_trigger_model->get_email_trigger_records($params), $params
)
);
$data['trigger_table'] = $this->email_trigger_model->get_email_trigger_records(
$params, $data['limit'], $data['offset']
);
$this->renderNotificationPage('view_emailtrigger', $data);
}
public function getValueOfEmailTriggerForm() {
return [
'trigger_id' => trim($this->input->get('trigger_id') ?? ''),
'next_action' => trim($this->input->get('next_action') ?? ''),
'card_key' => trim($this->input->get('card_key') ?? ''),
'email_template' => trim($this->input->get('email_template') ?? ''),
'send_mail' => trim($this->input->get('card_send_mail') ?? -1),
'send_notification' => trim($this->input->get('card_send_notification') ?? -1),
'status' => trim($this->input->get('card_status') ?? -1),
];
}
public function validateValueForEmailTriggerForm($params) {
$this->load->library('form_validation');
$this->form_validation->set_data($params);
$this->setFormRuleForEmailTriggerForm();
$errors = [];
if ($this->form_validation->run() === FALSE) {
$errors = $this->form_validation->error_array();
}
return $errors;
}
public function setFormRuleForEmailTriggerForm() {
$yes_no_pattern = 'regex_match[/^(?:[0-1])$/]';
$this->form_validation->set_rules('send_mail', 'Send email', $yes_no_pattern);
$this->form_validation->set_rules('send_notification', 'Send Notification', $yes_no_pattern);
$this->form_validation->set_rules('status', 'Status', $yes_no_pattern);
}
public function generateCard() {
$out = array();
$notice_id = (int) $this->input->get('notice_id');
$member_id = (int) $this->input->get('member_id');
$message = "";
global $trigger_card;
// print_r($trigger_card);
$trigger_key = "";
$dynamic_key = "";
$status_msg = '';
$cat = '';
if ($notice_id != '' && $member_id != '') {
$mysql = "SELECT * FROM members_notification WHERE id=$notice_id AND member_id=$member_id";
$query = $this->read_replica->query($mysql);
$row = $query->row();
if (isset($row)) {
$trigger_key = $row->trigger_key;
$message = $row->msg;
}
$card_allowded = false;
print_r( $trigger_card );
// print_r( $trigger_key );
// echo $trigger_key." -:- ".$trigger_card;
if (array_key_exists($trigger_key, $trigger_card)) {
$status_msg = "The $trigger_key is in the array";
// print_r( $trigger_card[$trigger_key] );
$dynamic_key = $trigger_card[$trigger_key]["dynamic_key"];
$cat = $trigger_card[$trigger_key]["cat"];
$card_allowded = true;
} else {
$status_msg = "The $trigger_key not set up for cards";
}
if (true == $card_allowded && $message != '' && $trigger_key != '' && $dynamic_key != '') {
$in = array();
$in["dynamic_key"] = $dynamic_key;
$in["member_id"] = $member_id;
$in["trigger_key"] = $trigger_key;
$in["message"] = $message;
$in["notice_id"] = $notice_id;
$in["cat"] = $cat;
$in['action'] = FLOAT_SYSTEM_CREATE_DYNAMICCARD;
$ret = $this->savvy_api($in, $out);
print_r($out);
if ($ret == PHP_API_OK) {
$message = 'Completed!';
} else {
$message = 'Failed to Create';
}
}
}
echo $status_msg;
}
public function sendAllnotification(){
$this->sendnotification();
$this->generateCard();
}
public function sendnotification() {
//notice_id='+notice_id+'&member_id=' + member_id
// echo 'Ameye';
$out = array();
$message = "";
$notice_id = (int) $this->input->get('notice_id');
$member_id = (int) $this->input->get('member_id');
if ($notice_id != '' && $member_id != '') {
// get the message
/*
* savvy=> SELECT * FROM members_notification WHERE member_id =1 AND id = 4967;;
id | member_id | notice_type | msg | status | added | mmode | trigger_key
------+-----------+-------------+---------------------------------------------+--------+---------------------------+-------+-------------
4967 | 1 | GENALERT | You are spending too much. Let's save money | 1 | 2020-02-23 04:00:03.58477 | AUTO | ETRG0003
(1 row)
*/
$mysql = "SELECT * FROM members_notification WHERE member_id = ${member_id} AND id = ${notice_id}"; //SELECT * FROM members_devices WHERE member_id=${member_id}";
$query = $this->read_replica->query($mysql);
$row = $query->row();
if (isset($row)) {
$message = $row->msg;
}
//echo $message;
$device_count = 0;
$q = "SELECT * FROM members_devices WHERE member_id=${member_id}";
$r = $this->read_replica->query($q);
foreach ($r->result() as $row) {
$data["devices"][] = $row->player_id;
$device_count++;
}
// $data["devices"] = ['a','b','c'];
$arrayData = array("NEXTSCREEN" => "bar");
if ($device_count > 0 && $message != '') {
$this->load->model('onesignal_model');
// print_r($data["devices"]);
$out = $this->onesignal_model->sendmemberMessage($member_id, $data["devices"], $message, $arrayData);
// print_r($out);
}
}
}
protected function renderNotificationPage($page_name, $data) {
$this->load->view('admin/view_admin_header', $data);
$this->load->view('notifications/' . $page_name, $data);
$this->load->view('admin/view_admin_footer', $data);
}
public function update() {
$result = $this->notification->updateDescription([
'id' => $this->input->post('id'),
'description' => $this->input->post('description'),
]);
echo json_encode([
'message' => $result ? "Updated" : "Failed",
'code' => $result ? 1 : 0
]);
}
public function update_trigger() {
// echo "updateTriggerItem Ameye";
// url: "/notifications/updateTriggerItem?category_settings=" + category_settings + "&e_trigger=" + e_trigger
$data = array();
$this->load->model('combo_model');
$points_settings_value = '';
$message_card = "";
if ($this->input->get()) {
$category_settings = $this->input->get('category_settings');
$e_trigger = $this->input->get('e_trigger');
$card_settings = $this->input->get('card_settings');
$override_text = $this->input->get('override_text');
$expiration = $this->input->get('expiration');
$mysql = "SELECT e.*,m.id AS card_id FROM email_trigger e LEFT JOIN main_cards m ON m.dynamic_key = e.dynamic_key WHERE e.e_trigger='$e_trigger'";
$query = $this->read_replica->query($mysql);
$mr = $query->row_array();
$data["e_trigger"] = $mr["e_trigger"];
$data["category"] = $mr["category"];
$dynamic_key = $mr["dynamic_key"];
$card_id = $mr["card_id"];
if ($e_trigger != '' && $category_settings != '' && $card_settings != '') {
$mysql = "UPDATE email_trigger SET category='$category_settings',override_text=$override_text,expiration='$expiration' WHERE e_trigger='$e_trigger'";
$query = $this->db->query($mysql);
$mysql = "SELECT * FROM main_cards WHERE dynamic_key='$dynamic_key' ";
$query = $this->read_replica->query($mysql);
if ($query->num_rows() == 0) {
$message_card = "Okay not in use";
$mysql = "UPDATE main_cards SET dynamic_key='$dynamic_key' WHERE id = $card_settings AND dynamic_key IS NULL";
$this->db->query($mysql);
} else {
$message_card = "This is in use";
}
$message = "Updated <br>" . $message_card;
echo $message;
}
}
}
public function editTrigger() {
$data = array();
$this->load->model('combo_model');
$points_settings_value = '';
if ($this->input->get()) {
$trigger_id = $this->input->get('trigger_id');
/*
id | e_trigger | category | action_detail | template_name | status | added | updated | dynamic_key | message | send_mail | send_notification
----+-----------+------------+------------------------------------------+---------------+--------+----------------------------+----------------------------+-------------+-------------------------------+-----------+-------------------
2 | ETRG0002 | GOACTIVITY | <p>Good Job, you&#39;re saving money</p>+| etrg0002.html | 1 | 2020-02-18 15:06:46.721542 | 2020-02-18 15:06:46.721542 | ETRG0002KEY | Good Job, you're saving money | 0 | 1
| | | | | | | | | | |
(1 row)
*/
if ($trigger_id != '') {
$mysql = "SELECT e.*,m.id AS card_id FROM email_trigger e LEFT JOIN main_cards m ON m.dynamic_key = e.dynamic_key WHERE e.e_trigger='$trigger_id'";
$query = $this->read_replica->query($mysql);
$mr = $query->row_array();
// print_r($mr);
$data["e_trigger"] = $mr["e_trigger"];
$data["category"] = $mr["category"];
$data["dynamic_key"] = $mr["dynamic_key"];
$data["card_id"] = $mr["card_id"];
$data["override_text"] = $mr["override_text"];
$data["expiration"] = $mr["expiration"];
// $this->memberPointsItems($member_id, $data);
$data["category_settings"] = $this->combo_model->getCardCategoryCombo("category_settings", $data["category"], '', 'CARDDYNAMIC');
// $data['member_id'] = $member_id;
$data['card_settings'] = $this->combo_model->getTriggerCardsCombo("card_settings", $data["card_id"]);
$data["override_text_combo"] = $this->combo_model->getYesNoCombo("override_text", $data["override_text"]);
$data["expiration_combo"] = $this->combo_model->getTriggerExpirationCombo("expiration", $data["expiration"]);
$this->load->view('notifications/extra/notifications_extra', $data);
}
}
}
}
+149
View File
@@ -0,0 +1,149 @@
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Parsed_Receipts extends Admin_Controller {
public function __construct() {
parent::__construct();
$this->load->helper('form');
$this->load->library('form_validation');
$this->load->library('session');
$this->load->library('table');
$this->load->model('parsed_item_payment_model');
$this->load->model('combo_model');
}
public function index() {
$data['page_title'] = 'Parsed Receipts';
$this->table->set_template($this->template);
$this->table->set_heading([
'User ID',
'User Email',
'Merchant Name',
'Receipt(Travel) Date',
'Receipt Parsed Date',
'Amount',
'Currency',
'Transport Provider ID',
'Tracked Email ID',
'Category'
]);
$params = $this->getValueOfParsedReceipts();
$data['card_transport_provider'] =
$this
->combo_model
->getTransportProvidersCombo(
'card_transport_provider',
$params['transport_provider_id']
);
$params = array_filter($params, function($ele) {
return $ele !== "";
});
$errors = $this->validateValueForParsedReceipts($params);
$params = array_diff_key($params, $errors);
$data = array_merge(
$data,
$params,
$this->load_pagination(
$this
->parsed_item_payment_model
->get_parsed_item_payment_record($params)[0]['all_count'],
$params,
'index'
)
);
$records = $this->parsed_item_payment_model->get_parsed_item_payment_record(
$params, SELF::NONE_COUNT_RECORD, $data['limit'], $data['offset']
);
$data['parsed_item_payment_table'] = $this->table->generate($records);
$this->renderParsedReceiptsPage('view_parsed_item_payment', $data);
}
public function getValueOfParsedReceipts() {
return [
'from_date' => trim($this->input->get('from_date')),
'to_date' => trim($this->input->get('to_date')),
'transport_provider_id' => trim($this->input->get('card_transport_provider'))
? trim($this->input->get('card_transport_provider'))
: trim($this->input->get('transport_provider_id')),
'category' => trim($this->input->get('category')),
'email' => trim($this->input->get('email')),
];
}
public function validateValueForParsedReceipts($params) {
$this->load->library('form_validation');
$this->form_validation->set_data($params);
$this->setFormRuleForParsedReceipts();
$errors = [];
if ($this->form_validation->run() === FALSE) {
$errors = $this->form_validation->error_array();
}
return $errors;
}
public function setFormRuleForParsedReceipts() {
$date_pattern = 'regex_match[/\d{4}-\d{2}-\d{2}/]';
$this->form_validation->set_rules('from_date', 'from_date', $date_pattern);
$this->form_validation->set_rules('to_date', 'to_date', $date_pattern);
$this->form_validation->set_rules('transport_provider_id', 'transport_provider_id', 'integer');
}
public function load_pagination($total_record, $params, $action) {
// pagination
$this->load->library('pagination');
$config["total_rows"] = $total_record;
$config["base_url"] = base_url() . '/' . get_class($this) . '/' . $action;
$config["per_page"] = 10;
$config["uri_segment"] = 3;
$config["num_links"] = 5;
$config["suffix"] = '?'
. http_build_query($params);
$config["first_url"] = '/' . get_class($this) . "/{$action}/0?"
. http_build_query($params);
$config['full_tag_open'] = "<ul class='pagination'>";
$config['full_tag_close'] = "</ul>";
$config['num_tag_open'] = '<li>';
$config['num_tag_close'] = '</li>';
$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
$config['next_tag_open'] = "<li>";
$config['next_tagl_close'] = "</li>";
$config['prev_tag_open'] = "<li>";
$config['prev_tagl_close'] = "</li>";
$config['first_tag_open'] = "<li>";
$config['first_tagl_close'] = "</li>";
$config['last_tag_open'] = "<li>";
$config['last_tagl_close'] = "</li>";
$this->pagination->initialize($config);
$page = ( $this->uri->segment(3) ) ? $this->uri->segment(3) : 0;
$offset = is_numeric($page) ? $page : 0;
return [
'link' => $this->pagination->create_links(),
'offset' => $offset,
'limit' => $config["per_page"]
];
}
protected function renderParsedReceiptsPage($page_name, $data) {
$this->load->view('admin/view_admin_header', $data);
$this->load->view('parsed_receipts/' . $page_name, $data);
$this->load->view('admin/view_admin_footer', $data);
}
}
@@ -0,0 +1,205 @@
<?php
defined('BASEPATH') or exit('No direct script access allowed');
class Phone_farm_phones extends Admin_Controller
{
public $viewData = array();
public $pagePerItem = 20;
public $statusOptions = [
'Inactive' => 0,
'Active' => 1,
'Ping Failure' => 2,
'GPS Telnet Failure' => 3,
'Other Failure' => 4,
];
public function __construct()
{
parent::__construct();
// Load model
$this->load->model('phone_farm_phone_model', 'phone_farm_phone');
$this->load->helper('pagination');
}
public function index()
{
$this->load->helper(array('url'));
//get query string filter
$filterData = $this->input->get();
$queryString = $this->input->server('QUERY_STRING');
// remove empty value
$filterData = array_filter($filterData, function ($v, $k) {
return $v != '';
}, ARRAY_FILTER_USE_BOTH);
$pagingUrl = empty($queryString) ? uri_string() : uri_string() . '?' . $queryString;
$pagingUrl = remove_querystring_var($pagingUrl, 'page');
$data = $this->phone_farm_phone->getPhones($filterData);
$this->viewData['list'] = $data['list'];
$this->viewData['statusOptions'] = $this->statusOptions;
$this->viewData['filterData'] = $filterData;
$this->viewData['pagination'] = initPagination($this->pagePerItem, $data['totalItems'], $data['page'], $pagingUrl);
$this->renderAdminPage('phone_farm_phones/list', $this->viewData);
}
public function create()
{
$this->load->helper(array('form', 'url'));
$this->viewData['statusOptions'] = $this->statusOptions;
$this->viewData['phone'] = null;
$this->renderAdminPage('phone_farm_phones/create', $this->viewData);
}
public function store()
{
$this->load->helper(array('form', 'url'));
$this->load->library('form_validation');
$this->viewData['phone'] = null;
$this->viewData['statusOptions'] = $this->statusOptions;
$this->setPhoneCreationRules();
if ($this->form_validation->run() == false) {
$this->renderAdminPage('phone_farm_phones/create', $this->viewData);
return;
}
$inputData = $this->getFormData();
$res = $this->phone_farm_phone->createPhone($inputData);
if ($res['status'] == 'success') {
$this->session->set_flashdata('success', isSet($res['message']) ? $res['message'] : 'Create success.');
redirect('/phone_farm_phones');
} else {
$this->session->set_flashdata('error', isSet($res['message']) ? $res['message'] : 'Create fail.');
$this->renderAdminPage('phone_farm_phones/create', $this->viewData);
return;
}
}
public function edit($id)
{
$this->load->helper(array('form', 'url'));
$res= $this->phone_farm_phone->getPhoneById($id);
$this->viewData['phone'] = isSet($res['data']) ? $res['data'] : [];
$this->viewData['statusOptions'] = $this->statusOptions;
$this->viewData['phoneId'] = $id;
$this->renderAdminPage('phone_farm_phones/edit', $this->viewData);
}
public function update($id)
{
$this->load->helper(array('form', 'url'));
$this->load->library('form_validation');
$this->viewData['statusOptions'] = $this->statusOptions;
$this->viewData['phone'] = null;
$this->viewData['phoneId'] = $id;
$this->setPhoneCreationRules();
if ($this->form_validation->run() == false) {
$this->renderAdminPage('phone_farm_phones/edit', $this->viewData);
return;
}
$inputData = $this->getFormData();
$inputData['id'] = (int) $id;
$res = $this->phone_farm_phone->updatePhoneById($id, $inputData);
if ($res['status'] == 'success') {
$this->session->set_flashdata('success', isSet($res['message']) ? $res['message'] : 'Create success');
redirect('/phone_farm_phones');
} else {
$this->session->set_flashdata('error', $res['message']);
$this->renderAdminPage('phone_farm_phones/edit', $this->viewData);
return;
}
}
public function remove($param)
{
$res = $this->phone_farm_phone->removePhoneById($param);
if (!$res['success'] != 'success') {
$this->viewData['errMsg'] = isSet($res['message']) ? $res['message'] : 'Something went wrong. Please try again later.';
$this->renderAdminPage('phone_farm_phones', $this->viewData);
return;
}
redirect('/phone_farm_phones');
}
protected function renderAdminPage($page_name, $data) {
$this->load->view('admin/view_admin_header', $data);
$this->load->view($page_name, $data);
$this->load->view('admin/view_admin_footer', $data);
}
private function getFormData() {
return [
'phone_name' => $this->input->post('phone_name'),
'phone_model' => $this->input->post('phone_model'),
'phone_vendor' => $this->input->post('phone_vendor'),
'phone_serial' => $this->input->post('phone_serial'),
'ip_address' => $this->input->post('ip_address'),
'gps_emulator_port' => $this->input->post('gps_emulator_port'),
'phone_number' => $this->input->post('phone_number'),
'status' => (int) $this->input->post('status'),
];
}
private function setPhoneCreationRules()
{
$config = [
[
'field' => 'phone_name',
'label' => 'Name',
'rules' => 'required|max_length[12]',
'errors' => array(
'max_length' => 'Max length is 20.'
),
],
[
'field' => 'phone_model',
'label' => 'Model',
'rules' => 'required|max_length[40]',
'errors' => array(
'max_length' => 'Max length is 40.'
)
],
[
'field' => 'phone_vendor',
'label' => 'Vendor',
'rules' => 'required|max_length[40]',
'errors' => array(
'max_length' => 'Max length is 40.'
)
],
[
'field' => 'phone_serial',
'label' => 'Serial',
'rules' => 'required|max_length[20]',
'errors' => array(
'max_length' => 'Max length is 20.',
)
],
[
'field' => 'phone_number',
'label' => 'Phone number',
'rules' => 'required|max_length[20]',
'errors' => array(
'max_length' => 'Max length is 20.'
)
]
];
$this->form_validation->set_rules($config);
}
}
+463
View File
@@ -0,0 +1,463 @@
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Points extends Admin_Controller {
public function __construct()
{
parent::__construct();
$this->load->model('point_model');
$this->load->model('combo_model');
}
public function index() {
$data = array();
$this->load->helper('url');
$this->reportpoints();
}
protected function renderPointsPage($page_name, $data) {
$this->load->view('admin/view_admin_header', $data);
$this->load->view('points/' . $page_name, $data);
$this->load->view('admin/view_admin_footer', $data);
}
public function getValueOfPointReport() {
return [
'member_id' => trim($this->input->get('member_id') ?? ''),
'description' => trim($this->input->get('description') ?? ''),
'id' => trim($this->input->get('id') ?? ''),
'from_points' => trim($this->input->get('from_points') ?? ''),
'to_points' => trim($this->input->get('to_points') ?? ''),
'from_date' => trim($this->input->get('from_date') ?? ''),
'to_date' => trim($this->input->get('to_date') ?? ''),
'status' => trim($this->input->get('card_status')
?? ($this->input->get('status') ?? -1)),
];
}
public function setOnePastMonth(&$params, $default_date = 'on') {
if (strcmp($default_date, 'on') === 0) {
$params['from_date'] = date("Y-m-d", strtotime("-1 months"));
$params['to_date'] = date("Y-m-d");
}
}
public function setComboForPointReport($params) {
$this->load->model('combo_model');
$combo['card_status'] = $this->combo_model->getStatusComboFromZeroToNine(
'card_status',
$params['status']
);
return $combo;
}
public function getValueCombo($val) {
$status_value = range(0, 9);
return in_array($val, $status_value)
? $val
: '';
}
public function validateValueForPointReport($params) {
$this->load->library('form_validation');
$this->form_validation->set_data($params);
$this->setFormRuleForPointReportForm();
$errors = [];
if ($this->form_validation->run() === FALSE) {
$errors = $this->form_validation->error_array();
}
return $errors;
}
public function setFormRuleForPointReportForm() {
$status_pattern = 'regex_match[/^(?:[0-9])$/]';
$date_pattern = 'regex_match[/\d{4}-\d{2}-\d{2}/]';
$this->form_validation->set_rules('member_id', 'Member ID', 'numeric');
$this->form_validation->set_rules('id', 'ID', 'numeric');
$this->form_validation->set_rules('from_points', 'From Points', 'numeric');
$this->form_validation->set_rules('to_points', 'To Points', 'numeric');
$this->form_validation->set_rules('from_date', 'From Added', $date_pattern);
$this->form_validation->set_rules('to_date', 'To Added', $date_pattern);
$this->form_validation->set_rules('status', 'Status', $status_pattern);
}
public function load_pagination($all_record, $params, $action) {
$action_hidden = $this->input->get('action_hidden');
// pagination
$this->load->library('pagination');
$config["total_rows"] = count($all_record);
$config["base_url"] = base_url() . "/points/" . $action;
$config["per_page"] = 10;
$config["uri_segment"] = 3;
$config["num_links"] = 5;
$config["suffix"] =
"?action_hidden=${action_hidden}&"
. http_build_query($params);
$config["first_url"] =
"/points/{$action}/0?action_hidden=${action_hidden}&"
. http_build_query($params);
$config['full_tag_open'] = "<ul class='pagination'>";
$config['full_tag_close'] = "</ul>";
$config['num_tag_open'] = '<li>';
$config['num_tag_close'] = '</li>';
$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
$config['next_tag_open'] = "<li>";
$config['next_tagl_close'] = "</li>";
$config['prev_tag_open'] = "<li>";
$config['prev_tagl_close'] = "</li>";
$config['first_tag_open'] = "<li>";
$config['first_tagl_close'] = "</li>";
$config['last_tag_open'] = "<li>";
$config['last_tagl_close'] = "</li>";
$this->pagination->initialize($config);
$page = ( $this->uri->segment(3) ) ? $this->uri->segment(3) : 0;
$offset = is_numeric($page) ? $page : 0;
return [
'link' => $this->pagination->create_links(),
'offset' => $offset,
'limit' => $config["per_page"]
];
}
public function reportpoints() {
$this->load->model('report_point_model');
$this->load->library('table');
$this->table->set_template($this->template);
$this->table->set_heading([
'FirstName',
'Lastname',
'ID',
'Description',
'Points',
'Added',
'Status',
]);
$params = $this->getValueOfPointReport();
$default_date = $this->input->get('default_date');
if ($this->input->get('action_hidden')) {
$this->setOnePastMonth($params, $default_date);
} else {
$this->setOnePastMonth($params);
}
$data = $this->setComboForPointReport($params);
$params['status'] = $this->getValueCombo($params['status']);
$params = array_filter($params, function($ele) {
return $ele !== "";
});
$errors = $this->validateValueForPointReport($params);
$params = array_diff_key($params, $errors);
$data = array_merge(
$data,
$params,
$this->load_pagination(
$this->report_point_model->get_report_point_records($params),
$params,
'index'
)
);
$data['points_report'] = $this->table->generate(
$this->report_point_model->get_report_point_records(
$params,
$data['limit'],
$data['offset']
)
);
if ($this->input->get('action_hidden')) {
$data['default_date'] = $default_date;
} else {
$data['default_date'] = 'on';
}
$data["page_title"] = "Points Redemption";
$this->renderPointsPage("view_pointsreport", $data);
}
public function getValueOfAssignsReport() {
return [
'search_text' => trim($this->input->get('search_text') ?? ''),
'find_select_value' =>
trim( ! empty($this->input->get('find_select'))
? $this->input->get('find_select')
: $this->input->get('find_select_value')),
'from_points' => trim($this->input->get('from_points') ?? ''),
'to_points' => trim($this->input->get('to_points') ?? ''),
];
}
public function setComboForAssignsReport($params) {
$this->load->model('combo_model');
$combo['find_select'] = $this->combo_model->getfindMemberType(
'find_select',
$params['find_select_value']
);
$combo['descsion_group'] = $this->combo_model->getDescisionGroupCombo(
'descsion_group',
trim($this->input->post('decision_group') ?? '')
);
return $combo;
}
public function validateValueForAssignsReport($params) {
$this->load->library('form_validation');
$this->form_validation->set_data($params);
$this->setFormRuleForAssignsReport();
$errors = [];
if ($this->form_validation->run() === FALSE) {
$errors = $this->form_validation->error_array();
}
return $errors;
}
public function setFormRuleForAssignsReport() {
$this->form_validation->set_rules(
'find_select_value',
'Select Value',
'in_list[email,firstname,lastname]'
);
$this->form_validation->set_rules(
'from_points',
'Points',
'numeric'
);
$this->form_validation->set_rules(
'to_points',
'Points',
'numeric'
);
}
public function assignpoints() {
$this->load->model('assigns_point_model');
$this->load->library('table');
$this->table->set_template($this->template);
$this->table->set_heading([
'ID',
'Username',
'FirstName',
'LastName',
'Points',
'Act',
]);
$params = $this->getValueOfAssignsReport();
$data = $this->setComboForAssignsReport($params);
$errors = $this->validateValueForAssignsReport($params);
$params = array_filter($params, function($ele) {
return $ele !== "";
});
$params = array_diff_key($params, $errors);
if (isset($params['search_text'])) {
// set ['email' => 'test@gmail.com']
$params[$params['find_select_value']] = $params['search_text'];
}
$data = array_merge(
$data,
$params,
$this->load_pagination(
$this->assigns_point_model->get_assigns_point_records($params),
$params,
'assignpoints'
)
);
$data['points_report'] = $this->table->generate(
$this->assigns_point_model->get_assigns_point_records(
$params,
$data['limit'],
$data['offset']
)
);
$data["page_title"] = "Allocate Point";
$this->renderPointsPage("view_assignpoints", $data);
}
public function viewAssignDetail() {
$data = array();
$this->load->model('combo_model');
$points_settings_value = '';
if ($this->input->get()) {
$member_id = $this->input->get('member_id');
if ($member_id != '' && $member_id > 0) {
$this->memberPointsItems($member_id, $data);
$data["points_settings"] = $this->combo_model->getPointsSettingsCombo("points_settings", $points_settings_value);
$data['member_id'] = $member_id;
$mysql = "SELECT * FROM members WHERE id = " . $member_id;
$query = $this->read_replica->query($mysql);
$mr = $query->row_array();
// print_r($mr);
$data["firstname"] = $mr["firstname"];
$data["lastname"] = $mr["lastname"];
$data["email"] = $mr["email"];
$this->load->view('points/extra/point_extra', $data);
}
/*
/*
$mysql = "SELECT a.*,a.id AS member_id, b.format AS picture_format ";
$mysql .= " FROM members a LEFT JOIN card_images b ON (b.id=a.profile_picture) WHERE a.id = $member_id";
$query = $this->db->query($mysql);
$data = $query->row_array();
$data["devices"] = [];
$data['storage'] = $savvyext->cfgReadChar('system.storage_url');
$data['start_date'] = $this->input->get('start_date');
$data['end_date'] = $this->input->get('end_date');
$data['status'] = !is_null($this->input->get('card_status')) ? $this->input->get('card_status') : 1;
$data['card_status'] = $this->combo_model->getStatusCombo(
'card_status', $data['status']
);
$q = "SELECT * FROM members_devices WHERE member_id=${member_id}";
$q .= $this->query_condition_member_detail($data);
$r = $this->db->query($q);
foreach ($r->result() as $row) {
$data["devices"][] = $row->player_id;
}
$this->load->view('points/extra/point_extra', $data);
} else {
echo "Not found - illegal call";
}
*/
}
}
private function memberPointsItems($member_id, &$data) {
$this->load->library('table');
$this->table->set_template($this->template);
$data['points_recieved'] = '';
$mysql = "SELECT s.point_key,s.name,p.points,p.added::date "
. " FROM members_points p "
. " LEFT JOIN points_settings s ON s.point_key=p.point_key "
. " WHERE p.member_id = " . $member_id . " ORDER BY p.added DESC";
$query = $this->read_replica->query($mysql);
$data["points_recieved"] = $this->table->generate($query);
return $data;
}
public function SendMemberPoints() {
// echo "ameye aaaa olusesan bbbb";
$data = array();
$this->load->model('combo_model');
$points_settings_value = '';
if ($this->input->get()) {
$member_id = $this->input->get('member_id');
$point_key = $this->input->get('point_key');
if ($member_id != '' && $member_id > 0) {
$in = array();
$in["action"] = SAVVY_BKO_ASSIGN_POINTS;
$in['member_id'] = $member_id; // for session testing - not used
$in['point_key'] = $point_key;
$out = array();
$ret = $this->savvy_api($in, $out);
// print_r($out);
$message = $out["status_message"];
// if ($ret == PHP_API_OK) {
// $message = $out["status_message"];
// } else {
// $message = $out["status_message"];
// }
echo $message;
}
}
// $this->load->view('points/extra/point_extra', $data);
}
/**
* Systemic Points Summary Report
*
* @return view
*/
public function systemicPointsSummary() {
$data_report = $this->point_model->getSystemicPointsSummary();
$data = [
'page_title' => 'Systemic Points Summary',
'data_report' => $data_report,
'country_filter' => $this->combo_model->getCountriesHasAccount('country_filter', ''),
'point_key' => $this->combo_model->getPointKeyUsed('point_key', ''),
'point_value' => $this->combo_model->getPointValueUsed('point_value', ''),
];
$this->renderPointsPage('view_systemic_points_summary', $data);
}
public function getSystemicPointsDatatables() {
$data = $this->point_model->getSystemicPointsDatatables($this->input->post(), 'search');
header('Content-Type: application/json');
echo json_encode($data);
}
public function systemicPointsReportCSV()
{
$this->load->library('session');
$postData = $this->session->userdata("SPR_PARAM");
if ($postData) {
$this->point_model->getSystemicPointsDatatables($postData, 'export_csv');
} else {
echo 'Please try again!';
die();
}
}
}
@@ -0,0 +1,63 @@
<?php
defined('BASEPATH') or exit('No direct script access allowed');
class Quote_Estimates extends Admin_Controller
{
public $viewData = array();
public $pagePerItem = 10;
public function __construct()
{
parent::__construct();
// Load model
$this->load->model('quote_estimate_model', 'quoteEstimate');
$this->viewData['selectedTab'] = 'quote_estimate';
$this->load->helper('pagination');
}
public function index()
{
$this->viewData['pagination'] = initPagination($this->pagePerItem, 95, 1, '/quote_estimates');
$this->viewData['list'] = $this->quoteEstimate->getQuoteEstimates();
$this->renderAdminPage('quote_estimates/list', $this->viewData);
}
public function create()
{
$this->template->load('quote_estimates/create', $this->viewData);
}
public function createQuoteEstimate()
{
redirect('/quote_estimates');
}
public function edit()
{
redirect('/quote_estimates');
}
public function search()
{
$this->viewData['pagination'] = initPagination($this->pagePerItem, 50, 1, '/quotes_estimates');
$this->viewData['list'] = $this->address->getAddresses();
$this->template->load('quote_estimates/list', $this->viewData);
}
public function quoteEstimateDetail($param)
{
$this->template->load('quote_estimates/edit', $this->viewData);
}
public function remove($param)
{
redirect('/addresses');
}
protected function renderAdminPage($page_name, $data) {
$this->load->view('admin/view_admin_header', $data);
$this->load->view($page_name, $data);
$this->load->view('admin/view_admin_footer', $data);
}
}
+62
View File
@@ -0,0 +1,62 @@
<?php
defined('BASEPATH') or exit('No direct script access allowed');
class Quotes extends Admin_Controller
{
public $viewData = array();
public $pagePerItem = 10;
public function __construct()
{
parent::__construct();
// Load model
$this->load->model('quote_model');
$this->viewData['selectedTab'] = 'quote';
$this->load->helper('pagination');
}
public function index()
{
$this->viewData['pagination'] = initPagination($this->pagePerItem, 95, 1, '/quotes');
$this->viewData['list'] = $this->quote_model->getQuotes();
$this->renderAdminPage('quotes/list', $this->viewData);
}
public function create()
{
$this->template->load('quotes/create', $this->viewData);
}
public function createQuote()
{
redirect('/quotes');
}
public function edit()
{
redirect('/edit');
}
// public function search() {
// $this->viewData['pagination'] = initPagination($this->pagePerItem, 50, 1, '/address');
// $this->viewData['list'] = $this->address->getAddresses();
// $this->template->load('addresses/list', $this->viewData);
// }
public function quoteDetail($param)
{
$this->template->load('quotes/edit', $this->viewData);
}
public function remove($param)
{
redirect('/quotes');
}
protected function renderAdminPage($page_name, $data) {
$this->load->view('admin/view_admin_header', $data);
$this->load->view($page_name, $data);
$this->load->view('admin/view_admin_footer', $data);
}
}
+432
View File
@@ -0,0 +1,432 @@
<?php
defined('BASEPATH') or exit('No direct script access allowed');
use Phpml\Regression\LeastSquares;
class Report extends Admin_Controller
{
public function __construct()
{
parent::__construct();
$this->load->model('report_model');
}
public function chart()
{
ini_set('memory_limit', '256M');
$params = $this->input->get();
$data = [];
$errors = [];
$chartData1 = [];
$chartData2 = [];
$data['transport_providers_dropdown'] = [
['id' => 1, 'name' => 'Uber', 'color' => 'rgb(45, 230, 92)'],
['id' => 2, 'name' => 'Lyft', 'color' => 'rgb(255, 0, 255)'],
['id' => 3, 'name' => 'Grab' , 'color' => 'rgb(54, 162, 235)'],
['id' => 4, 'name' => 'ComfortDelGro', 'color' => 'rgb(0, 255, 255)'],
['id' => 5, 'name' => 'GOJEK', 'color' => 'rgb(255, 191, 0)'],
];
if (!empty($params)) {
// get data for period of time 1
$period1_input = [
'start_date' => $params['start_date_1'] ?? '',
'end_date' => $params['end_date_1'] ?? '',
'transport_providers' => $params['transport_providers'] ?? '',
];
// get data for period of time 2
$period2_input = [
'start_date' => $params['start_date_2'] ?? '',
'end_date' => $params['end_date_2'] ?? '',
'transport_providers' => $params['transport_providers'] ?? '',
];
// chart1 and chart2 are same data (just different how to plot chart) => load first to have good performance
$loadDataFromDatabase1 = $response = $this->report_model->getPriceComparisonTrend($period1_input); // for period of time 1
$loadDataFromDatabase2 = $response = $this->report_model->getPriceComparisonTrend($period2_input); // for period of time 2
$chartDataResponse1 = $this->getChartData1($loadDataFromDatabase1, $loadDataFromDatabase2, $data['transport_providers_dropdown']);
$chartDataResponse2 = $this->getChartData2($loadDataFromDatabase1, $loadDataFromDatabase2, $data['transport_providers_dropdown']);
if (!$chartDataResponse1['success'] || !$chartDataResponse2['success']) {
if (!empty($chartDataResponse1['message'])) {
$errors[] = $chartDataResponse1['message'];
}
if (!empty($chartDataResponse2['message'])) {
$errors[] = $chartDataResponse2['message'];
}
} else {
$chartData1 = $chartDataResponse1['data'];
$chartData2 = $chartDataResponse2['data'];
}
}
$data['chartData1'] = json_encode($chartData1);
$data['chartData2'] = json_encode($chartData2);
$data['filterData'] = $params;
$data['errors'] = $errors;
$this->renderAdminPage('report/view_price_comparison_trend', $data);
}
public function getChartData2(array $loadDataFromDatabase1, array $loadDataFromDatabase2, array $transport_providers_map)
{
$errors = [];
$datasets = [];
$general_index_date_map = [];
$datasets_1 = $this->generateChartDataset(
$loadDataFromDatabase1,
$transport_providers_map,
$general_index_date_map,
'Period1'
);
$datasets_2 = $this->generateChartDataset(
$loadDataFromDatabase2,
$transport_providers_map,
$general_index_date_map,
'Period2'
);
if (!$datasets_1['success'] || !$datasets_2['success']) {
if (!empty($datasets_1['message'])) {
$errors[] = $datasets_1['message'];
}
if (!empty($datasets_2['message'])) {
$errors[] = $datasets_2['message'];
}
} else {
$datasets = array_merge($datasets_1['data'], $datasets_2['data']);
}
if (!empty($errors)) {
return [
'success' => false,
'message' => $errors[0]
];
}
$chartData = [
'datasets' => $datasets,
'general_index_date_map' => $general_index_date_map ?? [],
];
return [
'success' => true,
'data' => $chartData
];
}
public function getChartData1(array $loadDataFromDatabase1, array $loadDataFromDatabase2, array $transport_providers_map)
{
$errors = [];
$datasets = [];
$index_date_map_1 = [];
$index_date_map_2 = [];
$datasets_1 = $this->generateChartDataset(
$loadDataFromDatabase1,
$transport_providers_map,
$index_date_map_1,
'Period1',
true
);
$datasets_2 = $this->generateChartDataset(
$loadDataFromDatabase2,
$transport_providers_map,
$index_date_map_2,
'Period2',
true
);
if (!$datasets_1['success'] || !$datasets_2['success']) {
if (!empty($datasets_1['message'])) {
$errors[] = $datasets_1['message'];
}
if (!empty($datasets_2['message'])) {
$errors[] = $datasets_2['message'];
}
} else {
$datasets = array_merge($datasets_1['data'], $datasets_2['data']);
}
if (!empty($errors)) {
return [
'success' => false,
'message' => $errors[0]
];
}
$chartData = [
'datasets' => $datasets,
'index_date_map_1' => $index_date_map_1 ?? [],
'index_date_map_2' => $index_date_map_2 ?? [],
];
return [
'success' => true,
'data' => $chartData
];
}
protected function generateChartDataset(
array $loadDataFromDatabase,
array $transport_providers_map,
array &$index_date_map,
string $period_name,
bool $is_mutiple_x_axis = false) : array
{
if (!$loadDataFromDatabase['success']) {
return [
'success' => false,
'message' => $loadDataFromDatabase['message']
];
}
$datasets = [];
$dataset = [];
$i = count($index_date_map);
foreach ($loadDataFromDatabase['data'] as $key => $item) {
if (!array_key_exists($item['travel_date'], $index_date_map))
{
$index_date_map[$item['travel_date']] = $i;
$i++;
}
$dataset[$item['transport_provider_id']][] = [
'x' => $index_date_map[$item['travel_date']],
'count' => (int) $item['count'],
'y' => $item['cost']
];
}
foreach ($dataset as $transport_provider_id => $chart_data ) {
$found_key = array_search($transport_provider_id, array_column($transport_providers_map, 'id'));
if ($found_key === FALSE) {
continue;
}
$label = $transport_providers_map[$found_key]['name'];
$color = $transport_providers_map[$found_key]['color'];
// add scatter (data point)
$dataset_item = [
'type' => 'scatter',
'showLine' => false,
'label' => $label . " (${period_name})",
// only get [x, y] points to plot chart
'data' => array_map(function($el) {
return ['x' => $el['x'], 'y' => $el['y']];
}, $chart_data),
'backgroundColor' => $color
];
// add trend line based on scatter
$trendLineData = $this->calculateTrendLine($chart_data);
$trend_line_dataset = [
'type' => 'line',
'showLine'=> true,
'fill' => false,
'pointRadius' => 0,
'cubicInterpolationMode' => 'monotone',
'label' => $label . " - Trend line (${period_name})",
'data' => $trendLineData,
'backgroundColor' => $color,
'borderColor'=> $color,
];
if ($is_mutiple_x_axis) {
$dataset_item['xAxisID'] = 'x-' . $period_name;
$trend_line_dataset['xAxisID'] = 'x-' . $period_name;
}
$datasets[] = $dataset_item;
$datasets[] = $trend_line_dataset;
}
return [
'success' => true,
'data' => $datasets
];
}
protected function calculateTrendLine(array $data)
{
// e.g.
// $samples = [[73676, 1996], [77006, 1998], [10565, 2000], [146088, 1995]];
// $targets = [2000, 2750, 15500, 960];
$samples = array_map(function($el) {
return [$el['x'], $el['count']];
}, $data);
$targets = array_map(function($el) {
return $el['y'];
}, $data);
$regression = new LeastSquares();
$regression->train($samples, $targets);
$coefficients = $regression->getCoefficients();
$intercept = $regression->getIntercept();
$result = [];
foreach ($samples as $el) {
$y = $intercept + $el[0] * $coefficients[0] + 1 * $coefficients[1];
$result[] = ['x' => $el[0], 'y' => $y];
}
return $result;
}
public function surgePricingVaraition()
{
global $savvyext;
$this->load->helper('surge_pricing_varaition');
$regression1 = new LeastSquares();
$t = 3;
$date1 = "2020-01-01";
$date2 = "2020-05-10";
$area1 = 14;
$area2 = 11;
$areas = [
10 => 'Central - Tanglin',
11 => 'Central - Newton',
17 => 'Far East - Changi',
14 => 'Central East - Eunos'
];
$t = isset($_GET['t'])?((int)$_GET['t']):$t;
$date1 = isset($_GET['date1'])?date("Y-m-d",strtotime($_GET['date1'])):$date1;
$date2 = isset($_GET['date2'])?date("Y-m-d",strtotime($_GET['date2'])):$date2;
$area1 = isset($_GET['area1'])?((int)$_GET['area1']):$area1;
$area2 = isset($_GET['area2'])?((int)$_GET['area2']):$area2;
if (3 > $t || $t > 5) $t = 3;
if (!array_key_exists($area1,$areas)) $area1 = 14;
if (!array_key_exists($area2,$areas)) $area2 = 11;
$providers = [3 => "Grab", 5 => "Gojek", 4 => "ComfortDelGro"];
$c = '#ff5555';
list($data1,$label1,$poly1) = $this->report_model->area_to_area($area1, $area2, $date1, $date2, $t, $c);
$res1 = $this->surgePricingTrendLine($regression1, $data1);
$pub1 = $res1[0];
$c = '#5555ff';
list($data2,$label2,$poly2) = $this->report_model->area_to_area($area2, $area1, $date1, $date2, $t, $c);
$res2 = $this->surgePricingTrendLine($regression1, $data2);
$pub2 = $res2[0];
$data = array_merge($data1, $data2);
$data = [
't' => $t,
'date1' => $date1,
'date2' => $date2,
'area1' => $area1,
'area2' => $area2,
'areas' => $areas,
'providers' => $providers,
'data' => $data,
'data1' => $data1,
'data2' => $data2,
'label1' => $label1,
'label2' => $label2,
'poly1' => $poly1,
'poly2' => $poly2,
'res1' => $res1,
'res2' => $res2,
'pub1' => $pub1,
'pub2' => $pub2,
'google_api_key' => $savvyext->cfgReadChar( 'google.api_key' )
];
$this->renderAdminPage('report/view_surge_pricing_varaition', $data);
}
/***
* Email & Bank Connection Log
*/
public function emailAndBankConnectionReport()
{
$this->load->model('combo_model');
$data_report = $this->report_model->getEmailAndBankConnectionReportSummary();
$data = [
'page_title' => 'Email & Bank Connection Report',
'data_report' => $data_report,
'country_filter' => $this->combo_model->getCountriesHasAccount('country_filter', ''),
];
$this->renderAdminPage('report/view_email_and_bank_connection_report', $data);
}
public function emailAndBankConnectionReportDatatables()
{
$data = $this->report_model->getEmailBankConnectionReportDatatables($this->input->post(), 'search');
header('Content-Type: application/json');
echo json_encode($data);
}
public function emailAndBankConnectionReportCSV()
{
$this->load->library('session');
$postData = $this->session->userdata("EBCRR_PARAM");
if ($postData) {
$this->report_model->getEmailBankConnectionReportDatatables($postData, 'export_csv');
} else {
echo 'Please try again!';
die();
}
}
public function getBankAccountDetailJson()
{
$member_id = $this->input->get('member_id');
$data = $this->report_model->getBankAccountDetail($member_id);
header('Content-Type: application/json');
echo json_encode($data);
}
public function surgePricingTrendLine($regression1, $data)
{
$i = 0;
$pub1 = array();
$xs1 = [];
$ys1 = [];
$ys2 = [];
foreach ($data as $f) {
$t = $f['time'];
$pub1[$t] = array($t,$f['cost']);
$xs1[] = [$t];
$ys1[] = $f['cost'];
$i++;
}
if ($i>0) {
$regression1->train($xs1,$ys1);
}
foreach ($pub1 as $key=>$f) {
$y = $regression1->predict( [$f[0]] );
$f[2] = $y;
$pub1[$key] = $f;
}
return [$pub1,$xs1,$ys2];
}
protected function renderAdminPage($page_name, $data)
{
$this->load->view('admin/view_admin_header', $data);
$this->load->view($page_name, $data);
$this->load->view('admin/view_admin_footer', $data);
}
}
+212
View File
@@ -0,0 +1,212 @@
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Scanners extends Admin_Controller {
var $template = array(
'table_open' => "<table class='table table-striped table-hover table-bordered table-condensed'>",
'thead_open' => '<thead class=\'bg-indigo\'>',
'thead_close' => '</thead>',
'heading_row_start' => '<tr>',
'heading_row_end' => '</tr>',
'heading_cell_start' => '<th>',
'heading_cell_end' => '</th>',
'tbody_open' => '<tbody>',
'tbody_close' => '</tbody>',
'row_start' => '<tr>',
'row_end' => '</tr>',
'cell_start' => '<td>',
'cell_end' => '</td>',
'row_alt_start' => '<tr>',
'row_alt_end' => '</tr>',
'cell_alt_start' => '<td>',
'cell_alt_end' => '</td>',
'table_close' => '</table>'
);
public function index() {
$this->load->helper('url');
$data = array();
/*
$this->load->model('admindash_model');
$out = $this->admindash_model->getAdminDashData($data);
$data['recent_signup'] = $out['recent_signup'];
$this->load->model('service_model');
$outx = $this->service_model->getServiceRequestList(100);
$data['transport_request'] = $outx['service_request_list'];
$this->load->library('googlemaps');
$config['center'] = 'atalnta,GA,USA';
$config['zoom'] = 'auto';
$config['directions'] = TRUE;
$config['directionsStart'] = '4201 defoors farm trail, powder springs, GA 30127, USA';
$config['directionsEnd'] = '2324 stancrest ln, lawrenceville, 30044, GA, USA';
$config['directionsDivID'] = 'directionsDiv';
$this->googlemaps->initialize($config);
$data['map'] = $this->googlemaps->create_map();
*/
$this->load->library('table');
$this->table->set_template($this->template);
$mysql = "SELECT '<button type=\"button\" class=\"btn btn-danger btn-xs\" onclick=\"viewMember('||id||');\" >View</button>' AS action ,subject FROM trackedemail_item ";
$member_id = 0;
if ($this->input->get()) {
$member_id = (int)$this->input->get('member_id');
if ($member_id>0) {
$mysql.= " WHERE member_id='".$member_id."'";
}
}
$query = $this->read_replica->query($mysql);
$this->table->set_heading(array('data' => 'ACTION', 'style' => 'width:90px'), 'Subject');
$data['member_table'] = $this->table->generate($query);
$data['members'] = array();
$q = "SELECT id,firstname||' '||lastname||' &lt;'||email||'&gt; ' AS option FROM members ORDER BY firstname,lastname";
$r = $this->read_replica->query($q);
foreach ($r->result() as $row) {
$data['members'][$row->id] = $row->option;
}
$data['member_id'] = $member_id;
//$data['js'] = array('https://maps.googleapis.com/maps/api/js?key=AIzaSyDvjiRTxngOQyBP4zpqFlZuiquc0ROvo9c&callback=initMap');
$this->renderScannedPage('view_scannemail', $data);
// echo 'Ameye Olu';
}
public function viewscanned() {
$data = array();
if ($this->input->get()) {
$member_id = $this->input->get('member_id');
if ($member_id != '' && $member_id > 0) {
$mysql = "SELECT * FROM trackedemail_item WHERE id = $member_id";
$query = $this->read_replica->query($mysql);
$data['selected_user'] = $query->row_array();
// print_r($data);
$this->load->view('scanned/extra/scanned_activity', $data);
}
}
/*
$this->load->model('admindash_model');
$out = $this->admindash_model->getAdminDashData($data);
$data['recent_signup'] = $out['recent_signup'];
$this->load->model('service_model');
$outx = $this->service_model->getServiceRequestList(100);
$data['transport_request'] = $outx['service_request_list'];
$this->load->library('googlemaps');
$config['center'] = 'atalnta,GA,USA';
$config['zoom'] = 'auto';
$config['directions'] = TRUE;
$config['directionsStart'] = '4201 defoors farm trail, powder springs, GA 30127, USA';
$config['directionsEnd'] = '2324 stancrest ln, lawrenceville, 30044, GA, USA';
$config['directionsDivID'] = 'directionsDiv';
$this->googlemaps->initialize($config);
$data['map'] = $this->googlemaps->create_map();
*/
}
public function processbody() {
$data = array();
if ($this->input->get()) {
$msg_id = $this->input->get('id');
if ($msg_id != '' && $msg_id > 0) {
$mysql = "SELECT * FROM trackedemail_item WHERE id = $msg_id";
$query = $this->read_replica->query($mysql);
$data['message'] = $query->row_array();
$this->load->library('messageparser');
// print_r($data);
error_log('msg_id='.$msg_id);
$data['parsed'] = $this->messageparser->parse($msg_id, $this->db);
$data['id'] = $msg_id;
//$this->cacheParsedItem($data);
$this->load->view('scanned/extra/processed_body', $data);
}
}
}
private function cacheParsedItem($src) {
return NULL; //this code is obsolete and there is a new one in the API
if ($src['parsed']['location_start_value']=='N/A' && $src['parsed']['location_end_value']=='N/A' && $src['parsed']['cost_value']=='N/A') return;
sscanf($src['parsed']['duration_value'], "%d:%d:%d", $hours, $minutes, $seconds);
$data = array(
'travel_date' => date('Y-m-d H:i', strtotime($src['parsed']['date_value'])),
'location_start' => pg_escape_string(trim($src['parsed']['location_start_value'])),
'location_end' => pg_escape_string(trim($src['parsed']['location_end_value'])),
'distance' => filter_var($src['parsed']['distance_value'], FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION),
'duration' => 60*$hours+$minutes,
'cost_raw' => pg_escape_string(trim(filter_var($src['parsed']['cost_value'],FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_BACKTICK))),
'trackedemail_item_id' => $src['id'],
'cost' => filter_var($src['parsed']['cost_value'], FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION)
);
// New location code:
$location_start_id = $this->getAddress($data['location_start']);
$location_end_id = $this->getAddress($data['location_end']);
$data['location_start_id'] = $location_start_id;
$data['location_end_id'] = $location_end_id;
unset($data['location_start']);
unset($data['location_end']);
$q = "SELECT * FROM parsedemail_item WHERE trackedemail_item_id='".$data['trackedemail_item_id']."'";
$r = $this->read_replica->query($q);
$f = $r->row_array();
if ($f==NULL) {
$ql = "updated"; $qv = "NOW()";
foreach($data as $key=>$val) {
$ql.= ",${key}";
$qv.= ",'${val}'";
}
$q = "INSERT INTO parsedemail_item (${ql}) VALUES(${qv})";
} else {
unset($data['trackedemail_item_id']);
$q = "UPDATE parsedemail_item SET updated=NOW()";
foreach ($data as $key=>$val) {
$q.= ",${key}='${val}'";
}
$q.= " WHERE id='".$f['id']."'";
}
//echo $q;
//var_dump($src['parsed']);
//echo "<pre>";var_dump($data); echo "</pre>";
$this->db->query($q);
//*/
}
protected function getAddress($address) {
$q = "SELECT id FROM address WHERE lower(address)=lower('".pg_escape_string($address)."')";
$r = $this->read_replica->query($q);
$f = $r->row_array();
if ($f!=NULL && is_array($f) && $f["id"]>0) {
return $f["id"];
}
$q = "INSERT INTO address (address) VALUES ('".pg_escape_string($address)."') RETURNING id";
$r = $this->db->query($q);
$f = $r->row_array();
if ($f!=NULL && is_array($f) && $f["id"]>0) {
return $f["id"];
}
return NULL;
}
protected function renderScannedPage($page_name, $data) {
$this->load->view('admin/view_admin_header',$data);
$this->load->view('scanned/'.$page_name,$data);
$this->load->view('admin/view_admin_footer',$data);
}
}
+109
View File
@@ -0,0 +1,109 @@
<?php
defined('BASEPATH') or exit('No direct script access allowed');
class Screen_Cards extends Admin_Controller
{
public function __construct()
{
parent::__construct();
$this->load->model('screen_cards_model');
$this->load->helper('url');
$this->load->model('combo_model');
}
public function list()
{
$params = $this->input->get();
$data = [
'card_models' => []
];
$this->load->library('table');
$this->table->set_heading(
[
['data' => 'ID', 'style' => 'width:120px'],
'Screen Name',
'Trigger ID',
['data' => 'Status', 'style' => 'width:120px'],
['data' => '...', 'style' => 'width:200px'],
]
);
$query = $this->screen_cards_model->getQueryAll();
$tableData = $this->returnAdminTable(
[
'count_query' => $query,
'query' => $query,
],
'/Screen_Cards/list/',
[
'per_page' => 20,
'reuse_query_string' => TRUE,
'uri_segment' => 3,
]
);
$data['filterData'] = $params;
$data['screen_cards_table'] = $tableData['output_table'];
$data['links'] = $tableData['links'];
$data['screen_name_ddl'] = $this->combo_model->getScreenNames('screen_name', '');
$data['trigger_id_ddl'] = $this->combo_model->getTriggerIds('trigger_id', '');
$this->renderView('view_list', $data);
}
public function ajax_toggle()
{
$id = $this->input->post('id');
$cur_status = $this->input->post('cur_status');
$rs = $this->screen_cards_model->toggle($id, $cur_status);
header('Content-Type: application/json');
echo json_encode($rs);
}
private function renderView($page_name, $data)
{
$this->load->view('admin/view_admin_header', $data);
$this->load->view('screencards/' . $page_name, $data);
$this->load->view('admin/view_admin_footer', $data);
}
public function create_or_update()
{
$data = $this->input->post();
$rs = $this->screen_cards_model->create_or_update($data);
if($rs){
$this->session->set_flashdata('msg', empty($data['id']) ? 'Added' : 'Updated');
}else{
$this->session->set_flashdata('error', 'Screen Name & Trigger ID already exist, please try again!');
}
redirect('/Screen_Cards/list', 'refresh');
}
public function get_by_id()
{
$id = $this->input->get('id');
$data = $this->screen_cards_model->getById($id);
header('Content-Type: application/json');
echo json_encode($data);
}
//post delete
public function delete()
{
$id = $this->input->post('id');
if (!empty($id)) {
$rs = $this->screen_cards_model->delete($id);
} else {
$rs = false;
}
header('Content-Type: application/json');
echo json_encode($rs);
}
// ajax validate is exists screen name - trigger id
public function is_exists(){
$id = $this->input->post('id'); // 0 if create new
$screen_name = $this->input->post('screen_name');
$trigger_id = $this->input->post('trigger_id');
$is_exists = $this->screen_cards_model->is_exists($id, $screen_name, $trigger_id);
header('Content-Type: application/json');
echo json_encode($is_exists);
}
}
+107
View File
@@ -0,0 +1,107 @@
<?php
class Security extends Admin_Controller {
const COUNT_SQL = "SELECT COUNT(*) as total FROM block_ip;
INSERT INTO block_ip (ip, reason) VALUES ('176.117.172.40','something 20 chars');
";
public function index() {
return $this->blockedIpData();
}
protected function renderSecurityPage($page_name, $data) {
$this->load->view('admin/view_admin_header', $data);
$this->load->view('points/' . $page_name, $data);
$this->load->view('admin/view_admin_footer', $data);
}
public function blockedIpData() {
$this->load->model('block_ip_model');
$data = array();
$data["page_title"] = "Security";
$params = [];
$params = $this->input->get();
$this->load->library('table');
$this->table->set_heading(
array( 'data' => 'ID','style' => 'width:50px'),
'IP Address',
'Reason',
'Blocked',
array( 'data' => 'ACT', 'style' => 'width:40px; text-align: center;')
);
$query = $this->block_ip_model->getBlockIpQuery($params);
$tableData = $this->returnAdminTable(
[
'count_query' => $query,
'query' => $query,
],
'/security/blockedIpData',
[
'per_page' => 20,
'reuse_query_string' => TRUE,
]
);
$data['filterData'] = $params;
$data['links'] = $tableData['links'];
$data['blocked_ip_table'] = $tableData['output_table'];
$this->renderAdminPage("view_blocked_ip", $data);
}
public function blockMember() {
if ($this->input->post()) {
$memberId = $this->input->post('member_id');
$sql = "UPDATE members SET login_failures=5, status=0 WHERE id=".$memberId;
$this->db->query( $sql );
$result = json_encode(["status"=>"ok"]);
echo $result;
}
}
public function unblockMember() {
if ($this->input->post()) {
$memberId = $this->input->post('member_id');
$sql = "UPDATE members SET login_failures=0, status=1 WHERE id=".$memberId;
$this->db->query( $sql );
$result = json_encode(["status"=>"ok"]);
echo $result;
}
}
public function blockIp() {
if ($this->input->post()) {
$ipAddress = $this->input->post('ip_address');
$reason = $this->input->post('reason');
$sql = "INSERT INTO block_ip (ip, reason) VALUES ('{$ipAddress}','{$reason}')";
$this->db->query( $sql );
$result = json_encode(["status"=>"ok"]);
echo $result;
}
}
public function unblockIp() {
if ($this->input->post()) {
$ipAddress = $this->input->post('ip_address');
if(stripos($ipAddress, "*")) {
$ipAddress = str_replace("*", "%", $ipAddress);
$sql = "DELETE FROM block_ip WHERE ip::text LIKE '{$ipAddress}'";
} else {
$sql = "DELETE FROM block_ip WHERE ip = '{$ipAddress}'::inet";
}
$this->db->query( $sql );
$result = json_encode(["status"=>"ok"]);
echo $result;
}
}
}
+666
View File
@@ -0,0 +1,666 @@
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Subscription extends Admin_Controller {
var $template = array(
'table_open' => "<table class='table table-striped table-hover table-bordered table-condensed'>",
'thead_open' => '<thead class=\'bg-indigo\'>',
'thead_close' => '</thead>',
'heading_row_start' => '<tr>',
'heading_row_end' => '</tr>',
'heading_cell_start' => '<th>',
'heading_cell_end' => '</th>',
'tbody_open' => '<tbody>',
'tbody_close' => '</tbody>',
'row_start' => '<tr>',
'row_end' => '</tr>',
'cell_start' => '<td>',
'cell_end' => '</td>',
'row_alt_start' => '<tr>',
'row_alt_end' => '</tr>',
'cell_alt_start' => '<td>',
'cell_alt_end' => '</td>',
'table_close' => '</table>'
);
public function index() {
$this->load->helper('url');
$data = array();
$this->load->library('table');
$this->table->set_template($this->template);
$data['backoffice_users'] = "";
$mysql = "SELECT c.country, '<button type=\"button\" onclick=\"viewSubscription('||s.id||');\" class=\"btn\"> >> </button>' AS View FROM subscriptions s LEFT JOIN country c ON c.code =s.country ORDER by s.id ASC";
$query = $this->read_replica->query($mysql);
$this->table->set_heading('Country', array('data' => 'View', 'style' => 'width:50px'));
$data['subscription_country'] = $this->table->generate($query);
$this->renderSubscriptionPage('view_subscription', $data);
// echo 'Ameye Olu';
}
public function viewsubscription() {
$subscription_id = $this->input->get('subscription_id');
if ($subscription_id > 0) {
$this->load->library('table');
$this->table->set_template($this->template);
$mysql = "SELECT '<h4><b>Title:</b> :'||title||'</h4><p><b>Description :</b>'||description||'<p></p><b>Price :</b>'|| price*0.01 AS Subscription FROM subscriptions_detail WHERE subscriptions =" . $subscription_id;
$query = $this->read_replica->query($mysql);
//$this->table->set_heading( 'Country', array('data' => 'View', 'style' => 'width:50px') );
$data['subscription_table'] = $this->table->generate($query);
$this->load->view('admin/common/subscription_detail', $data);
}
}
/*
SELECT mca.*,mc.card_points,mc.card_reciept,mc.title,UPPER(tp.name) AS transporter FROM members_card_assign mca LEFT JOIN main_cards mc ON mc.id =mca.card_id LEFT JOIN transport_providers tp ON tp.id::text =mc.card_reciept WHERE mca.id =2654162;
id | member_id | card_id | status | added | list_order | subscribe | how | card_points | card_reciept | title | transporter
---------+-----------+---------+--------+----------------------------+------------+----------------------------+-----+-------------+--------------+--------------------------------------------------+-------------
2654162 | 74 | 49 | 1 | 2019-11-10 15:13:11.904596 | 0 | 2019-11-11 07:45:15.314858 | | 0 | 3 | Earn points worth $5 on your next ride with Grab | GRAB
(1 row)
*/
public function procSubscription() {
echo "Get Subscription ID<br>Check Status<br>Insert The Points<br>Modify Status<br>Clean-up - email if needed";
$assign_id = $this->input->get('assign_id'); // this is like the assign ID
echo "<br> Assign ID = " . $assign_id . "<br>";
if ($assign_id > 0) {
$mysql = " SELECT tp.name AS card_reciept_name, mca.*,mc.card_points,mc.card_reciept,mc.title,UPPER(tp.name) AS transporter "
. " FROM members_card_assign mca "
. " LEFT JOIN main_cards mc ON mc.id =mca.card_id "
. " LEFT JOIN transport_providers tp ON tp.id::text =mc.card_reciept "
. " WHERE mca.id =" . $assign_id;
// echo $mysql;
$query = $this->read_replica->query($mysql);
if ($query->num_rows() == 1) {
$inx = $query->result_array();
// print_r($inx);
$member_id = $inx[0]['member_id'];
$card_points = $inx[0]['card_points']*50;
$card_reciept_name = $inx[0]['card_reciept_name'];
$out = array();
$inx['action'] = SAVVY_BKO_PROCESS_POINTS;
$inx["assign_id"] = $assign_id;
$ret = $this->savvy_api($inx, $out);
if ($ret == PHP_API_OK) {
// $message = $id > 0 ? 'Updated!' : 'Created!';
$this->pointsNotification($member_id, $assign_id, $card_points,$card_reciept_name );
echo "Points Allocated";
} else {
// $message = 'Failed to ' . ($id > 0 ? 'update' : 'create') . ' card: ' . isset($out["status"]) ? $out["status"] : '';
echo "Points allocation error";
}
}
} else {
echo "The selected sction not found";
}
return 0;
}
/*
* savvy=> SELECT mca.*,mc.card_points,mc.card_reciept,mc.title,UPPER(tp.name) AS transporter FROM members_card_assign mca LEFT JOIN main_cards mc ON mc.id =mca.card_id LEFT JOIN transport_providers tp ON tp.id::text =mc.card_reciept WHERE mca.id =2655337;
id | member_id | card_id | status | added | list_order | subscribe | how | completed | trigger_key | message | cat | reciept_count | updated | card_points | card_reciept | title | transporter
---------+-----------+---------+--------+----------------------------+------------+----------------------------+-----+-----------+-------------+---------+-----+---------------+----------------------------+-------------+--------------+-------------------------------+-------------
2655337 | 251 | 132 | 1 | 2020-04-10 07:47:50.809046 | 0 | 2020-04-10 07:49:00.380875 | | | | | | 0 | 2020-05-14 16:35:03.030581 | 0 | | Get $10 back on Anywheel Bike |
(1 row)
*/
private function pointsNotification($member_id, $assign_id, $points,$card_reciept_name ) {
$outX = array();
$x = [];
$x["mmode"] = "AUTO";
$x["trigger_key"] = "ETRG0019";
$x["action"] = FLOAT_SYSTEM_CREATE_NOTIFICATION;
$x["msg"] = "You've just earned $points float Points for ".$card_reciept_name ;
$x["pid"] = 0;
$x["member_id"] = $member_id;
$x["notice_type"] = "INSTANT";
$ret = $this->savvy_api($x, $outX);
// print_r($x);
return 0;
}
public function load_pagination($all_record, $params, $action, $limit = 10) {
$action_hidden = $this->input->get('action_hidden');
// pagination
$this->load->library('pagination');
$config["total_rows"] = count($all_record);
$config["base_url"] = base_url() . "/subscription/" . $action;
$config["per_page"] = $limit;
$config["uri_segment"] = 3;
$config["num_links"] = 5;
$config["suffix"] = "?action_hidden=${action_hidden}&"
. http_build_query($params);
$config["first_url"] = "/subscription/{$action}/0?action_hidden=${action_hidden}&"
. http_build_query($params);
$config['full_tag_open'] = "<ul class='pagination'>";
$config['full_tag_close'] = "</ul>";
$config['num_tag_open'] = '<li>';
$config['num_tag_close'] = '</li>';
$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
$config['next_tag_open'] = "<li>";
$config['next_tagl_close'] = "</li>";
$config['prev_tag_open'] = "<li>";
$config['prev_tagl_close'] = "</li>";
$config['first_tag_open'] = "<li>";
$config['first_tagl_close'] = "</li>";
$config['last_tag_open'] = "<li>";
$config['last_tagl_close'] = "</li>";
$this->pagination->initialize($config);
$page = ( $this->uri->segment(3) ) ? $this->uri->segment(3) : 0;
$offset = is_numeric($page) ? $page : 0;
return [
'link' => $this->pagination->create_links(),
'offset' => $offset,
'limit' => $config["per_page"]
];
}
public function getValueCombo($val) {
$status_value = range(0, 9);
return in_array($val, $status_value) ? $val : '';
}
public function setComboForSubscriptionReport($params) {
$this->load->model('combo_model');
$combo['card_status'] = $this->combo_model->getStatusComboFromZeroToOne(
'card_status', $params['status']
);
$combo['card_ready'] = $this->combo_model->getYesNoComboWithAll(
'card_ready', $params['ready']
);
$combo['card_completed'] = $this->combo_model->getCompletedCombo(
'card_completed', $params['completed']
);
return $combo;
}
/**
* prepare search params
* @param array &$data
* @param array $params
*/
public function subscribed_deals_searching(&$data, &$params) {
// load combo model
$this->load->model('combo_model');
$data['points'] = $this->combo_model->getPointsSubscribedDeals( 'points', isset( $params['points'] ) ? $params['points'] : 0 );
unset( $params['points'] );
}
public function setFormRuleForSubscriptionReportForm() {
$status_pattern = 'regex_match[/^(?:[0-9])$/]';
$date_pattern = 'regex_match[/\d{4}-\d{2}-\d{2}/]';
$this->form_validation->set_rules('reciept_count', 'Reciepts', 'numeric');
$this->form_validation->set_rules('from_date', 'Created date', $date_pattern);
$this->form_validation->set_rules('to_date', 'Created date', $date_pattern);
$this->form_validation->set_rules('status', 'Status', $status_pattern);
}
public function getValueOfSubscriptionReportForm() {
return [
'title' => trim($this->input->get('title') ?? ''),
'card_receipts' => trim($this->input->get('card_receipts') ?? ''),
'reciept_count' => trim($this->input->get('reciept_count') ?? ''),
'from_date' => trim($this->input->get('from_date') ?? ''),
'to_date' => trim($this->input->get('to_date') ?? ''),
'status' => 1,
'ready' => trim($this->input->get('card_ready') ?? ($this->input->get('ready') ?? -1)),
'completed' => trim($this->input->get('card_completed') ?? ($this->input->get('completed') ?? -1)),
'email' => trim($this->input->get('email')),
'id' => trim($this->input->get('id'))
];
}
public function validateValueForSubscriptionReport($params) {
$this->load->library('form_validation');
$this->form_validation->set_data($params);
$this->setFormRuleForSubscriptionReportForm();
$errors = [];
if ($this->form_validation->run() === FALSE) {
$errors = $this->form_validation->error_array();
}
return $errors;
}
public function setOnePastMonth(&$params, $default_date = 'on') {
if (strcmp($default_date, 'on') === 0) {
$params['from_date'] = date("Y-m-d", strtotime("-1 months"));
$params['to_date'] = date("Y-m-d");
}
}
public function subscriptionreport() {
$this->load->model('subscription_model');
$this->load->library('table');
$this->table->set_template($this->template);
$this->table->set_heading([
'ID',
'FirstName',
'Lastname',
'Description',
'Date Subscribed',
'Status',
'Card Id',
'Card Reciept',
'Reciepts',
'Ready',
'Action',
'Dt. Completed'
]);
$params = $this->getValueOfSubscriptionReportForm();
$default_date = $this->input->get('default_date');
if ($this->input->get('action_hidden')) {
$this->setOnePastMonth($params, $default_date);
} else {
$this->setOnePastMonth($params);
}
$data = $this->setComboForSubscriptionReport($params);
$data["page_title"] = "Subscription Report";
$params['status'] = $this->getValueCombo($params['status']);
$params = array_filter($params, function($ele) {
return $ele !== "";
});
$errors = $this->validateValueForSubscriptionReport($params);
$params = array_diff_key($params, $errors);
$data = array_merge(
$data, $params, $this->load_pagination(
$this->subscription_model->get_subscription_report_records($params), $params, 'SubscriptionReport'
)
);
$data['subscription_table'] = $this->table->generate(
$this->subscription_model->get_subscription_report_records(
$params, $data['limit'], $data['offset']
)
);
if ($this->input->get('action_hidden')) {
$data['default_date'] = $default_date;
} else {
$data['default_date'] = 'on';
}
$this->renderSubscriptionPage('view_subscriptionreport', $data);
}
/**
* Show Subscribed Deals report
* @return mixed
*/
public function subscribed_deals() {
$this->load->model('summary_report_model');
// load table library
$this->load->library('table');
$this->table->set_template($this->template);
$this->table->set_heading([
'Card ID',
'Deal Name',
'Location',
'Deal Value (Card Points)',
'Total Subscribed in past 24 hours',
'Total Subscribed in past 7 days',
'Total Subscribed in past 14 days',
'Total Subscribed in past 30 days',
'Total Subscribed All Time',
'Deals Redeemed'
]);
$data = array();
$params = $this->input->get();
// total report
$data['page_title'] = 'Subscribed Deals Report';
$data['overall_summary'] = $this->summary_report_model->getSummaryReport( $params );
$data = array_merge(
$data,
$params,
$this->load_pagination(
$data['overall_summary'], $params, 'subscribed_deals', $limit = 20
)
);
// get subscribed summary report
$data['summary_report'] = $this->table->generate(
$this->summary_report_model->getSummaryReport( $params, $data['limit'], $data['offset'] )
);
// prepare filter combo
$this->subscribed_deals_searching( $data, $params );
$this->renderSubscriptionPage( 'view_subscribed_deals', $data );
}
public function validateValueForCarpoolReport($params) {
$this->load->library('form_validation');
$this->form_validation->set_data($params);
$this->setFormRuleForCarpoolReportForm();
$errors = [];
if ($this->form_validation->run() === FALSE) {
$errors = $this->form_validation->error_array();
}
return $errors;
}
public function setFormRuleForCarpoolReportForm() {
$status_pattern = 'regex_match[/^(?:[0-9])$/]';
$date_pattern = 'regex_match[/\d{4}-\d{2}-\d{2}/]';
$this->form_validation->set_rules('card_id', 'Card ID', 'numeric');
$this->form_validation->set_rules('pool', 'Pool', 'numeric');
$this->form_validation->set_rules('from_date', 'Created date', $date_pattern);
$this->form_validation->set_rules('to_date', 'Created date', $date_pattern);
$this->form_validation->set_rules('status', 'Status', 'numeric');
}
public function getValueOfCarpoolReportForm() {
return [
'email' => trim($this->input->get('email') ?? ''),
'title' => trim($this->input->get('title') ?? ''),
'from_date' => trim($this->input->get('from_date') ?? ''),
'to_date' => trim($this->input->get('to_date') ?? ''),
'pool' => trim($this->input->get('pool') ?? ''),
'card_id' => trim($this->input->get('card_id') ?? ''),
'status' => trim($this->input->get('status') ?? '')
];
}
public function carpoolreport() {
$this->load->model('carpool_report_model');
$this->load->library('table');
$this->table->set_template($this->template);
$data["page_title"] = "Carpool Report";
$this->table->set_heading([
'CarPool ID',
'?column?',
'LastName',
'Email',
'Pool',
'Title',
'Card ID',
'Added',
'Updated',
'Status',
'Proc1'
]);
$params = $this->getValueOfCarpoolReportForm();
$default_date = $this->input->get('default_date');
if ($this->input->get('action_hidden')) {
$this->setOnePastMonth($params, $default_date);
} else {
$this->setOnePastMonth($params);
}
$params = array_filter($params, function($ele) {
return $ele !== "";
});
$errors = $this->validateValueForCarpoolReport($params);
$params = array_diff_key($params, $errors);
$data = array_merge(
$data, $params, $this->load_pagination(
$this->carpool_report_model->get_carpool_records($params), $params, 'carpoolreport'
)
);
$data['carpool_table'] = $this->table->generate(
$this->carpool_report_model->get_carpool_records(
$params, $data['limit'], $data['offset']
)
);
if ($this->input->get('action_hidden')) {
$data['default_date'] = $default_date;
} else {
$data['default_date'] = 'on';
}
$this->renderSubscriptionPage('view_carpoolreport', $data);
}
public function setComboForCarPoolFriendReport($params) {
$this->load->model('combo_model');
$combo['card_status'] = $this->combo_model->getStatusComboFromZeroToNine(
'card_status', $params['status']
);
return $combo;
}
public function setFormRuleForCarPoolFriendReportForm() {
$status_pattern = 'regex_match[/^(?:[0-9])$/]';
$date_pattern = 'regex_match[/\d{4}-\d{2}-\d{2}/]';
$this->form_validation->set_rules('member_id', 'Member ID', 'numeric');
$this->form_validation->set_rules('carpool_id', 'Carpool ID', 'numeric');
$this->form_validation->set_rules('from_date', 'Created date', $date_pattern);
$this->form_validation->set_rules('to_date', 'Created date', $date_pattern);
$this->form_validation->set_rules('status', 'Status', 'numeric');
}
public function getValueOfCarPoolFriendReportForm() {
return [
'member_id' => trim($this->input->get('member_id') ?? ''),
'carpool_id' => trim($this->input->get('carpool_id') ?? ''),
'from_date' => trim($this->input->get('from_date') ?? ''),
'to_date' => trim($this->input->get('to_date') ?? ''),
'email' => trim($this->input->get('email') ?? ''),
'status' => trim($this->input->get('card_status') ?? ($this->input->get('status') ?? -1)),
];
}
public function validateValueForCarPoolFriendReport($params) {
$this->load->library('form_validation');
$this->form_validation->set_data($params);
$this->setFormRuleForCarPoolFriendReportForm();
$errors = [];
if ($this->form_validation->run() === FALSE) {
$errors = $this->form_validation->error_array();
}
return $errors;
}
public function carpoolfriend() {
$this->load->model('carpool_friend_model');
$this->load->library('table');
$this->table->set_template($this->template);
$data["page_title"] = "Carpool Friend Report";
$this->table->set_heading([
'Proc Status',
'Member',
'Member ID',
'ID',
'Carpool ID',
'FirstName',
'LastName',
'Email',
'Status',
'Accept Status',
'Pool Status',
'Level A',
'Level B',
'Added',
'Last Message',
'Updated',
'Link'
]);
$params = $this->getValueOfCarpoolFriendReportForm();
$default_date = $this->input->get('default_date');
if ($this->input->get('action_hidden')) {
$this->setOnePastMonth($params, $default_date);
} else {
$this->setOnePastMonth($params);
}
$data = $this->setComboForCarpoolFriendReport($params);
$data["page_title"] = "Carpool Friend Report";
$params['status'] = $this->getValueCombo($params['status']);
$params = array_filter($params, function($ele) {
return $ele !== "";
});
$errors = $this->validateValueForCarPoolFriendReport($params);
$params = array_diff_key($params, $errors);
$data = array_merge(
$data, $params, $this->load_pagination(
$this->carpool_friend_model->get_carpool_friend_records($params), $params, 'carpoolfriend'
)
);
$data['carpool_friend_table'] = $this->table->generate(
$this->carpool_friend_model->get_carpool_friend_records(
$params, $data['limit'], $data['offset']
)
);
if ($this->input->get('action_hidden')) {
$data['default_date'] = $default_date;
} else {
$data['default_date'] = 'on';
}
$this->renderSubscriptionPage('view_carpoolfriend', $data);
}
public function setFormRuleForSurveyReportForm() {
$status_pattern = 'regex_match[/^(?:[0-9])$/]';
$date_pattern = 'regex_match[/\d{4}-\d{2}-\d{2}/]';
$this->form_validation->set_rules('member_id', 'Member ID', 'numeric');
$this->form_validation->set_rules('from_date', 'Created date', $date_pattern);
$this->form_validation->set_rules('to_date', 'Created date', $date_pattern);
$this->form_validation->set_rules('status', 'Status', $status_pattern);
}
public function getValueOfSurveyReportForm() {
return [
'member_id' => trim($this->input->get('member_id') ?? ''),
'description' => trim($this->input->get('description') ?? ''),
'answer' => trim($this->input->get('answer') ?? ''),
'action' => trim($this->input->get('action') ?? ''),
'from_date' => trim($this->input->get('from_date') ?? ''),
'to_date' => trim($this->input->get('to_date') ?? ''),
'status' => trim($this->input->get('card_status') ?? ($this->input->get('status') ?? -1)),
'ready' => trim($this->input->get('card_ready') ?? ($this->input->get('ready') ?? -1)),
'completed' => trim($this->input->get('card_completed') ?? ($this->input->get('completed') ?? -1)),
];
}
public function validateValueForSurveyReport($params) {
$this->load->library('form_validation');
$this->form_validation->set_data($params);
$this->setFormRuleForSurveyReportForm();
$errors = [];
if ($this->form_validation->run() === FALSE) {
$errors = $this->form_validation->error_array();
}
return $errors;
}
public function surveyreport() {
$this->load->model('survey_report_model');
$this->load->library('table');
$this->table->set_template($this->template);
$this->table->set_heading([
'ID:MEMBER_ID',
'FirstName',
'Lastname',
'Description',
'Answer',
'Status',
'Date',
'Action',
]);
$params = $this->getValueOfSurveyReportForm();
$default_date = $this->input->get('default_date');
if ($this->input->get('action_hidden')) {
$this->setOnePastMonth($params, $default_date);
} else {
$this->setOnePastMonth($params);
}
$data = $this->setComboForSubscriptionReport($params);
$data["page_title"] = "Survey Report";
$params['status'] = $this->getValueCombo($params['status']);
$params = array_filter($params, function($ele) {
return $ele !== "";
});
$errors = $this->validateValueForSurveyReport($params);
$params = array_diff_key($params, $errors);
$data = array_merge(
$data, $params, $this->load_pagination(
$this->survey_report_model->get_survey_report_records($params), $params, 'surveyreport'
)
);
$data['subscription_table'] = $this->table->generate(
$this->survey_report_model->get_survey_report_records(
$params, $data['limit'], $data['offset']
)
);
if ($this->input->get('action_hidden')) {
$data['default_date'] = $default_date;
} else {
$data['default_date'] = 'on';
}
$this->renderSubscriptionPage('view_surveyreport', $data);
}
protected function renderSubscriptionPage($page_name, $data) {
$this->load->view('admin/view_admin_header', $data);
$this->load->view('subscription/' . $page_name, $data);
$this->load->view('admin/view_admin_footer', $data);
}
}
+43
View File
@@ -0,0 +1,43 @@
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Surveys extends Admin_Controller {
public function index() {
$this->load->helper('url');
$data = array();
$this->load->library('table');
$this->table->set_template($this->template);
}
public function onoardsurveys() {
$this->load->helper('url');
$data = array();
$this->load->library('table');
$this->table->set_template($this->template);
$data['backoffice_users'] = "";
$mysql = "SELECT id,group_key,answers_key,status,answers, ' <input type=\"text\" class=\"form-control\" value=\"'||answers||'\">' AS ans1,'<button type=\"button\" onclick=\"viewSubscription('||id||');\" class=\"btn btn-danger\"> Update </button>' AS View FROM onboarding_survey ";
$query = $this->read_replica->query($mysql);
// $this->table->set_heading('Country', array('data' => 'View', 'style' => 'width:50px'));
$data['onboard_survey'] = $this->table->generate($query);
//print_r( $data );
$this->renderSurveyPage('view_onboardsurvey', $data);
}
protected function renderSurveyPage($page_name, $data) {
$this->load->view('admin/view_admin_header', $data);
$this->load->view('surveys/' . $page_name, $data);
$this->load->view('admin/view_admin_footer', $data);
}
}
File diff suppressed because it is too large Load Diff
+236
View File
@@ -0,0 +1,236 @@
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Tracking extends Admin_Controller {
var $template = array(
'table_open' => "<table class='table table-striped table-hover table-bordered table-condensed'>",
'thead_open' => '<thead class=\'bg-indigo\'>',
'thead_close' => '</thead>',
'heading_row_start' => '<tr>',
'heading_row_end' => '</tr>',
'heading_cell_start' => '<th>',
'heading_cell_end' => '</th>',
'tbody_open' => '<tbody>',
'tbody_close' => '</tbody>',
'row_start' => '<tr>',
'row_end' => '</tr>',
'cell_start' => '<td>',
'cell_end' => '</td>',
'row_alt_start' => '<tr>',
'row_alt_end' => '</tr>',
'cell_alt_start' => '<td>',
'cell_alt_end' => '</td>',
'table_close' => '</table>'
);
public function index() {
$this->load->helper('url');
$data = array();
/*
$this->load->model('admindash_model');
$out = $this->admindash_model->getAdminDashData($data);
$data['recent_signup'] = $out['recent_signup'];
$this->load->model('service_model');
$outx = $this->service_model->getServiceRequestList(100);
$data['transport_request'] = $outx['service_request_list'];
$this->load->library('googlemaps');
$config['center'] = 'atalnta,GA,USA';
$config['zoom'] = 'auto';
$config['directions'] = TRUE;
$config['directionsStart'] = '4201 defoors farm trail, powder springs, GA 30127, USA';
$config['directionsEnd'] = '2324 stancrest ln, lawrenceville, 30044, GA, USA';
$config['directionsDivID'] = 'directionsDiv';
$this->googlemaps->initialize($config);
$data['map'] = $this->googlemaps->create_map();
*/
$this->load->library('table');
$this->table->set_template($this->template);
$mysql = "SELECT id,username,firstname,lastname,'<button type=\"button\" class=\"btn btn-info\">View</button>' As action FROM members";
$query = $this->read_replica->query($mysql);
$this->table->set_heading(array('data' => 'ID', 'style' => 'width:10px'), 'USERNAME', 'FIRSTNAME', 'LASTNAME', array('data' => 'ACTION', 'style' => 'width:90px'));
$data['member_table'] = $this->table->generate($query);
//$data['js'] = array('https://maps.googleapis.com/maps/api/js?key=AIzaSyDvjiRTxngOQyBP4zpqFlZuiquc0ROvo9c&callback=initMap');
$this->renderAdminPage('view_dash', $data);
// echo 'Ameye Olu';
}
protected function renderAdminPage($page_name, $data) {
$this->load->view('admin/view_admin_header', $data);
$this->load->view('admin/' . $page_name, $data);
$this->load->view('admin/view_admin_footer', $data);
}
public function gpsdata() {
$data = array();
/*
$this->load->model('admindash_model');
$out = $this->admindash_model->getAdminDashData($data);
$data['recent_signup'] = $out['recent_signup'];
$this->load->model('service_model');
$outx = $this->service_model->getServiceRequestList(100);
$data['transport_request'] = $outx['service_request_list'];
$this->load->library('googlemaps');
$config['center'] = 'atalnta,GA,USA';
$config['zoom'] = 'auto';
$config['directions'] = TRUE;
$config['directionsStart'] = '4201 defoors farm trail, powder springs, GA 30127, USA';
$config['directionsEnd'] = '2324 stancrest ln, lawrenceville, 30044, GA, USA';
$config['directionsDivID'] = 'directionsDiv';
$this->googlemaps->initialize($config);
$data['map'] = $this->googlemaps->create_map();
*/
ob_start();
$this->load->library('table');
$this->table->set_template($this->template);
$data['page_title'] = "Recent Tracking Data";
$mysql = "SELECT m.id,m.firstname,'<button type=\"button\" class=\"btn btn-info\">View</button>' As action FROM members m";
$query = $this->read_replica->query($mysql);
// $this->table->set_heading(array('data' => 'ID', 'style' => 'width:10px'), 'USERNAME','FIRSTNAME','LASTNAME', array('data' => 'ACTION', 'style' => 'width:90px'));
$res = array(array('First Name','Action','ID','Member ID','Tracked Group','Speed','Latitude','Longitude','Time','Location','Created'));
$gps = $this->load->database('gps', TRUE);
$dummy = new stdClass;
$dummy->id = "";
$dummy->member_id = "";
$dummy->traked_group = "";
$dummy->speed = "";
$dummy->lat = "";
$dummy->lng = "";
$dummy->ttime = "";
$dummy->loc = "";
$dummy->created = "";
foreach ($query->result() as $row) {
$q = "SELECT * FROM members_tracking WHERE member_id=".$row->id." ORDER BY id DESC LIMIT 1";
$r = $gps->query($q);
$d = $r->result();
if (is_array($d) && count($d)>0 && is_object($d[0])) {
list($f) = $d;
$res[] = array($row->firstname,$row->action,$f->id,$f->member_id,$f->traked_group,$f->speed,$f->lat,$f->lng,$f->ttime,$f->loc,$f->created);
}
}
$data['member_table'] = $this->table->generate($res);
ob_get_clean();
//$data['js'] = array('https://maps.googleapis.com/maps/api/js?key=AIzaSyDvjiRTxngOQyBP4zpqFlZuiquc0ROvo9c&callback=initMap');
$this->renderAdminPage('view_gpstrack', $data);
}
public function crashlog() {
$this->load->model('crash_log_model');
$data = [];
$params = [];
$params = $this->input->get();
$query = $this->crash_log_model->getLogQuery($params);
$tableData = $this->returnAdminTable(
[
'count_query' => $query,
'query' => $query,
],
'/tracking/crashlog',
[
'per_page' => 20,
'reuse_query_string' => TRUE,
]
);
$data['filterData'] = $params;
$data['links'] = $tableData['links'];
$data['crashlog_table'] = $tableData['output_table'];
$this->renderAdminPage('view_crashlog', $data);
}
public function crashlogentry() {
$id = (int)$this->input->get('id');
if ($id>0) {
$q = "SELECT * FROM crash_log WHERE id=${id}";
$r = $this->read_replica->query($q);
$f = $r->result_array();
if (is_array($f) and count($f)>0) {
$data['entry'] = $f[0];
$data['entry']['data'] = Tracking::prettyPrint($data['entry']['data']);
$this->load->view('admin/view_crashlog_entry', $data);
} else {
echo "Record was not found";
return;
}
} else {
echo "Invalid ID";
return;
}
}
public static function prettyPrint( $json ) {
$result = '';
$level = 0;
$in_quotes = false;
$in_escape = false;
$ends_line_level = NULL;
$json_length = strlen( $json );
for( $i = 0; $i < $json_length; $i++ ) {
$char = $json[$i];
$new_line_level = NULL;
$post = "";
if( $ends_line_level !== NULL ) {
$new_line_level = $ends_line_level;
$ends_line_level = NULL;
}
if ( $in_escape ) {
$in_escape = false;
} else if( $char === '"' ) {
$in_quotes = !$in_quotes;
} else if( ! $in_quotes ) {
switch( $char ) {
case '}': case ']':
$level--;
$ends_line_level = NULL;
$new_line_level = $level;
break;
case '{': case '[':
$level++;
case ',':
$ends_line_level = $level;
break;
case ':':
$post = " ";
break;
case " ": case "\t": case "\n": case "\r":
$char = "";
$ends_line_level = $new_line_level;
$new_line_level = NULL;
break;
}
} else if ( $char === '\\' ) {
$in_escape = true;
}
if( $new_line_level !== NULL ) {
$result .= "\n".str_repeat( "\t", $new_line_level );
}
$result .= $char.$post;
}
return $result;
}
}
@@ -0,0 +1,265 @@
<?php
defined('BASEPATH') or exit('No direct script access allowed');
class Transport_provider extends Admin_Controller
{
public $viewData = array();
public $pagePerItem = 20;
public $statusOptions = [
'Inactive' => '0',
'Active' => '1',
];
public function __construct()
{
parent::__construct();
// Load model
$this->load->model('transport_provider_model', 'transport_provider');
$this->load->helper('pagination');
}
public function index()
{
$this->load->helper(array('url'));
//get query string filter
$filterData = $this->input->get();
$queryString = $this->input->server('QUERY_STRING');
// remove empty value
$filterData = array_filter($filterData, function ($v, $k) {
return $v != '';
}, ARRAY_FILTER_USE_BOTH);
$pagingUrl = empty($queryString) ? uri_string() : uri_string() . '?' . $queryString;
$pagingUrl = remove_querystring_var($pagingUrl, 'page');
$data = $this->transport_provider->getTransportProvider($filterData);
$this->viewData['list'] = $data['list'];
$this->viewData['statusOptions'] = $this->statusOptions;
$this->viewData['filterData'] = $filterData;
$this->viewData['pagination'] = initPagination($this->pagePerItem, $data['totalItems'], $data['page'], $pagingUrl);
$this->renderAdminPage('transport_providers/list', $this->viewData);
}
public function create()
{
$this->load->helper(array('form', 'url'));
$this->viewData['statusOptions'] = $this->statusOptions;
$this->viewData['transport_provider'] = null;
$this->renderAdminPage('transport_providers/create', $this->viewData);
}
public function store()
{
$this->load->helper(array('form', 'url'));
$this->load->library('form_validation');
$this->viewData['transport_provider'] = null;
$this->viewData['statusOptions'] = $this->statusOptions;
$this->setTransportProviderCreationRules();
if ($this->form_validation->run() == false) {
$this->renderAdminPage('transport_providers/create', $this->viewData);
return;
}
$inputData = $this->getFormData();
$res = $this->transport_provider->createTransportProvider($inputData);
if ($res['status'] == 'success') {
$this->session->set_flashdata('success', isSet($res['message']) ? $res['message'] : 'Create success.');
redirect('/transport_provider');
} else {
$this->session->set_flashdata('error', isSet($res['message']) ? $res['message'] : 'Create fail.');
$this->renderAdminPage('transport_providers/create', $this->viewData);
return;
}
}
public function edit($id)
{
$this->load->helper(array('form', 'url'));
$res= $this->transport_provider->getTransportByID($id);
$this->viewData['transport_provider'] = isSet($res['data']) ? $res['data'] : [];
$this->viewData['statusOptions'] = $this->statusOptions;
$this->viewData['id'] = $id;
$this->renderAdminPage('transport_providers/edit', $this->viewData);
}
public function update($id)
{
$this->load->helper(array('form', 'url'));
$this->load->library('form_validation');
$this->viewData['statusOptions'] = $this->statusOptions;
$this->viewData['transport_provider'] = null;
$this->viewData['id'] = $id;
$this->setTransportProviderCreationRules();
if ($this->form_validation->run() == false) {
$this->renderAdminPage('transport_providers/edit', $this->viewData);
return;
}
$inputData = $this->getFormData();
$inputData['id'] = (int) $id;
$res = $this->transport_provider->updateTransportProviderById($id, $inputData);
if ($res['status'] == 'success') {
$this->session->set_flashdata('success', isSet($res['message']) ? $res['message'] : 'Create success');
redirect('/transport_provider');
} else {
$this->session->set_flashdata('error', $res['message']);
$this->renderAdminPage('transport_provider/edit', $this->viewData);
return;
}
}
public function remove($param)
{
$res = $this->transport_provider->removeTransportProviderById($param);
if (!$res['success'] != 'success') {
$this->viewData['errMsg'] = isSet($res['message']) ? $res['message'] : 'Something went wrong. Please try again later.';
$this->renderAdminPage('transport_provider', $this->viewData);
return;
}
redirect('/transport_provider');
}
protected function renderAdminPage($page_name, $data) {
$this->load->view('admin/view_admin_header', $data);
$this->load->view($page_name, $data);
$this->load->view('admin/view_admin_footer', $data);
}
private function getFormData() {
return [
'name' => $this->input->post('name'),
'client' => $this->input->post('client'),
'token' => $this->input->post('token'),
'code' => $this->input->post('code'),
'access_token' => $this->input->post('access_token'),
'timeout' => $this->input->post('timeout'),
'retries' => $this->input->post('retries'),
'active' => (int)$this->input->post('active'),
'custom' => $this->input->post('custom'),
];
}
private function setTransportProviderCreationRules()
{
$config = [
[
'field' => 'name',
'label' => 'Name',
'rules' => 'required|max_length[50]',
'errors' => array(
'max_length' => 'Max length is 50.'
),
],
[
'field' => 'client',
'label' => 'Client',
'rules' => 'required|max_length[100]',
'errors' => array(
'max_length' => 'Max length is 100.'
)
],
[
'field' => 'token',
'label' => 'Token',
'rules' => 'required|max_length[200]',
'errors' => array(
'max_length' => 'Max length is 200.'
)
],
[
'field' => 'code',
'label' => 'Code',
'rules' => 'required|max_length[100]',
'errors' => array(
'max_length' => 'Max length is 100.',
)
],
[
'field' => 'access_token',
'label' => 'Access Token',
'rules' => 'required|max_length[200]',
'errors' => array(
'max_length' => 'Max length is 200.'
)
],
[
'field' => 'timeout',
'label' => 'Timeout',
'rules' => 'required|numeric|callback_is_out_of_range_int2',
'errors' => array(
'is_out_of_range_int2' => 'Please input the value between ' . MIN_INT_2 . ' and ' . MAX_INT_2
)
],
[
'field' => 'retries',
'label' => 'Retries',
'rules' => 'required|numeric|callback_is_out_of_range_int4',
'errors' => array(
'is_out_of_range_int4' => 'Please input the value between ' . MIN_INT_4 . ' and ' . MAX_INT_4
)
],
[
'field' => 'active',
'label' => 'Active',
'rules' => 'required|numeric|callback_is_out_of_range_int4',
'errors' => array(
'is_out_of_range_int4' => 'Please input the value between ' . MIN_INT_4 . ' and ' . MAX_INT_4
)
],
[
'field' => 'custom',
'label' => 'Custom',
'rules' => 'required|callback_is_json',
'errors' => array(
'is_json' => 'Only input json.'
)
]
];
$this->form_validation->set_rules($config);
}
public function is_json($data) {
return (json_decode($data) != NULL) ? true : false;
}
public function is_out_of_range_int4($number) {
return is_numeric($number) && $number >= MIN_INT_4 && $number <= MAX_INT_4;
}
public function is_out_of_range_int2($number) {
return is_numeric($number) && $number >= MIN_INT_2 && $number <= MAX_INT_2;
}
public function searchTransportProvider() {
$filterData = $this->input->get();
// remove empty value
$filterData = array_filter($filterData, function ($v, $k) {
return $v != '';
}, ARRAY_FILTER_USE_BOTH);
$res = $this->transport_provider->getTransportProviderByName($filterData);
echo json_encode($res);
}
}
@@ -0,0 +1,336 @@
<?php
defined('BASEPATH') or exit('No direct script access allowed');
class Transport_provider_accounts extends Admin_Controller
{
public $viewData = array();
public $pagePerItem = 50;
public $statusOptions = [
'Inactive' => '0',
'Active' => '1',
];
public function __construct()
{
parent::__construct();
// Load model
$this->load->model('transport_provider_account_model', 'transport_provider_account');
$this->load->model('transport_provider_model', 'transport_provider');
$this->load->helper('pagination');
}
public function index()
{
$this->load->model('combo_model');
$this->load->helper(array('url'));
//get query string filter
$filterData = $this->input->get();
$queryString = $this->input->server('QUERY_STRING');
$pagingUrl = empty($queryString) ? uri_string() : uri_string() . '?' . $queryString;
$pagingUrl = remove_querystring_var($pagingUrl, 'page');
$filterData['perPage'] = $this->pagePerItem;
$data = $this->transport_provider_account->getTransportProviderAccount($filterData);
$data['list'] = array_map(function($item) {
$item['added'] = $this->formatDate($item['added']);
$item['used'] = $this->formatDate($item['used']);
$item['updated'] = $this->formatDate($item['updated']);
return $item;
}, $data['list']);
$this->viewData['list'] = $data['list'];
$this->viewData['statusSelection'] = $this->combo_model->getStatusComboWithAll(
'status',
$filterData['status'] ?? $this->statusOptions['Active']
);
$this->viewData['filterData'] = $filterData;
$this->viewData['pagination'] = initPagination($this->pagePerItem, $data['totalItems'], $data['page'], $pagingUrl);
$this->renderAdminPage('transport_provider_accounts/list', $this->viewData);
}
public function create()
{
$this->load->helper(array('form', 'url'));
$this->viewData['statusOptions'] = $this->statusOptions;
$this->viewData['transport_provider_account'] = null;
$this->renderAdminPage('transport_provider_accounts/create', $this->viewData);
}
public function store()
{
$this->load->helper(array('form', 'url'));
$this->load->library('form_validation');
$inputData = $this->getFormData();
$this->viewData['transport_provider_account'] = $inputData;
$this->viewData['statusOptions'] = $this->statusOptions;
$this->setTransportProviderAccountCreationRules();
if ($this->form_validation->run() == false) {
$this->renderAdminPage('transport_provider_accounts/create', $this->viewData);
return;
}
$res = $this->transport_provider_account->createTransportProviderAccount($inputData);
if ($res['status'] == 'success') {
$this->session->set_flashdata('success', isset($res['message']) ? $res['message'] : 'Create success.');
redirect('/transport_provider_accounts');
} else {
$this->session->set_flashdata('error', isset($res['message']) ? $res['message'] : 'Create fail.');
$this->renderAdminPage('transport_provider_accounts/create', $this->viewData);
return;
}
}
private function formatDate($date) {
if (!empty($date)) {
return (new DateTime($date))->format('Y-m-d');
}
return '';
}
public function edit($id)
{
$this->load->helper(array('form', 'url'));
$res = $this->transport_provider_account->getTransportProviderAccountByID($id);
if ($res['data']) {
$res['data']['added'] = $this->formatDate($res['data']['added']);
$res['data']['updated'] = $this->formatDate($res['data']['updated']);
$res['data']['used'] = $this->formatDate($res['data']['used']);
}
$this->viewData['transport_provider_account'] = isset($res['data']) ? $res['data'] : [];
$this->viewData['statusOptions'] = $this->statusOptions;
$this->viewData['id'] = $id;
$this->renderAdminPage('transport_provider_accounts/edit', $this->viewData);
}
public function update($id)
{
$this->load->helper(array('form', 'url'));
$this->load->library('form_validation');
$inputData = $this->getFormData();
$this->viewData['statusOptions'] = $this->statusOptions;
$this->viewData['transport_provider_account'] = $inputData;
$this->viewData['id'] = $id;
$this->setTransportProviderAccountUpdateRules();
// $this->setTransportProviderAccountCreationRules();
if ($this->form_validation->run() == false) {
$this->renderAdminPage('transport_provider_accounts/edit', $this->viewData);
return;
}
$inputData = array_filter($inputData, function($value) {
return (isset($value) && trim(''.$value) !== '');
});
$res = $this->transport_provider_account->updateTransportProviderAccountById($id, $inputData);
if ($res['status'] == 'success') {
$this->session->set_flashdata('success', isset($res['message']) ? $res['message'] : 'Create success');
redirect('/transport_provider_accounts');
} else {
$this->session->set_flashdata('error', $res['message']);
$this->renderAdminPage('transport_provider_accounts/edit', $this->viewData);
return;
}
}
public function remove($param)
{
$res = $this->transport_provider_account->removeTransportProviderAccountById($param);
if (!$res['success'] != 'success') {
$this->viewData['errMsg'] = isset($res['message']) ? $res['message'] : 'Something went wrong. Please try again later.';
$this->renderAdminPage('transport_provider_accounts', $this->viewData);
return;
}
redirect('/transport_provider_accounts');
}
protected function renderAdminPage($page_name, $data)
{
$this->load->view('admin/view_admin_header', $data);
$this->load->view($page_name, $data);
$this->load->view('admin/view_admin_footer', $data);
}
private function getFormData()
{
return [
'transport_provider_id' => $this->input->post('transport_provider_id'),
'transport_provider_name' => $this->input->post('transport_provider_name'),
'email' => $this->input->post('email'),
'phone' => $this->input->post('phone'),
'name' => $this->input->post('name'),
'added' => $this->input->post('added'),
'updated' => $this->input->post('updated'),
'active' => (boolean)$this->input->post('active'),
'parameters' => json_decode($this->input->post('parameters'), true),
'used' => $this->input->post('used'),
'pool' => (int)$this->input->post('pool'),
];
}
private function setTransportProviderAccountCreationRules()
{
$config = [
[
'field' => 'transport_provider_id',
'label' => 'Transport Provider ID',
'rules' => 'required',
'errors' => array(
'max_length' => 'Max length is 50.'
),
],
[
'field' => 'email',
'label' => 'Email',
'rules' => 'required|max_length[200]|callback_valid_email',
'errors' => array(
'max_length' => 'Max length is 200.',
'valid_email' => 'Email is invalid !!!'
)
],
[
'field' => 'phone',
'label' => 'Phone',
'rules' => 'required|max_length[20]', // TODO: regex
'errors' => array(
'max_length' => 'Max length is 200.'
)
],
[
'field' => 'name',
'label' => 'Name',
'rules' => 'required|max_length[50]',
'errors' => array(
'max_length' => 'Max length is 50.'
)
],
/* [
'field' => 'added',
'label' => 'Added',
'rules' => 'required', // TODO: timestamp
],
[
'field' => 'updated',
'label' => 'Updated', // TODO: timestamp
'rules' => 'required|max_length[200]',
'errors' => array(
'max_length' => 'Max length is 200.'
)
],*/
[
'field' => 'timeout',
'label' => 'Timeout',
'rules' => 'd', // TODO: timestamp
],
[
'field' => 'active',
'label' => 'Active',
'rules' => 'required', // TODO: boolean
],
/* [
'field' => 'used',
'label' => 'Used',
'rules' => 'required',
],
*/
[
'field' => 'pool',
'label' => 'Pool',
'rules' => 'required|callback_valid_pool',
],
[
'field' => 'parameters',
'label' => 'Parameters',
'rules' => 'required|callback_is_json',
'errors' => array(
'is_json' => 'Only input json.'
)
]
];
$this->form_validation->set_rules($config);
}
private function setTransportProviderAccountUpdateRules() {
$config = [
[
'field' => 'transport_provider_id',
'label' => 'Transport Provider ID',
'rules' => 'required',
'errors' => array(
'max_length' => 'Max length is 50.'
),
],
[
'field' => 'pool',
'label' => 'Pool',
'rules' => 'required|callback_valid_pool',
],
];
$this->form_validation->set_rules($config);
}
public function is_json($data)
{
return (json_decode($data) != NULL) ? true : false;
}
public function is_out_of_range_int4($number)
{
return is_numeric($number) && $number >= MIN_INT_4 && $number <= MAX_INT_4;
}
public function is_out_of_range_int2($number)
{
return is_numeric($number) && $number >= MIN_INT_2 && $number <= MAX_INT_2;
}
/**
* Valid Email
*
* @access public
* @param string
* @return bool
*/
public function valid_email($str)
{
return ( ! preg_match("/^([a-z0-9\+_\-]+)(\.[a-z0-9\+_\-]+)*@([a-z0-9\-]+\.)+[a-z]{2,6}$/ix", $str)) ? FALSE : TRUE;
}
public function valid_pool($number) {
return is_numeric($number) && $number > 0 && $number < 1000;
}
public function getTransportProviderByName() {
$name = $this->input->get()['q'];
$res = $this->transport_provider->getTransportProviderByName([ 'name' => $name ]);
echo json_encode($res);
}
}
+216
View File
@@ -0,0 +1,216 @@
<?php
defined('BASEPATH') or exit('No direct script access allowed');
use Carbon\Carbon;
class Trips extends Admin_Controller
{
public $viewData = array();
public $pagePerItem = 10;
public function __construct()
{
parent::__construct();
// Load model
$this->load->model('parsedEmailItem_model', 'parsedEmailItem');
$this->viewData['selectedTab'] = 'trip';
$this->load->helper('pagination');
}
public function index()
{
$this->load->helper(array('form', 'url'));
//get query string filter
$page = $this->input->get('page', true);
$travelDate = $this->input->get('travel_date', true);
$duration = $this->input->get('duration', true);
$cost = $this->input->get('cost', true);
$transportProviderId = $this->input->get('transport_provider_id', true);
$distance = $this->input->get('distance', true);
$filterData = $this->input->get();
$queryString = $this->input->server('QUERY_STRING');
// remove empty value
$filterData = array_filter($filterData, function ($v, $k) {
return $v != '';
}, ARRAY_FILTER_USE_BOTH);
$pagingUrl = empty($queryString) ? uri_string() : uri_string() . '?' . $queryString;
$pagingUrl = remove_querystring_var($pagingUrl, 'page');
$data = $this->parsedEmailItem->getParsedEmailItemList($filterData);
$this->viewData['list'] = $data['list'];
$this->viewData['filterData'] = $filterData;
$this->viewData['pagination'] = initPagination($this->pagePerItem, $data['itemTotal'], $data['page'], $pagingUrl);
//$this->template->load('trips/trips', $this->viewData);
$this->renderAdminPage('trips/trips', $this->viewData);
}
public function create()
{
$this->load->helper(array('form', 'url'));
$this->viewData['tripItem'] = null;
$this->template->load('trips/create', $this->viewData);
}
public function store()
{
$this->load->helper(array('form', 'url'));
$this->load->library('form_validation');
$this->viewData['tripItem'] = null;
$this->setTripCreationRules();
if ($this->form_validation->run() == false) {
$this->template->load('trips/create', $this->viewData);
return;
}
$inputData = [
'travel_date' => Carbon::parse($this->input->post('travel_date'))->format('Y-m-d'),
'travel_date_end' => Carbon::parse($this->input->post('travel_date_end'))->format('Y-m-d'),
'cost' => $this->input->post('cost'),
'cost_raw' => $this->input->post('cost_raw'),
'duration' => $this->input->post('duration'),
'distance' => $this->input->post('distance'),
'transport_provider_id' => $this->input->post('transport_provider_id'),
'location_start_id' => $this->input->post('location_start_id'),
'location_end_id' => $this->input->post('location_end_id'),
'scheduled' => Carbon::now()->format('Y-m-d')
];
$res = $this->parsedEmailItem->createParsedEmailItem($inputData);
if ($res['success']) {
$this->session->set_flashdata('success', $res['message']);
redirect('/trips');
} else {
$this->session->set_flashdata('error', $res['message']);
$this->template->load('trips/create', $this->viewData);
return;
}
}
public function edit($id)
{
$this->load->helper(array('form', 'url'));
$tripItem = $this->parsedEmailItem->getParsedEmailItem($id);
$this->viewData['tripItem'] = $tripItem;
$this->viewData['tripId'] = $id;
$this->template->load('trips/edit', $this->viewData);
}
public function update($id)
{
$this->load->helper(array('form', 'url'));
$this->load->library('form_validation');
$this->viewData['tripItem'] = null;
$this->viewData['tripId'] = $id;
$this->setTripCreationRules();
if ($this->form_validation->run() == false) {
$this->template->load('trips/edit', $this->viewData);
return;
}
$inputData = [
'travel_date' => Carbon::parse($this->input->post('travel_date'))->format('Y-m-d'),
'travel_date_end' => Carbon::parse($this->input->post('travel_date_end'))->format('Y-m-d'),
'cost' => $this->input->post('cost'),
'cost_raw' => $this->input->post('cost_raw'),
'duration' => $this->input->post('duration'),
'distance' => $this->input->post('distance'),
'transport_provider_id' => $this->input->post('transport_provider_id'),
'location_start_id' => $this->input->post('location_start_id'),
'location_end_id' => $this->input->post('location_end_id')
];
$res = $this->parsedEmailItem->updateParsedEmailItem($id, $inputData);
if ($res['success']) {
$this->session->set_flashdata('success', $res['message']);
redirect('/trips');
} else {
$this->session->set_flashdata('error', $res['message']);
$this->template->load('trips/edit', $this->viewData);
return;
}
}
public function delete($id)
{
$res = $this->parsedEmailItem->deleteParsedEmailItem($id);
if (!$res['success']) {
$this->session->set_flashdata('success', $res['message']);
} else {
$this->session->set_flashdata('error', $res['error']);
}
redirect('/trips');
}
private function setTripCreationRules()
{
$config = [
[
'field' => 'travel_date',
'label' => 'Travel date',
'rules' => 'required',
],
[
'field' => 'travel_date_end',
'label' => 'Travel date end',
'rules' => 'required',
],
[
'field' => 'location_start_id',
'label' => 'Location start',
'rules' => 'required',
],
[
'field' => 'location_end_id',
'label' => 'Location end',
'rules' => 'required',
],
[
'field' => 'duration',
'label' => 'Duration',
'rules' => 'required',
],
[
'field' => 'distance',
'label' => 'Distance',
'rules' => 'required',
],
[
'field' => 'cost_raw',
'label' => 'Cost raw',
'rules' => 'required',
],
[
'field' => 'cost',
'label' => 'Cost',
'rules' => 'required',
],
[
'field' => 'transport_provider_id',
'label' => 'Transport provider',
'rules' => 'required',
]
];
$this->form_validation->set_rules($config);
}
protected function renderAdminPage($page_name, $data) {
$this->load->view('admin/view_admin_header', $data);
$this->load->view($page_name, $data);
$this->load->view('admin/view_admin_footer', $data);
}
}
+329
View File
@@ -0,0 +1,329 @@
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Uploads extends Admin_Controller {
var $template = array(
'table_open' => "<table class='table table-striped table-hover table-bordered table-condensed'>",
'thead_open' => '<thead class=\'bg-indigo\'>',
'thead_close' => '</thead>',
'heading_row_start' => '<tr>',
'heading_row_end' => '</tr>',
'heading_cell_start' => '<th>',
'heading_cell_end' => '</th>',
'tbody_open' => '<tbody>',
'tbody_close' => '</tbody>',
'row_start' => '<tr>',
'row_end' => '</tr>',
'cell_start' => '<td>',
'cell_end' => '</td>',
'row_alt_start' => '<tr>',
'row_alt_end' => '</tr>',
'cell_alt_start' => '<td>',
'cell_alt_end' => '</td>',
'table_close' => '</table>'
);
public function index() {
$this->load->helper('url');
$data = array();
$this->renderUploadPage('view_dash', $data);
// echo 'Ameye Olu';
}
protected function renderAdminPage($page_name, $data) {
$this->load->view('admin/view_admin_header', $data);
$this->load->view('admin/' . $page_name, $data);
$this->load->view('admin/view_admin_footer', $data);
}
public function getValueOfCardImages() {
return [
'category_id' => trim($this->input->get('card_category')),
'unique_id' => trim($this->input->get('unique_id')),
'from_date' => trim($this->input->get('from_date')),
'to_date' => trim($this->input->get('to_date')),
'catid' => trim($this->input->get('catid'))
];
}
public function setComboForCardImages($params) {
$this->load->model('combo_model');
$combo['card_category'] = $this->combo_model->getCardImageCategoryCombo(
'card_category',
$params['category_id']
);
$combo['catid'] = $this->combo_model->getCardImageCategoryCombo(
'catid',
$params['catid']
);
return $combo;
}
public function validateValueForCardImages($params) {
$this->load->library('form_validation');
$this->form_validation->set_data($params);
$this->setFormRuleForCardImages();
$errors = [];
if ($this->form_validation->run() === FALSE) {
$errors = $this->form_validation->error_array();
}
return $errors;
}
public function setFormRuleForCardImages() {
$date_pattern = 'regex_match[/\d{4}-\d{2}-\d{2}/]';
$this->form_validation->set_rules(
'card_category',
'Category Card',
'numberic'
);
$this->form_validation->set_rules(
'from_added',
'From Added',
$date_pattern
);
$this->form_validation->set_rules(
'to_added',
'To Added',
$date_pattern
);
}
public function load_pagination($all_record, $params, $action) {
$action_hidden = $this->input->get('action_hidden');
if ( isset( $params['category_id'] ) ) {
$category = $params['category_id'];
unset( $params['category_id'] );
$params['card_category'] = $category;
}
// pagination
$this->load->library('pagination');
$config["total_rows"] = count($all_record);
$config["base_url"] = base_url() . "/" . get_class($this) . "/" . $action;
$config["per_page"] = 10;
$config["uri_segment"] = 3;
$config["num_links"] = 5;
$config["suffix"] =
"?action_hidden=${action_hidden}&"
. http_build_query($params);
$config["first_url"] =
"/uploads/{$action}/0?action_hidden=${action_hidden}&"
. http_build_query($params);
$config['full_tag_open'] = "<ul class='pagination'>";
$config['full_tag_close'] = "</ul>";
$config['num_tag_open'] = '<li>';
$config['num_tag_close'] = '</li>';
$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
$config['next_tag_open'] = "<li>";
$config['next_tagl_close'] = "</li>";
$config['prev_tag_open'] = "<li>";
$config['prev_tagl_close'] = "</li>";
$config['first_tag_open'] = "<li>";
$config['first_tagl_close'] = "</li>";
$config['last_tag_open'] = "<li>";
$config['last_tagl_close'] = "</li>";
$this->pagination->initialize($config);
$page = ( $this->uri->segment(3) ) ? $this->uri->segment(3) : 0;
$offset = is_numeric($page) ? $page : 0;
return [
'link' => $this->pagination->create_links(),
'offset' => $offset,
'limit' => $config["per_page"]
];
}
public function cardimages() {
global $savvyext;
$this->load->model('card_image_model');
$data['storage'] = $savvyext->cfgReadChar('system.storage_url');
$data['message'] = "";
if ($this->input->post()) {
$data = $this->cardimagesPost($data);
}
$params = $this->getValueOfCardImages();
$data = array_merge($data, $this->setComboForCardImages($params));
$errors = $this->validateValueForCardImages($params);
$params = array_filter($params, function($ele) {
return $ele !== "";
});
$params = array_diff_key($params, $errors);
$data = array_merge(
$data,
$params,
$this->load_pagination(
$this->card_image_model->get_card_image_records($params),
$params,
'cardimages'
)
);
$data['images'] =
array_map(
function($ele) {
$ele['file_size'] = $this->human_filesize($ele['file_size']);
return $ele;
},
$this->card_image_model->get_card_image_records(
$params,
$data['limit'],
$data['offset']
)
);
// add filter after update card images
$filter = $this->add_filter_after_submit();
if ( ($_SERVER['REQUEST_METHOD'] === 'POST') ) {
redirect( sprintf( '/uploads/cardimages?%s', $filter ) );
}
$this->renderUploadPage( 'cardimages', $data);
}
private function add_filter_after_submit( $http_query = '' ) {
$history = filter_var( $_SERVER['HTTP_REFERER'], FILTER_SANITIZE_URL );
$history = parse_url( $history );
if ( isset( $history['query'] ) ) {
parse_str( $history['query'], $query );
$http_query = http_build_query( $query );
}
return $http_query;
}
private function human_filesize($bytes, $decimals = 2) {
$sz = 'BKMGTP';
$factor = floor((strlen($bytes) - 1) / 3);
return sprintf("%.{$decimals}f", $bytes / pow(1024, $factor)) . @$sz[$factor];
}
public function uploadInterface($data) {
return $this->cardimagesPost($data);
}
private function cardimagesPost($data) {
global $savvyext;
$bucket_name = '';
$catid = (int)$this->input->post('catid');
if ($catid<1) { $data['message'] = 'Please select category'; return $data; }
$q = "SELECT name FROM card_image_category WHERE id='${catid}'";
$r = $this->read_replica->query($q);
foreach ($r->result() as $row) {
$bucket_name = $row->name;
break;
}
if ($bucket_name=='') {
$data['message'] = 'Invalid category';
return $data;
}
// Process file
$imgData = $this->processFile('cardimg', array('jpg'=>1,'jpeg'=>1,'png'=>1,'gif'=>1));
if ($imgData==NULL || !is_array($imgData)) {
$data['message'] = 'Failed to process uploaded image! ('.$imgData.')';
return $data;
}
$this->load->library('googlestorage');
$this->googlestorage->Init(
$savvyext->cfgReadChar('google.storage_project_id'),
$savvyext->cfgReadChar('google.storage_auth_file')
);
$storage = $this->googlestorage;
// Get bucket
$buckets = $storage->ListBuckets();
if (array_key_exists($bucket_name, $buckets)) {
$bucket = $buckets[$bucket_name];
} else {
// Create bucket
$bucket = $storage->CreateBucket($bucket_name);
}
if ($bucket==NULL || !is_object($bucket)) {
$data['message'] = 'Cannot get or create bucket!';
return $data;
}
$total = count($imgData['name']);
// Loop through each file
for ($i = 0 ; $i < $total; $i++) {
$uniqueId = $storage->UniqueId();
$objectName = $uniqueId.".".$imgData['format'][$i];
$source = $imgData['tmp_name'][$i];
$object = $storage->UploadObject($bucket_name, $objectName, $source);
if ($object==NULL || !is_object($object)) {
$data['message'] = 'Failed to upload image!' . $imgData['name'][$i];
break;
} else {
$data['message'] = 'Image uploaded!';
// Save image data
$q = "INSERT INTO card_images (catid, uniqueid, name, file_size, format, dimensions) VALUES(";
$q.= "'${catid}','${uniqueId}','".$imgData['name'][$i]."','".$imgData['file_size'][$i]."','".$imgData['format'][$i]."','".$imgData['dimensions'][$i]."') RETURNING id";
//error_log($q);
$r = $this->db->query($q);
$f = $r->row_array();
$data["card_image_id"][$i] = $f["id"];
}
}
return $data;
}
private function processFile($var, $formats) {
if (!isset($_FILES[$var])) return 'The file was not uploaded!';
if (is_array($_FILES[$var]['error'])) {
foreach ($_FILES[$var]['error'] as $key => $error) {
if ($error != UPLOAD_ERR_OK) {
return $error;
}
}
} else if (isset($_FILES[$var]['error']) && $_FILES[$var]['error'] != UPLOAD_ERR_OK) {
return $_FILES[$var]['error'];
}
$error = $_FILES[$var]['error'];
$name = $_FILES[$var]['name'];
$file_size = $_FILES[$var]['size'];
$tmp_name = $_FILES[$var]['tmp_name'];
// Count # of uploaded files in array
$total = count($_FILES[$var]['name']);
$result_formats = [];
$result_dimensions = [];
// Loop through each file
for ( $i=0 ; $i < $total ; $i++ ) {
$format = strtolower(pathinfo($_FILES[$var]['name'][$i], PATHINFO_EXTENSION));
if (!isset($formats[$format]) || $formats[$format]!=1) {
return 'Invalid file format: '.$format;
}
list($width, $height, $type, $attr) = getimagesize($tmp_name[$i]);
$dimensions = $width . 'x' . $height;
array_push($result_formats, $format);
array_push($result_dimensions, $dimensions);
}
$result = array(
'tmp_name' => $tmp_name,
'name' => $name,
'file_size' => $file_size,
'format' => $result_formats,
'dimensions' => $result_dimensions
);
return $result;
}
}
+53
View File
@@ -0,0 +1,53 @@
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Welcome extends Bko_Controller {
public function index() {
$data['action_message'] = '';
$data['ip'] ='';
if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
$data['ip'] = $_SERVER['HTTP_CLIENT_IP'];
} elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
$data['ip'] = $_SERVER['HTTP_X_FORWARDED_FOR'];
} else {
$data['ip'] = $_SERVER['REMOTE_ADDR'];
}
if ($this->input->post()) {
$valid_entry = false;
$username = $password = $error_message = '';
$this->testLoginInput($username, $password, $error_message, $valid_entry);
// echo $valid_entry;
if ($valid_entry == true) {
$in['username'] = $username;
$in['password'] = $password;
$in['action'] = SAVVY_BKO_LOGIN;
$out = array();
$ret = $this->savvy_api($in, $out);
//var_dump($ret);
//var_dump($out);
if ($ret == PHP_API_OK) {
$this->buildUserSession($ret, $out);
redirect('dash');
} else {
$data['action_message'] = $this->formatedMesage('ERROR', 'Invalid Username/Password');
}
} else {
$data['action_message'] = $this->formatedMesage('ERROR', $error_message);
}
}
// echo rand(100,999);
$this->load->view('home/view_home', $data);
}
function formatedMesage($msgType, $theMessage) {
return "<div class=\"text-left\"><div class=\"alert alert-danger no-border\">" . $theMessage . "</div></div>";
}
}
+252
View File
@@ -0,0 +1,252 @@
{
"BD": "Bangladesh",
"BE": "Belgium",
"BF": "Burkina Faso",
"BG": "Bulgaria",
"BA": "Bosnia and Herzegovina",
"BB": "Barbados",
"WF": "Wallis and Futuna",
"BL": "Saint Barthelemy",
"BM": "Bermuda",
"BN": "Brunei",
"BO": "Bolivia",
"BH": "Bahrain",
"BI": "Burundi",
"BJ": "Benin",
"BT": "Bhutan",
"JM": "Jamaica",
"BV": "Bouvet Island",
"BW": "Botswana",
"WS": "Samoa",
"BQ": "Bonaire, Saint Eustatius and Saba ",
"BR": "Brazil",
"BS": "Bahamas",
"JE": "Jersey",
"BY": "Belarus",
"BZ": "Belize",
"RU": "Russia",
"RW": "Rwanda",
"RS": "Serbia",
"TL": "East Timor",
"RE": "Reunion",
"TM": "Turkmenistan",
"TJ": "Tajikistan",
"RO": "Romania",
"TK": "Tokelau",
"GW": "Guinea-Bissau",
"GU": "Guam",
"GT": "Guatemala",
"GS": "South Georgia and the South Sandwich Islands",
"GR": "Greece",
"GQ": "Equatorial Guinea",
"GP": "Guadeloupe",
"JP": "Japan",
"GY": "Guyana",
"GG": "Guernsey",
"GF": "French Guiana",
"GE": "Georgia",
"GD": "Grenada",
"GB": "United Kingdom",
"GA": "Gabon",
"SV": "El Salvador",
"GN": "Guinea",
"GM": "Gambia",
"GL": "Greenland",
"GI": "Gibraltar",
"GH": "Ghana",
"OM": "Oman",
"TN": "Tunisia",
"JO": "Jordan",
"HR": "Croatia",
"HT": "Haiti",
"HU": "Hungary",
"HK": "Hong Kong",
"HN": "Honduras",
"HM": "Heard Island and McDonald Islands",
"VE": "Venezuela",
"PR": "Puerto Rico",
"PS": "Palestinian Territory",
"PW": "Palau",
"PT": "Portugal",
"SJ": "Svalbard and Jan Mayen",
"PY": "Paraguay",
"IQ": "Iraq",
"PA": "Panama",
"PF": "French Polynesia",
"PG": "Papua New Guinea",
"PE": "Peru",
"PK": "Pakistan",
"PH": "Philippines",
"PN": "Pitcairn",
"PL": "Poland",
"PM": "Saint Pierre and Miquelon",
"ZM": "Zambia",
"EH": "Western Sahara",
"EE": "Estonia",
"EG": "Egypt",
"ZA": "South Africa",
"EC": "Ecuador",
"IT": "Italy",
"VN": "Vietnam",
"SB": "Solomon Islands",
"ET": "Ethiopia",
"SO": "Somalia",
"ZW": "Zimbabwe",
"SA": "Saudi Arabia",
"ES": "Spain",
"ER": "Eritrea",
"ME": "Montenegro",
"MD": "Moldova",
"MG": "Madagascar",
"MF": "Saint Martin",
"MA": "Morocco",
"MC": "Monaco",
"UZ": "Uzbekistan",
"MM": "Myanmar",
"ML": "Mali",
"MO": "Macao",
"MN": "Mongolia",
"MH": "Marshall Islands",
"MK": "Macedonia",
"MU": "Mauritius",
"MT": "Malta",
"MW": "Malawi",
"MV": "Maldives",
"MQ": "Martinique",
"MP": "Northern Mariana Islands",
"MS": "Montserrat",
"MR": "Mauritania",
"IM": "Isle of Man",
"UG": "Uganda",
"TZ": "Tanzania",
"MY": "Malaysia",
"MX": "Mexico",
"IL": "Israel",
"FR": "France",
"IO": "British Indian Ocean Territory",
"SH": "Saint Helena",
"FI": "Finland",
"FJ": "Fiji",
"FK": "Falkland Islands",
"FM": "Micronesia",
"FO": "Faroe Islands",
"NI": "Nicaragua",
"NL": "Netherlands",
"NO": "Norway",
"NA": "Namibia",
"VU": "Vanuatu",
"NC": "New Caledonia",
"NE": "Niger",
"NF": "Norfolk Island",
"NG": "Nigeria",
"NZ": "New Zealand",
"NP": "Nepal",
"NR": "Nauru",
"NU": "Niue",
"CK": "Cook Islands",
"XK": "Kosovo",
"CI": "Ivory Coast",
"CH": "Switzerland",
"CO": "Colombia",
"CN": "China",
"CM": "Cameroon",
"CL": "Chile",
"CC": "Cocos Islands",
"CA": "Canada",
"CG": "Republic of the Congo",
"CF": "Central African Republic",
"CD": "Democratic Republic of the Congo",
"CZ": "Czech Republic",
"CY": "Cyprus",
"CX": "Christmas Island",
"CR": "Costa Rica",
"CW": "Curacao",
"CV": "Cape Verde",
"CU": "Cuba",
"SZ": "Swaziland",
"SY": "Syria",
"SX": "Sint Maarten",
"KG": "Kyrgyzstan",
"KE": "Kenya",
"SS": "South Sudan",
"SR": "Suriname",
"KI": "Kiribati",
"KH": "Cambodia",
"KN": "Saint Kitts and Nevis",
"KM": "Comoros",
"ST": "Sao Tome and Principe",
"SK": "Slovakia",
"KR": "South Korea",
"SI": "Slovenia",
"KP": "North Korea",
"KW": "Kuwait",
"SN": "Senegal",
"SM": "San Marino",
"SL": "Sierra Leone",
"SC": "Seychelles",
"KZ": "Kazakhstan",
"KY": "Cayman Islands",
"SG": "Singapore",
"SE": "Sweden",
"SD": "Sudan",
"DO": "Dominican Republic",
"DM": "Dominica",
"DJ": "Djibouti",
"DK": "Denmark",
"VG": "British Virgin Islands",
"DE": "Germany",
"YE": "Yemen",
"DZ": "Algeria",
"US": "United States",
"UY": "Uruguay",
"YT": "Mayotte",
"UM": "United States Minor Outlying Islands",
"LB": "Lebanon",
"LC": "Saint Lucia",
"LA": "Laos",
"TV": "Tuvalu",
"TW": "Taiwan",
"TT": "Trinidad and Tobago",
"TR": "Turkey",
"LK": "Sri Lanka",
"LI": "Liechtenstein",
"LV": "Latvia",
"TO": "Tonga",
"LT": "Lithuania",
"LU": "Luxembourg",
"LR": "Liberia",
"LS": "Lesotho",
"TH": "Thailand",
"TF": "French Southern Territories",
"TG": "Togo",
"TD": "Chad",
"TC": "Turks and Caicos Islands",
"LY": "Libya",
"VA": "Vatican",
"VC": "Saint Vincent and the Grenadines",
"AE": "United Arab Emirates",
"AD": "Andorra",
"AG": "Antigua and Barbuda",
"AF": "Afghanistan",
"AI": "Anguilla",
"VI": "U.S. Virgin Islands",
"IS": "Iceland",
"IR": "Iran",
"AM": "Armenia",
"AL": "Albania",
"AO": "Angola",
"AQ": "Antarctica",
"AS": "American Samoa",
"AR": "Argentina",
"AU": "Australia",
"AT": "Austria",
"AW": "Aruba",
"IN": "India",
"AX": "Aland Islands",
"AZ": "Azerbaijan",
"IE": "Ireland",
"ID": "Indonesia",
"UA": "Ukraine",
"QA": "Qatar",
"MZ": "Mozambique"
}
+11
View File
@@ -0,0 +1,11 @@
<!DOCTYPE html>
<html>
<head>
<title>403 Forbidden</title>
</head>
<body>
<p>Directory access is forbidden.</p>
</body>
</html>
+211
View File
@@ -0,0 +1,211 @@
<?php
class SAV_Controller extends CI_Controller {
var $template = array(
'table_open' => "<table class='table-responsive table-striped table-hover table-bordered table-condensed'>",
'thead_open' => '<thead class=\'bg-indigo\'>',
'thead_close' => '</thead>',
'heading_row_start' => '<tr style=\'padding:1px;\'>',
'heading_row_end' => '</tr>',
'heading_cell_start' => '<th>',
'heading_cell_end' => '</th>',
'tbody_open' => '<tbody>',
'tbody_close' => '</tbody>',
'row_start' => '<tr style=\'padding:0px;\'>',
'row_end' => '</tr>',
'cell_start' => '<td>',
'cell_end' => '</td>',
'row_alt_start' => '<tr>',
'row_alt_end' => '</tr>',
'cell_alt_start' => '<td>',
'cell_alt_end' => '</td>',
'table_close' => '</table>'
);
var $template_nohead = array(
'table_open' => "<table class='table-responsive table-striped table-hover table-bordered table-condensed'>",
'thead_open' => '<thead>',
'thead_close' => '</thead>',
'heading_row_start' => '<tr style=\'padding:3px;\'>',
'heading_row_end' => '</tr>',
'heading_cell_start' => '<th>',
'heading_cell_end' => '</th>',
'tbody_open' => '<tbody>',
'tbody_close' => '</tbody>',
'row_start' => '<tr style=\'padding:3px;\'>',
'row_end' => '</tr>',
'cell_start' => '<td>',
'cell_end' => '</td>',
'row_alt_start' => '<tr>',
'row_alt_end' => '</tr>',
'cell_alt_start' => '<td>',
'cell_alt_end' => '</td>',
'table_close' => '</table>'
);
public $data = array();
function __construct() {
parent::__construct();
}
protected function smart_htmlspecialchars($str) {
if (substr($str, 0, 1) == '<')
return $str;
return htmlspecialchars($str);
}
protected function sql_escape_func($inp) {
if (is_array($inp)) {
return array_map(__METHOD__, $inp);
}
if (!empty($inp) && is_string($inp)) {
return str_replace(array('\\', "\0", "\n", "\r", "'", '"', "\x1a"), array('\\\\', '\\0', '\\n', '\\r', "\\'", '\\"', '\\Z'), $inp);
}
return $inp;
}
protected function savvy_api($in, &$out) {
global $savvyext;
$ret = -1;
$in['pid'] = 115;
$in['backoffice'] = 1;
error_log(json_encode($in));
$out = $savvyext->savvyext_api($in);
$ret = $out["retval"];
error_log("ret = $ret");
error_log(json_encode($out));
return $ret;
}
// call API with no default params
protected function savvy_api_clearly($in, &$out) {
global $savvyext;
$ret = -1;
error_log(json_encode($in));
$out = $savvyext->savvyext_api($in);
$ret = $out["retval"];
error_log("ret = $ret");
error_log(json_encode($out));
return $ret;
}
protected function main_api_post($endpoint,$payload) {
global $savvyext;
$httpAuthToken = $savvyext->cfgReadChar('system.oauth2_token');
$encryptionAlg = $savvyext->cfgReadChar('encryption.algorithm');
$encryptionKey = $savvyext->cfgReadChar('encryption.key');
$encryptionIV = $savvyext->cfgReadChar('encryption.iv');
$encrypted_payload = bin2hex(
openssl_encrypt(
$payload,
$encryptionAlg,
$encryptionKey,
OPENSSL_RAW_DATA,
$encryptionIV
));
$postdata = "{\"encrypted_payload\": \"${encrypted_payload}\"}";
$url = $savvyext->cfgReadChar('system.api_url').$endpoint;
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata);
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',
'Content-Length: ' . strlen($postdata),
'Authorization: Server-Token ' . $httpAuthToken)
);
$body = curl_exec($ch);
$result = json_decode($body,true);
if (is_array($result) && array_key_exists('payload',$result)) {
$decrypted = openssl_decrypt(
hex2bin(
$result['payload']
),
$encryptionAlg,
$encryptionKey,
OPENSSL_RAW_DATA,
$encryptionIV
);
} else {
$decrypted = $body; // Attempt without encryption
}
$payload = json_decode($decrypted, true);
return [$payload,$decrypted,$result,$body];
}
protected function main_api_get($endpoint,$payload) {
global $savvyext;
$httpAuthToken = $savvyext->cfgReadChar('system.oauth2_token');
$encryptionAlg = $savvyext->cfgReadChar('encryption.algorithm');
$encryptionKey = $savvyext->cfgReadChar('encryption.key');
$encryptionIV = $savvyext->cfgReadChar('encryption.iv');
$url = $savvyext->cfgReadChar('system.api_url').$endpoint.$payload;
//echo $url;
$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);
if (is_array($result) && array_key_exists('payload',$result)) {
$decrypted = openssl_decrypt(
hex2bin(
$result['payload']
),
$encryptionAlg,
$encryptionKey,
OPENSSL_RAW_DATA,
$encryptionIV
);
} else {
$decrypted = $body; // Attempt without encryption
}
$payload = json_decode($decrypted, true);
return [$payload,$decrypted,$result,$body];
}
function formatedMesage($msgType, $theMessage) {
return "<div class=\"text-left\"><div class=\"alert alert-danger no-border\">" . $theMessage . "</div></div>";
}
protected function renderMemberPage($page_name, $data) {
$this->load->view('admin/view_admin_header', $data);
$this->load->view('member/' . $page_name, $data);
$this->load->view('admin/view_admin_footer', $data);
}
protected function renderAdminPage($page_name, $data) {
$this->load->view('admin/view_admin_header', $data);
$this->load->view('admin/' . $page_name, $data);
$this->load->view('admin/view_admin_footer', $data);
}
protected function renderUploadPage($page_name, $data) {
$this->load->view('admin/view_admin_header', $data);
$this->load->view('upload/' . $page_name, $data);
$this->load->view('admin/view_admin_footer', $data);
}
}
+11
View File
@@ -0,0 +1,11 @@
<!DOCTYPE html>
<html>
<head>
<title>403 Forbidden</title>
</head>
<body>
<p>Directory access is forbidden.</p>
</body>
</html>
+20
View File
@@ -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;
}
}
+163
View File
@@ -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);
}
}
+155
View File
@@ -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;
}
+46
View File
@@ -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();
}
}
+23
View File
@@ -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();
}
+11
View File
@@ -0,0 +1,11 @@
<!DOCTYPE html>
<html>
<head>
<title>403 Forbidden</title>
</head>
<body>
<p>Directory access is forbidden.</p>
</body>
</html>
+193
View File
@@ -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
);
}
}
+43
View File
@@ -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);
}
+8
View File
@@ -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");
}
+11
View File
@@ -0,0 +1,11 @@
<!DOCTYPE html>
<html>
<head>
<title>403 Forbidden</title>
</head>
<body>
<p>Directory access is forbidden.</p>
</body>
</html>
+11
View File
@@ -0,0 +1,11 @@
<!DOCTYPE html>
<html>
<head>
<title>403 Forbidden</title>
</head>
<body>
<p>Directory access is forbidden.</p>
</body>
</html>
+11
View File
@@ -0,0 +1,11 @@
<!DOCTYPE html>
<html>
<head>
<title>403 Forbidden</title>
</head>
<body>
<p>Directory access is forbidden.</p>
</body>
</html>
+11
View File
@@ -0,0 +1,11 @@
<!DOCTYPE html>
<html>
<head>
<title>403 Forbidden</title>
</head>
<body>
<p>Directory access is forbidden.</p>
</body>
</html>
+130
View File
@@ -0,0 +1,130 @@
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Admin_Controller extends SAV_Controller {
const NONE_COUNT_RECORD = false;
const TEMP_DIRECTORY_UPLOAD = 'application/cache/upload';
const TEMP_DIRECTORY_DOWNLOAD = 'application/cache/download';
protected $read_replica;
var $template = array(
'table_open' => "<table style='background-color:aliceblue' class='table table-striped table-hover table-bordered table-condensed'>",
'thead_open' => '<thead class=\'bg-indigo\'>',
'thead_close' => '</thead>',
'heading_row_start' => '<tr>',
'heading_row_end' => '</tr>',
'heading_cell_start' => '<th>',
'heading_cell_end' => '</th>',
'tbody_open' => '<tbody>',
'tbody_close' => '</tbody>',
'row_start' => '<tr>',
'row_end' => '</tr>',
'cell_start' => '<td>',
'cell_end' => '</td>',
'row_alt_start' => '<tr>',
'row_alt_end' => '</tr>',
'cell_alt_start' => '<td>',
'cell_alt_end' => '</td>',
'table_close' => '</table>'
);
var $template_small = array(
'table_open' => "<table class='table table-striped table-hover table-bordered table-condensed' style='font-size:10px;'>",
'thead_open' => '<thead class=\'bg-teal\'>',
'thead_close' => '</thead>',
'heading_row_start' => '<tr>',
'heading_row_end' => '</tr>',
'heading_cell_start' => '<th>',
'heading_cell_end' => '</th>',
'tbody_open' => '<tbody>',
'tbody_close' => '</tbody>',
'row_start' => '<tr>',
'row_end' => '</tr>',
'cell_start' => '<td>',
'cell_end' => '</td>',
'row_alt_start' => '<tr>',
'row_alt_end' => '</tr>',
'cell_alt_start' => '<td>',
'cell_alt_end' => '</td>',
'table_close' => '</table>'
);
public $data = array();
function __construct() {
parent::__construct();
$this->read_replica = $this->load->database('savvy_replica', TRUE);
if (!isset($_SESSION['username']) or $_SESSION['username'] == '' or $_SESSION['firstname'] == '') {
redirect('logout');
}
}
protected function renderCardPage($page_name, $data) {
$this->load->view('admin/view_admin_header', $data);
$this->load->view('cards/' . $page_name, $data);
$this->load->view('admin/view_admin_footer', $data);
}
protected function renderEmissionPage($page_name, $data){
$this->load->view('admin/view_admin_header', $data);
$this->load->view('emission/' . $page_name, $data);
$this->load->view('admin/view_admin_footer', $data);
}
protected function returnAdminTable($tbq, $pgLink, $config = []) {
$this->load->library('pagination');
$query = $this->read_replica->query($tbq['count_query']);
$config['total_rows'] = $query->num_rows();
$config['base_url'] = base_url() . $pgLink;
$config['per_page'] = $config['per_page'] ?? 5;
$config['reuse_query_string'] = $config['reuse_query_string'] ?? FALSE;
$config['uri_segment'] = $config['uri_segment'] ?? 3;
$config['num_links'] = 5;
$config['full_tag_open'] = "<ul class='pagination'>";
$config['full_tag_close'] = "</ul>";
$config['num_tag_open'] = '<li>';
$config['num_tag_close'] = '</li>';
$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
$config['next_tag_open'] = "<li>";
$config['next_tagl_close'] = "</li>";
$config['prev_tag_open'] = "<li>";
$config['prev_tagl_close'] = "</li>";
$config['first_tag_open'] = "<li>";
$config['first_tagl_close'] = "</li>";
$config['last_tag_open'] = "<li>";
$config['last_tagl_close'] = "</li>";
$this->pagination->initialize($config);
$page = ($this->uri->segment($config['uri_segment'])) ? $this->uri->segment($config['uri_segment']) : 0;
$page = is_numeric($page) ? $page : 0;
$mysql = $tbq['query'] . " LIMIT " . $config["per_page"] . " OFFSET " . $page;
$this->load->library('table');
$this->table->set_template($this->template);
$query = $this->read_replica->query($mysql);
$data['limited_data'] = $query->result_array();
$data['output_table'] = $this->table->generate($query);
$data['links'] = $this->pagination->create_links();
return $data;
}
protected function makeGoogleAddress($rect) {
$data['directionsStart'] = $rect['to_street'] . "," . $rect['to_city'] . "," . $rect['to_state'] . " " . $rect['to_zipcode'] . ", USA";
$data['directionsEnd'] = $rect['from_street'] . "," . $rect['from_city'] . "," . $rect['from_state'] . " " . $rect['from_zipcode'] . ", USA";
return $data;
}
}
+55
View File
@@ -0,0 +1,55 @@
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Bko_Controller extends SAV_Controller {
public $data = array();
function __construct() {
parent::__construct();
if (!isset($_SESSION['username']) or $_SESSION['username'] == '') {
//redirect('site');
} else {
// erase the session properly if here
redirect('dash');
}
}
protected function buildUserSession($ret, $out) {
if ($ret == PHP_API_OK) {
$_SESSION['session_id'] = $out["sessionid"];
$_SESSION['sessionid'] = $out["sessionid"];
$_SESSION['username'] = $out["username"]; // $this->input->post('username');
$_SESSION['firstname'] = $out["firstname"]; // $ret->firstname;
$_SESSION['lastname'] = $out["lastname"]; // $ret->lastname;
$_SESSION['email'] = $out["email"]; // $ret->email;
$_SESSION['backoffice_id'] = $out["username"]; // $ret->id;
$_SESSION['pid'] = $out["pid"]; // $ret->id;
$_SESSION['loc'] = $out["loc"];
}
if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
$_SESSION['loc'] = $_SERVER['HTTP_CLIENT_IP'];
} elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
$_SESSION['loc'] = $_SERVER['HTTP_X_FORWARDED_FOR'];
} else {
$_SESSION['loc'] = $_SERVER['REMOTE_ADDR'];
}
}
protected function testLoginInput(&$username, &$password, &$error_message, &$valid_entry) {
$valid_entry = true;
$username = trim($this->input->post('username'));
$password = trim($this->input->post('password'));
if ($username == '' or $password == '') {
$valid_entry = false;
$error_message = 'Enter a Username/Password to continue';
}
}
}
+548
View File
@@ -0,0 +1,548 @@
<?php
/*
* Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved.
* For licensing, see LICENSE.html or http://ckeditor.com/license
*/
/**
* \brief CKEditor class that can be used to create editor
* instances in PHP pages on server side.
* @see http://ckeditor.com
*
* Sample usage:
* @code
* $CKEditor = new CKEditor();
* $CKEditor->editor("editor1", "<p>Initial value.</p>");
* @endcode
*/
class Ckeditor
{
/**
* The version of %CKEditor.
*/
const version = '3.6.1';
/**
* A constant string unique for each release of %CKEditor.
*/
const timestamp = 'B5GJ5GG';
/**
* URL to the %CKEditor installation directory (absolute or relative to document root).
* If not set, CKEditor will try to guess it's path.
*
* Example usage:
* @code
* $CKEditor->basePath = '/ckeditor/';
* @endcode
*/
public $basePath;
/**
* An array that holds the global %CKEditor configuration.
* For the list of available options, see http://docs.cksource.com/ckeditor_api/symbols/CKEDITOR.config.html
*
* Example usage:
* @code
* $CKEditor->config['height'] = 400;
* // Use @@ at the beggining of a string to ouput it without surrounding quotes.
* $CKEditor->config['width'] = '@@screen.width * 0.8';
* @endcode
*/
public $config = array();
/**
* A boolean variable indicating whether CKEditor has been initialized.
* Set it to true only if you have already included
* &lt;script&gt; tag loading ckeditor.js in your website.
*/
public $initialized = false;
/**
* Boolean variable indicating whether created code should be printed out or returned by a function.
*
* Example 1: get the code creating %CKEditor instance and print it on a page with the "echo" function.
* @code
* $CKEditor = new CKEditor();
* $CKEditor->returnOutput = true;
* $code = $CKEditor->editor("editor1", "<p>Initial value.</p>");
* echo "<p>Editor 1:</p>";
* echo $code;
* @endcode
*/
public $returnOutput = false;
/**
* An array with textarea attributes.
*
* When %CKEditor is created with the editor() method, a HTML &lt;textarea&gt; element is created,
* it will be displayed to anyone with JavaScript disabled or with incompatible browser.
*/
public $textareaAttributes = array("rows" => 8, "cols" => 60);
/**
* A string indicating the creation date of %CKEditor.
* Do not change it unless you want to force browsers to not use previously cached version of %CKEditor.
*/
public $timestamp = "B5GJ5GG";
/**
* An array that holds event listeners.
*/
private $events = array();
/**
* An array that holds global event listeners.
*/
private $globalEvents = array();
/**
* Main Constructor.
*
* @param $basePath (string) URL to the %CKEditor installation directory (optional).
*/
function __construct($basePath = null)
{
if (!empty($basePath)) {
$this->basePath = $basePath;
}
}
/**
* Creates a %CKEditor instance.
* In incompatible browsers %CKEditor will downgrade to plain HTML &lt;textarea&gt; element.
*
* @param $name (string) Name of the %CKEditor instance (this will be also the "name" attribute of textarea element).
* @param $value (string) Initial value (optional).
* @param $config (array) The specific configurations to apply to this editor instance (optional).
* @param $events (array) Event listeners for this editor instance (optional).
*
* Example usage:
* @code
* $CKEditor = new CKEditor();
* $CKEditor->editor("field1", "<p>Initial value.</p>");
* @endcode
*
* Advanced example:
* @code
* $CKEditor = new CKEditor();
* $config = array();
* $config['toolbar'] = array(
* array( 'Source', '-', 'Bold', 'Italic', 'Underline', 'Strike' ),
* array( 'Image', 'Link', 'Unlink', 'Anchor' )
* );
* $events['instanceReady'] = 'function (ev) {
* alert("Loaded: " + ev.editor.name);
* }';
* $CKEditor->editor("field1", "<p>Initial value.</p>", $config, $events);
* @endcode
*/
public function editor($name, $value = "", $config = array(), $events = array())
{
$attr = "";
foreach ($this->textareaAttributes as $key => $val) {
$attr .= " " . $key . '="' . str_replace('"', '&quot;', $val) . '"';
}
$out = "<textarea name=\"" . $name . "\"" . $attr . ">" . htmlspecialchars($value) . "</textarea>\n";
if (!$this->initialized) {
$out .= $this->init();
}
$_config = $this->configSettings($config, $events);
$js = $this->returnGlobalEvents();
if (!empty($_config))
$js .= "CKEDITOR.replace('" . $name . "', " . $this->jsEncode($_config) . ");";
else
$js .= "CKEDITOR.replace('" . $name . "');";
$out .= $this->script($js);
if (!$this->returnOutput) {
print $out;
$out = "";
}
return $out;
}
/**
* Replaces a &lt;textarea&gt; with a %CKEditor instance.
*
* @param $id (string) The id or name of textarea element.
* @param $config (array) The specific configurations to apply to this editor instance (optional).
* @param $events (array) Event listeners for this editor instance (optional).
*
* Example 1: adding %CKEditor to &lt;textarea name="article"&gt;&lt;/textarea&gt; element:
* @code
* $CKEditor = new CKEditor();
* $CKEditor->replace("article");
* @endcode
*/
public function replace($id, $config = array(), $events = array())
{
$out = "";
if (!$this->initialized) {
$out .= $this->init();
}
$_config = $this->configSettings($config, $events);
$js = $this->returnGlobalEvents();
if (!empty($_config)) {
$js .= "CKEDITOR.replace('" . $id . "', " . $this->jsEncode($_config) . ");";
} else {
$js .= "CKEDITOR.replace('" . $id . "');";
}
$out .= $this->script($js);
if (!$this->returnOutput) {
print $out;
$out = "";
}
return $out;
}
/**
* Replace all &lt;textarea&gt; elements available in the document with editor instances.
*
* @param $className (string) If set, replace all textareas with class className in the page.
*
* Example 1: replace all &lt;textarea&gt; elements in the page.
* @code
* $CKEditor = new CKEditor();
* $CKEditor->replaceAll();
* @endcode
*
* Example 2: replace all &lt;textarea class="myClassName"&gt; elements in the page.
* @code
* $CKEditor = new CKEditor();
* $CKEditor->replaceAll( 'myClassName' );
* @endcode
*/
public function replaceAll($className = null)
{
$out = "";
if (!$this->initialized) {
$out .= $this->init();
}
$_config = $this->configSettings();
$js = $this->returnGlobalEvents();
if (empty($_config)) {
if (empty($className)) {
$js .= "CKEDITOR.replaceAll();";
} else {
$js .= "CKEDITOR.replaceAll('" . $className . "');";
}
} else {
$classDetection = "";
$js .= "CKEDITOR.replaceAll( function(textarea, config) {\n";
if (!empty($className)) {
$js .= " var classRegex = new RegExp('(?:^| )' + '" . $className . "' + '(?:$| )');\n";
$js .= " if (!classRegex.test(textarea.className))\n";
$js .= " return false;\n";
}
$js .= " CKEDITOR.tools.extend(config, " . $this->jsEncode($_config) . ", true);";
$js .= "} );";
}
$out .= $this->script($js);
if (!$this->returnOutput) {
print $out;
$out = "";
}
return $out;
}
/**
* Adds event listener.
* Events are fired by %CKEditor in various situations.
*
* @param $event (string) Event name.
* @param $javascriptCode (string) Javascript anonymous function or function name.
*
* Example usage:
* @code
* $CKEditor->addEventHandler('instanceReady', 'function (ev) {
* alert("Loaded: " + ev.editor.name);
* }');
* @endcode
*/
public function addEventHandler($event, $javascriptCode)
{
if (!isset($this->events[$event])) {
$this->events[$event] = array();
}
// Avoid duplicates.
if (!in_array($javascriptCode, $this->events[$event])) {
$this->events[$event][] = $javascriptCode;
}
}
/**
* Clear registered event handlers.
* Note: this function will have no effect on already created editor instances.
*
* @param $event (string) Event name, if not set all event handlers will be removed (optional).
*/
public function clearEventHandlers($event = null)
{
if (!empty($event)) {
$this->events[$event] = array();
} else {
$this->events = array();
}
}
/**
* Adds global event listener.
*
* @param $event (string) Event name.
* @param $javascriptCode (string) Javascript anonymous function or function name.
*
* Example usage:
* @code
* $CKEditor->addGlobalEventHandler('dialogDefinition', 'function (ev) {
* alert("Loading dialog: " + ev.data.name);
* }');
* @endcode
*/
public function addGlobalEventHandler($event, $javascriptCode)
{
if (!isset($this->globalEvents[$event])) {
$this->globalEvents[$event] = array();
}
// Avoid duplicates.
if (!in_array($javascriptCode, $this->globalEvents[$event])) {
$this->globalEvents[$event][] = $javascriptCode;
}
}
/**
* Clear registered global event handlers.
* Note: this function will have no effect if the event handler has been already printed/returned.
*
* @param $event (string) Event name, if not set all event handlers will be removed (optional).
*/
public function clearGlobalEventHandlers($event = null)
{
if (!empty($event)) {
$this->globalEvents[$event] = array();
} else {
$this->globalEvents = array();
}
}
/**
* Prints javascript code.
*
* @param string $js
*/
private function script($js)
{
$out = "<script type=\"text/javascript\">";
$out .= "//<![CDATA[\n";
$out .= $js;
$out .= "\n//]]>";
$out .= "</script>\n";
return $out;
}
/**
* Returns the configuration array (global and instance specific settings are merged into one array).
*
* @param $config (array) The specific configurations to apply to editor instance.
* @param $events (array) Event listeners for editor instance.
*/
private function configSettings($config = array(), $events = array())
{
$_config = $this->config;
$_events = $this->events;
if (is_array($config) && !empty($config)) {
$_config = array_merge($_config, $config);
}
if (is_array($events) && !empty($events)) {
foreach ($events as $eventName => $code) {
if (!isset($_events[$eventName])) {
$_events[$eventName] = array();
}
if (!in_array($code, $_events[$eventName])) {
$_events[$eventName][] = $code;
}
}
}
if (!empty($_events)) {
foreach ($_events as $eventName => $handlers) {
if (empty($handlers)) {
continue;
} else if (count($handlers) == 1) {
$_config['on'][$eventName] = '@@' . $handlers[0];
} else {
$_config['on'][$eventName] = '@@function (ev){';
foreach ($handlers as $handler => $code) {
$_config['on'][$eventName] .= '(' . $code . ')(ev);';
}
$_config['on'][$eventName] .= '}';
}
}
}
return $_config;
}
/**
* Return global event handlers.
*/
private function returnGlobalEvents()
{
static $returnedEvents;
$out = "";
if (!isset($returnedEvents)) {
$returnedEvents = array();
}
if (!empty($this->globalEvents)) {
foreach ($this->globalEvents as $eventName => $handlers) {
foreach ($handlers as $handler => $code) {
if (!isset($returnedEvents[$eventName])) {
$returnedEvents[$eventName] = array();
}
// Return only new events
if (!in_array($code, $returnedEvents[$eventName])) {
$out .= ($code ? "\n" : "") . "CKEDITOR.on('" . $eventName . "', $code);";
$returnedEvents[$eventName][] = $code;
}
}
}
}
return $out;
}
/**
* Initializes CKEditor (executed only once).
*/
private function init()
{
static $initComplete;
$out = "";
if (!empty($initComplete)) {
return "";
}
if ($this->initialized) {
$initComplete = true;
return "";
}
$args = "";
$ckeditorPath = $this->ckeditorPath();
if (!empty($this->timestamp) && $this->timestamp != "%" . "TIMESTAMP%") {
$args = '?t=' . $this->timestamp;
}
// Skip relative paths...
if (strpos($ckeditorPath, '..') !== 0) {
$out .= $this->script("window.CKEDITOR_BASEPATH='" . $ckeditorPath . "';");
}
$out .= "<script type=\"text/javascript\" src=\"" . $ckeditorPath . 'ckeditor.js' . $args . "\"></script>\n";
$extraCode = "";
if ($this->timestamp != self::timestamp) {
$extraCode .= ($extraCode ? "\n" : "") . "CKEDITOR.timestamp = '" . $this->timestamp . "';";
}
if ($extraCode) {
$out .= $this->script($extraCode);
}
$initComplete = $this->initialized = true;
return $out;
}
/**
* Return path to ckeditor.js.
*/
private function ckeditorPath()
{
if (!empty($this->basePath)) {
return $this->basePath;
}
/**
* The absolute pathname of the currently executing script.
* Note: If a script is executed with the CLI, as a relative path, such as file.php or ../file.php,
* $_SERVER['SCRIPT_FILENAME'] will contain the relative path specified by the user.
*/
if (isset($_SERVER['SCRIPT_FILENAME'])) {
$realPath = dirname($_SERVER['SCRIPT_FILENAME']);
} else {
/**
* realpath - Returns canonicalized absolute pathname
*/
$realPath = realpath('./');
}
/**
* The filename of the currently executing script, relative to the document root.
* For instance, $_SERVER['PHP_SELF'] in a script at the address http://example.com/test.php/foo.bar
* would be /test.php/foo.bar.
*/
$selfPath = dirname($_SERVER['PHP_SELF']);
$file = str_replace("\\", "/", __FILE__);
if (!$selfPath || !$realPath || !$file) {
return "/ckeditor/";
}
$documentRoot = substr($realPath, 0, strlen($realPath) - strlen($selfPath));
$fileUrl = substr($file, strlen($documentRoot));
$ckeditorUrl = str_replace("ckeditor_php5.php", "", $fileUrl);
return $ckeditorUrl;
}
/**
* This little function provides a basic JSON support.
*
* @param mixed $val
* @return string
*/
private function jsEncode($val)
{
if (is_null($val)) {
return 'null';
}
if (is_bool($val)) {
return $val ? 'true' : 'false';
}
if (is_int($val)) {
return $val;
}
if (is_float($val)) {
return str_replace(',', '.', $val);
}
if (is_array($val) || is_object($val)) {
if (is_array($val) && (array_keys($val) === range(0, count($val) - 1))) {
return '[' . implode(',', array_map(array($this, 'jsEncode'), $val)) . ']';
}
$temp = array();
foreach ($val as $k => $v) {
$temp[] = $this->jsEncode("{$k}") . ':' . $this->jsEncode($v);
}
return '{' . implode(',', $temp) . '}';
}
// String otherwise
if (strpos($val, '@@') === 0)
return substr($val, 2);
if (strtoupper(substr($val, 0, 9)) == 'CKEDITOR.')
return $val;
return '"' . str_replace(array("\\", "/", "\n", "\t", "\r", "\x08", "\x0c", '"'), array('\\\\', '\\/', '\\n', '\\t', '\\r', '\\b', '\\f', '\"'), $val) . '"';
}
}
+352
View File
@@ -0,0 +1,352 @@
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
require_once 'vendor/autoload.php';
# Imports the Google Cloud client library
use Google\Cloud\Storage\StorageClient;
class GoogleStorage {
private $storage;
private $projectId;
private $authFile;
public $prefix = 'adminsavvy';
public function __construct() {
}
public function Init($projectId, $authFile) {
// Your Google Cloud Platform project ID
$this->projectId = $projectId; // 'float-app-224118';
// The file path to credentials JSON
$this->authFile = $authFile; // './float-app-224118-52ef1783d2c5.json';
// Instantiates a client
$this->storage = new StorageClient([
'projectId' => $projectId,
'keyFile' => json_decode(file_get_contents($authFile), true)
]);
}
/*
* @type array $keyFile The contents of the service account credentials
* .json file retrieved from the Google Developer's Console.
* Ex: `json_decode(file_get_contents($path), true)`.
* @type string $keyFilePath The full path to your service account
* credentials .json file retrieved from the Google Developers
* Console.
*/
/**
* Create a Cloud Storage Bucket.
*
* @param Google\Cloud\Storage\StorageClient $storage Google storage service client
* @param string $bucketName name of the bucket to create.
* @param string $options options for the new bucket.
*
* @return Google\Cloud\Storage\Bucket the newly created bucket.
*/
public function CreateBucket($bucketName) {
// Creates the new bucket
$bucket = $this->storage->createBucket($bucketName);
//echo 'Bucket ' . $bucket->name() . ' created.';
return $bucket;
}
/**
* Delete a Cloud Storage Bucket.
*
* @param Google\Cloud\Storage\StorageClient $storage Google storage service client
* @param string $bucketName the name of the bucket to delete.
*
* @return void
*/
function DeleteBucket($bucketName)
{
$this->storage = new StorageClient();
$bucket = $this->storage->bucket($bucketName);
$bucket->delete();
printf('Bucket deleted: %s' . PHP_EOL, $bucket->name());
}
/**
* Upload a file.
*
* @param Google\Cloud\Storage\StorageClient $storage Google storage service client
* @param string $bucketName the name of your Google Cloud bucket.
* @param string $objectName the name of the object.
* @param string $source the path to the file to upload.
*
* @return Psr\Http\Message\StreamInterface
*/
function UploadObject($bucketName, $objectName, $source)
{
$file = fopen($source, 'r');
$bucket = $this->storage->bucket($bucketName);
$object = $bucket->upload($file, [
'name' => $objectName
]);
printf('Uploaded %s to gs://%s/%s' . PHP_EOL, basename($source), $bucketName, $objectName);
return $object;
}
/**
* Download an object from Cloud Storage and return it as a BLOB.
*
* @param Google\Cloud\Storage\StorageClient $storage Google storage service client
* @param string $bucketName the name of your Google Cloud bucket.
* @param string $objectName the name of your Google Cloud object.
*
* @return BLOB
*/
function DownloadObject($bucketName, $objectName)
{
$bucket = $this->storage->bucket($bucketName);
$object = $bucket->object($objectName);
$stream = $object->downloadAsStream();
return $stream->getContents();
}
/**
* Delete an object.
*
* @param Google\Cloud\Storage\StorageClient $storage Google storage service client
* @param string $bucketName the name of your Cloud Storage bucket.
* @param string $objectName the name of your Cloud Storage object.
* @param array $options
*
* @return void
*/
function DeleteObject($bucketName, $objectName, $options = [])
{
$bucket = $this->storage->bucket($bucketName);
$object = $bucket->object($objectName);
$object->delete();
$msg = sprintf('Deleted gs://%s/%s' . PHP_EOL, $bucketName, $objectName);
echo $msg;
return $msg;
}
/**
* Make an object publically accessible.
*
* @param Google\Cloud\Storage\StorageClient $storage Google storage service client
* @param string $bucketName the name of your Cloud Storage bucket.
* @param string $objectName the name of your Cloud Storage object.
*
* @return void
*/
function MakePublic($bucketName, $objectName)
{
$bucket = $this->storage->bucket($bucketName);
$object = $bucket->object($objectName);
$object->update(['acl' => []], ['predefinedAcl' => 'PUBLICREAD']);
printf('gs://%s/%s is now public' . PHP_EOL, $bucketName, $objectName);
}
/**
* List object metadata.
*
* @param Google\Cloud\Storage\StorageClient $storage Google storage service client
* @param string $bucketName the name of your Cloud Storage bucket.
* @param string $objectName the name of your Cloud Storage object.
*
* @return void
*/
function ObjectMetadata($bucketName, $objectName)
{
$bucket = $this->storage->bucket($bucketName);
$object = $bucket->object($objectName);
$info = $object->info();
printf('Blob: %s' . PHP_EOL, $info['name']);
printf('Bucket: %s' . PHP_EOL, $info['bucket']);
printf('Storage class: %s' . PHP_EOL, $info['storageClass']);
printf('ID: %s' . PHP_EOL, $info['id']);
printf('Size: %s' . PHP_EOL, $info['size']);
printf('Updated: %s' . PHP_EOL, $info['updated']);
printf('Generation: %s' . PHP_EOL, $info['generation']);
printf('Metageneration: %s' . PHP_EOL, $info['metageneration']);
printf('Etag: %s' . PHP_EOL, $info['etag']);
printf('Crc32c: %s' . PHP_EOL, $info['crc32c']);
printf('MD5 Hash: %s' . PHP_EOL, $info['md5Hash']);
printf('Content-type: %s' . PHP_EOL, $info['contentType']);
printf("Temporary hold: " . (isset($info['temporaryHold']) ? "enabled" : "disabled") . PHP_EOL);
printf("Event-based hold: " . (isset($info['eventBasedHold']) ? "enabled" : "disabled") . PHP_EOL);
if (isset($info['retentionExpirationTime'])) {
printf("retentionExpirationTime: " . $info['retentionExpirationTime'] . PHP_EOL);
}
if (isset($info['metadata'])) {
printf('Metadata: %s', print_r($info['metadata'], true));
}
}
/**
* List all Cloud Storage buckets for the current project.
*
* @param Google\Cloud\Storage\StorageClient $storage Google storage service client
* @return void
*/
function ListBuckets()
{
$buckets = array();
foreach ($this->storage->buckets() as $bucket) {
//printf('Bucket: %s' . PHP_EOL, $bucket->name());
$buckets[$bucket->name()] = $bucket;
}
return $buckets;
}
/**
* List Cloud Storage bucket objects.
* https://cloud.google.com/storage/docs/listing-objects
*
* @param Google\Cloud\Storage\StorageClient $storage Google storage service client
* @param string $bucketName the name of your Cloud Storage bucket.
*
* @return void
*/
function ListObjects($bucketName)
{
$objects = array();
$bucket = $this->storage->bucket($bucketName);
foreach ($bucket->objects() as $object) {
//printf('Object: %s' . PHP_EOL, $object->name());
$objects[$object->name()] = $object;
}
return $objects;
}
/**
* List Cloud Storage bucket objects.
* https://cloud.google.com/storage/docs/listing-objects
*
* @param Google\Cloud\Storage\StorageClient $storage Google storage service client
* @param string $bucketName the name of your Cloud Storage bucket.
* @param string $objectName the name of your Cloud Storage object.
* @param string $responseType Response content-type for the object URL
* @param integer $duration Number of seconds before the signature expires
* @param string $method Optional HTTP verb for URL
*
* @return string Signed google storage URL
*/
function SignedUrl($bucketName, $objectName, $responseType, $duration = 60, $method = 'GET')
{
$bucket = $this->storage->bucket($bucketName);
$object = $bucket->object($objectName);
$url = $object->signedUrl(
new \DateTime('+ ' . $duration . ' seconds'),
array(
'method' => $method,
'responseType' => $responseType,
'allowPost' => $method=='POST'
));
return $url;
}
/*
'method' => 'GET',
'cname' => self::DEFAULT_DOWNLOAD_URL,
'contentMd5' => null,
'contentType' => null,
'headers' => [],
'saveAsName' => null,
'responseDisposition' => null,
'responseType' => null,
'keyFile' => null,
'keyFilePath' => null,
'allowPost' => false,
'forceOpenssl' => false
*/
private function BaseEncode($num, $alphabet) {
$base_count = strlen($alphabet);
$encoded = '';
while ($num >= $base_count) {
$div = $num/$base_count;
$mod = ($num-($base_count*intval($div)));
if ($mod>=0 && $mod<$base_count) {
$encoded = $alphabet[$mod] . $encoded;
}
$num = intval($div);
}
if ($num) $encoded = $alphabet[$num] . $encoded;
return $encoded;
}
private function BaseDecode($num, $alphabet) {
$decoded = 0;
$multi = 1;
while (strlen($num) > 0) {
$digit = $num[strlen($num)-1];
$decoded += $multi * strpos($alphabet, $digit);
$multi = $multi * strlen($alphabet);
$num = substr($num, 0, -1);
}
return $decoded;
}
public function UniqueId() {
// 123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ
$alphabet = "pRFsNvKifkJtA5Umy9QSD8PTYcZH23dCeWg6aqVXwnr7jxuGMLhE4zBob1";
return $this->BaseEncode(
filter_var(microtime(),FILTER_SANITIZE_NUMBER_INT),
$alphabet);
}
}
//*
// run with GOOGLE_STORAGE_TEST=1 php -f GoogleStorage.php
if (isset($_SERVER['GOOGLE_STORAGE_TEST']) && $_SERVER['GOOGLE_STORAGE_TEST']==1) {
// Create bucket 'adminsavvy-card-images' and list buckets
//TestGoogleStorage(1,1,0,0,0,0,0,0);
// Upload 'singapore.jpg' file to 'adminsavvy-card-images' bucket and make the object public
//TestGoogleStorage(0,0,1,1,0,0,0,0);
// Download 'singapore.jpg' object from 'adminsavvy-card-images' bucket
//TestGoogleStorage(0,0,0,0,0,0,1,0);
// List buckets, List objects in 'adminsavvy-card-images' bucket, get 'singapore.jpg' object metadata, get signed URL
TestGoogleStorage(0,1,0,0,1,1,0,1);
}
//*/
/*
* Run the test suite for above defined function
*
* @param integer $testCreateBucket 1 to run the create bucket test
* @param integer $testListBuckets 1 to run the list buckets test
* @param integer $testUploadObject 1 to run the upload object test
* @param integer $testMakePublic 1 to run the make public test
* @param integer $testListObjects 1 to run the list objects test
* @param integer $testObjectMetadata 1 to run the object metadata test
* @param integer $testDownloadObject 1 to run the download object test
* @param integer $testSignedUrl 1 to run the signed URL test
*
* @return void
*/
function TestGoogleStorage(
$testCreateBucket,
$testListBuckets,
$testUploadObject,
$testMakePublic,
$testListObjects,
$testObjectMetadata,
$testDownloadObject,
$testSignedUrl) {
// Your Google Cloud Platform project ID
$projectId = 'float-app-224118';
// The name for the new bucket
$bucketName = 'adminsavvy-card-images';
// The file path to upload
$filePath = '/home/savvy/savvy/savvyoauth2/public/test/singapore.jpg';
// The file path to credentials JSON
$authFile = '/home/savvy/savvy/savvyoauth2/public/include/float-app-224118-52ef1783d2c5.json';
// Instantiates a client
$storage = new GoogleStorage($projectId, $authFile);
if ($testCreateBucket) var_dump($storage->CreateBucket($bucketName));
if ($testListBuckets) $storage->ListBuckets();
if ($testUploadObject) var_dump($storage->UploadObject($bucketName, basename($filePath), $filePath));
if ($testMakePublic) $storage->MakePublic($bucketName, basename($filePath));
if ($testListObjects) $storage->ListObjects($bucketName);
if ($testObjectMetadata) $storage->ObjectMetadata($bucketName, basename($filePath));
if ($testDownloadObject) file_put_contents('test.jpg',$storage->DownloadObject($bucketName, basename($filePath)));
if ($testSignedUrl) var_dump($storage->SignedUrl($bucketName, basename($filePath), mime_content_type($filePath), 864000));
}
+69
View File
@@ -0,0 +1,69 @@
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class MessageParser {
public function parse($id,$db) {
global $savvyext;
$data = array(
'source_vendor' => 'Error',
'date_value' => 'N/A',
'date_score' => 'N/A',
'date_end_value' => 'N/A',
'date_end_score' => 'N/A',
'location_start_value' => 'N/A',
'location_start_score' => 'N/A',
'location_end_value' => 'N/A',
'location_end_score' => 'N/A',
'distance_value' => 'N/A',
'distance_score' => 'N/A',
'duration_value' => 'N/A',
'duration_score' => 'N/A',
'cost_value' => 'N/A',
'cost_score' => 'N/A',
);
// check the cache
$q = "SELECT a.*, b.address AS location_start, b.latitude AS location_start_lat, b.longitude AS location_start_lng, b.timezone AS location_start_tz, b.geocoding_date AS location_geocoding_date, c.address AS location_end, c.latitude AS location_end_lat, c.longitude AS location_end_lng
FROM parsedemail_item a
LEFT JOIN address b ON b.id=a.location_start_id
LEFT JOIN address c ON c.id=a.location_end_id
WHERE a.trackedemail_item_id='${id}'";
$r = $db->query($q);
$f = $r->row_array();
if ($f!=NULL) {
$data['source_vendor'] = $f["transport_provider_id"];
$data['date_value'] = $f["travel_date"];
$data['date_end_value'] = $f["travel_date_end"];
$data['location_start_value'] = $f["location_start"];
$data['location_end_value'] = $f["location_end"];
$data['distance_value'] = $f["distance"]==0?'N/A':$f["distance"];
$data['duration_value'] = $f["duration"]==0?'N/A':$f["duration"];
$data['cost_value'] = $f["cost"];
return $data;
}
$url = $savvyext->cfgReadChar('system.oauth2_url')."parse/${id}";
error_log($url);
// hit the service
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Authorization: Server-Token '.$savvyext->cfgReadChar('system.oauth2_token')));
if( ! $result = curl_exec($ch)) {
// Error
} else {
$raw_data = json_decode($result,true);
if (is_array($raw_data) && !isset($raw_data['error']) && isset($raw_data['code']) &&
$raw_data['code']=='0' && is_array($raw_data['data'])) {
$data = $raw_data['data'];
}
}
curl_close($ch);
return $data;
}
}
/*
vi:ts=2
*/
@@ -0,0 +1,99 @@
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
class SAV_Form_validation extends CI_Form_validation
{
protected $CI;
public function __construct($rules = array())
{
parent::__construct($rules);
$this->CI = &get_instance();
}
/**
* is_unique_multiple
* check multiple unique field at time
* handy when checking if two or more column of some set of value
* e.g if firstname="something" and username="something"
* usage:
*is_unique_multiple[
* table_name,
* column_name1.column_name2.column_name3,
* post_filed_name1.post_field_name2.post_field_name3
*]
*real example $this->form_validation->set_rules('fee_name', 'fee_name', "required|is_unique_multiple[arasoft_fee, fee_name.fee_term.fee_users, fee_name.term.fee_users ]");
**/
public function is_unique_multiple($str, $data)
{
$data = explode(",", $data);
if (count($data) < 2)
return TRUE;
$table = @$data[0];
$str = @$data[1];
$str = explode(".", $str);
$field = @$data[2];
$field = empty($field) ? $str : explode(".", $field);
if (count($str) != count($field)) {
return TRUE;
}
$where = [];
foreach ($str as $key => $value) {
# code...
$q = $this->CI->input->post($field[$key]);
$where[$value] = $q;
}
$check = $this->CI->db->get_where($table, $where, 1);
if ($check->num_rows() > 0) {
$this->set_message('is_unique_multiple', 'This data exist already');
return FALSE;
}
return TRUE;
}
function exist($str, $data)
{
$data = explode(",", $data);
if (count($data) < 2)
return TRUE;
$table = @$data[0];
$str = @$data[1];
$str = explode(".", $str);
$field = @$data[2];
$field = empty($field) ? $str : explode(".", $field);
if (count($str) != count($field)) {
return TRUE;
}
$where = [];
foreach ($str as $key => $value) {
# code...
$q = ! is_null($this->CI->input->post($field[$key]))
? $this->CI->input->post($field[$key])
: $this->CI->input->get($field[$key]);
$where[$value] = $q;
}
$check = $this->CI->db->get_where($table, $where, 1);
if ($check->num_rows() === 0) {
$this->set_message('exist', 'This data does not exists');
return FALSE;
}
return TRUE;
}
}
+31
View File
@@ -0,0 +1,31 @@
<?php
class Template {
//ci instance
private $CI;
//template Data
var $template_data = array();
var $sideMenu = 'side_menu';
var $header = 'header';
var $footer = 'footer';
public function __construct()
{
$this->CI =& get_instance();
}
function set($content_area, $value)
{
$this->template_data[$content_area] = $value;
}
function load($view = '' , $view_data = array(), $return = FALSE)
{
$siteMenuData['selectedTab'] = $view_data['selectedTab'];
$this->set('header', $this->CI->load->view($this->header, null, TRUE));
$this->set('footer', $this->CI->load->view($this->footer, null, TRUE));
$this->set('side_menu', $this->CI->load->view($this->sideMenu, $siteMenuData, TRUE));
$this->set('contents' , $this->CI->load->view($view, $view_data, TRUE));
$this->CI->load->view('layouts/default_layout', $this->template_data);
}
}
?>
+147
View File
@@ -0,0 +1,147 @@
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class UploadHelper {
function deleteCardimageFile($data, $controller,$delete_table='',$delete_name='') {
global $savvyext;
$id = $data["id"];
$q = "SELECT a.catid,a.uniqueid,a.name,a.format,b.name as catname FROM card_images a, card_image_category b WHERE a.id='${id}' AND b.id=a.catid";
$r = $controller->db->query($q);
$f = $r->row_array();
if ($f==NULL || !is_array($f) || !isset($f["catname"])) {
$data["message"] = 'Failed to load image data!';
return $data;
}
$bucket_name = $f["catname"];
$uniqueId = $f["uniqueid"];
$controller->load->library('googlestorage');
$controller->googlestorage->Init(
$savvyext->cfgReadChar('google.storage_project_id'),
$savvyext->cfgReadChar('google.storage_auth_file')
);
$storage = $controller->googlestorage;
// Get bucket
$buckets = $storage->ListBuckets();
if (array_key_exists($bucket_name, $buckets)) {
$bucket = $buckets[$bucket_name];
}
if ($bucket==NULL || !is_object($bucket)) {
$data['message'] = 'Cannot get storage bucket!';
return $data;
}
$objectName = $uniqueId.".".$f['format'];
ob_start();
$storage->DeleteObject($bucket_name, $objectName);
$data["message"] = ob_get_clean();
if (preg_match('/^Deleted gs:\/\/(.*)\/(.*)\.(.*)$/', $data["message"], $arr)==1 &&
count($arr)>3 && $arr[1]==$bucket_name && $arr[2]==$uniqueId) {
if ($delete_table!='' && $delete_name!='') {
$q = "UPDATE ${delete_table} SET ${delete_name}=NULL WHERE ${delete_name}='${id}'";
$controller->db->query($q);
}
$q = "DELETE FROM card_images WHERE id='${id}'";
$controller->db->query($q);
$data["deleted"] = $id;
$data["message"] = "Image deleted!";
} else {
$data["deleted"] = 0;
}
return $data;
}
public function cardimagesPost($data,$controller,$uniqueId="") {
global $savvyext;
$bucket_name = '';
$catid = (int)$controller->input->post('catid');
if ($catid<1) { $data['message'] = 'Please select category'; return $data; }
$q = "SELECT name FROM card_image_category WHERE id='${catid}'";
$r = $controller->db->query($q);
foreach ($r->result() as $row) {
$bucket_name = $row->name;
break;
}
if ($bucket_name=='') {
$data['message'] = 'Invalid category';
return $data;
}
// Process file
$imgData = self::processFile('cardimg', array('jpg'=>1,'jpeg'=>1,'png'=>1,'gif'=>1));
if ($imgData==NULL || !is_array($imgData)) {
$data['message'] = 'Failed to process uploaded image! ('.$imgData.')';
return $data;
}
$controller->load->library('googlestorage');
$controller->googlestorage->Init(
$savvyext->cfgReadChar('google.storage_project_id'),
$savvyext->cfgReadChar('google.storage_auth_file')
);
$storage = $controller->googlestorage;
// Get bucket
$buckets = $storage->ListBuckets();
if (array_key_exists($bucket_name, $buckets)) {
$bucket = $buckets[$bucket_name];
} else {
// Create bucket
$bucket = $storage->CreateBucket($bucket_name);
}
if ($bucket==NULL || !is_object($bucket)) {
$data['message'] = 'Cannot get or create bucket!';
return $data;
}
if ($uniqueId=="") {
$uniqueId = $storage->UniqueId();
}
$data['format'] = $imgData['format'];
$objectName = $uniqueId.".".$imgData['format'];
$source = $imgData['tmp_name'];
$object = $storage->UploadObject($bucket_name, $objectName, $source);
if ($object==NULL || !is_object($object)) {
$data['message'] = 'Failed to upload image!';
} else {
$data['message'] = 'Image uploaded!';
// Save image data
$q = "INSERT INTO card_images (catid, uniqueid, name, file_size, format, dimensions) VALUES(";
$q.= "'${catid}','${uniqueId}','".$imgData['name']."','".$imgData['file_size']."','".$imgData['format']."','".$imgData['dimensions']."') RETURNING id";
$r = $controller->db->query($q);
$f = $r->row_array();
if ($f!=NULL && is_array($f) && $f["id"]>0) {
$data["card_image_id"] = $f["id"];
}
}
return $data;
}
private function processFile($var, $formats) {
if (!isset($_FILES[$var])) return 'The file was not uploaded!';
if (is_array($_FILES[$var]['error'])) {
foreach ($_FILES[$var]['error'] as $key => $error) {
if ($error != UPLOAD_ERR_OK) {
return $error;
}
}
} else if (isset($_FILES[$var]['error']) && $_FILES[$var]['error'] != UPLOAD_ERR_OK) {
return $_FILES[$var]['error'];
}
$error = $_FILES[$var]['error'];
$name = trim($_FILES[$var]['name']);
$file_size = $_FILES[$var]['size'];
$tmp_name = $_FILES[$var]['tmp_name'];
$format = strtolower(pathinfo($_FILES[$var]['name'], PATHINFO_EXTENSION));
if (!isset($formats[$format]) || $formats[$format]!=1) {
return 'Invalid file format: '.$format;
}
list($width, $height, $type, $attr) = getimagesize($tmp_name);
$dimensions = $width . 'x' . $height;
$result = array(
'tmp_name' => $tmp_name,
'name' => $name,
'file_size' => $file_size,
'format' => $format,
'dimensions' => $dimensions
);
return $result;
//return 'Not implemented!';
}
}

Some files were not shown because too many files have changed in this diff Show More