diff --git a/application/cache/index.html b/application/cache/index.html new file mode 100755 index 00000000..b702fbc3 --- /dev/null +++ b/application/cache/index.html @@ -0,0 +1,11 @@ + + + + 403 Forbidden + + + +

Directory access is forbidden.

+ + + diff --git a/application/config/autoload.php b/application/config/autoload.php new file mode 100755 index 00000000..7cdc9013 --- /dev/null +++ b/application/config/autoload.php @@ -0,0 +1,135 @@ + 'ua'); +*/ +$autoload['libraries'] = array(); + +/* +| ------------------------------------------------------------------- +| 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(); + +/* +| ------------------------------------------------------------------- +| 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(); diff --git a/application/config/config.php b/application/config/config.php new file mode 100755 index 00000000..5766ecc1 --- /dev/null +++ b/application/config/config.php @@ -0,0 +1,524 @@ +]+$/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'] = NULL; +$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; // DEFAULT +// $config['global_xss_filtering'] = TRUE; + +/* +|-------------------------------------------------------------------------- +| 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'] = ''; diff --git a/application/config/constants.php b/application/config/constants.php new file mode 100755 index 00000000..18d3b4b7 --- /dev/null +++ b/application/config/constants.php @@ -0,0 +1,85 @@ +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; + +$db['default'] = array( + 'dsn' => '', + 'hostname' => 'localhost', + 'username' => 'root', + 'password' => 'mcupramita123321', + 'database' => 'one', + 'dbdriver' => 'mysqli', + 'dbprefix' => '', + 'pconnect' => FALSE, + 'db_debug' => FALSE, + '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['onedev'] = array( + 'dsn' => '', + 'hostname' => 'localhost', + 'username' => 'root', + 'password' => 'mcupramita123321', + 'database' => 'one', + 'dbdriver' => 'mysqli', + 'dbprefix' => '', + 'pconnect' => FALSE, + 'db_debug' => FALSE, + '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['clinicdev'] = array( + 'dsn' => '', + 'hostname' => 'localhost', + 'username' => 'root', + 'password' => 'mcupramita123321', + 'database' => 'one_clinic', + 'dbdriver' => 'mysqli', + 'dbprefix' => '', + 'pconnect' => FALSE, + 'db_debug' => FALSE, + '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['antrione'] = array( + 'dsn' => '', + 'hostname' => 'localhost', + 'username' => 'root', + 'password' => 'mcupramita123321', + 'database' => 'antrione', + 'dbdriver' => 'mysqli', + 'dbprefix' => '', + 'pconnect' => FALSE, + 'db_debug' => FALSE, + '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['onelog'] = array( + 'dsn' => '', + 'hostname' => 'localhost', + 'username' => 'root', + 'password' => 'mcupramita123321', + 'database' => 'one_log', + 'dbdriver' => 'mysqli', + 'dbprefix' => '', + 'pconnect' => FALSE, + 'db_debug' => FALSE, + 'cache_on' => FALSE, + 'cachedir' => '', + 'char_set' => 'utf8', + 'dbcollat' => 'utf8_general_ci', + 'swap_pre' => '', + 'encrypt' => FALSE, + 'compress' => FALSE, + 'stricton' => FALSE, + 'failover' => array(), + 'save_queries' => TRUE +); diff --git a/application/config/database.php b/application/config/database.php new file mode 100755 index 00000000..45b43836 --- /dev/null +++ b/application/config/database.php @@ -0,0 +1,1992 @@ +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; + +$db['default'] = array( + 'dsn' => '', + 'hostname' => 'localhost', + 'username' => 'root', + 'password' => 'sasone102938', + 'database' => 'one_lab', + 'dbdriver' => 'mysqli', + 'dbprefix' => '', + 'pconnect' => FALSE, + 'db_debug' => FALSE, + '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['onedev'] = array( + 'dsn' => '', + 'hostname' => 'localhost', + 'username' => 'root', + 'password' => 'sasone102938', + 'database' => 'one_lab', + 'dbdriver' => 'mysqli', + 'dbprefix' => '', + 'pconnect' => FALSE, + 'db_debug' => FALSE, + '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['one_lab_log'] = array( + 'dsn' => '', + 'hostname' => 'localhost', + 'username' => 'root', + 'password' => 'sasone102938', + 'database' => 'one_lab_log', + 'dbdriver' => 'mysqli', + 'dbprefix' => '', + 'pconnect' => FALSE, + 'db_debug' => FALSE, + '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['klinik'] = array( + 'dsn' => '', + 'hostname' => 'localhost', + 'username' => 'root', + 'password' => 'sasone102938', + 'database' => 'one_klinik', + 'dbdriver' => 'mysqli', + 'dbprefix' => '', + 'pconnect' => FALSE, + 'db_debug' => FALSE, + '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['antrione'] = array( + 'dsn' => '', + 'hostname' => 'localhost', + 'username' => 'root', + 'password' => 'sasone102938', + 'database' => 'antrione', + 'dbdriver' => 'mysqli', + 'dbprefix' => '', + 'pconnect' => FALSE, + 'db_debug' => FALSE, + '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['onelog'] = array( + 'dsn' => '', + 'hostname' => 'localhost', + 'username' => 'root', + 'password' => 'sasone102938', + 'database' => 'one_log', + 'dbdriver' => 'mysqli', + 'dbprefix' => '', + 'pconnect' => FALSE, + 'db_debug' => FALSE, + '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['mcutemp'] = array( + 'dsn' => '', + 'hostname' => 'localhost', + 'username' => 'root', + 'password' => 'sasone102938', + 'database' => 'temp_mcu', + 'dbdriver' => 'mysqli', + 'dbprefix' => '', + 'pconnect' => FALSE, + 'db_debug' => FALSE, + '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['riau'] = array( + 'dsn' => '', + 'hostname' => '192.168.250.201', + 'username' => 'root', + 'password' => 'pramita102938', + 'database' => 'one', + 'dbdriver' => 'mysqli', + 'dbprefix' => '', + 'pconnect' => FALSE, + 'db_debug' => FALSE, + '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['pajajaran'] = array( + 'dsn' => '', + 'hostname' => '192.168.250.202', + 'username' => 'root', + 'password' => 'pramita102938', + 'database' => 'one', + 'dbdriver' => 'mysqli', + 'dbprefix' => '', + 'pconnect' => FALSE, + 'db_debug' => FALSE, + '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['toha'] = array( + 'dsn' => '', + 'hostname' => '192.168.250.203', + 'username' => 'root', + 'password' => 'sasone102938', + 'database' => 'one', + 'dbdriver' => 'mysqli', + 'dbprefix' => '', + 'pconnect' => FALSE, + 'db_debug' => FALSE, + '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['cimahi'] = array( + 'dsn' => '', + 'hostname' => '192.168.250.204', + 'username' => 'root', + 'password' => 'sasone102938', + 'database' => 'one', + 'dbdriver' => 'mysqli', + 'dbprefix' => '', + 'pconnect' => FALSE, + 'db_debug' => FALSE, + '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['ngagel'] = array( + 'dsn' => '', + 'hostname' => '192.168.250.241', + 'username' => 'root', + 'password' => 'pramita102938', + 'database' => 'one', + 'dbdriver' => 'mysqli', + 'dbprefix' => '', + 'pconnect' => FALSE, + 'db_debug' => FALSE, + '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['aditya'] = array( + 'dsn' => '', + 'hostname' => '192.168.250.242', + 'username' => 'root', + 'password' => 'pramita102938', + 'database' => 'one', + 'dbdriver' => 'mysqli', + 'dbprefix' => '', + 'pconnect' => FALSE, + 'db_debug' => FALSE, + '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['jemur'] = array( + 'dsn' => '', + 'hostname' => '192.168.250.243', + 'username' => 'root', + 'password' => 'pramita102938', + 'database' => 'one', + 'dbdriver' => 'mysqli', + 'dbprefix' => '', + 'pconnect' => FALSE, + 'db_debug' => FALSE, + '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['mulyo'] = array( + 'dsn' => '', + 'hostname' => '192.168.250.244', + 'username' => 'root', + 'password' => 'pramita102938', + 'database' => 'one', + 'dbdriver' => 'mysqli', + 'dbprefix' => '', + 'pconnect' => FALSE, + 'db_debug' => FALSE, + '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['parkus'] = array( + 'dsn' => '', + 'hostname' => '192.168.250.245', + 'username' => 'root', + 'password' => 'pramita102938', + 'database' => 'one', + 'dbdriver' => 'mysqli', + 'dbprefix' => '', + 'pconnect' => FALSE, + 'db_debug' => FALSE, + '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['hrm'] = array( + 'dsn' => '', + 'hostname' => '192.168.250.246', + 'username' => 'root', + 'password' => 'pramita102938', + 'database' => 'one', + 'dbdriver' => 'mysqli', + 'dbprefix' => '', + 'pconnect' => FALSE, + 'db_debug' => FALSE, + '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['cikditiro'] = array( + 'dsn' => '', + 'hostname' => '192.168.250.191', + 'username' => 'root', + 'password' => 'pramita102938', + 'database' => 'one', + 'dbdriver' => 'mysqli', + 'dbprefix' => '', + 'pconnect' => FALSE, + 'db_debug' => FALSE, + '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['sultan_agung'] = array( + 'dsn' => '', + 'hostname' => '192.168.250.192', + 'username' => 'root', + 'password' => 'pramita102938', + 'database' => 'one', + 'dbdriver' => 'mysqli', + 'dbprefix' => '', + 'pconnect' => FALSE, + 'db_debug' => FALSE, + '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['matraman'] = array( + 'dsn' => '', + 'hostname' => '192.168.250.181', + 'username' => 'root', + 'password' => 'pramita102938', + 'database' => 'one', + 'dbdriver' => 'mysqli', + 'dbprefix' => '', + 'pconnect' => FALSE, + 'db_debug' => FALSE, + '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['bonjer'] = array( + 'dsn' => '', + 'hostname' => '192.168.250.182', + 'username' => 'root', + 'password' => 'pramita102938', + 'database' => 'one', + 'dbdriver' => 'mysqli', + 'dbprefix' => '', + 'pconnect' => FALSE, + 'db_debug' => FALSE, + '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['samanhudi'] = array( + 'dsn' => '', + 'hostname' => '192.168.250.183', + 'username' => 'root', + 'password' => 'pramita102938', + 'database' => 'one', + 'dbdriver' => 'mysqli', + 'dbprefix' => '', + 'pconnect' => FALSE, + 'db_debug' => FALSE, + '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['ragunan'] = array( + 'dsn' => '', + 'hostname' => '192.168.250.184', + 'username' => 'root', + 'password' => 'pramita102938', + 'database' => 'one', + 'dbdriver' => 'mysqli', + 'dbprefix' => '', + 'pconnect' => FALSE, + 'db_debug' => FALSE, + '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['cirebon'] = array( + 'dsn' => '', + 'hostname' => '192.168.250.216', + 'username' => 'root', + 'password' => 'pramita102938', + 'database' => 'one', + 'dbdriver' => 'mysqli', + 'dbprefix' => '', + 'pconnect' => FALSE, + 'db_debug' => FALSE, + '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['veteran'] = array( + 'dsn' => '', + 'hostname' => '192.168.250.171', + 'username' => 'root', + 'password' => 'pramita102938', + 'database' => 'one', + 'dbdriver' => 'mysqli', + 'dbprefix' => '', + 'pconnect' => FALSE, + 'db_debug' => FALSE, + '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['dahlan'] = array( + 'dsn' => '', + 'hostname' => '192.168.250.172', + 'username' => 'root', + 'password' => 'pramita102938', + 'database' => 'one', + 'dbdriver' => 'mysqli', + 'dbprefix' => '', + 'pconnect' => FALSE, + 'db_debug' => FALSE, + '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['plaju'] = array( + 'dsn' => '', + 'hostname' => '192.168.250.173', + 'username' => 'root', + 'password' => 'pramita102938', + 'database' => 'one', + 'dbdriver' => 'mysqli', + 'dbprefix' => '', + 'pconnect' => FALSE, + 'db_debug' => FALSE, + '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['diponegoro'] = array( + 'dsn' => '', + 'hostname' => '192.168.250.161', + 'username' => 'root', + 'password' => 'pramita102938', + 'database' => 'one', + 'dbdriver' => 'mysqli', + 'dbprefix' => '', + 'pconnect' => FALSE, + 'db_debug' => FALSE, + '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['yamin'] = array( + 'dsn' => '', + 'hostname' => '192.168.250.162', + 'username' => 'root', + 'password' => 'pramita102938', + 'database' => 'one', + 'dbdriver' => 'mysqli', + 'dbprefix' => '', + 'pconnect' => FALSE, + 'db_debug' => FALSE, + '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['padang'] = array( + 'dsn' => '', + 'hostname' => '192.168.250.151', + 'username' => 'root', + 'password' => 'pramita102938', + 'database' => 'one', + 'dbdriver' => 'mysqli', + 'dbprefix' => '', + 'pconnect' => FALSE, + 'db_debug' => FALSE, + '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['tegal'] = array( + 'dsn' => '', + 'hostname' => '192.168.250.211', + 'username' => 'root', + 'password' => 'pramita102938', + 'database' => 'one', + 'dbdriver' => 'mysqli', + 'dbprefix' => '', + 'pconnect' => FALSE, + 'db_debug' => FALSE, + '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['manado'] = array( + 'dsn' => '', + 'hostname' => '192.168.250.221', + 'username' => 'root', + 'password' => 'pramita102938', + 'database' => 'one', + 'dbdriver' => 'mysqli', + 'dbprefix' => '', + 'pconnect' => FALSE, + 'db_debug' => FALSE, + '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['pontianak'] = array( + 'dsn' => '', + 'hostname' => '192.168.250.231', + 'username' => 'root', + 'password' => 'pramita102938', + 'database' => 'one', + 'dbdriver' => 'mysqli', + 'dbprefix' => '', + 'pconnect' => FALSE, + 'db_debug' => FALSE, + '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['sudirman'] = array( + 'dsn' => '', + 'hostname' => '192.168.250.156', + 'username' => 'root', + 'password' => 'pramita102938', + 'database' => 'one', + 'dbdriver' => 'mysqli', + 'dbprefix' => '', + 'pconnect' => FALSE, + 'db_debug' => FALSE, + '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['magelang'] = array( + 'dsn' => '', + 'hostname' => '192.168.250.141', + 'username' => 'root', + 'password' => 'pramita102938', + 'database' => 'one', + 'dbdriver' => 'mysqli', + 'dbprefix' => '', + 'pconnect' => FALSE, + 'db_debug' => FALSE, + '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['salatiga'] = array( + 'dsn' => '', + 'hostname' => '192.168.250.146', + 'username' => 'root', + 'password' => 'pramita102938', + 'database' => 'one', + 'dbdriver' => 'mysqli', + 'dbprefix' => '', + 'pconnect' => FALSE, + 'db_debug' => FALSE, + '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['semarang'] = array( + 'dsn' => '', + 'hostname' => '192.168.250.131', + 'username' => 'root', + 'password' => 'pramita102938', + 'database' => 'one', + 'dbdriver' => 'mysqli', + 'dbprefix' => '', + 'pconnect' => FALSE, + 'db_debug' => FALSE, + '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['balikpapan'] = array( + 'dsn' => '', + 'hostname' => '192.168.250.236', + 'username' => 'root', + 'password' => 'pramita102938', + 'database' => 'one', + 'dbdriver' => 'mysqli', + 'dbprefix' => '', + 'pconnect' => FALSE, + 'db_debug' => FALSE, + '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['madiun'] = array( + 'dsn' => '', + 'hostname' => '192.168.250.121', + 'username' => 'root', + 'password' => 'pramita102938', + 'database' => 'one', + 'dbdriver' => 'mysqli', + 'dbprefix' => '', + 'pconnect' => FALSE, + 'db_debug' => FALSE, + '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['makasar'] = array( + 'dsn' => '', + 'hostname' => '192.168.250.126', + 'username' => 'root', + 'password' => 'pramita102938', + 'database' => 'one', + 'dbdriver' => 'mysqli', + 'dbprefix' => '', + 'pconnect' => FALSE, + 'db_debug' => FALSE, + '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['denpasar'] = array( + 'dsn' => '', + 'hostname' => '192.168.250.136', + 'username' => 'root', + 'password' => 'pramita102938', + 'database' => 'one', + 'dbdriver' => 'mysqli', + 'dbprefix' => '', + 'pconnect' => FALSE, + 'db_debug' => FALSE, + '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['tasik'] = array( + 'dsn' => '', + 'hostname' => '192.168.250.176', + 'username' => 'root', + 'password' => 'pramita102938', + 'database' => 'one', + 'dbdriver' => 'mysqli', + 'dbprefix' => '', + 'pconnect' => FALSE, + 'db_debug' => FALSE, + '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['dupang'] = array( + 'dsn' => '', + 'hostname' => '192.168.250.251', + 'username' => 'root', + 'password' => 'pramita102938', + 'database' => 'one', + 'dbdriver' => 'mysqli', + 'dbprefix' => '', + 'pconnect' => FALSE, + 'db_debug' => FALSE, + '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['wonokusumo'] = array( + 'dsn' => '', + 'hostname' => '192.168.250.252', + 'username' => 'root', + 'password' => 'pramita102938', + 'database' => 'one', + 'dbdriver' => 'mysqli', + 'dbprefix' => '', + 'pconnect' => FALSE, + 'db_debug' => FALSE, + '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['tangkuban_perahu'] = array( + 'dsn' => '', + 'hostname' => '192.168.250.81', + 'username' => 'root', + 'password' => 'pramita102938', + 'database' => 'one', + 'dbdriver' => 'mysqli', + 'dbprefix' => '', + 'pconnect' => FALSE, + 'db_debug' => FALSE, + '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['ciliwung'] = array( + 'dsn' => '', + 'hostname' => '192.168.250.82', + 'username' => 'root', + 'password' => 'pramita102938', + 'database' => 'one', + 'dbdriver' => 'mysqli', + 'dbprefix' => '', + 'pconnect' => FALSE, + 'db_debug' => FALSE, + '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['kediri'] = array( + 'dsn' => '', + 'hostname' => '192.168.250.85', + 'username' => 'root', + 'password' => 'pramita102938', + 'database' => 'one', + 'dbdriver' => 'mysqli', + 'dbprefix' => '', + 'pconnect' => FALSE, + 'db_debug' => FALSE, + '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['jember'] = array( + 'dsn' => '', + 'hostname' => '192.168.250.88', + 'username' => 'root', + 'password' => 'pramita102938', + 'database' => 'one', + 'dbdriver' => 'mysqli', + 'dbprefix' => '', + 'pconnect' => FALSE, + 'db_debug' => FALSE, + '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['simokerto'] = array( + 'dsn' => '', + 'hostname' => '192.168.250.253', + 'username' => 'root', + 'password' => 'pramita102938', + 'database' => 'one', + 'dbdriver' => 'mysqli', + 'dbprefix' => '', + 'pconnect' => FALSE, + 'db_debug' => FALSE, + '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['hertasning'] = array( + 'dsn' => '', + 'hostname' => '192.168.250.127', + 'username' => 'root', + 'password' => 'pramita102938', + 'database' => 'one', + 'dbdriver' => 'mysqli', + 'dbprefix' => '', + 'pconnect' => FALSE, + 'db_debug' => FALSE, + '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['tulungagung'] = array( + 'dsn' => '', + 'hostname' => '192.168.250.91', + 'username' => 'root', + 'password' => 'pramita102938', + 'database' => 'one', + 'dbdriver' => 'mysqli', + 'dbprefix' => '', + 'pconnect' => FALSE, + 'db_debug' => FALSE, + '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['hasyim'] = array( + 'dsn' => '', + 'hostname' => '192.168.250.163', + 'username' => 'root', + 'password' => 'pramita102938', + 'database' => 'one', + 'dbdriver' => 'mysqli', + 'dbprefix' => '', + 'pconnect' => FALSE, + 'db_debug' => FALSE, + '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['sumarecon'] = array( + 'dsn' => '', + 'hostname' => '192.168.250.158', + 'username' => 'root', + 'password' => 'pramita102938', + 'database' => 'one', + 'dbdriver' => 'mysqli', + 'dbprefix' => '', + 'pconnect' => FALSE, + 'db_debug' => FALSE, + '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['kompolmaksum'] = array( + 'dsn' => '', + 'hostname' => '192.168.250.132', + 'username' => 'root', + 'password' => 'pramita102938', + 'database' => 'one', + 'dbdriver' => 'mysqli', + 'dbprefix' => '', + 'pconnect' => FALSE, + 'db_debug' => FALSE, + '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['mojokerto'] = array( + 'dsn' => '', + 'hostname' => '192.168.250.248', + 'username' => 'root', + 'password' => 'pramita102938', + 'database' => 'one', + 'dbdriver' => 'mysqli', + 'dbprefix' => '', + 'pconnect' => FALSE, + 'db_debug' => FALSE, + '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['reg_bandung'] = array( + 'dsn' => '', + 'hostname' => '192.168.250.206', + 'username' => 'root', + 'password' => 'pramita102938', + 'database' => 'bandung', + 'dbdriver' => 'mysqli', + 'dbprefix' => '', + 'pconnect' => FALSE, + 'db_debug' => FALSE, + '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['reg_tegal'] = array( + 'dsn' => '', + 'hostname' => '192.168.250.212', + 'username' => 'root', + 'password' => 'pramita102938', + 'database' => 'tegal', + 'dbdriver' => 'mysqli', + 'dbprefix' => '', + 'pconnect' => FALSE, + 'db_debug' => FALSE, + '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['reg_manado'] = array( + 'dsn' => '', + 'hostname' => '192.168.250.222', + 'username' => 'root', + 'password' => 'pramita102938', + 'database' => 'manado', + 'dbdriver' => 'mysqli', + 'dbprefix' => '', + 'pconnect' => FALSE, + 'db_debug' => FALSE, + '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['reg_pontianak'] = array( + 'dsn' => '', + 'hostname' => '192.168.250.230', + 'username' => 'root', + 'password' => 'pramita102938', + 'database' => 'pontianak', + 'dbdriver' => 'mysqli', + 'dbprefix' => '', + 'pconnect' => FALSE, + 'db_debug' => FALSE, + '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['reg_surabaya'] = array( + 'dsn' => '', + 'hostname' => '192.168.250.240', + 'username' => 'root', + 'password' => 'pramita102938', + 'database' => 'surabaya', + 'dbdriver' => 'mysqli', + 'dbprefix' => '', + 'pconnect' => FALSE, + 'db_debug' => FALSE, + '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['reg_yogya'] = array( + 'dsn' => '', + 'hostname' => '192.168.250.195', + 'username' => 'root', + 'password' => 'pramita102938', + 'database' => 'yogya', + 'dbdriver' => 'mysqli', + 'dbprefix' => '', + 'pconnect' => FALSE, + 'db_debug' => FALSE, + '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['reg_jakarta'] = array( + 'dsn' => '', + 'hostname' => '192.168.250.180', + 'username' => 'root', + 'password' => 'pramita102938', + 'database' => 'jakarta', + 'dbdriver' => 'mysqli', + 'dbprefix' => '', + 'pconnect' => FALSE, + 'db_debug' => FALSE, + '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['reg_cirebon'] = array( + 'dsn' => '', + 'hostname' => '192.168.250.215', + 'username' => 'root', + 'password' => 'pramita102938', + 'database' => 'cirebon', + 'dbdriver' => 'mysqli', + 'dbprefix' => '', + 'pconnect' => FALSE, + 'db_debug' => FALSE, + '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['reg_palembang'] = array( + 'dsn' => '', + 'hostname' => '192.168.250.170', + 'username' => 'root', + 'password' => 'pramita102938', + 'database' => 'palembang', + 'dbdriver' => 'mysqli', + 'dbprefix' => '', + 'pconnect' => FALSE, + 'db_debug' => FALSE, + '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['reg_medan'] = array( + 'dsn' => '', + 'hostname' => '192.168.250.160', + 'username' => 'root', + 'password' => 'pramita102938', + 'database' => 'medan', + 'dbdriver' => 'mysqli', + 'dbprefix' => '', + 'pconnect' => FALSE, + 'db_debug' => FALSE, + '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['reg_padang'] = array( + 'dsn' => '', + 'hostname' => '192.168.250.150', + 'username' => 'root', + 'password' => 'pramita102938', + 'database' => 'padang', + 'dbdriver' => 'mysqli', + 'dbprefix' => '', + 'pconnect' => FALSE, + 'db_debug' => FALSE, + '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['reg_pekanbaru'] = array( + 'dsn' => '', + 'hostname' => '192.168.250.155', + 'username' => 'root', + 'password' => 'pramita102938', + 'database' => 'pekanbaru', + 'dbdriver' => 'mysqli', + 'dbprefix' => '', + 'pconnect' => FALSE, + 'db_debug' => FALSE, + '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['reg_magelang'] = array( + 'dsn' => '', + 'hostname' => '192.168.250.140', + 'username' => 'root', + 'password' => 'pramita102938', + 'database' => 'magelang', + 'dbdriver' => 'mysqli', + 'dbprefix' => '', + 'pconnect' => FALSE, + 'db_debug' => FALSE, + '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['reg_salatiga'] = array( + 'dsn' => '', + 'hostname' => '192.168.250.148', + 'username' => 'root', + 'password' => 'pramita102938', + 'database' => 'salatiga', + 'dbdriver' => 'mysqli', + 'dbprefix' => '', + 'pconnect' => FALSE, + 'db_debug' => FALSE, + '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['reg_semarang'] = array( + 'dsn' => '', + 'hostname' => '192.168.250.130', + 'username' => 'root', + 'password' => 'pramita102938', + 'database' => 'semarang', + 'dbdriver' => 'mysqli', + 'dbprefix' => '', + 'pconnect' => FALSE, + 'db_debug' => FALSE, + '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['reg_balikpapan'] = array( + 'dsn' => '', + 'hostname' => '192.168.250.235', + 'username' => 'root', + 'password' => 'pramita102938', + 'database' => 'balikpapan', + 'dbdriver' => 'mysqli', + 'dbprefix' => '', + 'pconnect' => FALSE, + 'db_debug' => FALSE, + '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['reg_madiun'] = array( + 'dsn' => '', + 'hostname' => '192.168.250.120', + 'username' => 'root', + 'password' => 'pramita102938', + 'database' => 'madiun', + 'dbdriver' => 'mysqli', + 'dbprefix' => '', + 'pconnect' => FALSE, + 'db_debug' => FALSE, + '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['reg_makasar'] = array( + 'dsn' => '', + 'hostname' => '192.168.250.125', + 'username' => 'root', + 'password' => 'pramita102938', + 'database' => 'makasar', + 'dbdriver' => 'mysqli', + 'dbprefix' => '', + 'pconnect' => FALSE, + 'db_debug' => FALSE, + '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['reg_denpasar'] = array( + 'dsn' => '', + 'hostname' => '192.168.250.135', + 'username' => 'root', + 'password' => 'pramita102938', + 'database' => 'denpasar', + 'dbdriver' => 'mysqli', + 'dbprefix' => '', + 'pconnect' => FALSE, + 'db_debug' => FALSE, + '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['reg_tasik'] = array( + 'dsn' => '', + 'hostname' => '192.168.250.175', + 'username' => 'root', + 'password' => 'pramita102938', + 'database' => 'tasikmalaya', + 'dbdriver' => 'mysqli', + 'dbprefix' => '', + 'pconnect' => FALSE, + 'db_debug' => FALSE, + '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['reg_prospek'] = array( + 'dsn' => '', + 'hostname' => '192.168.250.250', + 'username' => 'root', + 'password' => 'pramita102938', + 'database' => 'prospek', + 'dbdriver' => 'mysqli', + 'dbprefix' => '', + 'pconnect' => FALSE, + 'db_debug' => FALSE, + '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['reg_sima_malang'] = array( + 'dsn' => '', + 'hostname' => '192.168.250.80', + 'username' => 'root', + 'password' => 'pramita102938', + 'database' => 'malang', + 'dbdriver' => 'mysqli', + 'dbprefix' => '', + 'pconnect' => FALSE, + 'db_debug' => FALSE, + '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['reg_sima_kediri'] = array( + 'dsn' => '', + 'hostname' => '192.168.250.84', + 'username' => 'root', + 'password' => 'pramita102938', + 'database' => 'kediri', + 'dbdriver' => 'mysqli', + 'dbprefix' => '', + 'pconnect' => FALSE, + 'db_debug' => FALSE, + '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['reg_sima_jember'] = array( + 'dsn' => '', + 'hostname' => '192.168.250.87', + 'username' => 'root', + 'password' => 'pramita102938', + 'database' => 'jember', + 'dbdriver' => 'mysqli', + 'dbprefix' => '', + 'pconnect' => FALSE, + 'db_debug' => FALSE, + '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['reg_tulungagung'] = array( + 'dsn' => '', + 'hostname' => '192.168.250.90', + 'username' => 'root', + 'password' => 'pramita102938', + 'database' => 'jember', + 'dbdriver' => 'mysqli', + 'dbprefix' => '', + 'pconnect' => FALSE, + 'db_debug' => FALSE, + '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['reg_bekasi'] = array( + 'dsn' => '', + 'hostname' => '192.168.250.157', + 'username' => 'root', + 'password' => 'pramita102938', + 'database' => 'jember', + 'dbdriver' => 'mysqli', + 'dbprefix' => '', + 'pconnect' => FALSE, + 'db_debug' => FALSE, + '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['reg_mojokerto'] = array( + 'dsn' => '', + 'hostname' => '192.168.250.249', + 'username' => 'root', + 'password' => 'pramita102938', + 'database' => 'mojokerto', + 'dbdriver' => 'mysqli', + 'dbprefix' => '', + 'pconnect' => FALSE, + 'db_debug' => FALSE, + '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['klinik'] = array( + 'dsn' => '', + 'hostname' => 'localhost', + 'username' => 'root', + 'password' => 'sasone102938', + 'database' => 'one_klinik', + 'dbdriver' => 'mysqli', + 'dbprefix' => '', + 'pconnect' => FALSE, + 'db_debug' => FALSE, + '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['inventory'] = array( + 'dsn' => '', + 'hostname' => 'localhost', + 'username' => 'root', + 'password' => 'sasone102938', + 'database' => 'one_inventory', + 'dbdriver' => 'mysqli', + 'dbprefix' => '', + 'pconnect' => FALSE, + 'db_debug' => FALSE, + '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['inventory_log'] = array( + 'dsn' => '', + 'hostname' => 'localhost', + 'username' => 'root', + 'password' => 'sasone102938', + 'database' => 'one_inventory_log', + 'dbdriver' => 'mysqli', + 'dbprefix' => '', + 'pconnect' => FALSE, + 'db_debug' => FALSE, + '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['bloodbank'] = array( + 'dsn' => '', + 'hostname' => 'localhost', + 'username' => 'root', + 'password' => 'sasone102938', + 'database' => 'one_bb', + 'dbdriver' => 'mysqli', + 'dbprefix' => '', + 'pconnect' => FALSE, + 'db_debug' => FALSE, + 'cache_on' => FALSE, + 'cachedir' => '', + 'char_set' => 'utf8', + 'dbcollat' => 'utf8_general_ci', + 'swap_pre' => '', + 'encrypt' => FALSE, + 'compress' => FALSE, + 'stricton' => FALSE, + 'failover' => array(), + 'save_queries' => TRUE + ); + + + diff --git a/application/config/doctypes.php b/application/config/doctypes.php new file mode 100755 index 00000000..59a7991e --- /dev/null +++ b/application/config/doctypes.php @@ -0,0 +1,24 @@ + '', + 'xhtml1-strict' => '', + 'xhtml1-trans' => '', + 'xhtml1-frame' => '', + 'xhtml-basic11' => '', + 'html5' => '', + 'html4-strict' => '', + 'html4-trans' => '', + 'html4-frame' => '', + 'mathml1' => '', + 'mathml2' => '', + 'svg10' => '', + 'svg11' => '', + 'svg11-basic' => '', + 'svg11-tiny' => '', + 'xhtml-math-svg-xh' => '', + 'xhtml-math-svg-sh' => '', + 'xhtml-rdfa-1' => '', + 'xhtml-rdfa-2' => '' +); diff --git a/application/config/foreign_chars.php b/application/config/foreign_chars.php new file mode 100755 index 00000000..995f4830 --- /dev/null +++ b/application/config/foreign_chars.php @@ -0,0 +1,103 @@ + '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' +); diff --git a/application/config/hooks.php b/application/config/hooks.php new file mode 100755 index 00000000..a8f38a5d --- /dev/null +++ b/application/config/hooks.php @@ -0,0 +1,13 @@ + + + + 403 Forbidden + + + +

Directory access is forbidden.

+ + + diff --git a/application/config/memcached.php b/application/config/memcached.php new file mode 100755 index 00000000..5c23b39c --- /dev/null +++ b/application/config/memcached.php @@ -0,0 +1,19 @@ + array( + 'hostname' => '127.0.0.1', + 'port' => '11211', + 'weight' => '1', + ), +); diff --git a/application/config/migration.php b/application/config/migration.php new file mode 100755 index 00000000..4b585a65 --- /dev/null +++ b/application/config/migration.php @@ -0,0 +1,84 @@ +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/'; diff --git a/application/config/mimes.php b/application/config/mimes.php new file mode 100755 index 00000000..0ec9db0a --- /dev/null +++ b/application/config/mimes.php @@ -0,0 +1,184 @@ + 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' +); diff --git a/application/config/mongo_db.php b/application/config/mongo_db.php new file mode 100644 index 00000000..b94e37d9 --- /dev/null +++ b/application/config/mongo_db.php @@ -0,0 +1,14 @@ +$config['mongo_db']['active'] = 'default'; +$config['mongo_db']['default']['no_auth'] = false; +$config['mongo_db']['default']['hostname'] = 'localhost'; +$config['mongo_db']['default']['port'] = '27017'; +$config['mongo_db']['default']['username'] = 'one'; +$config['mongo_db']['default']['password'] = 'sasone102938'; +$config['mongo_db']['default']['database'] = ''; +$config['mongo_db']['default']['db_debug'] = TRUE; +$config['mongo_db']['default']['return_as'] = 'array'; +$config['mongo_db']['default']['write_concerns'] = (int)1; +$config['mongo_db']['default']['journal'] = TRUE; +$config['mongo_db']['default']['read_preference'] = 'primary'; +$config['mongo_db']['default']['read_concern'] = 'local'; //'local', 'majority' or 'linearizable' +$config['mongo_db']['default']['legacy_support'] = TRUE; diff --git a/application/config/profiler.php b/application/config/profiler.php new file mode 100755 index 00000000..3db22e39 --- /dev/null +++ b/application/config/profiler.php @@ -0,0 +1,14 @@ + my_controller/index +| my-controller/my-method -> my_controller/my_method +*/ +$route['default_controller'] = 'welcome'; +$route['404_override'] = ''; +$route['translate_uri_dashes'] = FALSE; diff --git a/application/config/smileys.php b/application/config/smileys.php new file mode 100755 index 00000000..abf9a898 --- /dev/null +++ b/application/config/smileys.php @@ -0,0 +1,64 @@ + 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') + +); diff --git a/application/config/user_agents.php b/application/config/user_agents.php new file mode 100755 index 00000000..b6c85631 --- /dev/null +++ b/application/config/user_agents.php @@ -0,0 +1,214 @@ + '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/ 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' +); diff --git a/application/core/MY_Controller-bkp-autologout.php b/application/core/MY_Controller-bkp-autologout.php new file mode 100755 index 00000000..4dafed48 --- /dev/null +++ b/application/core/MY_Controller-bkp-autologout.php @@ -0,0 +1,135 @@ +sys_user = array( + "isExists" => false, + "user" => array( + "userName" => "", + "userLogin" => "", + "userID" => 0 + ) + ); + error_reporting(0); + $this->sys_input = json_decode($this->input->raw_input_stream, true); + if (! $this->sys_input) { + if (count($this->input->post()) > 0) { + $this->sys_input = $this->input->post(); + } else { + $this->sys_input = $this->input->get(); + } + } + $this->load->library("Jwt"); + try { + $prm = $this->sys_input; + if (! isset($prm["token"])) { + $this->isLogin = false; + } else { + $user = JWT::decode($prm["token"], $this->SECRET_KEY, true); + unset($this->sys_input["token"]); + $user = json_decode(json_encode($user), true); + if ($user["M_UserID"] > 0) { + $this->isLogin = true; + } + $this->sys_user = $user; + $this->db_onedev = $this->load->database("onedev", true); + $query = $this->db_onedev->query("update m_user SET M_UserLastAccess = now() WHERE M_UserID = ?", array($user["M_UserID"])); + if (!$query) { + $message = $this->db_onedev->error(); + $this->sys_error($message); + exit; + } + //update last accessed + } + } catch (Exception $e) { + $this->isLogin = false; + } + $this->load->database(); + } + public function sys_debug() + { + ini_set('display_errors', 1); + ini_set('display_startup_errors', 1); + error_reporting(E_ALL); + } + public function sys_error_db($message, $db = false) + { + if (! $db) { + echo json_encode( + array( + "status" => "ERR", + "message" => $message, + "query" => $this->db->last_query(), + "db_error" => $this->db->error() + ) + ); + } else { + echo json_encode( + array( + "status" => "ERR", + "message" => $message, + "query" => $db->last_query(), + "db_error" => $db->error() + ) + ); + } + } + public function sys_error($message) + { + echo json_encode( + array( + "status" => "ERR", + "message" => $message + ) + ); + } + public function sys_ok($data) + { + echo json_encode( + array( + "status" => "OK", + "data" => $data + ) + ); + } + + public function clean_mysqli_connection($dbc) + { + while (mysqli_more_results($dbc)) { + if (mysqli_next_result($dbc)) { + $result = mysqli_use_result($dbc); + + unset($result); + } + } + } +} diff --git a/application/core/MY_Controller.php b/application/core/MY_Controller.php new file mode 100644 index 00000000..c1e17324 --- /dev/null +++ b/application/core/MY_Controller.php @@ -0,0 +1,156 @@ +input = new MY_Input(); + + //for preflight + header('Access-Control-Allow-Origin: *'); + header('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS'); + header('Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept'); + //for disable cached + header('Last-Modified: ' . gmdate("D, d M Y H:i:s") . ' GMT'); + header('Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0'); + header('Pragma: no-cache'); + header("Expires: Mon, 26 Jul 1997 05:00:00 GMT"); + global $_SERVER; + if (isset($_SERVER["REQUEST_METHOD"]) && $_SERVER["REQUEST_METHOD"] == "OPTIONS") { + exit; + } + $this->sys_user = array( + "isExists" => false, + "user" => array( + "userName" => "", + "userLogin" => "", + "userID" => 0 + ) + ); + error_reporting(0); + // Refactored on 2025-02-11 + $this->sys_input = json_decode($this->input->raw_input_stream, true); + if (! $this->sys_input) { + if (count($this->input->post()) > 0) { + $this->sys_input = $this->input->post(); //default post(null, true) + } else { + $this->sys_input = $this->input->get(); //default get(null, true) + } + } + + $this->load->library("Jwt"); + try { + $prm = $this->sys_input; + if (! isset($prm["token"])) { + $this->isLogin = false; + } else { + $user = JWT::decode($prm["token"], $this->SECRET_KEY, true); + unset($this->sys_input["token"]); + $user = json_decode(json_encode($user), true); + if ($user["M_UserID"] > 0) { + $this->isLogin = true; + } + $this->sys_user = $user; + $this->db_onedev = $this->load->database("onedev", true); + $this->db_inventory = $this->load->database("inventory", true); + $this->db_inventory_log = $this->load->database("inventory_log", true); + $this->db_bloodbank = $this->load->database("bloodbank", true); + $this->db_onex = "one_aditya"; + $query = $this->db_onedev->query("update m_user SET M_UserLastAccess = now() WHERE M_UserID = ?", array($user["M_UserID"])); + if (!$query) { + $message = $this->db_onedev->error(); + $this->sys_error($message); + exit; + } + //update last accessed + } + } catch (Exception $e) { + $this->isLogin = false; + } + $this->load->database(); + } + public function sys_debug() + { + ini_set('display_errors', 1); + ini_set('display_startup_errors', 1); + error_reporting(E_ALL); + } + public function sys_error_db($message, $db = false) + { + if (! $db) { + echo json_encode( + array( + "status" => "ERR", + "message" => $message, + "query" => $this->db->last_query(), + "db_error" => $this->db->error() + ) + ); + } else { + echo json_encode( + array( + "status" => "ERR", + "message" => $message, + "query" => $db->last_query(), + "db_error" => $db->error() + ) + ); + } + } + public function sys_error($message) + { + echo json_encode( + array( + "status" => "ERR", + "message" => $message + ) + ); + } + public function sys_ok($data) + { + echo json_encode( + array( + "status" => "OK", + "data" => $data + ) + ); + } + + public function clean_mysqli_connection($dbc) + { + while (mysqli_more_results($dbc)) { + if (mysqli_next_result($dbc)) { + $result = mysqli_use_result($dbc); + + unset($result); + } + } + } + + public function __destruct() + { + $this->db_onedev->close(); + $this->db_inventory->close(); + $this->db_inventory_log->close(); + $this->db_bloodbank->close(); + } +} diff --git a/application/core/MY_Controller_old.php b/application/core/MY_Controller_old.php new file mode 100755 index 00000000..5f808865 --- /dev/null +++ b/application/core/MY_Controller_old.php @@ -0,0 +1,141 @@ +sys_user = array( + "isExists" => false, + "user" => array( + "userName" => "", + "userLogin" => "", + "userID" => 0 + ) + ); + error_reporting(0); + $this->sys_input = json_decode($this->input->raw_input_stream,true); + if (! $this->sys_input ) { + if ( count($this->input->post()) > 0 ) { + $this->sys_input = $this->input->post(); + } else { + $this->sys_input = $this->input->get(); + } + } + $this->load->library("Jwt"); + try { + $prm = $this->sys_input; + if (! isset($prm["token"])) { + $this->isLogin = false; + } else { + $user = JWT::decode($prm["token"],$this->SECRET_KEY,true); + unset($this->sys_input["token"]); + $user = json_decode(json_encode($user),true); + if ($user["M_UserID"] > 0 ) { + $this->isLogin = true; + } + $this->sys_user = $user; + $this->db_onedev = $this->load->database("onedev", true); + $this->db_inventory = $this->load->database("inventory", true); + $this->db_inventory_log = $this->load->database("inventory_log", true); + $this->db_bloodbank = $this->load->database("bloodbank", true); + $this->db_onex = "one_aditya"; + $query = $this->db_onedev->query("update m_user SET M_UserLastAccess = now() WHERE M_UserID = ?",array($user["M_UserID"])); + if (!$query) { + $message = $this->db_onedev->error(); + $this->sys_error($message); + exit; + } + //update last accessed + } + } catch(Exception $e) { + $this->isLogin = false; + } + $this->load->database(); + + } + public function sys_debug() { + ini_set('display_errors', 1); + ini_set('display_startup_errors', 1); + error_reporting(E_ALL); + } + public function sys_error_db($message,$db = false) { + if (! $db ) { + echo json_encode( + array( + "status" => "ERR", + "message" => $message, + "query" => $this->db->last_query(), + "db_error" => $this->db->error() + ) + ); + } else { + echo json_encode( + array( + "status" => "ERR", + "message" => $message, + "query" => $db->last_query(), + "db_error" => $db->error() + ) + ); + } + } + public function sys_error($message) { + echo json_encode( + array( + "status" => "ERR", + "message" => $message + ) + ); + } + public function sys_ok($data) { + echo json_encode( + array( + "status" => "OK", + "data" => $data + ) + ); + } + + public function clean_mysqli_connection( $dbc ) + { + while( mysqli_more_results($dbc) ) + { + if(mysqli_next_result($dbc)) + { + $result = mysqli_use_result($dbc); + + unset($result); + } + } + } +} +?> diff --git a/application/core/MY_Input.php b/application/core/MY_Input.php new file mode 100644 index 00000000..4d78504d --- /dev/null +++ b/application/core/MY_Input.php @@ -0,0 +1,292 @@ + 'UTF-8', + 'html_entities_flags' => ENT_QUOTES, + ]; + + /** + * @var array SQL injection patterns to detect + */ + private $sqlInjectionPatterns = [ + // Previous patterns + '/\b(union\s+all|union\s+select|insert\s+into|drop\s+table|exec\s+xp|exec\s+sp)\b/i', + '/\b(or\s+\d+=\d+|or\s+\'.*\'=\'.*\'|or\s+[\'"].*[\'"]=[\'"].*[\'"])\b/i', + '/(\-\-\s*$|\/\*|\*\/|#\s*$)/', + '/\b(concat|char|cast|convert|decode|encode|eval|exec)\s*\(/i', + '/\b(xp_cmdshell|xp_regread|sp_password|sp_executesql)\b/i', + + // Enhanced time-based injection patterns + '/\b(?:and|or|if)\s*\(?[\s\w]*(?:sleep|delay|benchmark|wait)\s*[\(\s]*\d+[^\w\s]*\)?/i', + + // Enhanced conditional patterns + '/\b(?:and|or|if)\s*\([^)]*(?:sleep|delay|benchmark|wait)[^)]*\)/i', + + // Case-insensitive function detection (including spaces and parentheses) + '/\b(?:s[\s]*l[\s]*e[\s]*e[\s]*p|d[\s]*e[\s]*l[\s]*a[\s]*y|b[\s]*e[\s]*n[\s]*c[\s]*h[\s]*m[\s]*a[\s]*r[\s]*k)\s*\(/i', + + // Additional patterns for IF statements + '/\b(?:if)\s*\(\s*(?:sleep|delay|benchmark|wait)\s*\(\s*\d+\s*\)\s*,\s*\d+\s*,\s*\d+\s*\)/i', + + // Pattern specifically for your case + '/\band\s+if\s*\(\s*sleep\s*\(\s*\d+\s*\)\s*,\s*\d+\s*,\s*\d+\s*\)/i', + + // Previous patterns continue + '/\b(0x[0-9a-f]+)\b/i', + '/(\s+and\s+\d+=\d+|\s+and\s+\'.*\'=\'.*\'|\s+and\s+[\'"].*[\'"]=[\'"].*[\'"])/i' + ]; + + /** + * @var array Suspicious characters that might indicate SQL injection + */ + private $suspiciousChars = [ + ';', // Statement terminator + '\'', // Single quote + '"', // Double quote + '`', // Backtick + '\\', // Backslash + '\x00', // Null byte + '\x1a', // Ctrl+Z + ]; + + /** + * Constructor + */ + public function __construct() + { + parent::__construct(); + } + + /** + * Get sanitized GET data + * + * @param string|null $index Index for retrieving the GET data + * @param bool $xss_clean Whether to apply XSS filtering + * @return mixed + */ + public function get($index = null, $xss_clean = true) + { + return $this->sanitizeInput( + parent::get($index, $xss_clean) + ); + } + + /** + * Get sanitized POST data + * + * @param string|null $index Index for retrieving the POST data + * @param bool $xss_clean Whether to apply XSS filtering + * @return mixed + */ + public function post($index = null, $xss_clean = true) + { + return $this->sanitizeInput( + parent::post($index, $xss_clean) + ); + } + + /** + * Get raw input stream + * + * @return string + */ + // Harusnya override raw_input_stream tapi takut kalau merubah banyak fungsi yang pakai input->raw_input_stream + // public function getRawInput() + public function raw_input_stream() + { + $input = file_get_contents('php://input'); + return $this->sanitizeInput($input); + } + + /** + * Sanitize input data + * + * @param mixed $input Input data to sanitize + * @return mixed + */ + protected function sanitizeInput($input) + { + if (is_string($input)) { + return $this->sanitizeString($input); + } + + if (is_array($input)) { + return $this->sanitizeArray($input); + } + + return $input; + } + + /** + * Sanitize an array recursively + * + * @param array $input Array to sanitize + * @return array + */ + protected function sanitizeArray(array $input): array + { + return array_map( + function ($item) { + return $this->sanitizeInput($item); + }, + $input + ); + } + + /** + * Sanitize a string value + * + * @param string $input String to sanitize + * @return string + */ + protected function sanitizeString(string $input): string + { + // Return empty string for null input + if ($input === null) { + return ''; + } + + $clean = trim($input); + + // Check for SQL injection attempts + if ($this->containsSQLInjection($clean)) { + // log_message('warning', 'Potential SQL injection detected: ' . $clean); + return ''; + } + + // Basic sanitization + $clean = filter_var($clean, FILTER_SANITIZE_STRING, FILTER_FLAG_NO_ENCODE_QUOTES); + + // Remove null bytes + $clean = str_replace(chr(0), '', $clean); + + // Remove control characters + $clean = preg_replace('/[\x00-\x1F\x7F]/u', '', $clean); + + // Convert special characters to HTML entities + $clean = htmlspecialchars( + $clean, + $this->config['html_entities_flags'], + $this->config['encoding'] + ); + + return $clean; + } + + /** + * Check if a string contains SQL injection attempts + * + * @param string $input String to check + * @return bool + */ + protected function containsSQLInjection(string $input): bool + { + // Normalize input for better detection + $normalizedInput = $this->normalizeInput($input); + + // Check original and normalized input against patterns + foreach ($this->sqlInjectionPatterns as $pattern) { + if (preg_match($pattern, $input) || preg_match($pattern, $normalizedInput)) { + return true; + } + } + + // Check for suspicious characters + foreach ($this->suspiciousChars as $char) { + if (strpos($input, $char) !== false) { + return true; + } + } + + // Additional check specifically for time-based attacks + if ($this->containsTimeBased($normalizedInput)) { + return true; + } + + return false; + } + + /** + * Normalize input for consistent checking + * + * @param string $input + * @return string + */ + private function normalizeInput(string $input): string + { + // Convert to lowercase + $normalized = strtolower($input); + + // Remove extra spaces + $normalized = preg_replace('/\s+/', ' ', $normalized); + + // Remove url encoding + $normalized = urldecode($normalized); + + // Replace common obfuscation patterns + $replacements = [ + '/s[\s]*l[\s]*e[\s]*e[\s]*p/' => 'sleep', + '/i[\s]*f/' => 'if', + '/a[\s]*n[\s]*d/' => 'and', + '/o[\s]*r/' => 'or', + '/b[\s]*e[\s]*n[\s]*c[\s]*h[\s]*m[\s]*a[\s]*r[\s]*k/' => 'benchmark', + '/w[\s]*a[\s]*i[\s]*t[\s]*f[\s]*o[\s]*r/' => 'waitfor' + ]; + + foreach ($replacements as $pattern => $replacement) { + $normalized = preg_replace($pattern, $replacement, $normalized); + } + + return $normalized; + } + + /** + * Specific check for time-based SQL injection attempts + * + * @param string $input + * @return bool + */ + private function containsTimeBased(string $input): bool + { + $timeBased = [ + // Detect IF(SLEEP()) pattern with variations + '/if\s*\(\s*sleep\s*\(\s*\d+\s*\)\s*,\s*\d+\s*,\s*\d+\s*\)/i', + + // Detect AND IF(SLEEP()) pattern + '/and\s+if\s*\(\s*sleep\s*\(\s*\d+\s*\)\s*,\s*\d+\s*,\s*\d+\s*\)/i', + + // Additional time-based patterns + '/benchmark\s*\(\s*\d+\s*,\s*[^)]+\)/i', + '/waitfor\s+delay\s+\'\d+\:\d+\:\d+\'/i', + '/pg_sleep\s*\(\s*\d+\s*\)/i' + ]; + + foreach ($timeBased as $pattern) { + if (preg_match($pattern, $input)) { + return true; + } + } + + return false; + } +} diff --git a/application/core/index.html b/application/core/index.html new file mode 100755 index 00000000..b702fbc3 --- /dev/null +++ b/application/core/index.html @@ -0,0 +1,11 @@ + + + + 403 Forbidden + + + +

Directory access is forbidden.

+ + + diff --git a/application/helpers/index.html b/application/helpers/index.html new file mode 100755 index 00000000..b702fbc3 --- /dev/null +++ b/application/helpers/index.html @@ -0,0 +1,11 @@ + + + + 403 Forbidden + + + +

Directory access is forbidden.

+ + + diff --git a/application/helpers/uuid_helper.php b/application/helpers/uuid_helper.php new file mode 100644 index 00000000..1828d216 --- /dev/null +++ b/application/helpers/uuid_helper.php @@ -0,0 +1,24 @@ + + + + 403 Forbidden + + + +

Directory access is forbidden.

+ + + diff --git a/application/index.html b/application/index.html new file mode 100755 index 00000000..b702fbc3 --- /dev/null +++ b/application/index.html @@ -0,0 +1,11 @@ + + + + 403 Forbidden + + + +

Directory access is forbidden.

+ + + diff --git a/application/language/english/index.html b/application/language/english/index.html new file mode 100755 index 00000000..b702fbc3 --- /dev/null +++ b/application/language/english/index.html @@ -0,0 +1,11 @@ + + + + 403 Forbidden + + + +

Directory access is forbidden.

+ + + diff --git a/application/language/index.html b/application/language/index.html new file mode 100755 index 00000000..b702fbc3 --- /dev/null +++ b/application/language/index.html @@ -0,0 +1,11 @@ + + + + 403 Forbidden + + + +

Directory access is forbidden.

+ + + diff --git a/application/libraries/Ai_whisper.php b/application/libraries/Ai_whisper.php new file mode 100644 index 00000000..e0425973 --- /dev/null +++ b/application/libraries/Ai_whisper.php @@ -0,0 +1,197 @@ + "ERR", "message" => "Error: File not found."]; + } + + // Get file extension and appropriate MIME type + $extension = strtolower(pathinfo($audioPath, PATHINFO_EXTENSION)); + $mimeType = $this->getMimeType($extension); + + // Create CURLFile with correct MIME type + $curlFile = new CURLFile( + $audioPath, // File path + $mimeType, // MIME type + basename($audioPath) // Filename + ); + + // Prepare the multipart form data + $postFields = [ + 'file' => $curlFile, + 'model' => $this->whisperModelName, + 'response_format' => 'verbose_json', + 'timestamp_granularities' => ['segment'], + 'language' => $this->whisperLanguage, + ]; + + // Initialize cURL session + $ch = curl_init(); + + // Set cURL options + curl_setopt_array($ch, [ + CURLOPT_URL => self::API_URL, + CURLOPT_RETURNTRANSFER => true, + CURLOPT_POST => true, + CURLOPT_POSTFIELDS => $postFields, + CURLOPT_HTTPHEADER => [ + 'Authorization: Bearer ' . self::API_KEY, + // Don't set Content-Type header - cURL will set it automatically with boundary + ], + CURLOPT_TIMEOUT => 300, // 5 minutes timeout for large files + CURLOPT_SSL_VERIFYPEER => true, + ]); + + // Execute request + $response = curl_exec($ch); + $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE); + $error = curl_error($ch); + + curl_close($ch); + + // Handle cURL errors + if ($error) { + return ["status" => "ERR", "message" => "cURL Error: " . json_encode($error, true)]; + } + + // Handle API errors + if ($httpCode !== 200) { + $errorData = json_decode($response, true); + return ["status" => "ERR", "message" => "API Error: " . ($errorData['error'] ?? "Unknown error occurred")]; + } + + // Decode and return the response + $result = json_decode($response, true); + return [ + 'status' => 'OK', + 'data' => $this->processDiarization($result, $persons), + ]; + } + + private function getMimeType($extension) + { + $mimeTypes = [ + 'mp3' => 'audio/mpeg', + 'wav' => 'audio/wav', + 'm4a' => 'audio/mp4', + 'ogg' => 'audio/ogg' + ]; + + return isset($mimeTypes[$extension]) ? $mimeTypes[$extension] : 'audio/mpeg'; + } + + // * INFO: Sementara begini dulu sampai bisa diarize pakai python + private function processDiarization($response, $persons) + { + $result = [ + 'diarized' => [], + 'raw' => $response + ]; + + // Create array of speaker IDs based on number of persons + $speakers = []; + for ($i = 1; $i <= $persons; $i++) { + $speakers[] = sprintf("SPEAKER_%02d", $i); + } + + // Track current speaker index + $currentSpeakerIndex = 0; + $speakerCount = count($speakers); + + foreach ($response['segments'] as $segment) { + // * 20250224: Maybe digunakan sometime + // $diarizedSegment = [ + // 'who' => $speakers[$currentSpeakerIndex], + // 'start' => $segment['start'], + // 'end' => $segment['end'], + // 'text' => trim($segment['text']) + // ]; + + $convo = $speakers[$currentSpeakerIndex] . ": " . trim($segment['text']); + + $result['diarized'][] = $convo; + // $result['raw'][] = $diarizedSegment; + + $currentSpeakerIndex = ($currentSpeakerIndex + 1) % $speakerCount; + } + + return $result; + } + + private function langChainDiarization($response) + { + $prompt = "This is a Whisper transcript of a 2-person conversation using Bahasa Indonesia. " . + "Identify speakers and segment the dialogue based on context because segmentation from whisper is sometimes wrong. " . + "Return the result in JSON format:\n" . + "{\n" . + "\"text\": \"Full transcription text...\",\n" . + "\"diarized\": [\n" . + "{\n" . + "\"who\": \"Speaker 1 or Speaker 2\",\n" . + "\"start\": timestamp,\n" . + "\"end\": timestamp,\n" . + "\"text\": \"...\"\n" . + "}\n" . + "]\n" . + "}\n" . + "Ensure accurate segmentation and speaker attribution.\n" . + "The convo:\n\n" . + $response['text']; + + $payload = json_encode([ + "model" => $this->diarizeModelName, + "messages" => [ + [ + "role" => "system", + "content" => "You are a helpful assistant that analyzes conversations and identifies speakers." + ], + [ + "role" => "user", + "content" => $prompt, + ] + ], + "options" => ["temperature" => $this->temperatureDiarize], + "stream" => false + ]); + + // Initialize cURL + $ch = curl_init(self::API_URL); + curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); + curl_setopt($ch, CURLOPT_POST, true); + curl_setopt($ch, CURLOPT_HTTPHEADER, [ + "Content-Type: application/json", + "Authorization: Bearer " . self::API_KEY + ]); + curl_setopt($ch, CURLOPT_POSTFIELDS, $payload); + + // Execute request + $response = curl_exec($ch); + if (curl_errno($ch)) { + $error = curl_error($ch); + curl_close($ch); + return ["status" => "ERR", "message" => curl_error($ch)]; + } + curl_close($ch); + + $response = strip_tags($response); + $responseData = json_decode($response, true); + $content = $responseData['choices'][0]['message']['content']; + + if (is_null($responseData) || !isset($content)) { + return ["status" => "ERR", "message" => "raw : $response"]; + } + } +} diff --git a/application/libraries/Autosamplingverif.php b/application/libraries/Autosamplingverif.php new file mode 100644 index 00000000..326e7620 --- /dev/null +++ b/application/libraries/Autosamplingverif.php @@ -0,0 +1,230 @@ +db_onedev = $CI->load->database("default", true); + } + + function clean_mysqli_connection( $dbc ) +{ + while( mysqli_more_results($dbc) ) + { + if(mysqli_next_result($dbc)) + { + $result = mysqli_use_result($dbc); + + if( get_class($result) == 'mysqli_stmt' ) + { + mysqli_stmt_free_result($result); + } + else + { + unset($result); + } + } + } +} + + function doaction($rst_id,$samplingtime,$userid){ + $sql = "call sp_fo_barcode_generate_again_not_exist(" . $rst_id . ")"; + $this->db_onedev->query($sql); + $this->clean_mysqli_connection($this->db_onedev->conn_id); + + $sql = "SELECT * + FROM t_orderheader + JOIN t_orderheaderaddon ON T_OrderHeaderAddOnT_OrderHeaderID = T_OrderHeaderID + WHERE T_OrderHeaderID = {$rst_id}"; + //echo $sql; + $row_addon = $this->db_onedev->query($sql)->row_array(); + + $readytime = date('Y-m-d H:i:s', strtotime($samplingtime)); + //echo $readytime; + $sql = "UPDATE t_ordersample + SET + T_OrderSampleSampling = 'Y', + T_OrderSampleSamplingDate = DATE('{$samplingtime}'), + T_OrderSampleSamplingTime = TIME('{$samplingtime}'), + T_OrderSampleSamplingUserID = {$userid}, + T_OrderSampleReceive = 'Y', + T_OrderSampleReceiveDate = DATE('{$samplingtime}'), + T_OrderSampleReceiveTime = TIME('{$samplingtime}'), + T_OrderSampleReadyToProcessDateTime = '{$readytime}', + T_OrderSampleVerification = 'Y', + T_OrderSampleVerificationDate = CURDATE(), + T_OrderSampleVerificationTime = CURTIME(), + T_OrderSampleVerificationUserID = {$userid}, + T_OrderSampleSendHandling = 'Y', + T_OrderSampleSendHandlingDate = CURDATE(), + T_OrderSampleSendHandlingTime = CURTIME(), + T_OrderSampleSendHandlingUserID = {$userid}, + T_OrderSampleReceiveUserID = {$userid}, + T_OrderSampleReceiveHandling = 'Y', + T_OrderSampleReceiveHandlingDate = CURDATE(), + T_OrderSampleReceiveHandlingTime = CURTIME(), + T_OrderSampleReceiveHandlingUserID = {$userid} + WHERE + T_OrderSampleT_OrderHeaderID = {$rst_id}"; + $upd_ordersample = $this->db_onedev->query($sql); + //echo $sql; + $sql = "SELECT * + FROM t_ordersample + JOIN t_barcodelab ON T_OrderSampleT_BarcodeLabID = T_BarcodeLabID AND T_BarcodeLabIsActive = 'Y' + JOIN t_sampletype ON T_SampleTypeID = T_OrderSampleT_SampleTypeID + JOIN t_bahan ON T_SampleTypeT_BahanID = T_BahanID + JOIN t_samplestation ON T_BahanT_SampleStationID = T_SampleStationID + WHERE + T_OrderSampleT_OrderHeaderID = {$rst_id} AND + T_OrderSampleIsActive = 'Y'"; + $data_loop = $this->db_onedev->query($sql)->result_array(); + if ($data_loop) { + foreach ($data_loop as $ks => $vs) { + $sql = "INSERT INTO t_ordersamplereq( + T_OrderSampleReqT_OrderHeaderID, + T_OrderSampleReqT_SampleStationID, + T_OrderSampleReqT_OrderSampleID, + T_OrderSampleReqNat_PositionID, + T_OrderSampleReqStatus, + T_OrderSampleReqs, + T_OrderSampleReqUserID, + T_OrderSampleReqCreated + ) + VALUES( + {$rst_id}, + {$vs['T_SampleStationID']}, + {$vs['T_OrderSampleID']}, + '2', + 'Y', + '[]', + {$userid}, + NOW() + )ON DUPLICATE KEY UPDATE + T_OrderSampleReqStatus = 'Y', + T_OrderSampleReqs = '[]', + T_OrderSampleReqUserID = {$userid}"; + //echo $sql; + $this->db_onedev->query($sql); + + $sql = "INSERT INTO sample_by_step( + SampleByStepM_StatusSampleCode, + SampleByStepT_OrderHeaderID, + SampleByStepT_BarcodeLabID, + SampleByStepRequirementStatus, + SampleByStepRequirements, + SampleByStepUserID, + SampleByStepDateTime + ) + VALUES( + 'SAMPLING.Sampling.Sampled', + {$rst_id}, + {$vs['T_BarcodeLabID']}, + 'Y', + '[]', + {$userid}, + '{$row_addon['T_OrderHeaderAddOnOnlySampleTime']}' + )"; + $this->db_onedev->query($sql); + + $sql = "INSERT INTO sample_by_step( + SampleByStepM_StatusSampleCode, + SampleByStepT_OrderHeaderID, + SampleByStepT_BarcodeLabID, + SampleByStepRequirementStatus, + SampleByStepRequirements, + SampleByStepUserID, + SampleByStepDateTime + ) + VALUES( + 'SAMPLING.Sampling.Received', + {$rst_id}, + {$vs['T_BarcodeLabID']}, + 'Y', + '[]', + {$userid}, + '{$row_addon['T_OrderHeaderAddOnOnlySampleTime']}' + )"; + $this->db_onedev->query($sql); + + $sql = "INSERT INTO sample_by_step( + SampleByStepM_StatusSampleCode, + SampleByStepT_OrderHeaderID, + SampleByStepT_BarcodeLabID, + SampleByStepRequirementStatus, + SampleByStepRequirements, + SampleByStepUserID, + SampleByStepDateTime + ) + VALUES( + 'SAMPLING.Verification.Verify', + {$prm['sample']['T_OrderHeaderID']}, + {$prm['sample']['T_BarcodeLabID']}, + '{$prm['sample']['requirement_status']}', + '{$requirements}', + {$userid}, + NOW() + )"; + $this->db_onedev->query($sql); + + $sql = "INSERT INTO sample_by_step( + SampleByStepM_StatusSampleCode, + SampleByStepT_OrderHeaderID, + SampleByStepT_BarcodeLabID, + SampleByStepRequirementStatus, + SampleByStepRequirements, + SampleByStepUserID, + SampleByStepDateTime + ) + VALUES( + 'SAMPLING.Verification.To.Handling', + {$prm['sample']['T_OrderHeaderID']}, + {$prm['sample']['T_BarcodeLabID']}, + '{$prm['sample']['requirement_status']}', + '{$requirements}', + {$userid}, + NOW() + )"; + $this->db_onedev->query($sql); + + $sql = "INSERT INTO sample_by_step( + SampleByStepM_StatusSampleCode, + SampleByStepT_OrderHeaderID, + SampleByStepT_BarcodeLabID, + SampleByStepRequirementStatus, + SampleByStepRequirements, + SampleByStepUserID, + SampleByStepDateTime + ) + VALUES( + 'SAMPLING.Handling.From.Verification', + {$prm['sample']['T_OrderHeaderID']}, + {$prm['sample']['T_BarcodeLabID']}, + '{$prm['sample']['requirement_status']}', + '{$requirements}', + {$userid}, + NOW() + )"; + $this->db_onedev->query($sql); + + $query = " INSERT INTO t_sampling_queue_last_status ( + T_SamplingQueueLastStatusT_SampleStationID, + T_SamplingQueueLastStatusT_OrderHeaderID, + T_SamplingQueueLastStatusT_SamplingQueueStatusID, + T_SamplingQueueLastStatusUserID) + VALUES( + {$vs['T_SampleStationID']}, + {$rst_id}, + '5', + {$userid}) + ON DUPLICATE KEY UPDATE + T_SamplingQueueLastStatusT_SamplingQueueStatusID = 5, + T_SamplingQueueLastStatusUserID = {$userid}"; + //echo $query; + $this->db_onedev->query($query); + } + } + + } + +} diff --git a/application/libraries/Ciqrcode.php b/application/libraries/Ciqrcode.php new file mode 100644 index 00000000..da7cad7c --- /dev/null +++ b/application/libraries/Ciqrcode.php @@ -0,0 +1,106 @@ +initialize($config); + } + + public function initialize($config = array()) { + $this->cacheable = (isset($config['cacheable'])) ? $config['cacheable'] : $this->cacheable; + $this->cachedir = (isset($config['cachedir'])) ? $config['cachedir'] : FCPATH.$this->cachedir; + $this->errorlog = (isset($config['errorlog'])) ? $config['errorlog'] : FCPATH.$this->errorlog; + $this->quality = (isset($config['quality'])) ? $config['quality'] : $this->quality; + $this->size = (isset($config['size'])) ? $config['size'] : $this->size; + + // use cache - more disk reads but less CPU power, masks and format templates are stored there + if (!defined('QR_CACHEABLE')) define('QR_CACHEABLE', $this->cacheable); + + // used when QR_CACHEABLE === true + if (!defined('QR_CACHE_DIR')) define('QR_CACHE_DIR', $this->cachedir); + + // default error logs dir + if (!defined('QR_LOG_DIR')) define('QR_LOG_DIR', $this->errorlog); + + // if true, estimates best mask (spec. default, but extremally slow; set to false to significant performance boost but (propably) worst quality code + if ($this->quality) { + if (!defined('QR_FIND_BEST_MASK')) define('QR_FIND_BEST_MASK', true); + } else { + if (!defined('QR_FIND_BEST_MASK')) define('QR_FIND_BEST_MASK', false); + if (!defined('QR_DEFAULT_MASK')) define('QR_DEFAULT_MASK', $this->quality); + } + + // if false, checks all masks available, otherwise value tells count of masks need to be checked, mask id are got randomly + if (!defined('QR_FIND_FROM_RANDOM')) define('QR_FIND_FROM_RANDOM', false); + + // maximum allowed png image width (in pixels), tune to make sure GD and PHP can handle such big images + if (!defined('QR_PNG_MAXIMUM_SIZE')) define('QR_PNG_MAXIMUM_SIZE', $this->size); + } + + public function generate($params = array()) { + if (isset($params['black']) + && is_array($params['black']) + && count($params['black']) == 3 + && array_filter($params['black'], 'is_int') === $params['black']) { + QRimage::$black = $params['black']; + } + + if (isset($params['white']) + && is_array($params['white']) + && count($params['white']) == 3 + && array_filter($params['white'], 'is_int') === $params['white']) { + QRimage::$white = $params['white']; + } + + $params['data'] = (isset($params['data'])) ? $params['data'] : 'QR Code Library'; + if (isset($params['savename'])) { + $level = 'L'; + if (isset($params['level']) && in_array($params['level'], array('L','M','Q','H'))) $level = $params['level']; + + $size = 4; + if (isset($params['size'])) $size = min(max((int)$params['size'], 1), 10); + + QRcode::png($params['data'], $params['savename'], $level, $size, 2); + return $params['savename']; + } else { + $level = 'L'; + if (isset($params['level']) && in_array($params['level'], array('L','M','Q','H'))) $level = $params['level']; + + $size = 4; + if (isset($params['size'])) $size = min(max((int)$params['size'], 1), 10); + + QRcode::png($params['data'], NULL, $level, $size, 2); + } + } +} + +/* end of file */ diff --git a/application/libraries/Etlfisik.php b/application/libraries/Etlfisik.php new file mode 100644 index 00000000..b41a55b3 --- /dev/null +++ b/application/libraries/Etlfisik.php @@ -0,0 +1,3273 @@ +db_smartone = $CI->load->database("default", true); + $this->db_onedev = $CI->load->database("default", true); + } + + function clean_mysqli_connection($dbc) + { + while (mysqli_more_results($dbc)) { + if (mysqli_next_result($dbc)) { + $result = mysqli_use_result($dbc); + + if (get_class($result) == 'mysqli_stmt') { + mysqli_stmt_free_result($result); + } else { + unset($result); + } + } + } + } + + function generate_kelainan_by_order($orderID,$userID){ + $this->generate_kelainan_nonlab($orderID,$userID); + $this->generate_kelainan_lab($orderID,$userID); + //$this->generate_kelainan_lab($orderID,$userID); + $this->generate_all_fisik($orderID,$userID); + $sql = "SELECT * + FROM t_orderheader + JOIN so_resultentry ON So_ResultEntryT_OrderHeaderID = T_OrderHeaderID AND So_ResultEntryNonlab_TemplateID = 27 AND + So_ResultEntryIsActive = 'Y' + WHERE + T_OrderHeaderID = ? AND T_OrderHeaderIsActive = 'Y'"; + $query = $this->db_onedev->query($sql,array($orderID)); + $rst_fisik = $query->result_array(); + $soReID = 0; + if(count($rst_fisik)> 0){ + $soReID = $rst_fisik[0]['So_ResultEntryID']; + } + + $this->generate_summaries($orderID,$soReID,$userID,$debugID=0); + + $sql = " SELECT 'lab' as type, + T_KelainanLabID, + Mcu_KelainanName, + fn_get_translate_word_separator_comma(Mcu_KelainanName,2) as Mcu_KelainanNameEng, + Mcu_FitnessCategoryID, + Mcu_FitnessCategoryName, + Mcu_FitnessCategoryEng, + Mcu_FitnessCategoryLevel, + Nat_TestName + FROM t_kelainan_lab + JOIN mcu_summarylab ON T_KelainanLabMcu_SummaryLabID = Mcu_SummaryLabID + JOIN mcu_kelainan ON Mcu_summaryLabMcu_KelainanID = Mcu_KelainanID + JOIN mcu_fitness_category ON Mcu_SummaryLabMcu_FitnessCategoryID = Mcu_FitnessCategoryID + JOIN nat_test ON Mcu_SummaryLabNat_TestID = Nat_TestID + WHERE + T_KelainanLabT_OrderHeaderID = ? AND + T_KelainanLabIsActive= 'Y' + UNION + SELECT 'nonlab' as type, + T_KelainanNonLabID, + Mcu_KelainanName, + fn_get_translate_word_separator_comma(Mcu_KelainanName,2) as Mcu_KelainanNameEng, + Mcu_FitnessCategoryID, + Mcu_FitnessCategoryName, + Mcu_FitnessCategoryEng, + Mcu_FitnessCategoryLevel, + Nat_TestName + FROM t_kelainan_nonlab + JOIN mcu_summarynonlab ON T_KelainanNonLabMcu_SummaryNonlabID = Mcu_SummaryNonlabID + JOIN mcu_kelainan ON Mcu_SummaryNonlabMcu_KelainanID = Mcu_KelainanID + JOIN mcu_fitness_category ON Mcu_SummaryNonlabMcu_FitnessCategoryID = Mcu_FitnessCategoryID + JOIN nat_test ON Mcu_SummaryNonlabNat_TestID = Nat_TestID + WHERE + T_KelainanNonLabT_OrderHeaderID = ? AND + T_KelainanNonLabIsActive= 'Y' + UNION + SELECT 'fisik' as type, + T_KelainanFiskID, + Mcu_KelainanName, + fn_get_translate_word_separator_comma(Mcu_KelainanName,2) as Mcu_KelainanNameEng, + Mcu_FitnessCategoryID, + Mcu_FitnessCategoryName, + Mcu_FitnessCategoryEng, + Mcu_FitnessCategoryLevel, + GROUP_CONCAT(CONCAT(Mcu_FisikValueLabel,'|',Mcu_FisikValueSegment,'|',Mcu_FisikValueCategory)) as Nat_TestName + FROM t_kelainan_fisik + JOIN mcu_fisiksummary ON T_KelainanFiskMcu_FisikSummaryID = Mcu_FisikSummaryID + JOIN mcu_kelainan ON Mcu_FisikSummaryMcu_KelainanID = Mcu_KelainanID + JOIN mcu_fitness_category ON Mcu_FisikSummaryMcu_FitnessCategoryID = Mcu_FitnessCategoryID + JOIN mcu_fisiksummarydetail ON Mcu_FisikSummaryDetailMcu_FisikSummaryID = Mcu_FisikSummaryID AND + Mcu_FisikSummaryDetailIsActive = 'Y' + JOIN mcu_fisikvalue ON Mcu_FisikValueT_OrderHeaderID = T_KelainanFiskT_OrderHeaderID AND + Mcu_FisikSummaryDetailCode = Mcu_FisikValueCode AND Mcu_FisikValueIsActive = 'Y' + WHERE + T_KelainanFiskT_OrderHeaderID = ? AND + T_KelainanFiskIsActive = 'Y' + GROUP BY T_KelainanFiskID"; + $query = $this->db_onedev->query($sql,array($orderID,$orderID,$orderID)); + //echo $this->db_onedev->last_query(); + $rtn = $query->result_array(); + $status = array("id"=>"1","name" => "BAIK", "name_eng" => "FIT FOR WORK" ,"level" => "1"); + if(count($rtn) > 0){ + $max = 0; + foreach ($rtn as $key => $value) { + if(intval($value['Mcu_FitnessCategoryLevel']) > $max){ + $max = intval($value['Mcu_FitnessCategoryLevel']); + $status = array("id"=> $value['Mcu_FitnessCategoryID'],"name" => $value['Mcu_FitnessCategoryName'], "name_eng" => $value['Mcu_FitnessCategoryEng'] ,"level" => $value['Mcu_FitnessCategoryLevel']); + } + + } + } + + + $resposne = array("status" => $status,"data" => $rtn); + + return $resposne; + } + + function generate_kelainan_nonlab($orderID,$userID){ + $sql = "SELECT So_ResultEntryID, T_OrderHeaderID, T_TestNat_TestID, Mcu_SummaryNonlabID, Mcu_SummaryNonlabMcu_KelainanID, Mcu_SummaryNonlabID + FROM so_resultentry_category_result + JOIN so_resultentry ON So_ResultEntryCategoryResultSo_ResultEntryID = So_ResultEntryID AND + So_ResultEntryStatus <> 'NEW' AND So_ResultEntryIsActive = 'Y' + JOIN t_orderheader ON So_ResultEntryT_OrderHeaderID = T_OrderHeaderID AND T_OrderHeaderIsActive = 'Y' AND + T_OrderHeaderID = ? + JOIN t_orderdetail ON So_ResultEntryT_OrderDetailID = T_OrderDetailID AND T_OrderDetailIsActive = 'Y' + JOIN t_test ON T_OrderDetailT_TestID = T_TestID + JOIN mcu_summarynonlab ON Mcu_SummaryNonlabNat_TestID = T_TestNat_TestID AND + Mcu_SummaryNonlabIsActive = 'Y' AND So_ResultEntryCategoryNonlabConclusionDetailID IN (Mcu_SummaryNonlabConclusionDetailIDs) + WHERE + So_ResultEntryCategoryResultIsActive = 'Y'"; + + $qry = $this->db_onedev->query($sql,array($orderID)); + if (!$qry) { + echo $this->db_onedev->last_query(); + echo json_encode([ + "status" => "ERR", + "message" => "Error get order | " . $this->db_onedev->error()["message"] + ]); + exit; + } + + $rows = $qry->result_array(); + $sql = "UPDATE t_kelainan_nonlab SET + T_KelainanNonLabIsActive = 'N' + WHERE + T_KelainanNonLabT_OrderHeaderID = ? AND + T_KelainanNonLabIsActive = 'Y' + "; + $qry = $this->db_onedev->query($sql,array($orderID)); + + foreach ($rows as $key => $value) { + + + $sql = "INSERT INTO t_kelainan_nonlab ( + T_KelainanNonLabSo_ResultEntryID, + T_KelainanNonLabT_OrderHeaderID, + T_KelainanNonLabNat_TestID, + T_KelainanNonLabMcu_SummaryNonlabID, + T_KelainanNonLabCreatedUserID, + T_KelainanLabNonCreated + ) VALUES(?,?,?,?,?,NOW())"; + $qry = $this->db_onedev->query($sql,[ + $value['So_ResultEntryID'], + $value['T_OrderHeaderID'], + $value['T_TestNat_TestID'], + $value['Mcu_SummaryNonlabID'], + $userID + ]); + } + + } + + function generate_kelainan_lab($orderid) + { + $sql = "SELECT + T_OrderHeaderID,T_OrderHeaderLabNumber, + T_TestName, T_OrderDetailID, T_OrderDetailResult, T_OrderDetailNat_MethodeID, + T_OrderDetailNat_MethodeID, T_OrderDetailNat_MethodeName, + T_OrderDetailMinValue, T_OrderDetailMaxValue, T_OrderDetailMinValueInclusive, + T_OrderDetailMaxValueInclusive, + T_OrderDetailNormalValueNote, + Mcu_SummaryLabID, + Mcu_SummaryLabValue, + Mcu_SummaryLabNat_MethodeID, + Mcu_SummaryLabWithMethode, + Mcu_SummaryLabType, + Mcu_SummaryLabIsNormalValue, + Mcu_SummaryLabIsRange, + Mcu_SummaryLabMinInclusive, + Mcu_SummaryLabMinValue, + Mcu_SummaryLabMaxInclusive, + Mcu_SummaryLabMaxValue, + Mcu_KelainanID, Mcu_KelainanName, Mcu_KelainanClasification, + Nat_TestID, + Nat_TestCode, + mcu_kelainangroup.* + from t_orderdetail + join t_orderheader on T_OrderHeaderID = {$orderid} + and T_OrderHeaderID = T_OrderDetailT_OrderHeaderID + and T_OrderDetailIsActive = 'Y' + JOIN m_patient + ON T_OrderHeaderM_PatientID = M_PatientID + JOIN m_sex ON M_PatientM_SexID = M_SexID + join t_test + on T_OrderDetailT_TestID = T_TestID + join nat_test ON T_TestNat_TestID = Nat_TestID + join mcu_summarylab on T_TestNat_TestID = Mcu_SummaryLabNat_TestID AND Mcu_SummaryLabIsActive = 'Y' + AND (Mcu_SummaryLabGender = 'A' OR (Mcu_SummaryLabGender <> 'A' AND Mcu_SummaryLabGender = CASE + WHEN LOWER(M_SexNameLang) = 'male' THEN 'M' + WHEN LOWER(M_SexNameLang) = 'female' THEN 'F' + else '' + END)) + join mcu_kelainan on Mcu_SummaryLabMcu_KelainanID = Mcu_KelainanID + join mcu_kelainangroup on Mcu_KelainanMcu_KelainanGroupID = Mcu_KelainanGroupID"; + //echo $sql; + $qry = $this->db_onedev->query($sql); + if (!$qry) { + echo $this->db_onedev->last_query(); + echo json_encode([ + "status" => "ERR", + "message" => "Error get order | " . $this->db_onedev->error()["message"] + ]); + exit; + } + + $rows = $qry->result_array(); + $results = []; + + + + foreach ($rows as $r) { + $result_value = $r['T_OrderDetailResult']; + + $value_comparison = 0; + //echo $r['Mcu_SummaryLabIsNormalValue']; + $kelainan = []; + $notavailable = []; + if (trim($result_value) == 'NA') { + $notavailable = $r; + } elseif ($r['Mcu_SummaryLabIsNormalValue'] == 'Y') { + if ($r['Mcu_SummaryLabType'] == '<' || $r['Mcu_SummaryLabType'] == '<=') { + $value_comparison = $r['T_OrderDetailMinValue']; + } + if ($r['Mcu_SummaryLabType'] == '>' || $r['Mcu_SummaryLabType'] == '>=') { + $value_comparison = $r['T_OrderDetailMaxValue']; + } + if ($r['Mcu_SummaryLabType'] == '!=') { + $result_value = strtolower(trim($result_value)); + $value_comparison = strtolower(trim($r['T_OrderDetailNormalValueNote'])); + } + + + + //echo "Y"; + if ($r['Mcu_SummaryLabWithMethode'] == 'N' && $this->dynamic_comparison($result_value, $r['Mcu_SummaryLabType'], $value_comparison)) { + //echo $r['T_TestName']." : ".$r['Mcu_KelainanName'].", "; + $kelainan = $r; + $results[] = array('test' => $r['T_TestName'], 'nat_test' => $r['Nat_TestCode'], 'kelainan' => $r['Mcu_KelainanName'], 'orderdetailID' => $r['T_OrderDetailID'], 'orderheaderID' => $r['T_OrderHeaderID'], 'nat_testID' => $r['Nat_TestID'], 'mcu_summarylabID' => $r['Mcu_SummaryLabID']); + } + } else if ($r['Mcu_SummaryLabIsRange'] == 'Y') { + // Mcu_SummaryLabIsNormalValue, + // Mcu_SummaryLabIsRange, + // Mcu_SummaryLabMinInclusive, + // Mcu_SummaryLabMinValue, + // Mcu_SummaryLabMaxInclusive, + // Mcu_SummaryLabMaxValue, + $isWithinMin = $r['Mcu_SummaryLabMinInclusive'] === 'Y' ? floatval($result_value) >= floatval($r['Mcu_SummaryLabMinValue']) : floatval($result_value) > floatval($r['Mcu_SummaryLabMinValue']); + $isWithinMax = $r['Mcu_SummaryLabMaxInclusive'] === 'Y' ? floatval($result_value) <= floatval($r['Mcu_SummaryLabMaxValue']) : floatval($result_value) < floatval($r['Mcu_SummaryLabMaxValue']); + + if ($isWithinMax && $isWithinMin) { + $kelainan = $r; + $results[] = array('test' => $r['T_TestName'], 'nat_test' => $r['Nat_TestCode'], 'kelainan' => $r['Mcu_KelainanName'], 'orderdetailID' => $r['T_OrderDetailID'], 'orderheaderID' => $r['T_OrderHeaderID'], 'nat_testID' => $r['Nat_TestID'], 'mcu_summarylabID' => $r['Mcu_SummaryLabID']); + } + } else { + $value_comparison = $r['Mcu_SummaryLabValue']; + if ($r['Mcu_SummaryLabType'] == '!=' || $r['Mcu_SummaryLabType'] == '==') { + if ($this->dynamic_comparison($result_value, $r['Mcu_SummaryLabType'], $value_comparison)) { + //echo $r['T_TestName']." : ".$r['Mcu_KelainanName'].", "; + $kelainan = $r; + $results[] = array('test' => $r['T_TestName'], 'nat_test' => $r['Nat_TestCode'], 'kelainan' => $r['Mcu_KelainanName'], 'orderdetailID' => $r['T_OrderDetailID'], 'orderheaderID' => $r['T_OrderHeaderID'], 'nat_testID' => $r['Nat_TestID'], 'mcu_summarylabID' => $r['Mcu_SummaryLabID']); + } + } else { + if (is_numeric($result_value) && $this->dynamic_comparison($result_value, $r['Mcu_SummaryLabType'], $value_comparison)) { + //echo $r['T_TestName']." : ".$r['Mcu_KelainanName'].", "; + $kelainan = $r; + $results[] = array('test' => $r['T_TestName'], 'nat_test' => $r['Nat_TestCode'], 'kelainan' => $r['Mcu_KelainanName'], 'orderdetailID' => $r['T_OrderDetailID'], 'orderheaderID' => $r['T_OrderHeaderID'], 'nat_testID' => $r['Nat_TestID'], 'mcu_summarylabID' => $r['Mcu_SummaryLabID']); + } + } + } + + if (count($results) > 0) { + $sql = "UPDATE t_kelainan_lab + SET T_KelainanLabIsActive = 'N' + WHERE + T_KelainanLabT_OrderHeaderID = {$orderid}"; + $this->db_onedev->query($sql); + + foreach ($results as $v_result) { + $sql_kel_lab = "SELECT * + FROM t_kelainan_lab + WHERE T_KelainanLabT_OrderDetailID = ? + GROUP BY T_KelainanLabT_OrderDetailID"; + $qry_kel_lab = $this->db_onedev->query($sql_kel_lab, array($v_result['orderdetailID'])); + if ($qry_kel_lab) { + $rows_kel = $qry_kel_lab->result_array(); + } else { + $this->sys_error_db("select kelainan lab", $this->db_onedev); + exit; + } + + if (count($rows_kel) > 0) { + + // print_r($v_result['orderdetailID']); + // exit; + + $sql_update_kel = "UPDATE t_kelainan_lab + SET T_KelainanLabT_OrderDetailID = {$v_result['orderdetailID']}, + T_KelainanLabT_OrderHeaderID = {$v_result['orderheaderID']}, + T_KelainanLabNat_TestID = {$v_result['nat_testID']}, + T_KelainanLabMcu_SummaryLabID = {$v_result['mcu_summarylabID']}, + T_KelainanLabCreatedUserID = 1, + T_KelainanLabIsActive = 'Y', + T_KelainanLabCreated = NOW() + WHERE T_KelainanLabID = {$rows_kel[0]['T_KelainanLabID']}"; + $qry_update_kel = $this->db_onedev->query($sql_update_kel); + if (!$qry_update_kel) { + echo $this->db_onedev->last_query(); + //$this->db_onedev->trans_rollback(); + $this->sys_error_db('error', 'Error update lab: ' . $this->db_onedev); + exit; + } + } else { + // print_r('insert'); + // exit; + $sql_insert_lab = "INSERT INTO t_kelainan_lab( + T_KelainanLabT_OrderDetailID, + T_KelainanLabT_OrderHeaderID, + T_KelainanLabNat_TestID, + T_KelainanLabMcu_SummaryLabID, + T_KelainanLabCreatedUserID, + T_KelainanLabCreated) + VALUES( + '{$v_result['orderdetailID']}', + '{$v_result['orderheaderID']}', + '{$v_result['nat_testID']}', + '{$v_result['mcu_summarylabID']}', + 1, + NOW())"; + $qry_insert_lab = $this->db_onedev->query($sql_insert_lab); + + if (!$qry_insert_lab) { + //$this->db_onedev->trans_rollback(); + echo $this->db_onedev->last_query(); + $this->sys_error_db('error', 'Error insert kelainan lab: ' . $this->db_onedev); + exit; + } + } + } + } + } + } + + function generate_kelainan_lab_x($orderid) + { + $sql = "SELECT + T_OrderHeaderID,T_OrderHeaderLabNumber, + T_TestName, T_OrderDetailID, T_OrderDetailResult, T_OrderDetailNat_MethodeID, + T_OrderDetailNat_MethodeID, T_OrderDetailNat_MethodeName, + T_OrderDetailMinValue, T_OrderDetailMaxValue, T_OrderDetailMinValueInclusive, + T_OrderDetailMaxValueInclusive, + Mcu_SummaryLabID, + Mcu_SummaryLabValue, + Mcu_SummaryLabNat_MethodeID, + Mcu_SummaryLabWithMethode, + Mcu_SummaryLabType, + Mcu_SummaryLabIsNormalValue, + Mcu_SummaryLabIsRange, + Mcu_SummaryLabMinInclusive, + Mcu_SummaryLabMinValue, + Mcu_SummaryLabMaxInclusive, + Mcu_SummaryLabMaxValue, + Mcu_KelainanID, Mcu_KelainanName, Mcu_KelainanClasification, + Nat_TestID, + Nat_TestCode, + mcu_kelainangroup.* + from t_orderdetail + join t_orderheader on T_OrderHeaderID = {$orderid} + and T_OrderHeaderID = T_OrderDetailT_OrderHeaderID + and T_OrderDetailIsActive = 'Y' + JOIN m_patient + ON T_OrderHeaderM_PatientID = M_PatientID + join t_test + on T_OrderDetailT_TestID = T_TestID + join nat_test ON T_TestNat_TestID = Nat_TestID + join mcu_summarylab on T_TestNat_TestID = Mcu_SummaryLabNat_TestID AND Mcu_SummaryLabIsActive = 'Y' + AND (Mcu_SummaryLabGender = 'A' OR (Mcu_SummaryLabGender <> 'A' AND Mcu_SummaryLabGender = CASE + WHEN LOWER(M_PatientGender) = 'male' THEN 'M' + WHEN LOWER(M_PatientGender) = 'female' THEN 'F' + else '' + END)) + join mcu_kelainan on Mcu_SummaryLabMcu_KelainanID = Mcu_KelainanID + join mcu_kelainangroup on Mcu_KelainanMcu_KelainanGroupID = Mcu_KelainanGroupID"; + //echo $sql; + $qry = $this->db_onedev->query($sql); + if (!$qry) { + echo $this->db_onedev->last_query(); + echo json_encode([ + "status" => "ERR", + "message" => "Error get order | " . $this->db_onedev->error()["message"] + ]); + exit; + } + + $rows = $qry->result_array(); + $results = []; + + + + foreach ($rows as $r) { + $result_value = $r['T_OrderDetailResult']; + + $value_comparison = 0; + //echo $r['Mcu_SummaryLabIsNormalValue']; + $kelainan = []; + $notavailable = []; + if (trim($result_value) == 'NA') { + $notavailable = $r; + } elseif ($r['Mcu_SummaryLabIsNormalValue'] == 'Y') { + if ($r['Mcu_SummaryLabType'] == '<' || $r['Mcu_SummaryLabType'] == '<=') { + $value_comparison = $r['T_OrderDetailMinValue']; + } + if ($r['Mcu_SummaryLabType'] == '>' || $r['Mcu_SummaryLabType'] == '>=') { + $value_comparison = $r['T_OrderDetailMaxValue']; + } + //echo "Y"; + if ($r['Mcu_SummaryLabWithMethode'] == 'N' && $this->dynamic_comparison($result_value, $r['Mcu_SummaryLabType'], $value_comparison)) { + //echo $r['T_TestName']." : ".$r['Mcu_KelainanName'].", "; + $kelainan = $r; + $results[] = array('test' => $r['T_TestName'], 'nat_test' => $r['Nat_TestCode'], 'kelainan' => $r['Mcu_KelainanName'], 'orderdetailID' => $r['T_OrderDetailID'], 'orderheaderID' => $r['T_OrderHeaderID'], 'nat_testID' => $r['Nat_TestID'], 'mcu_summarylabID' => $r['Mcu_SummaryLabID']); + } + } else if ($r['Mcu_SummaryLabIsRange'] == 'Y') { + // Mcu_SummaryLabIsNormalValue, + // Mcu_SummaryLabIsRange, + // Mcu_SummaryLabMinInclusive, + // Mcu_SummaryLabMinValue, + // Mcu_SummaryLabMaxInclusive, + // Mcu_SummaryLabMaxValue, + $isWithinMin = $r['Mcu_SummaryLabMinInclusive'] === 'Y' ? floatval($result_value) >= floatval($r['Mcu_SummaryLabMinValue']) : floatval($result_value) > floatval($r['Mcu_SummaryLabMinValue']); + $isWithinMax = $r['Mcu_SummaryLabMaxInclusive'] === 'Y' ? floatval($result_value) <= floatval($r['Mcu_SummaryLabMaxValue']) : floatval($result_value) < floatval($r['Mcu_SummaryLabMaxValue']); + + if ($isWithinMax && $isWithinMin) { + $kelainan = $r; + $results[] = array('test' => $r['T_TestName'], 'nat_test' => $r['Nat_TestCode'], 'kelainan' => $r['Mcu_KelainanName'], 'orderdetailID' => $r['T_OrderDetailID'], 'orderheaderID' => $r['T_OrderHeaderID'], 'nat_testID' => $r['Nat_TestID'], 'mcu_summarylabID' => $r['Mcu_SummaryLabID']); + } + } else { + $value_comparison = $r['Mcu_SummaryLabValue']; + if ($r['Mcu_SummaryLabType'] == '!=' || $r['Mcu_SummaryLabType'] == '==') { + if ($this->dynamic_comparison($result_value, $r['Mcu_SummaryLabType'], $value_comparison)) { + //echo $r['T_TestName']." : ".$r['Mcu_KelainanName'].", "; + $kelainan = $r; + $results[] = array('test' => $r['T_TestName'], 'nat_test' => $r['Nat_TestCode'], 'kelainan' => $r['Mcu_KelainanName'], 'orderdetailID' => $r['T_OrderDetailID'], 'orderheaderID' => $r['T_OrderHeaderID'], 'nat_testID' => $r['Nat_TestID'], 'mcu_summarylabID' => $r['Mcu_SummaryLabID']); + } + } else { + if (is_numeric($result_value) && $this->dynamic_comparison($result_value, $r['Mcu_SummaryLabType'], $value_comparison)) { + //echo $r['T_TestName']." : ".$r['Mcu_KelainanName'].", "; + $kelainan = $r; + $results[] = array('test' => $r['T_TestName'], 'nat_test' => $r['Nat_TestCode'], 'kelainan' => $r['Mcu_KelainanName'], 'orderdetailID' => $r['T_OrderDetailID'], 'orderheaderID' => $r['T_OrderHeaderID'], 'nat_testID' => $r['Nat_TestID'], 'mcu_summarylabID' => $r['Mcu_SummaryLabID']); + } + } + } + + if (count($results) > 0) { + $sql = "UPDATE t_kelainan_lab + SET T_KelainanLabIsActive = 'N' + WHERE + T_KelainanLabT_OrderHeaderID = {$orderid}"; + $this->db_onedev->query($sql); + + foreach ($results as $v_result) { + $sql_kel_lab = "SELECT * + FROM t_kelainan_lab + WHERE T_KelainanLabT_OrderDetailID = ? + GROUP BY T_KelainanLabT_OrderDetailID"; + $qry_kel_lab = $this->db_onedev->query($sql_kel_lab, array($v_result['orderdetailID'])); + if ($qry_kel_lab) { + $rows_kel = $qry_kel_lab->result_array(); + } else { + $this->sys_error_db("select kelainan lab", $this->db_onedev); + exit; + } + + if (count($rows_kel) > 0) { + + // print_r($v_result['orderdetailID']); + // exit; + + $sql_update_kel = "UPDATE t_kelainan_lab + SET T_KelainanLabT_OrderDetailID = {$v_result['orderdetailID']}, + T_KelainanLabT_OrderHeaderID = {$v_result['orderheaderID']}, + T_KelainanLabNat_TestID = {$v_result['nat_testID']}, + T_KelainanLabMcu_SummaryLabID = {$v_result['mcu_summarylabID']}, + T_KelainanLabCreatedUserID = 1, + T_KelainanLabIsActive = 'Y', + T_KelainanLabCreated = NOW() + WHERE T_KelainanLabID = {$rows_kel[0]['T_KelainanLabID']}"; + $qry_update_kel = $this->db_onedev->query($sql_update_kel); + if (!$qry_update_kel) { + echo $this->db_onedev->last_query(); + //$this->db_onedev->trans_rollback(); + $this->sys_error_db('error', 'Error update lab: ' . $this->db_onedev); + exit; + } + } else { + // print_r('insert'); + // exit; + $sql_insert_lab = "INSERT INTO t_kelainan_lab( + T_KelainanLabT_OrderDetailID, + T_KelainanLabT_OrderHeaderID, + T_KelainanLabNat_TestID, + T_KelainanLabMcu_SummaryLabID, + T_KelainanLabCreatedUserID, + T_KelainanLabCreated) + VALUES( + '{$v_result['orderdetailID']}', + '{$v_result['orderheaderID']}', + '{$v_result['nat_testID']}', + '{$v_result['mcu_summarylabID']}', + 1, + NOW())"; + $qry_insert_lab = $this->db_onedev->query($sql_insert_lab); + + if (!$qry_insert_lab) { + //$this->db_onedev->trans_rollback(); + echo $this->db_onedev->last_query(); + $this->sys_error_db('error', 'Error insert kelainan lab: ' . $this->db_onedev); + exit; + } + } + } + } + } + } + + function dynamic_comparison($varleft, $op, $varright) + { + + switch ($op) { + case "=": + return $varleft == $varright; + case "!=": + return $varleft != $varright; + case ">=": + return $varleft >= $varright; + case "<=": + return $varleft <= $varright; + case ">": + return $varleft > $varright; + case "<": + return $varleft < $varright; + default: + return true; + } + } + + function generate_kelainan_lab_old($orderid) + { + $sql = "select + T_OrderHeaderID,T_OrderHeaderLabNumber, + T_TestName, T_OrderDetailID, T_OrderDetailResult, T_OrderDetailNat_MethodeID, + T_OrderDetailNat_MethodeID, T_OrderDetailNat_MethodeName, + T_OrderDetailMinValue, T_OrderDetailMaxValue, T_OrderDetailMinValueInclusive, + T_OrderDetailMaxValueInclusive, + Mcu_SummaryLabID, + Mcu_SummaryLabValue, + Mcu_SummaryLabNat_MethodeID, + Mcu_SummaryLabWithMethode, + Mcu_SummaryLabType, + Mcu_SummaryLabIsNormalValue, + Mcu_KelainanID, Mcu_KelainanName, Mcu_KelainanClasification, + Nat_TestID, + Nat_TestCode, + mcu_kelainangroup.* + from t_orderdetail + join t_orderheader on T_OrderHeaderID = {$orderid} + and T_OrderHeaderID = T_OrderDetailT_OrderHeaderID + and T_OrderDetailIsActive = 'Y' + join t_test + on T_OrderDetailT_TestID = T_TestID + join nat_test ON T_TestNat_TestID = Nat_TestID + join mcu_summarylab on T_TestNat_TestID = Mcu_SummaryLabNat_TestID AND Mcu_SummaryLabIsActive = 'Y' + join mcu_kelainan on Mcu_SummaryLabMcu_KelainanID = Mcu_KelainanID + join mcu_kelainangroup on Mcu_KelainanMcu_KelainanGroupID = Mcu_KelainanGroupID"; + //echo $sql; + $qry = $this->db_onedev->query($sql); + if (!$qry) { + echo $this->db_onedev->last_query(); + echo json_encode([ + "status" => "ERR", + "message" => "Error get order | " . $this->db_onedev->error()["message"] + ]); + exit; + } + + $rows = $qry->result_array(); + $results = []; + + + + foreach ($rows as $r) { + $result_value = $r['T_OrderDetailResult']; + + $value_comparison = 0; + //echo $r['Mcu_SummaryLabIsNormalValue']; + $kelainan = []; + $notavailable = []; + if (trim($result_value) == 'NA') { + $notavailable = $r; + } elseif ($r['Mcu_SummaryLabIsNormalValue'] == 'Y') { + if ($r['Mcu_SummaryLabType'] == '<' || $r['Mcu_SummaryLabType'] == '<=') { + $value_comparison = $r['T_OrderDetailMinValue']; + } + if ($r['Mcu_SummaryLabType'] == '>' || $r['Mcu_SummaryLabType'] == '>=') { + $value_comparison = $r['T_OrderDetailMaxValue']; + } + //echo "Y"; + if ($r['Mcu_SummaryLabWithMethode'] == 'N' && $this->dynamic_comparison($result_value, $r['Mcu_SummaryLabType'], $value_comparison)) { + //echo $r['T_TestName']." : ".$r['Mcu_KelainanName'].", "; + $kelainan = $r; + $results[] = array('test' => $r['T_TestName'], 'nat_test' => $r['Nat_TestCode'], 'kelainan' => $r['Mcu_KelainanName'], 'orderdetailID' => $r['T_OrderDetailID'], 'orderheaderID' => $r['T_OrderHeaderID'], 'nat_testID' => $r['Nat_TestID'], 'mcu_summarylabID' => $r['Mcu_SummaryLabID']); + } + } else { + $value_comparison = $r['Mcu_SummaryLabValue']; + if ($r['Mcu_SummaryLabType'] == '!=' || $r['Mcu_SummaryLabType'] == '==') { + if ($this->dynamic_comparison($result_value, $r['Mcu_SummaryLabType'], $value_comparison)) { + //echo $r['T_TestName']." : ".$r['Mcu_KelainanName'].", "; + $kelainan = $r; + $results[] = array('test' => $r['T_TestName'], 'nat_test' => $r['Nat_TestCode'], 'kelainan' => $r['Mcu_KelainanName'], 'orderdetailID' => $r['T_OrderDetailID'], 'orderheaderID' => $r['T_OrderHeaderID'], 'nat_testID' => $r['Nat_TestID'], 'mcu_summarylabID' => $r['Mcu_SummaryLabID']); + } + } else { + if (is_numeric($result_value) && $this->dynamic_comparison($result_value, $r['Mcu_SummaryLabType'], $value_comparison)) { + //echo $r['T_TestName']." : ".$r['Mcu_KelainanName'].", "; + $kelainan = $r; + $results[] = array('test' => $r['T_TestName'], 'nat_test' => $r['Nat_TestCode'], 'kelainan' => $r['Mcu_KelainanName'], 'orderdetailID' => $r['T_OrderDetailID'], 'orderheaderID' => $r['T_OrderHeaderID'], 'nat_testID' => $r['Nat_TestID'], 'mcu_summarylabID' => $r['Mcu_SummaryLabID']); + } + } + } + + if (count($results) > 0) { + $sql = "UPDATE t_kelainan_lab + SET T_KelainanLabIsActive = 'N' + WHERE + T_KelainanLabT_OrderHeaderID = {$orderid}"; + $this->db_onedev->query($sql); + + foreach ($results as $v_result) { + $sql_kel_lab = "SELECT * + FROM t_kelainan_lab + WHERE T_KelainanLabT_OrderDetailID = ? + GROUP BY T_KelainanLabT_OrderDetailID"; + $qry_kel_lab = $this->db_onedev->query($sql_kel_lab, array($v_result['orderdetailID'])); + if ($qry_kel_lab) { + $rows_kel = $qry_kel_lab->result_array(); + } else { + $this->sys_error_db("select kelainan lab", $this->db_onedev); + exit; + } + + if (count($rows_kel) > 0) { + + $sql_update_kel = "UPDATE t_kelainan_lab + SET T_KelainanLabT_OrderDetailID = {$v_result['orderdetailID']}, + T_KelainanLabT_OrderHeaderID = {$v_result['orderheaderID']}, + T_KelainanLabNat_TestID = {$v_result['nat_testID']}, + T_KelainanLabMcu_SummaryLabID = {$v_result['mcu_summarylabID']}, + T_KelainanLabCreatedUserID = 1, + T_KelainanLabIsActive = 'Y', + T_KelainanLabCreated = NOW() + WHERE T_KelainanLabID = {$rows_kel[0]['T_KelainanLabID']}"; + $qry_update_kel = $this->db_onedev->query($sql_update_kel); + if (!$qry_update_kel) { + echo $this->db_onedev->last_query(); + //$this->db_onedev->trans_rollback(); + $this->sys_error_db('error', 'Error update lab: ' . $this->db_onedev); + exit; + } + } else { + // print_r('insert'); + // exit; + $sql_insert_lab = "INSERT INTO t_kelainan_lab( + T_KelainanLabT_OrderDetailID, + T_KelainanLabT_OrderHeaderID, + T_KelainanLabNat_TestID, + T_KelainanLabMcu_SummaryLabID, + T_KelainanLabCreatedUserID, + T_KelainanLabCreated) + VALUES( + '{$v_result['orderdetailID']}', + '{$v_result['orderheaderID']}', + '{$v_result['nat_testID']}', + '{$v_result['mcu_summarylabID']}', + 1, + NOW())"; + $qry_insert_lab = $this->db_onedev->query($sql_insert_lab); + + if (!$qry_insert_lab) { + //$this->db_onedev->trans_rollback(); + echo $this->db_onedev->last_query(); + $this->sys_error_db('error', 'Error insert kelainan lab: ' . $this->db_onedev); + exit; + } + } + } + } + } + } + + function insert_data_etl($data,$userid){ + if($data){ + + /*$sql = "UPDATE mcu_fisikvalue SET + Mcu_FisikValueIsActive = 'N', + Mcu_FisikValueLastUpdated = NOW() , + Mcu_FisikValueLastUpdatedUserID = ? + WHERE + Mcu_FisikValueT_OrderHeaderID = ? AND + Mcu_FisikValueCode = ? AND + Mcu_FisikValueIsActive = 'Y'"; + $qry = $this->db_smartone->query($sql,array($userid,$data['order_id'],$data['code'])); + if (! $qry) { + return false; + }*/ + + $sql = "SELECT COUNT(*) as xcount, Mcu_FisikValueID as id + FROM mcu_fisikvalue + WHERE + Mcu_FisikValueT_OrderHeaderID = ? AND + Mcu_FisikValueCode = ? + LIMIT 1 + "; + $qry = $this->db_smartone->query($sql,array($data['order_id'],$data['code'])); + if (! $qry) { + return false; + } + + //echo $this->db_smartone->last_query(); + //print_r($data); + //echo $data['code']; + /*if($data['code'] == 'bmi_classification_asia_pacific'){ + echo $this->db_smartone->last_query(); + }*/ + + $exist_dt = $qry->row_array(); + /*if($data['code'] == 'bmi_classification_asia_pacific'){ + print_r($exist_dt); + }*/ + + if($exist_dt['xcount'] > 0){ + $sql = "UPDATE mcu_fisikvalue SET + Mcu_FisikValueIsActive = 'Y', + Mcu_FisikValueLastUpdated = NOW() , + Mcu_FisikValueLastUpdatedUserID = ?, + Mcu_FisikValueLabel = ?, + Mcu_FisikValueNote = ?, + Mcu_FisikValueSegment = ?, + Mcu_FisikValueCategory = ? + WHERE + Mcu_FisikValueID = ? + "; + $qry = $this->db_smartone->query($sql,array($userid,$data['label'],$data['note'],$data['segment'],$data['category'],$exist_dt['id'])); + }else{ + $sql = "INSERT INTO mcu_fisikvalue ( + `Mcu_FisikValueT_OrderHeaderID`, + `Mcu_FisikValueCode`, + `Mcu_FisikValueLabel`, + `Mcu_FisikValueNote`, + `Mcu_FisikValueSegment`, + `Mcu_FisikValueCategory`, + `Mcu_FisikValueCreated`, + `Mcu_FisikValueCreatedUserID` + ) VALUES(?,?,?,?,?,?,NOW(),?)"; + $qry = $this->db_smartone->query($sql,array( + $data['order_id'], + $data['code'], + $data['label'], + $data['note'], + $data['segment'], + $data['category'], + $userid + )); + if (! $qry) { + return false; + } + } + } + } + + function generate_all_fisik($orderID,$userid){ + $this->status_gizi($orderID,$userid); + $this->persepsi_warna($orderID,$userid); + $this->visus($orderID,$userid); + + $sql = "SELECT * + FROM so_resultentry + WHERE + So_ResultEntryNonlab_TemplateID = 27 AND + So_ResultEntryT_OrderHeaderID = ? AND + So_ResultEntryIsActive = 'Y' + LIMIT 1"; + $qry = $this->db_smartone->query($sql,array($orderID)); + if (! $qry) { + return false; + } + //echo $this->db_smartone->last_query(); + $results = $qry->result_array(); + if(count($results) > 0){ + $soReID = $results[0]['So_ResultEntryID']; + + $this->keluhan($soReID,$userid); + $this->riwayat_penyakit($soReID,$userid); + $this->penyakit_keluarga($soReID,$userid); + $this->kebiasaan_hidup($soReID,$userid); + $this->fisik_konsumsiobatteratur($soReID,$userid); + $this->imunasi($soReID,$userid); + $this->vital_sign($soReID,$userid); + $this->keadaan_umum($soReID,$userid); + $this->kepala_wajah($soReID,$userid); + $this->mata($soReID,$userid); + $this->lapang_pandang($soReID,$userid); + $this->telinga($soReID,$userid); + $this->hidung($soReID,$userid); + $this->gigi($soReID,$userid); + $this->mulut($soReID,$userid); + $this->leher($soReID,$userid); + $this->thorax($soReID,$userid); + $this->paru($soReID,$userid); + $this->jantung($soReID,$userid); + $this->perut($soReID,$userid); + $this->sistem_integumen($soReID,$userid); + $this->genitourinaria($soReID,$userid); + $this->anggota_gerak($soReID,$userid); + $this->sistem_persyarafan($soReID,$userid); + $this->smell_test($soReID,$userid); + $this->low_back_pain_screening_test($soReID,$userid); + $this->loop_k3($soReID,$userid); + + } + + return true; + } + + function visus($orderID,$userid) { + $ret_array = []; + + $sql = " SELECT * , T_SamplingAdditionalFisikVisusID as visus_id + FROM t_samplingso_additional_fisik_visus + WHERE + T_SamplingAdditionalFisikVisusT_OrderHeaderID = ? LIMIT 1"; + $qry = $this->db_smartone->query($sql,array($orderID)); + if (! $qry) { + return false; + } + + $row_result = $qry->row_array(); + //echo $this->db_smartone->last_query(); + + + if($row_result && intval($row_result['visus_id']) > 0){ + + + + $visus = array(); + $visus_kiri = ""; + $visus_kanan = ""; + $visus_kesimpulan = ""; + $normal = array("20/20", "20/25","6/6","6/7.5","6/7,5"); + $miopia_od = false; + $miopia_os = false; + $miopia_od_value = ''; + $miopia_os_value = ''; + $astigmatismus_od = false; + $astigmatismus_os = false; + $astigmatismus_od_value = ''; + $astigmatismus_os_value = ''; + $presbiopia_ods = false; + $presbiopia_ods_value = ''; + $x_od = false; + $x_os = false; + $x_od_value = ""; + $x_os_value = ""; + $od_visus = "20/20"; + $os_visus = "20/20"; + if($row_result['T_SamplingAdditionalFisikVisusTKODV'] == '6/7,5' || $row_result['T_SamplingAdditionalFisikVisusTKODV'] == '6/6' || $row_result['T_SamplingAdditionalFisikVisusTKODV'] == '6/7.5') + $od_visus = $row_result['T_SamplingAdditionalFisikVisusTKODV'] ; + + if($row_result['T_SamplingAdditionalFisikVisusTKOSV'] == '6/7,5' || $row_result['T_SamplingAdditionalFisikVisusTKOSV'] == '6/6' || $row_result['T_SamplingAdditionalFisikVisusTKOSV'] == '6/7.5') + $os_visus = $row_result['T_SamplingAdditionalFisikVisusTKOSV'] ; + + + + if((strtolower($row_result['T_SamplingAdditionalFisikVisusTKODV']) != "normal" && $row_result['T_SamplingAdditionalFisikVisusTKODV'] != "" && $row_result['T_SamplingAdditionalFisikVisusTKODV'] != "-") && ($row_result['T_SamplingAdditionalFisikVisusTKOSV'] != "" && $row_result['T_SamplingAdditionalFisikVisusTKOSV'] != "-" && strtolower($row_result['T_SamplingAdditionalFisikVisusTKODV']) != "normal" && strtolower($row_result['T_SamplingAdditionalFisikVisusTKOSV']) != "normal")){ + $visus[] = array( + "xx1" => "Tanpa Kacamata", + "xx2" => "OD : ", + "xx3" => $row_result['T_SamplingAdditionalFisikVisusTKODV'] + ); + + $visus[] = array( + "xx1" => "Tanpa Kacamata", + "xx2" => "OS", + "xx3" => $row_result['T_SamplingAdditionalFisikVisusTKOSV'] + ); + + + $rst['kelainan'] = "Kelainan refraksi (tanpa kacamata)"; + + if (!in_array($row_result['T_SamplingAdditionalFisikVisusTKODV'], $normal)){ + $value_koreksi_od = ""; + $od_sph = $row_result['T_SamplingAdditionalFisikVisusODSPH']; + if($od_sph != "" && $od_sph != "-" && $od_sph != "--" && $od_sph != "/-" && $od_sph != "/" && $od_sph != "-/" && strtolower(trim($od_sph)) != 'plano'){ + if ($visus_kanan != "") $visus_kanan .= ", "; + $visus_kanan .= $od_sph." (Miopia)"; + + $miopia_od = true; + $miopia_od_value = $od_sph; + } + + + $od_cyl = $row_result['T_SamplingAdditionalFisikVisusODCYL']; + + //$od_cyl = $row_result['T_SamplingAdditionalFisikVisusODCYL']; + if($od_cyl != "" && $od_cyl != "-" && $od_cyl != "--" && $od_cyl != "/-" && $od_cyl != "/" && $od_cyl != "-/"){ + if ($visus_kanan != "") $visus_kanan .= ", "; + $visus_kanan .= "Cyl ".$od_cyl; + + $astigmatismus_od = true; + $astigmatismus_od_value = $od_cyl; + } + + + $od_x = $row_result['T_SamplingAdditionalFisikVisusODX']; + //echo $od_x; + if($od_x != "" && $od_x != "-" && $od_x != "--" && $od_x != "/-" && $od_x != "/" && $od_x != "-/"){ + $visus_kanan .= " axis ".$od_x." (Astigmatismus)"; + $x_od = true; + $x_od = $od_x; + }else{ + if($od_cyl != "" && $od_cyl != "-" && $od_cyl != "--" && $od_cyl != "/-" && $od_cyl != "/" && $od_cyl != "-/") + $visus_kanan .= " (Astigmatismus)"; + } + //$value_koreksi_od .= "X (".$od_x.") "; + + + + } + + if (!in_array($row_result['T_SamplingAdditionalFisikVisusTKOSV'], $normal)){ + $value_koreksi_os = ""; + $os_sph = $row_result['T_SamplingAdditionalFisikVisusOSSPH']; + if(strtolower(trim($os_sph)) != "tidak terkoreksi" && strtolower(trim($os_sph)) != "tidak dapat dinilai" && $os_sph != "" && $os_sph != "-" && $os_sph != "--" && $os_sph != "/-" && $os_sph != "/" && $os_sph != "-/" && strtolower(trim($os_sph)) != 'plano'){ + if ($visus_kiri != "") $visus_kiri .= ", "; + $visus_kiri .= $os_sph." (Miopia)"; + + $miopia_os = true; + $miopia_os_value = $os_sph; + } + + $os_cyl = $row_result['T_SamplingAdditionalFisikVisusOSCYL']; + + if(strtolower(trim($os_cyl)) != "tidak terkoreksi" && strtolower(trim($os_cyl)) != "tidak dapat dinilai" && $os_cyl != "" && $os_cyl != "-" && $os_cyl != "--" && $os_cyl != "/-" && $os_cyl != "/" && $os_cyl != "-/"){ + if ($visus_kiri != "") $visus_kiri .= ", "; + $visus_kiri .= "Cyl ".$os_cyl; + + $astigmatismus_os = true; + $astigmatismus_os_value = $os_cyl; + } + + + $os_x = $row_result['T_SamplingAdditionalFisikVisusOSX']; + + if(strtolower(trim($os_x)) != "tidak terkoreksi" && strtolower(trim($os_x)) != "tidak dapat dinilai" && $os_x != "" && $os_x != "-" && $os_x != "--" && $os_x != "/-" && $os_x != "/" && $os_x != "-/"){ + //if ($visus_kiri != "") $visus_kiri .= ", "; + $visus_kiri .= " axis ".$os_x." (Astigmatismus)"; + $x_os = true; + $x_os = $os_x; + }else{ + if($os_cyl != "" && $os_cyl != "-") + $visus_kiri .= " (Astigmatismus)"; + } + + } + + } + + if((strtolower($row_result['T_SamplingAdditionalFisikVisusDKODV']) != "normal" && $row_result['T_SamplingAdditionalFisikVisusDKODV'] != "" && $row_result['T_SamplingAdditionalFisikVisusDKODV'] != "-") && ($row_result['T_SamplingAdditionalFisikVisusDKOSV'] != "" && $row_result['T_SamplingAdditionalFisikVisusDKOSV'] != "-" && strtolower($row_result['T_SamplingAdditionalFisikVisusDKODV']) != "normal" && strtolower($row_result['T_SamplingAdditionalFisikVisusDKOSV']) != "normal")){ + $visus[] = array( + "xx1" => "Dengan Kacamata", + "xx2" => "OD : ", + "xx3" => $row_result['T_SamplingAdditionalFisikVisusDKODV'] + ); + + $visus[] = array( + "xx1" => "Dengan Kacamata", + "xx2" => "OS", + "xx3" => $row_result['T_SamplingAdditionalFisikVisusDKOSV'] + ); + + $rst['kelainan'] = "Kelainan refraksi (dengan kacamata)"; + $od_visus = $row_result['T_SamplingAdditionalFisikVisusDKODV'] ; + $os_visus = $row_result['T_SamplingAdditionalFisikVisusDKOSV'] ; + + + $value_koreksi_od = ""; + $od_sph = $row_result['T_SamplingAdditionalFisikVisusODSPH']; + if(strtolower(trim($od_sph)) != "tidak terkoreksi" && strtolower(trim($od_sph)) != "tidak dapat dinilai" && $od_sph != "" && $od_sph != "-" && $od_sph != "--" && $od_sph != "/-" && $od_sph != "/" && $od_sph != "-/" && strtolower(trim($od_sph)) != 'plano'){ + if ($visus_kanan != "") $visus_kanan .= ", "; + $visus_kanan .= $od_sph." (Miopia)"; + + $miopia_od = true; + $miopia_od_value = $od_sph; + } + + $od_cyl = $row_result['T_SamplingAdditionalFisikVisusODCYL']; + + if(strtolower(trim($od_cyl)) != "tidak terkoreksi" && strtolower(trim($od_cyl)) != "tidak dapat dinilai" && $od_cyl != "" && $od_cyl != "-" && $od_cyl != "--" && $od_cyl != "/-" && $od_cyl != "/" && $od_cyl != "-/"){ + if ($visus_kanan != "") $visus_kanan .= ", "; + $visus_kanan .= "Cyl ".$od_cyl; + + $astigmatismus_od = true; + $astigmatismus_od_value = $od_cyl; + } + + $od_x = $row_result['T_SamplingAdditionalFisikVisusODX']; + if(strtolower(trim($od_x)) != "tidak terkoreksi" && strtolower(trim($od_x)) != "tidak dapat dinilai" && $od_x != "" && $od_x != "-" && $od_x != "--" && $od_x != "/-" && $od_x != "/" && $od_x != "-/"){ + //if ($visus_kanan != "") $visus_kanan .= ", "; + $visus_kanan .= " axis ".$od_x." (Astigmatismus)"; + $x_od = true; + $x_od = $od_x; + }else{ + if($od_cyl != "" && $od_cyl != "-" && $od_cyl != "--" && $od_cyl != "/-" && $od_cyl != "/" && $od_cyl != "-/") + $visus_kanan .= " (Astigmatismus)"; + } + //$value_koreksi_od .= "X (".$od_x.") "; + + + + + + $value_koreksi_os = ""; + $os_sph = $row_result['T_SamplingAdditionalFisikVisusOSSPH']; + if(strtolower(trim($os_sph)) != "tidak terkoreksi" && strtolower(trim($os_sph)) != "tidak dapat dinilai" && $os_sph != "" && $os_sph != "-" && $os_sph != "--" && $os_sph != "/-" && $os_sph != "/" && $os_sph != "-/" && strtolower(trim($os_sph)) != 'plano'){ + if ($visus_kiri != "") $visus_kiri .= ", "; + $visus_kiri .= $os_sph." (Miopia)"; + + $miopia_os = true; + $miopia_os_value = $os_sph; + } + + $os_cyl = $row_result['T_SamplingAdditionalFisikVisusOSCYL']; + + if(strtolower(trim($os_cyl)) != "tidak terkoreksi" && strtolower(trim($os_cyl)) != "tidak dapat dinilai" && $os_cyl != "" && $os_cyl != "-" && $os_cyl != "--" && $os_cyl != "/-" && $os_cyl != "/" && $os_cyl != "-/"){ + if ($visus_kiri != "") $visus_kiri .= ", "; + $visus_kiri .= "Cyl ".$os_cyl; + + $astigmatismus_os = true; + $astigmatismus_os_value = $os_cyl; + } + + $os_x = $row_result['T_SamplingAdditionalFisikVisusOSX']; + + if(strtolower(trim($os_x)) != "tidak terkoreksi" && strtolower(trim($os_x)) != "tidak dapat dinilai" && $os_x != "" && $os_x != "-" && $os_x != "--" && $os_x != "/-" && $os_x != "/" && $os_x != "-/"){ + $visus_kiri .= " axis ".$os_x." (Astigmatismus)"; + $x_os = true; + $x_os = $os_x; + }else{ + if($os_cyl != "" && $os_cyl != "-" && $os_cyl != "--" && $os_cyl != "/-" && $os_cyl != "/" && $os_cyl != "-/") + $visus_kiri .= " (Astigmatismus)"; + } + //$value_koreksi_os .= "X (".$os_x.") "; + + + } + + if(($row_result['T_SamplingAdditionalFisikVisusTKODV'] != "" && $row_result['T_SamplingAdditionalFisikVisusTKODV'] != "-") && ($row_result['T_SamplingAdditionalFisikVisusTKOSV'] != "" && $row_result['T_SamplingAdditionalFisikVisusTKOSV'] != "-")){ + if (!in_array($row_result['T_SamplingAdditionalFisikVisusTKODV'], $normal) && $visus_kanan == ''){ + $visus_kanan = "Miopia"; + $miopia_od = true; + $miopia_od_value = ""; + } + + if (!in_array($row_result['T_SamplingAdditionalFisikVisusTKOSV'], $normal) && $visus_kiri == ''){ + $visus_kiri = "Miopia"; + $miopia_os = true; + $miopia_os_value = ""; + } + } + + if(($row_result['T_SamplingAdditionalFisikVisusDKODV'] != "" && $row_result['T_SamplingAdditionalFisikVisusDKODV'] != "-") && ($row_result['T_SamplingAdditionalFisikVisusDKOSV'] != "" && $row_result['T_SamplingAdditionalFisikVisusDKOSV'] != "-")){ + if (!in_array($row_result['T_SamplingAdditionalFisikVisusDKODV'], $normal) && $visus_kanan == ''){ + $visus_kanan = "Miopia"; + $miopia_od = true; + $miopia_od_value = ""; + } + + if (!in_array($row_result['T_SamplingAdditionalFisikVisusDKOSV'], $normal) && $visus_kiri == ''){ + $visus_kiri = "Miopia"; + $miopia_os = true; + $miopia_os_value = ""; + } + } + + $od_add = $row_result['T_SamplingAdditionalFisikVisusADD']; + if($od_add != "" && $od_add != "-" && $od_add != "--" && $od_add != "/-" && $od_add != "/" && $od_add != "-/"){ + if ($visus_kanan != "") $visus_kanan .= ", "; + $visus_kanan .= $od_add." (Presbiopia)"; + + if ($visus_kiri != "") $visus_kiri .= ", "; + $visus_kiri .= $od_add." (Presbiopia)"; + + + $presbiopia_ods = true; + $presbiopia_ods_value = $od_add; + } + + + + } + + $data_insert = array( + 'code' => 'visus', + 'label' => 'visus', + 'note' => $rst['kelainan'], + 'segment' => 'visus', + 'category' => 'mata', + 'order_id' => $orderID + ); + $this->insert_data_etl($data_insert,$userid); + //$this->insert_code('visus','visus'); + + if($miopia_od){ + $data_insert = array( + 'code' => 'visus_miopia_od', + 'label' => 'visus Miopia OD', + 'note' => $miopia_od_value, + 'segment' => 'visus', + 'category' => 'mata', + 'order_id' => $orderID + ); + $this->insert_data_etl($data_insert,$userid); + //$this->insert_code('visus_miopia_od','visus Miopia OD'); + } + if($miopia_os){ + $data_insert = array( + 'code' => 'visus_miopia_os', + 'label' => 'visus Miopia OS', + 'note' => $miopia_os_value, + 'segment' => 'visus', + 'category' => 'mata', + 'order_id' => $orderID + ); + $this->insert_data_etl($data_insert,$userid); + //$this->insert_code('visus_miopia_os','visus Miopia OS'); + } + if($miopia_od){ + $in_value = ["20/30","20/40"]; + $exp_value_od = explode("/",$od_visus); + if(isset($exp_value_od[1]) && intval($exp_value_od[1]) < 50){ + $data_insert = array( + 'code' => 'visus_miopia_od_30_40', + 'label' => 'visus Miopia OD 20/30 20/40', + 'note' => $miopia_od_value, + 'segment' => 'visus', + 'category' => 'mata', + 'order_id' => $orderID + ); + $this->insert_data_etl($data_insert,$userid); + //$this->insert_code('visus_miopia_od_30_40','visus Miopia OD 20/30 20/40'); + } + if(isset($exp_value_od[1]) && intval($exp_value_od[1]) > 50){ + $data_insert = array( + 'code' => 'visus_miopia_od_over_50', + 'label' => 'visus Miopia OD > 20/50', + 'note' => $miopia_od_value, + 'segment' => 'visus', + 'category' => 'mata', + 'order_id' => $orderID + ); + $this->insert_data_etl($data_insert,$userid); + //$this->insert_code('visus_miopia_ods_over_50','visus Miopia ODS > 20/50'); + } + } + + if($miopia_os){ + + $in_value = ["20/30","20/40"]; + $exp_value_os = explode("/",$os_visus); + //print_r($exp_value_os); + if(isset($exp_value_os[1]) && intval($exp_value_os[1]) < 50){ + $data_insert = array( + 'code' => 'visus_miopia_os_30_40', + 'label' => 'visus Miopia OS 20/30 20/40', + 'note' => $miopia_os_value, + 'segment' => 'visus', + 'category' => 'mata', + 'order_id' => $orderID + ); + $this->insert_data_etl($data_insert,$userid); + //$this->insert_code('visus_miopia_od_30_40','visus Miopia OD 20/30 20/40'); + } + if(isset($exp_value_os[1]) && intval($exp_value_os[1]) > 50){ + $data_insert = array( + 'code' => 'visus_miopia_os_over_50', + 'label' => 'visus Miopia OS > 20/50', + 'note' => $miopia_os_value, + 'segment' => 'visus', + 'category' => 'mata', + 'order_id' => $orderID + ); + $this->insert_data_etl($data_insert,$userid); + //$this->insert_code('visus_miopia_ods_over_50','visus Miopia ODS > 20/50'); + } + } + + if($astigmatismus_od){ + $data_insert = array( + 'code' => 'visus_astigmatismus_od', + 'label' => 'visus Astigmatismus OD', + 'note' => $astigmatismus_od_value, + 'segment' => 'visus', + 'category' => 'mata', + 'order_id' => $orderID + ); + $this->insert_data_etl($data_insert,$userid); + //$this->insert_code('visus_astigmatismus_od','visus Astigmatismus OD'); + } + if($astigmatismus_os){ + $data_insert = array( + 'code' => 'visus_astigmatismus_os', + 'label' => 'visus Astigmatismus OS', + 'note' => $astigmatismus_os_value, + 'segment' => 'visus', + 'category' => 'mata', + 'order_id' => $orderID + ); + $this->insert_data_etl($data_insert,$userid); + //$this->insert_code('visus_astigmatismus_os','visus Astigmatismus OS'); + } + if($astigmatismus_od && $astigmatismus_os){ + $data_insert = array( + 'code' => 'visus_astigmatismus_ods', + 'label' => 'visus Astigmatismus ODS', + 'note' => $astigmatismus_os_value, + 'segment' => 'visus', + 'category' => 'mata', + 'order_id' => $orderID + ); + $this->insert_data_etl($data_insert,$userid); + //$this->insert_code('visus_astigmatismus_ods','visus Astigmatismus ODS'); + } + if($x_od){ + $data_insert = array( + 'code' => 'visus_x_od', + 'label' => 'visus X OD', + 'note' => $x_od_value, + 'segment' => 'visus', + 'category' => 'mata', + 'order_id' => $orderID + ); + $this->insert_data_etl($data_insert,$userid); + //$this->insert_code('visus_x_od','visus X OD'); + } + if($x_os){ + $data_insert = array( + 'code' => 'visus_x_os', + 'label' => 'visus X OS', + 'note' => $x_od_value, + 'segment' => 'visus', + 'category' => 'mata', + 'order_id' => $orderID + ); + $this->insert_data_etl($data_insert,$userid); + //$this->insert_code('visus_x_os','visus X OS'); + } + if($presbiopia_ods){ + $data_insert = array( + 'code' => 'visus_presbiopia_ods', + 'label' => 'visus Presbiopia ODS', + 'note' => $presbiopia_ods_value, + 'segment' => 'visus', + 'category' => 'mata', + 'order_id' => $orderID + ); + $this->insert_data_etl($data_insert,$userid); + //$this->insert_code('visus_presbiopia_ods','visus Presbiopia ODS'); + } + } + + function visus_old($orderID,$userid) { + $sql = " SELECT * , T_SamplingAdditionalFisikVisusID as visus_id + FROM t_samplingso_additional_fisik_visus + WHERE + T_SamplingAdditionalFisikVisusT_OrderHeaderID = ? LIMIT 1"; + $qry = $this->db_smartone->query($sql,array($orderID)); + if (! $qry) { + return false; + } + + $row_result = $qry->row_array(); + + + $visus = array(); + $visus_kiri = ""; + $visus_kanan = ""; + $visus_kesimpulan = ""; + $normal = array("20/20", "20/25"); + $rst['kelainan'] = "Normal"; + $miopia_od = false; + $miopia_os = false; + $miopia_od_value = ''; + $miopia_os_value = ''; + $astigmatismus_od = false; + $astigmatismus_os = false; + $astigmatismus_od_value = ''; + $astigmatismus_os_value = ''; + $presbiopia_od = false; + $presbiopia_os = false; + $presbiopia_od_value = ''; + $presbiopia_os_value = ''; + + if($row_result){ + if(($row_result['T_SamplingAdditionalFisikVisusTKODV'] != "" && $row_result['T_SamplingAdditionalFisikVisusTKODV'] != "-") && ($row_result['T_SamplingAdditionalFisikVisusTKOSV'] != "" && $row_result['T_SamplingAdditionalFisikVisusTKOSV'] != "-")){ + $visus[] = array( + "xx1" => "Tanpa Kacamata", + "xx2" => "OD : ", + "xx3" => $row_result['T_SamplingAdditionalFisikVisusTKODV'] + ); + + $visus[] = array( + "xx1" => "Tanpa Kacamata", + "xx2" => "OS", + "xx3" => $row_result['T_SamplingAdditionalFisikVisusTKOSV'] + ); + + $rst['kelainan'] = "Kelainan refraksi (tanpa kacamata)"; + + if (!in_array($row_result['T_SamplingAdditionalFisikVisusTKODV'], $normal)){ + $value_koreksi_od = ""; + $od_sph = $row_result['T_SamplingAdditionalFisikVisusODSPH']; + if($od_sph != "" && $od_sph != "-" && $od_sph != "--" && $od_sph != "/-" && $od_sph != "/" && $od_sph != "-/" && strtolower(trim($od_sph)) != 'plano'){ + if ($visus_kesimpulan != "") $visus_kesimpulan .= ", "; + $visus_kesimpulan .= "Miopia OD"; + + $miopia_od = true; + $miopia_od_value = $od_sph; + } + + $od_cyl = $row_result['T_SamplingAdditionalFisikVisusODCYL']; + if($od_cyl != "" && $od_cyl != "-" && $od_cyl != "--" && $od_cyl != "/-" && $od_cyl != "/" && $od_cyl != "-/"){ + if ($visus_kesimpulan != "") $visus_kesimpulan .= ", "; + $visus_kesimpulan .= "Astigmatismus OD"; + + $astigmatismus_od = true; + $astigmatismus_od_value = $od_cyl; + } + + + $od_x = $row_result['T_SamplingAdditionalFisikVisusODX']; + if($od_x != "" && $od_x != "-" && $od_x != "--" && $od_x != "/-" && $od_x != "/" && $od_x != "-/") + $value_koreksi_od .= "X (".$od_x.") "; + + $od_add = $row_result['T_SamplingAdditionalFisikVisusADD']; + if($od_add != "" && $od_add != "-" && $od_add != "--" && $od_add != "/-" && $od_add != "/" && $od_add != "-/"){ + if ($visus_kesimpulan != "") $visus_kesimpulan .= ", "; + $visus_kesimpulan .= "Presbiopia OD"; + + $presbiopia_od = true; + + $presbiopia_od_value = ""; + $presbiopia_os_value = ""; + + } + + } + + if (!in_array($row_result['T_SamplingAdditionalFisikVisusTKOSV'], $normal)){ + $value_koreksi_os = ""; + $os_sph = $row_result['T_SamplingAdditionalFisikVisusOSSPH']; + if(strtolower(trim($os_sph)) != "tidak terkoreksi" && strtolower(trim($os_sph)) != "tidak dapat dinilai" && $os_sph != "" && $os_sph != "-" && $os_sph != "--" && $os_sph != "/-" && $os_sph != "/" && $os_sph != "-/" && strtolower(trim($os_sph)) != 'plano'){ + if ($visus_kesimpulan != "") $visus_kesimpulan .= ", "; + $visus_kesimpulan .= "Miopia OS"; + } + + + $os_cyl = $row_result['T_SamplingAdditionalFisikVisusOSCYL']; + if(strtolower(trim($os_cyl)) != "tidak terkoreksi" && strtolower(trim($os_cyl)) != "tidak dapat dinilai" && $os_cyl != "" && $os_cyl != "-" && $os_cyl != "--" && $os_cyl != "/-" && $os_cyl != "/" && $os_cyl != "-/"){ + if ($visus_kesimpulan != "") $visus_kesimpulan .= ", "; + $visus_kesimpulan .= "Astigmatismus OS"; + } + + + $os_x = $row_result['T_SamplingAdditionalFisikVisusOSX']; + if(strtolower(trim($os_x)) != "tidak terkoreksi" && strtolower(trim($os_x)) != "tidak dapat dinilai" && $os_x != "" && $os_x != "-" && $os_x != "--" && $os_x != "/-" && $os_x != "/" && $os_x != "-/") + $value_koreksi_os .= "X (".$os_x.") "; + + $od_add = $row_result['T_SamplingAdditionalFisikVisusADD']; + if($od_add != "" && $od_add != "-" && $od_add != "--" && $od_add != "/-" && $od_add != "/" && $od_add != "-/"){ + if ($visus_kesimpulan != "") $visus_kesimpulan .= ", "; + $visus_kesimpulan .= "Presbiopia OS"; + } + + + } + } + + if(($row_result['T_SamplingAdditionalFisikVisusDKODV'] != "" && $row_result['T_SamplingAdditionalFisikVisusDKODV'] != "-") && ($row_result['T_SamplingAdditionalFisikVisusDKOSV'] != "" && $row_result['T_SamplingAdditionalFisikVisusDKOSV'] != "-")){ + $visus[] = array( + "xx1" => "Dengan Kacamata", + "xx2" => "OD : ", + "xx3" => $row_result['T_SamplingAdditionalFisikVisusDKODV'] + ); + + $visus[] = array( + "xx1" => "Dengan Kacamata", + "xx2" => "OS", + "xx3" => $row_result['T_SamplingAdditionalFisikVisusDKOSV'] + ); + + $rst['kelainan'] = "Kelainan refraksi (dengan kacamata)"; + + + $value_koreksi_od = ""; + $od_sph = $row_result['T_SamplingAdditionalFisikVisusODSPH']; + if(strtolower(trim($od_sph)) != "tidak terkoreksi" && strtolower(trim($od_sph)) != "tidak dapat dinilai" && $od_sph != "" && $od_sph != "-" && $od_sph != "--" && $od_sph != "/-" && $od_sph != "/" && $od_sph != "-/" && strtolower(trim($od_sph)) != 'plano'){ + if ($visus_kesimpulan != "") $visus_kesimpulan .= ", "; + $visus_kesimpulan .= "Miopia OD"; + } + + + $od_cyl = $row_result['T_SamplingAdditionalFisikVisusODCYL']; + if(strtolower(trim($od_cyl)) != "tidak terkoreksi" && strtolower(trim($od_cyl)) != "tidak dapat dinilai" && $od_cyl != "" && $od_cyl != "-" && $od_cyl != "--" && $od_cyl != "/-" && $od_cyl != "/" && $od_cyl != "-/"){ + if ($visus_kesimpulan != "") $visus_kesimpulan .= ", "; + $visus_kesimpulan .= "Astigmatismus OD"; + } + + + $od_x = $row_result['T_SamplingAdditionalFisikVisusODX']; + if(strtolower(trim($od_x)) != "tidak terkoreksi" && strtolower(trim($od_x)) != "tidak dapat dinilai" && $od_x != "" && $od_x != "-" && $od_x != "--" && $od_x != "/-" && $od_x != "/" && $od_x != "-/") + $value_koreksi_od .= "X (".$od_x.") "; + + $od_add = $row_result['T_SamplingAdditionalFisikVisusADD']; + if($od_add != "" && $od_add != "-" && $od_add != "--" && $od_add != "/-" && $od_add != "/" && $od_add != "-/"){ + if ($visus_kesimpulan != "") $visus_kesimpulan .= ", "; + $visus_kesimpulan .= "Presbiopia OD"; + } + + + + + $value_koreksi_os = ""; + $os_sph = $row_result['T_SamplingAdditionalFisikVisusOSSPH']; + if(strtolower(trim($os_sph)) != "tidak terkoreksi" && strtolower(trim($os_sph)) != "tidak dapat dinilai" && $os_sph != "" && $os_sph != "-" && $os_sph != "--" && $os_sph != "/-" && $os_sph != "/" && $os_sph != "-/" && strtolower(trim($os_sph)) != 'plano'){ + if ($visus_kesimpulan != "") $visus_kesimpulan .= ", "; + $visus_kesimpulan .= "Miopia OS"; + } + + $os_cyl = $row_result['T_SamplingAdditionalFisikVisusOSCYL']; + if(strtolower(trim($os_cyl)) != "tidak terkoreksi" && strtolower(trim($os_cyl)) != "tidak dapat dinilai" && $os_cyl != "" && $os_cyl != "-" && $os_cyl != "--" && $os_cyl != "/-" && $os_cyl != "/" && $os_cyl != "-/"){ + if ($visus_kesimpulan != "") $visus_kesimpulan .= ", "; + $visus_kesimpulan .= "Astigmatismus OS"; + } + + $os_x = $row_result['T_SamplingAdditionalFisikVisusOSX']; + if(strtolower(trim($os_x)) != "tidak terkoreksi" && strtolower(trim($os_x)) != "tidak dapat dinilai" && $os_x != "" && $os_x != "-" && $os_x != "--" && $os_x != "/-" && $os_x != "/" && $os_x != "-/") + $value_koreksi_os .= "X (".$os_x.") "; + + $od_add = $row_result['T_SamplingAdditionalFisikVisusADD']; + if($od_add != "" && $od_add != "-" && $od_add != "--" && $od_add != "/-" && $od_add != "/" && $od_add != "-/"){ + if ($visus_kesimpulan != "") $visus_kesimpulan .= ", "; + $visus_kesimpulan .= "Presbiopia OS"; + } + + + } + + $rst['kesimpulan'] = $visus_kesimpulan; + + $data_insert = array( + 'code' => 'visus', + 'label' => 'visus', + 'note' => $rst['kelainan'], + 'segment' => 'visus', + 'category' => 'mata', + 'order_id' => $orderID + ); + $this->insert_data_etl($data_insert,$userid); + } + } + + function insert_code($code,$label){ + /*$sql = "INSERT INTO fisik_template_code( + FisikTemplateCodeName, + FisikTemplateCodeLabel, + FisikTemplateCodeCreated, + FisikTemplateCodeCreatedUserID + ) + VALUES( + ?,?,NOW(),555 + )"; + $qry = $this->db_smartone->query($sql,array($code,$label)); + if (! $qry) { + return false; + }*/ + } + + function status_gizi($id,$userid) { + $sql = "SELECT * + FROM t_samplingso_additional_fisik_bbtb + WHERE + T_SamplingAdditionalFisikBBTBT_OrderHeaderID = ? AND + T_SamplingAdditionalFisikBBTBIsActive = 'Y' + LIMIT 1"; + $qry = $this->db_smartone->query($sql,array($id)); + if (! $qry) { + return false; + } + //echo $this->db_smartone->last_query(); + $row_results = $qry->result_array(); + //print_r($row_result); + if(count($row_results) > 0){ + $row_result = $row_results[0]; + $status_gizi = array(); + $bb = $row_result["T_SamplingAdditionalFisikBBTBValueBB"]; + $tb = $row_result["T_SamplingAdditionalFisikBBTBValueTB"]; + $standart_bmi = $row_result["T_SamplingAdditionalFisikBBTBStandart"]; + $get_bmi = $this->hitung_bmi($bb,$tb,$standart_bmi); + $bmi = $get_bmi['bmi']; + + $classification = $get_bmi['class']; + //echo $classification; + + $data_insert_tb = array( + 'code' => 'tb', + 'label' => $tb, + 'note' => $tb, + 'segment' => 'status_gizi', + 'category' => '', + 'order_id' => $id + ); + $this->insert_data_etl($data_insert_tb,$userid); + //$this->insert_code('tb',$tb); + + $data_insert_bb = array( + 'code' => 'bb', + 'label' => $bb, + 'note' => $bb, + 'segment' => 'status_gizi', + 'category' => '', + 'order_id' => $id + ); + $this->insert_data_etl($data_insert_bb,$userid); + //$this->insert_code('bb',$bb); + + $data_insert_bmi = array( + 'code' => 'bmi', + 'label' => $bmi, + 'note' => $bmi, + 'segment' => 'status_gizi', + 'category' => $standart_bmi, + 'order_id' => $id + ); + $this->insert_data_etl($data_insert_bmi,$userid); + //$this->insert_code('bmi',$bmi); + + $data_insert_bmi_class = array( + 'code' => 'bmi_classification_'.$standart_bmi, + 'label' => $classification, + 'note' => $classification, + 'segment' => 'status_gizi', + 'category' => $standart_bmi, + 'order_id' => $id + ); + //print_r($data_insert_bmi_class); + $this->insert_data_etl($data_insert_bmi_class,$userid); + //$this->insert_code('bmi_classification_'.$standart_bmi,$classification); + } + + return true; + } + + function persepsi_warna($id,$userid) { + $sql = "SELECT IFNULL(T_SamplingAdditionalFisikBWPWValue,'Z') as result, + IFNULL(T_SamplingAdditionalFisikBWPWVAngka,'') as angka + FROM t_samplingso_additional_fisik_bw + WHERE + T_SamplingAdditionalFisikBWT_OrderHeaderID = ? + LIMIT 1"; + $qry = $this->db_smartone->query($sql,array($id)); + if (! $qry) { + return false; + } + + + $row_results = $qry->result_array(); + if(count($row_results) > 0){ + $row_result = $row_results[0]; + $hasil = 'Bahan belum'; + if($row_result['result'] == 'BW'){ + $hasil = 'Red Green Deficiency'; + } + if($row_result['result'] == 'N'){ + $hasil = 'Normal'; + } + if($row_result['result'] == 'X'){ + $hasil = 'Tidak dilakukan'; + } + $data_insert_bw = array( + 'code' => 'bw', + 'label' => $row_result['result'], + 'note' => $hasil, + 'segment' => 'mata', + 'category' => '', + 'order_id' => $id + ); + $this->insert_data_etl($data_insert_bw,$userid); + //$this->insert_code('bw',$row_result['result']); + + $data_insert_bwv = array( + 'code' => 'bw_value', + 'label' => $row_result['angka'], + 'note' => $row_result['angka'], + 'segment' => 'mata', + 'category' => '', + 'order_id' => $id + ); + $this->insert_data_etl($data_insert_bwv,$userid); + //$this->insert_code('bw_value',$row_result['angka']); + } + + + } + + + + function hitung_bmi($bb,$tb,$standart_bmi){ + $tb = $tb/100; + $bmi = ''; + $classs = ""; + $bmi_valuex= 0; + if(intval($bb) != 0 && intval($tb) != 0){ + $bmi = $bb / ($tb * $tb); + $bmi_valuex = number_format($bmi,2); + + if($standart_bmi === 'asia_pacific'){ + if($bmi_valuex < 18.5) + $classs = 'Underweight'; + + if($bmi_valuex >= 18.5 && $bmi_valuex < 23) + $classs = 'Normal'; + + if($bmi_valuex >= 23 && $bmi_valuex < 25) + $classs = 'Overweight'; + + if($bmi_valuex >= 25 && $bmi_valuex < 30) + $classs = 'Obese I'; + + if($bmi_valuex >= 30) + $classs = 'Obese II'; + } + + if($standart_bmi === 'who'){ + if($bmi_valuex < 18.5) + $classs = 'Underweight'; + + if($bmi_valuex >= 18.5 && $bmi_valuex < 25){ + $classs = 'Normal'; + } + + if($bmi_valuex >= 25 && $bmi_valuex < 30){ + $classs = 'Overweight'; + } + + if($bmi_valuex >= 30) + $classs = 'Obese'; + } + + if($standart_bmi === 'kemenkes'){ + if($bmi_valuex < 18.5) + $classs = 'Underweight'; + + if($bmi_valuex >= 18.5 && $bmi_valuex < 25.1) + $classs = 'Normal'; + + if($bmi_valuex >= 25.1 && $bmi_valuex < 27) + $classs = 'Overweight'; + + if($bmi_valuex >= 27) + $classs = 'Obese'; + } + } + + + + + + return array( + 'bmi' => $bmi_valuex, + 'class' => $classs + ); + } + + function keluhan($id,$userid){ + $rst = []; + $sql = "SELECT * + FROM fisik_template + JOIN so_resultentry_fisik_umum ON So_ResultEntryFisikUmumFisikTemplateID = FisikTemplateID AND So_ResultEntryFisikUmumSo_ResultEntryID = ? + JOIN so_resultentry ON So_ResultEntryFisikUmumSo_ResultEntryID = So_ResultEntryID + WHERE + FisikTemplateIsActive = 'Y' AND + FisikTemplateTableName = 'fisik_keluhan' + ORDER BY FisikTemplateCode ASC + LIMIT 1 + "; + $qry = $this->db_smartone->query($sql, array($id)); + // echo $this->db_smartone->last_query(); + $datas = $qry->result_array(); + if($datas && count($datas) > 0){ + $order_header_id = $datas[0]['So_ResultEntryT_OrderHeaderID']; + $valdata = json_decode($datas[0]['So_ResultEntryFisikUmumDetails'], true); + $details = $valdata['details']; + foreach ($details as $key => $value) { + if($value['chx'] == '1'){ + $data_insert = array( + 'order_id' => $order_header_id, + 'code' => $value['id_code'], + 'label' => $value['label'], + 'note' => $value['value'], + 'segment' => 'fisik_keluhan', + 'category' => '' + ); + $this->insert_data_etl($data_insert,$userid); + $rst[] = $data_insert; + } + //$this->insert_code($value['id_code'],$value['label']); + + } + } + + return $rst; + } + + function riwayat_penyakit($id,$userid){ + $rst = []; + $sql = "SELECT * + FROM fisik_template + JOIN so_resultentry_fisik_umum ON So_ResultEntryFisikUmumFisikTemplateID = FisikTemplateID AND + So_ResultEntryFisikUmumSo_ResultEntryID = ? + JOIN so_resultentry ON So_ResultEntryFisikUmumSo_ResultEntryID = So_ResultEntryID + WHERE + FisikTemplateIsActive = 'Y' AND + FisikTemplateTableName = 'fisik_penyakit' + ORDER BY FisikTemplateCode ASC + LIMIT 1 + "; + $qry = $this->db_smartone->query($sql, array($id)); + // echo $this->db_smartone->last_query(); + $datas = $qry->result_array(); + if($datas && count($datas) > 0){ + $order_header_id = $datas[0]['So_ResultEntryT_OrderHeaderID']; + $valdata = json_decode($datas[0]['So_ResultEntryFisikUmumDetails'], true); + $header_details = $valdata['details']; + foreach ($header_details as $k => $v) { + $details = $v['details']; + foreach ($details as $key => $value) { + if($value['chx'] == '1'){ + $data_insert = array( + 'order_id' => $order_header_id, + 'code' => $value['id_code'], + 'label' => $value['label'], + 'note' => $value['value'], + 'segment' => $value['segment_name'], + 'category' => $value['table_name'] + ); + $this->insert_data_etl($data_insert,$userid); + $rst[] = $data_insert; + } + //$this->insert_code($value['id_code'],$value['label']." | ".$value['segment_name']); + + } + } + } + + return $rst; + } + + function penyakit_keluarga($id,$userid){ + $rst = []; + $sql = "SELECT * + FROM fisik_template + JOIN so_resultentry_fisik_umum ON So_ResultEntryFisikUmumFisikTemplateID = FisikTemplateID AND So_ResultEntryFisikUmumSo_ResultEntryID = ? + JOIN so_resultentry ON So_ResultEntryFisikUmumSo_ResultEntryID = So_ResultEntryID + WHERE + FisikTemplateIsActive = 'Y' AND + FisikTemplateTableName = 'fisik_penyakitkeluarga' + ORDER BY FisikTemplateCode ASC + LIMIT 1 + "; + $qry = $this->db_smartone->query($sql, array($id)); + // echo $this->db_smartone->last_query(); + $datas = $qry->result_array(); + if($datas && count($datas) > 0){ + $order_header_id = $datas[0]['So_ResultEntryT_OrderHeaderID']; + $valdata = json_decode($datas[0]['So_ResultEntryFisikUmumDetails'], true); + $details = $valdata['details']; + foreach ($details as $key => $value) { + $results = []; + $options = $value['options']; + foreach ($options as $ko => $vo) { + if($vo['selected'] == '1') + $results[] = $vo['label']; + } + + if(count($results) > 0){ + $data_insert = array( + 'order_id' => $order_header_id, + 'code' => $value['id_code'], + 'label' => $value['label'], + 'note' => join(", ",$results), + 'segment' => $value['table_name'], + 'category' => $value['table_name'], + ); + $this->insert_data_etl($data_insert,$userid); + $rst[] = $data_insert; + } + //$this->insert_code($value['id_code'],$value['label']); + + } + } + + return $rst; + } + + + function kebiasaan_hidup($id,$userid){ + $rst = []; + $sql = "SELECT * + FROM fisik_template + JOIN so_resultentry_fisik_umum ON So_ResultEntryFisikUmumFisikTemplateID = FisikTemplateID AND So_ResultEntryFisikUmumSo_ResultEntryID = ? + JOIN so_resultentry ON So_ResultEntryFisikUmumSo_ResultEntryID = So_ResultEntryID + WHERE + FisikTemplateIsActive = 'Y' AND + FisikTemplateTableName = 'fisik_kebiasaanhidup' + ORDER BY FisikTemplateCode ASC + LIMIT 1 + "; + $qry = $this->db_smartone->query($sql, array($id)); + // echo $this->db_smartone->last_query(); + $datas = $qry->result_array(); + if($datas && count($datas) > 0){ + $order_header_id = $datas[0]['So_ResultEntryT_OrderHeaderID']; + $valdata = json_decode($datas[0]['So_ResultEntryFisikUmumDetails'], true); + $header_details = $valdata['details']; + foreach ($header_details as $k => $v) { + $details = $v['details']; + foreach ($details as $key => $value) { + if($value['chx'] == '1'){ + $data_insert = array( + 'order_id' => $order_header_id, + 'code' => $value['id_code'], + 'label' => $value['label'], + 'note' => $value['value'], + 'segment' => $value['segment_name'], + 'category' => $value['table_name'] + ); + $this->insert_data_etl($data_insert,$userid); + $rst[] = $data_insert; + } + //$this->insert_code($value['id_code'],$value['label']." | ".$value['segment_name']); + } + } + } + + return $rst; + } + + function fisik_konsumsiobatteratur($id,$userid){ + $rst = []; + $sql = "SELECT * + FROM fisik_template + JOIN so_resultentry_fisik_umum ON So_ResultEntryFisikUmumFisikTemplateID = FisikTemplateID AND So_ResultEntryFisikUmumSo_ResultEntryID = ? + JOIN so_resultentry ON So_ResultEntryFisikUmumSo_ResultEntryID = So_ResultEntryID + WHERE + FisikTemplateIsActive = 'Y' AND + FisikTemplateTableName = 'fisik_konsumsiobatteratur' + ORDER BY FisikTemplateCode ASC + LIMIT 1 + "; + $qry = $this->db_smartone->query($sql, array($id)); + // echo $this->db_smartone->last_query(); + $datas = $qry->result_array(); + if($datas && count($datas) > 0){ + $order_header_id = $datas[0]['So_ResultEntryT_OrderHeaderID']; + $valdata = json_decode($datas[0]['So_ResultEntryFisikUmumDetails'], true); + $details = $valdata['details']; + foreach ($details as $key => $value) { + if($value['chx'] == '1'){ + $data_insert = array( + 'order_id' => $order_header_id, + 'code' => $value['id_code'], + 'label' => $value['label'], + 'note' => $value['value'], + 'segment' => $value['table_name'], + 'category' => $value['table_name'] + ); + $this->insert_data_etl($data_insert,$userid); + $rst[] = $data_insert; + } + //$this->insert_code($value['id_code'],$value['label']); + } + } + + return $rst; + } + + + function imunasi($id,$userid){ + $rst = []; + $sql = "SELECT * + FROM fisik_template + JOIN so_resultentry_fisik_umum ON So_ResultEntryFisikUmumFisikTemplateID = FisikTemplateID AND So_ResultEntryFisikUmumSo_ResultEntryID = ? + JOIN so_resultentry ON So_ResultEntryFisikUmumSo_ResultEntryID = So_ResultEntryID + WHERE + FisikTemplateIsActive = 'Y' AND + FisikTemplateTableName = 'fisik_riwayatimunisasi' + ORDER BY FisikTemplateCode ASC + LIMIT 1 + "; + $qry = $this->db_smartone->query($sql, array($id)); + // echo $this->db_smartone->last_query(); + $datas = $qry->result_array(); + if($datas && count($datas) > 0){ + $order_header_id = $datas[0]['So_ResultEntryT_OrderHeaderID']; + $valdata = json_decode($datas[0]['So_ResultEntryFisikUmumDetails'], true); + $header_details = $valdata['details']; + foreach ($header_details as $k => $v) { + $details = $v['details']; + foreach ($details as $key => $value) { + if($value['chx'] == '1'){ + $data_insert = array( + 'order_id' => $order_header_id, + 'code' => $value['id_code'], + 'label' => $value['label'], + 'note' => $value['value'], + 'segment' => $value['segment_name'], + 'category' => $value['table_name'] + ); + $this->insert_data_etl($data_insert,$userid); + $rst[] = $data_insert; + } + //$this->insert_code($value['id_code'],$value['label']." | ".$value['segment_name']); + } + } + } + + return $rst; + } + + function vital_sign($id,$userid){ + $rst = []; + $sql = "SELECT * + FROM fisik_template + JOIN so_resultentry_fisik_umum ON So_ResultEntryFisikUmumFisikTemplateID = FisikTemplateID AND So_ResultEntryFisikUmumSo_ResultEntryID = ? + JOIN so_resultentry ON So_ResultEntryFisikUmumSo_ResultEntryID = So_ResultEntryID + WHERE + FisikTemplateIsActive = 'Y' AND + FisikTemplateTableName = 'tanda_vital' + ORDER BY FisikTemplateCode ASC + LIMIT 1 + "; + $qry = $this->db_smartone->query($sql, array($id)); + // echo $this->db_smartone->last_query(); + $datas = $qry->result_array(); + if($datas && count($datas) > 0){ + $order_header_id = $datas[0]['So_ResultEntryT_OrderHeaderID']; + $valdata = json_decode($datas[0]['So_ResultEntryFisikUmumDetails'], true); + $details = $valdata['details']; + foreach ($details as $key => $value) { + if($value['id_code'] == 'tanda_vital_5'){ + $data_insert = array( + 'order_id' => $order_header_id, + 'code' => $value['id_code'].'_1', + 'label' => $value['label_x'], + 'note' => $value['value_x'], + 'segment' => 'tekanan_darah', + 'category' => $value['table_name'] + ); + $this->insert_data_etl($data_insert,$userid); + //$this->insert_code($value['id_code'].'_1',$value['label_x']); + $rst[] = $data_insert; + $data_insert = array( + 'order_id' => $order_header_id, + 'code' => $value['id_code'].'_2', + 'label' => $value['label_y'], + 'note' => $value['value_y'], + 'segment' => 'tekanan_darah', + 'category' => $value['table_name'] + ); + $this->insert_data_etl($data_insert,$userid); + //$this->insert_code($value['id_code'].'_2',$value['label_y']); + $rst[] = $data_insert; + $data_insert = array( + 'order_id' => $order_header_id, + 'code' => 'tekanan_darah_conclusion', + 'label' => $value['standart'], + 'note' => $value['value'], + 'segment' => 'tekanan_darah', + 'category' => $value['table_name'] + ); + $this->insert_data_etl($data_insert,$userid); + //$this->insert_code('tekanan_darah_conclusion',$value['label_y']); + $rst[] = $data_insert; + } + + if($value['id_code'] == 'tanda_vital_6'){ + $data_insert = array( + 'order_id' => $order_header_id, + 'code' => $value['id_code'], + 'label' => $value['chx_y'] == '1'?$value['label_y']:$value['label_x'], + 'note' => $value['value'], + 'segment' => 'suhu', + 'category' => $value['table_name'] + ); + $this->insert_data_etl($data_insert,$userid); + //$this->insert_code($value['id_code'],'Suhu'); + $rst[] = $data_insert; + } + + if($value['id_code'] == 'tanda_vital_1'){ + $data_insert = array( + 'order_id' => $order_header_id, + 'code' => $value['id_code'], + 'label' => $value['label'], + 'note' => $value['value'], + 'segment' => 'denyut_nadi', + 'category' => $value['table_name'] + ); + $this->insert_data_etl($data_insert,$userid); + //$this->insert_code($value['id_code'],$value['label']); + $rst[] = $data_insert; + } + + if($value['id_code'] == 'tanda_vital_2'){ + $data_insert = array( + 'order_id' => $order_header_id, + 'code' => $value['id_code'], + 'label' => $value['chx_y'] == '1'?$value['label_y']:$value['label_x'], + 'note' => $value['value'], + 'segment' => 'ritme_denyut_nadi', + 'category' => $value['table_name'] + ); + $this->insert_data_etl($data_insert,$userid); + //$this->insert_code($value['id_code'],'Denyut Nadi'); + $rst[] = $data_insert; + } + + if($value['id_code'] == 'tanda_vital_3'){ + $data_insert = array( + 'order_id' => $order_header_id, + 'code' => $value['id_code'], + 'label' => $value['label'], + 'note' => $value['value'], + 'segment' => 'laju_pernafasan', + 'category' => $value['table_name'] + ); + $this->insert_data_etl($data_insert,$userid); + //$this->insert_code($value['id_code'],$value['label']); + $rst[] = $data_insert; + } + + if($value['id_code'] == 'tanda_vital_4'){ + $data_insert = array( + 'order_id' => $order_header_id, + 'code' => $value['id_code'], + 'label' => $value['chx_y'] == '1'?$value['label_y']:$value['label_x'], + 'note' => $value['value'], + 'segment' => 'pola_nafas', + 'category' => $value['table_name'] + ); + $this->insert_data_etl($data_insert,$userid); + //$this->insert_code($value['id_code'],'Pola Nafas'); + $rst[] = $data_insert; + } + + } + } + + return $rst; + } + + + function keadaan_umum($id,$userid){ + $rst = []; + $sql = "SELECT * + FROM fisik_template + JOIN so_resultentry_fisik_umum ON So_ResultEntryFisikUmumFisikTemplateID = FisikTemplateID AND So_ResultEntryFisikUmumSo_ResultEntryID = ? + JOIN so_resultentry ON So_ResultEntryFisikUmumSo_ResultEntryID = So_ResultEntryID + WHERE + FisikTemplateIsActive = 'Y' AND + FisikTemplateTableName = 'keadaan_umum' + ORDER BY FisikTemplateCode ASC + LIMIT 1 + "; + $qry = $this->db_smartone->query($sql, array($id)); + // echo $this->db_smartone->last_query(); + $datas = $qry->result_array(); + if($datas && count($datas) > 0){ + $order_header_id = $datas[0]['So_ResultEntryT_OrderHeaderID']; + $valdata = json_decode($datas[0]['So_ResultEntryFisikUmumDetails'], true); + $details = $valdata['details']; + foreach ($details as $key => $value) { + if($value['chx_x'] == '1'){ + $data_insert = array( + 'order_id' => $order_header_id, + 'code' => $value['id_code']+'_x', + 'label' => $value['label_x'], + 'note' => $value['value'], + 'segment' => $value['table_name'], + 'category' => $value['table_name'] + ); + $this->insert_data_etl($data_insert,$userid); + } + if($value['chx_y'] == '1'){ + $data_insert = array( + 'order_id' => $order_header_id, + 'code' => $value['id_code'].'_y', + 'label' => $value['label_y'], + 'note' => $value['value'], + 'segment' => $value['table_name'], + 'category' => $value['table_name'] + ); + $this->insert_data_etl($data_insert,$userid); + } + + ////$this->insert_code($value['id_code'],'Keadaan Umum'); + $rst[] = $data_insert; + } + } + + return $rst; + } + + function kepala_wajah($id,$userid){ + $rst = []; + $sql = "SELECT * + FROM fisik_template + JOIN so_resultentry_fisik_umum ON So_ResultEntryFisikUmumFisikTemplateID = FisikTemplateID AND So_ResultEntryFisikUmumSo_ResultEntryID = ? + JOIN so_resultentry ON So_ResultEntryFisikUmumSo_ResultEntryID = So_ResultEntryID + WHERE + FisikTemplateIsActive = 'Y' AND + FisikTemplateTableName = 'kepala_wajah' + ORDER BY FisikTemplateCode ASC + LIMIT 1 + "; + $qry = $this->db_smartone->query($sql, array($id)); + // echo $this->db_smartone->last_query(); + $datas = $qry->result_array(); + if($datas && count($datas) > 0){ + $order_header_id = $datas[0]['So_ResultEntryT_OrderHeaderID']; + $valdata = json_decode($datas[0]['So_ResultEntryFisikUmumDetails'], true); + $details = $valdata['details']; + foreach ($details as $key => $value) { + if($value['chx'] == '1' && $value['is_normal'] == 'N'){ + $data_insert = array( + 'order_id' => $order_header_id, + 'code' => $value['id_code'], + 'label' => $value['label'], + 'note' => $value['value'], + 'segment' => $value['table_name'], + 'category' => $value['table_name'] + ); + $this->insert_data_etl($data_insert,$userid); + $rst[] = $data_insert; + } + //$this->insert_code($value['id_code'],$value['label'].' | '.$value['table_name']); + } + } + + return $rst; + } + + function mata($id,$userid){ + $rst = []; + $sql = "SELECT * + FROM fisik_template + JOIN so_resultentry_fisik_umum ON So_ResultEntryFisikUmumFisikTemplateID = FisikTemplateID AND + So_ResultEntryFisikUmumSo_ResultEntryID = ? + JOIN so_resultentry ON So_ResultEntryFisikUmumSo_ResultEntryID = So_ResultEntryID + WHERE + FisikTemplateIsActive = 'Y' AND + FisikTemplateTableName = 'mata' + ORDER BY FisikTemplateCode ASC + LIMIT 1 + "; + $qry = $this->db_smartone->query($sql, array($id)); + // echo $this->db_smartone->last_query(); + $datas = $qry->result_array(); + if($datas && count($datas) > 0){ + $order_header_id = $datas[0]['So_ResultEntryT_OrderHeaderID']; + $valdata = json_decode($datas[0]['So_ResultEntryFisikUmumDetails'], true); + $details = $valdata['details']; + foreach ($details as $key => $value) { + if($value['chx'] == '1'){ + $data_insert = array( + 'order_id' => $order_header_id, + 'code' => $value['id_code'], + 'label' => $value['label'], + 'note' => $value['value'], + 'segment' => 'mata', + 'category' => 'mata' + ); + $this->insert_data_etl($data_insert,$userid); + $rst[] = $data_insert; + } + //$this->insert_code($value['id_code'],$value['label']." | Mata"); + + } + } + + return $rst; + } + + function lapang_pandang($id,$userid){ + $rst = []; + $sql = "SELECT * + FROM fisik_template + JOIN so_resultentry_fisik_umum ON So_ResultEntryFisikUmumFisikTemplateID = FisikTemplateID AND + So_ResultEntryFisikUmumSo_ResultEntryID = ? + JOIN so_resultentry ON So_ResultEntryFisikUmumSo_ResultEntryID = So_ResultEntryID + WHERE + FisikTemplateIsActive = 'Y' AND + FisikTemplateTableName = 'lapang_pandang' + ORDER BY FisikTemplateCode ASC + LIMIT 1 + "; + $qry = $this->db_smartone->query($sql, array($id)); + // echo $this->db_smartone->last_query(); + $datas = $qry->result_array(); + if($datas && count($datas) > 0){ + $order_header_id = $datas[0]['So_ResultEntryT_OrderHeaderID']; + $valdata = json_decode($datas[0]['So_ResultEntryFisikUmumDetails'], true); + $details = $valdata['details']; + $value_data = $details[0]; + + if($value_data['chx_x'] == '1'){ + $data_insert = array( + 'order_id' => $order_header_id, + 'code' => 'lapang_pandang_x', + 'label' => $value_data['label_x'], + 'note' => $value_data['value'], + 'segment' => 'lapang_pandang', + 'category' => 'lapang_pandang' + ); + $this->insert_data_etl($data_insert,$userid); + + $rst[] = $data_insert; + } + + if($value_data['chx_y'] == '1'){ + $data_insert = array( + 'order_id' => $order_header_id, + 'code' => 'lapang_pandang_y', + 'label' => $value_data['label_y'], + 'note' => $value_data['value'], + 'segment' => 'lapang_pandang', + 'category' => 'lapang_pandang' + ); + $this->insert_data_etl($data_insert,$userid); + + $rst[] = $data_insert; + } + //$this->insert_code('lapang_pandang_x','Lapang Pandang Tidak Normal'); + //$this->insert_code('lapang_pandang_y','Lapang Pandang Normal'); + } + + return $rst; + } + + function telinga($id,$userid){ + $rst = []; + $sql = "SELECT * + FROM fisik_template + JOIN so_resultentry_fisik_umum ON So_ResultEntryFisikUmumFisikTemplateID = FisikTemplateID AND + So_ResultEntryFisikUmumSo_ResultEntryID = ? + JOIN so_resultentry ON So_ResultEntryFisikUmumSo_ResultEntryID = So_ResultEntryID + WHERE + FisikTemplateIsActive = 'Y' AND + FisikTemplateTableName = 'telinga' + ORDER BY FisikTemplateCode ASC + LIMIT 1 + "; + $qry = $this->db_smartone->query($sql, array($id)); + // echo $this->db_smartone->last_query(); + $datas = $qry->result_array(); + if($datas && count($datas) > 0){ + $order_header_id = $datas[0]['So_ResultEntryT_OrderHeaderID']; + $valdata = json_decode($datas[0]['So_ResultEntryFisikUmumDetails'], true); + $details = $valdata['details']; + foreach ($details as $key => $value) { + if($value['chx'] == '1'){ + $data_insert = array( + 'order_id' => $order_header_id, + 'code' => $value['id_code'], + 'label' => $value['label'], + 'note' => $value['value'], + 'segment' => 'telinga', + 'category' => 'telinga' + ); + $this->insert_data_etl($data_insert,$userid); + $rst[] = $data_insert; + } + //$this->insert_code($value['id_code'],$value['label'].' | Telinga'); + } + } + + return $rst; + } + + function hidung($id,$userid){ + $rst = []; + $sql = "SELECT * + FROM fisik_template + JOIN so_resultentry_fisik_umum ON So_ResultEntryFisikUmumFisikTemplateID = FisikTemplateID AND + So_ResultEntryFisikUmumSo_ResultEntryID = ? + JOIN so_resultentry ON So_ResultEntryFisikUmumSo_ResultEntryID = So_ResultEntryID + WHERE + FisikTemplateIsActive = 'Y' AND + FisikTemplateTableName = 'hidung' + ORDER BY FisikTemplateCode ASC + LIMIT 1 + "; + $qry = $this->db_smartone->query($sql, array($id)); + // echo $this->db_smartone->last_query(); + $datas = $qry->result_array(); + if($datas && count($datas) > 0){ + $order_header_id = $datas[0]['So_ResultEntryT_OrderHeaderID']; + $valdata = json_decode($datas[0]['So_ResultEntryFisikUmumDetails'], true); + $details = $valdata['details']; + foreach ($details as $key => $value) { + if($value['chx'] == '1'){ + $data_insert = array( + 'order_id' => $order_header_id, + 'code' => $value['id_code'], + 'label' => $value['label'], + 'note' => $value['value'], + 'segment' => 'hidung', + 'category' => 'hidung' + ); + $this->insert_data_etl($data_insert,$userid); + $rst[] = $data_insert; + } + //$this->insert_code($value['id_code'],$value['label'].' | Hidung'); + } + } + + return $rst; + } + + function gigi($id,$userid){ + $rst = []; + $sql = "SELECT * + FROM fisik_template + JOIN so_resultentry_fisik_umum ON So_ResultEntryFisikUmumFisikTemplateID = FisikTemplateID AND + So_ResultEntryFisikUmumSo_ResultEntryID = ? + JOIN so_resultentry ON So_ResultEntryFisikUmumSo_ResultEntryID = So_ResultEntryID + WHERE + FisikTemplateIsActive = 'Y' AND + FisikTemplateTableName = 'gigi' + ORDER BY FisikTemplateCode ASC + LIMIT 1 + "; + $qry = $this->db_smartone->query($sql, array($id)); + // echo $this->db_smartone->last_query(); + $datas = $qry->result_array(); + if($datas && count($datas) > 0){ + $order_header_id = $datas[0]['So_ResultEntryT_OrderHeaderID']; + $valdata = json_decode($datas[0]['So_ResultEntryFisikUmumDetails'], true); + $details = $valdata['details']; + foreach ($details as $key => $value) { + if($value['chx'] == '1'){ + $data_insert = array( + 'order_id' => $order_header_id, + 'code' => $value['id_code'], + 'label' => $value['label'], + 'note' => $value['value'], + 'segment' => 'gigi', + 'category' => 'gigi' + ); + $this->insert_data_etl($data_insert,$userid); + $rst[] = $data_insert; + } + //$this->insert_code($value['id_code'],$value['label'].' | Gigi'); + + } + } + + return $rst; + } + + function mulut($id,$userid){ + $rst = []; + $sql = "SELECT * + FROM fisik_template + JOIN so_resultentry_fisik_umum ON So_ResultEntryFisikUmumFisikTemplateID = FisikTemplateID AND So_ResultEntryFisikUmumSo_ResultEntryID = ? + JOIN so_resultentry ON So_ResultEntryFisikUmumSo_ResultEntryID = So_ResultEntryID + WHERE + FisikTemplateIsActive = 'Y' AND + FisikTemplateTableName = 'mukosa_rongga_mulut' + ORDER BY FisikTemplateCode ASC + LIMIT 1 + "; + $qry = $this->db_smartone->query($sql, array($id)); + //echo $this->db_smartone->last_query(); + $datas = $qry->result_array(); + if($datas && count($datas) > 0){ + $order_header_id = $datas[0]['So_ResultEntryT_OrderHeaderID']; + $valdata = json_decode($datas[0]['So_ResultEntryFisikUmumDetails'], true); + $header_details = $valdata['details']; + //print_r($header_details); + foreach ($header_details as $k => $v) { + $details = $v['details']; + foreach ($details as $key => $value) { + $segment = strtolower(str_replace(" ","_",$value['segment_name'])); + if($value['chx'] == '1'){ + $data_insert = array( + 'order_id' => $order_header_id, + 'code' => $value['id_code'], + 'label' => $value['label'], + 'note' => $value['value'], + 'segment' => $segment, + 'category' => $value['table_name'] + ); + $this->insert_data_etl($data_insert,$userid); + $rst[] = $data_insert; + } + //$this->insert_code($value['id_code'],$value['label']." | ".$segment); + + } + } + } + + return $rst; + } + + function leher($id,$userid){ + $rst = []; + $sql = "SELECT * + FROM fisik_template + JOIN so_resultentry_fisik_umum ON So_ResultEntryFisikUmumFisikTemplateID = FisikTemplateID AND + So_ResultEntryFisikUmumSo_ResultEntryID = ? + JOIN so_resultentry ON So_ResultEntryFisikUmumSo_ResultEntryID = So_ResultEntryID + WHERE + FisikTemplateIsActive = 'Y' AND + FisikTemplateTableName = 'leher' + ORDER BY FisikTemplateCode ASC + LIMIT 1 + "; + $qry = $this->db_smartone->query($sql, array($id)); + // echo $this->db_smartone->last_query(); + $datas = $qry->result_array(); + if($datas && count($datas) > 0){ + $order_header_id = $datas[0]['So_ResultEntryT_OrderHeaderID']; + $valdata = json_decode($datas[0]['So_ResultEntryFisikUmumDetails'], true); + $details = $valdata['details']; + foreach ($details as $key => $value) { + if($value['chx'] == '1'){ + $data_insert = array( + 'order_id' => $order_header_id, + 'code' => $value['id_code'], + 'label' => $value['label'], + 'note' => $value['value'], + 'segment' => 'leher', + 'category' => 'leher' + ); + $this->insert_data_etl($data_insert,$userid); + $rst[] = $data_insert; + } + //$this->insert_code($value['id_code'],$value['label'].' | Leher'); + } + } + + return $rst; + } + + function thorax($id,$userid){ + $rst = []; + $sql = "SELECT * + FROM fisik_template + JOIN so_resultentry_fisik_umum ON So_ResultEntryFisikUmumFisikTemplateID = FisikTemplateID AND + So_ResultEntryFisikUmumSo_ResultEntryID = ? + JOIN so_resultentry ON So_ResultEntryFisikUmumSo_ResultEntryID = So_ResultEntryID + WHERE + FisikTemplateIsActive = 'Y' AND + FisikTemplateTableName = 'thorax' + ORDER BY FisikTemplateCode ASC + LIMIT 1 + "; + $qry = $this->db_smartone->query($sql, array($id)); + // echo $this->db_smartone->last_query(); + $datas = $qry->result_array(); + if($datas && count($datas) > 0){ + $order_header_id = $datas[0]['So_ResultEntryT_OrderHeaderID']; + $valdata = json_decode($datas[0]['So_ResultEntryFisikUmumDetails'], true); + $details = $valdata['details']; + foreach ($details as $key => $value) { + if($value['chx'] == '1'){ + $data_insert = array( + 'order_id' => $order_header_id, + 'code' => $value['id_code'], + 'label' => $value['label'], + 'note' => $value['value'], + 'segment' => 'thorax', + 'category' => 'thorax' + ); + $this->insert_data_etl($data_insert,$userid); + $rst[] = $data_insert; + } + //$this->insert_code($value['id_code'],$value['label'].' | Thorax'); + } + } + + return $rst; + } + + function paru($id,$userid){ + $rst = []; + $sql = "SELECT * + FROM fisik_template + JOIN so_resultentry_fisik_umum ON So_ResultEntryFisikUmumFisikTemplateID = FisikTemplateID AND + So_ResultEntryFisikUmumSo_ResultEntryID = ? + JOIN so_resultentry ON So_ResultEntryFisikUmumSo_ResultEntryID = So_ResultEntryID + WHERE + FisikTemplateIsActive = 'Y' AND + FisikTemplateTableName = 'paru' + ORDER BY FisikTemplateCode ASC + LIMIT 1 + "; + $qry = $this->db_smartone->query($sql, array($id)); + // echo $this->db_smartone->last_query(); + $datas = $qry->result_array(); + if($datas && count($datas) > 0){ + $order_header_id = $datas[0]['So_ResultEntryT_OrderHeaderID']; + $valdata = json_decode($datas[0]['So_ResultEntryFisikUmumDetails'], true); + $details = $valdata['details']; + foreach ($details as $key => $value) { + if($value['chx'] == '1'){ + $data_insert = array( + 'order_id' => $order_header_id, + 'code' => $value['id_code'], + 'label' => $value['label'], + 'note' => $value['value'], + 'segment' => 'paru', + 'category' => 'paru' + ); + $this->insert_data_etl($data_insert,$userid); + $rst[] = $data_insert; + } + //$this->insert_code($value['id_code'],$value['label'].' | Paru'); + } + } + + return $rst; + } + + function jantung($id,$userid){ + $rst = []; + $sql = "SELECT * + FROM fisik_template + JOIN so_resultentry_fisik_umum ON So_ResultEntryFisikUmumFisikTemplateID = FisikTemplateID AND So_ResultEntryFisikUmumSo_ResultEntryID = ? + JOIN so_resultentry ON So_ResultEntryFisikUmumSo_ResultEntryID = So_ResultEntryID + WHERE + FisikTemplateIsActive = 'Y' AND + FisikTemplateTableName = 'jantung' + ORDER BY FisikTemplateCode ASC + LIMIT 1 + "; + $qry = $this->db_smartone->query($sql, array($id)); + //echo $this->db_smartone->last_query(); + $datas = $qry->result_array(); + if($datas && count($datas) > 0){ + $order_header_id = $datas[0]['So_ResultEntryT_OrderHeaderID']; + $valdata = json_decode($datas[0]['So_ResultEntryFisikUmumDetails'], true); + $header_details = $valdata['details']; + //print_r($header_details); + foreach ($header_details as $k => $v) { + $details = $v['details']; + foreach ($details as $key => $value) { + $segment = strtolower(str_replace(" ","_",str_replace("/","",$value['segment_name']))); + if($value['chx'] == '1'){ + + $data_insert = array( + 'order_id' => $order_header_id, + 'code' => $value['id_code'], + 'label' => $value['label'], + 'note' => $value['value'], + 'segment' => $segment, + 'category' => $value['table_name'] + ); + $this->insert_data_etl($data_insert,$userid); + $rst[] = $data_insert; + } + //$this->insert_code($value['id_code'],$value['label']." | ".$segment); + } + } + } + + return $rst; + } + + function perut($id,$userid){ + $rst = []; + $sql = "SELECT * + FROM fisik_template + JOIN so_resultentry_fisik_umum ON So_ResultEntryFisikUmumFisikTemplateID = FisikTemplateID AND So_ResultEntryFisikUmumSo_ResultEntryID = ? + JOIN so_resultentry ON So_ResultEntryFisikUmumSo_ResultEntryID = So_ResultEntryID + WHERE + FisikTemplateIsActive = 'Y' AND + FisikTemplateTableName = 'perut' + ORDER BY FisikTemplateCode ASC + LIMIT 1 + "; + $qry = $this->db_smartone->query($sql, array($id)); + //echo $this->db_smartone->last_query(); + $datas = $qry->result_array(); + if($datas && count($datas) > 0){ + $order_header_id = $datas[0]['So_ResultEntryT_OrderHeaderID']; + $valdata = json_decode($datas[0]['So_ResultEntryFisikUmumDetails'], true); + $header_details = $valdata['details']; + //print_r($header_details); + foreach ($header_details as $k => $v) { + if($v['name'] != 'Hernia' && $v['name'] != 'Pengukuran'){ + $details = $v['details']; + foreach ($details as $key => $value) { + $segment = strtolower(str_replace(" ","_",$v['name'])); + if($value['chx'] == '1'){ + + $data_insert = array( + 'order_id' => $order_header_id, + 'code' => $value['id_code'], + 'label' => $value['label'], + 'note' => $value['value'], + 'segment' => $segment, + 'category' => $value['table_name'] + ); + $this->insert_data_etl($data_insert,$userid); + $rst[] = $data_insert; + } + //$this->insert_code($value['id_code'],$value['label']." | ".$segment); + } + } + + if($v['name'] == 'Hernia'){ + $details = $v['details']; + foreach ($details as $key => $value) { + if($value['id_code'] == 'perut_13'){ + if($value['chx'] == '1'){ + $segment = strtolower(str_replace(" ","_",$v['name'])); + $data_insert = array( + 'order_id' => $order_header_id, + 'code' => $value['id_code'], + 'label' => $value['label'], + 'note' => $value['value'], + 'segment' => $segment, + 'category' => $value['table_name'] + ); + $this->insert_data_etl($data_insert,$userid); + $rst[] = $data_insert; + } + //$this->insert_code($value['id_code'],$value['label'].' | Hernia '.$segment); + } + + if($value['id_code'] == 'perut_14'){ + $segment = strtolower(str_replace(" ","_",$v['name'])); + if($value['chx'] == '1'){ + $child_details = $value['details']; + foreach ($child_details as $kx => $vx) { + if($vx['id_code'] == 'perut_14_1'){ + if($vx['chx_value'] == '1'){ + $data_insert = array( + 'order_id' => $order_header_id, + 'code' => $vx['id_code'], + 'label' => $vx['label'], + 'note' => '', + 'segment' => $segment, + 'category' => $value['table_name'] + ); + $this->insert_data_etl($data_insert,$userid); + $rst[] = $data_insert; + } + //$this->insert_code($value['id_code'],$value['label'].' | Hernia '.$segment); + } + + if($vx['id_code'] != 'perut_14_1'){ + if($vx['chx_a_value'] == '1'){ + $data_insert = array( + 'order_id' => $order_header_id, + 'code' => $vx['id_code'].'_'.$vx['chx_a_label'], + 'label' => $vx['label'], + 'note' => $vx['chx_a_label'], + 'segment' => $segment, + 'category' => $value['table_name'] + ); + $this->insert_data_etl($data_insert,$userid); + $rst[] = $data_insert; + } + + if($vx['chx_b_value'] == '1'){ + $data_insert = array( + 'order_id' => $order_header_id, + 'code' => $vx['id_code'].'_'.$vx['chx_b_label'], + 'label' => $vx['label'], + 'note' => $vx['chx_b_label'], + 'segment' => $segment, + 'category' => $value['table_name'] + ); + $this->insert_data_etl($data_insert,$userid); + $rst[] = $data_insert; + } + //$this->insert_code($vx['id_code'].'_'.$vx['chx_a_label'],$value['label'].' | Hernia '.$segment); + //$this->insert_code($vx['id_code'].'_'.$vx['chx_b_label'],$value['label'].' | Hernia '.$segment); + } + + } + } + //$this->insert_code($value['id_code'],$value['label']); + } + + + } + } + + if($v['name'] == 'Hernia'){ + $details = $v['details']; + } + + } + } + + return $rst; + } + + function sistem_integumen($id,$userid){ + $rst = []; + $sql = "SELECT * + FROM fisik_template + JOIN so_resultentry_fisik_umum ON So_ResultEntryFisikUmumFisikTemplateID = FisikTemplateID AND So_ResultEntryFisikUmumSo_ResultEntryID = ? + JOIN so_resultentry ON So_ResultEntryFisikUmumSo_ResultEntryID = So_ResultEntryID + WHERE + FisikTemplateIsActive = 'Y' AND + FisikTemplateTableName = 'sistem_integumen' + ORDER BY FisikTemplateCode ASC + LIMIT 1 + "; + $qry = $this->db_smartone->query($sql, array($id)); + //echo $this->db_smartone->last_query(); + $datas = $qry->result_array(); + if($datas && count($datas) > 0){ + $order_header_id = $datas[0]['So_ResultEntryT_OrderHeaderID']; + $valdata = json_decode($datas[0]['So_ResultEntryFisikUmumDetails'], true); + $header_details = $valdata['details']; + //print_r($header_details); + foreach ($header_details as $k => $v) { + $details = $v['details']; + foreach ($details as $key => $value) { + $segment = strtolower(str_replace(" ","_",$value['segment_name'])); + if($value['chx'] == '1'){ + + $data_insert = array( + 'order_id' => $order_header_id, + 'code' => $value['id_code'], + 'label' => $value['label'], + 'note' => $value['value'], + 'segment' => $segment, + 'category' => $value['table_name'] + ); + $this->insert_data_etl($data_insert,$userid); + + $rst[] = $data_insert; + } + //$this->insert_code($value['id_code'],$value['label']." | ".$segment); + } + } + } + + return $rst; + } + + function genitourinaria($id,$userid){ + $rst = []; + $sql = "SELECT * + FROM fisik_template + JOIN so_resultentry_fisik_umum ON So_ResultEntryFisikUmumFisikTemplateID = FisikTemplateID AND + So_ResultEntryFisikUmumSo_ResultEntryID = ? + JOIN so_resultentry ON So_ResultEntryFisikUmumSo_ResultEntryID = So_ResultEntryID + WHERE + FisikTemplateIsActive = 'Y' AND + FisikTemplateTableName = 'genitourinaria' + ORDER BY FisikTemplateCode ASC + LIMIT 1 + "; + $qry = $this->db_smartone->query($sql, array($id)); + // echo $this->db_smartone->last_query(); + $datas = $qry->result_array(); + if($datas && count($datas) > 0){ + $order_header_id = $datas[0]['So_ResultEntryT_OrderHeaderID']; + $valdata = json_decode($datas[0]['So_ResultEntryFisikUmumDetails'], true); + $details = $valdata['details']; + foreach ($details as $key => $value) { + if($value['chx'] == '1'){ + $data_insert = array( + 'order_id' => $order_header_id, + 'code' => $value['id_code'], + 'label' => $value['label'], + 'note' => $value['value'], + 'segment' => 'genitourinaria', + 'category' => 'genitourinaria' + ); + $this->insert_data_etl($data_insert,$userid); + $rst[] = $data_insert; + } + //$this->insert_code($value['id_code'],$value['label'].' Genitourinaria'); + } + } + + return $rst; + } + + function anggota_gerak($id,$userid){ + $rst = []; + $sql = "SELECT * + FROM fisik_template + JOIN so_resultentry_fisik_umum ON So_ResultEntryFisikUmumFisikTemplateID = FisikTemplateID AND So_ResultEntryFisikUmumSo_ResultEntryID = ? + JOIN so_resultentry ON So_ResultEntryFisikUmumSo_ResultEntryID = So_ResultEntryID + WHERE + FisikTemplateIsActive = 'Y' AND + FisikTemplateTableName = 'anggota_gerak' + ORDER BY FisikTemplateCode ASC + LIMIT 1 + "; + $qry = $this->db_smartone->query($sql, array($id)); + //echo $this->db_smartone->last_query(); + $datas = $qry->result_array(); + if($datas && count($datas) > 0){ + $order_header_id = $datas[0]['So_ResultEntryT_OrderHeaderID']; + $valdata = json_decode($datas[0]['So_ResultEntryFisikUmumDetails'], true); + $header_details = $valdata['details']; + //print_r($header_details); + foreach ($header_details as $k => $v) { + $details = $v['details']; + foreach ($details as $key => $value) { + if($value['chx'] == '1'){ + $segment = strtolower(str_replace(" ","_",str_replace("/","",$value['segment_name']))); + $data_insert = array( + 'order_id' => $order_header_id, + 'code' => $value['id_code'], + 'label' => $value['label'], + 'note' => $value['value'], + 'segment' => $segment, + 'category' => $value['table_name'] + ); + $this->insert_data_etl($data_insert,$userid); + $rst[] = $data_insert; + } + //$this->insert_code($value['id_code'],$value['label']." | ".$segment); + } + } + } + + return $rst; + } + + function sistem_persyarafan($id,$userid){ + $rst = []; + $sql = "SELECT * + FROM fisik_template + JOIN so_resultentry_fisik_umum ON So_ResultEntryFisikUmumFisikTemplateID = FisikTemplateID AND So_ResultEntryFisikUmumSo_ResultEntryID = ? + JOIN so_resultentry ON So_ResultEntryFisikUmumSo_ResultEntryID = So_ResultEntryID + WHERE + FisikTemplateIsActive = 'Y' AND + FisikTemplateTableName = 'sistem_persyarafan' + ORDER BY FisikTemplateCode ASC + LIMIT 1 + "; + $qry = $this->db_smartone->query($sql, array($id)); + //echo $this->db_smartone->last_query(); + $datas = $qry->result_array(); + if($datas && count($datas) > 0){ + $order_header_id = $datas[0]['So_ResultEntryT_OrderHeaderID']; + $valdata = json_decode($datas[0]['So_ResultEntryFisikUmumDetails'], true); + $header_details = $valdata['details']; + //print_r($header_details); + foreach ($header_details as $k => $v) { + $details = $v['details']; + foreach ($details as $key => $value) { + if($value['chx'] == '1'){ + $segment = strtolower(str_replace(" ","_",str_replace("&","",$value['segment_name']))); + $data_insert = array( + 'order_id' => $order_header_id, + 'code' => $value['id_code'], + 'label' => $value['label'], + 'note' => $value['value'], + 'segment' => $segment, + 'category' => $value['table_name'] + ); + $this->insert_data_etl($data_insert,$userid); + $rst[] = $data_insert; + } + //$this->insert_code($value['id_code'],$value['label']." | ".$segment); + } + } + } + + return $rst; + } + + function smell_test($id,$userid){ + $rst = []; + $sql = "SELECT * + FROM fisik_template + JOIN so_resultentry_fisik_umum ON So_ResultEntryFisikUmumFisikTemplateID = FisikTemplateID AND So_ResultEntryFisikUmumSo_ResultEntryID = ? + JOIN so_resultentry ON So_ResultEntryFisikUmumSo_ResultEntryID = So_ResultEntryID + WHERE + FisikTemplateIsActive = 'Y' AND + FisikTemplateTableName = 'smell_test' + ORDER BY FisikTemplateCode ASC + LIMIT 1 + "; + $qry = $this->db_smartone->query($sql, array($id)); + //echo $this->db_smartone->last_query(); + $datas = $qry->result_array(); + if($datas && count($datas) > 0){ + $order_header_id = $datas[0]['So_ResultEntryT_OrderHeaderID']; + $valdata = json_decode($datas[0]['So_ResultEntryFisikUmumDetails'], true); + $header_details = $valdata['details']; + //print_r($header_details); + foreach ($header_details as $k => $v) { + $details = $v['details']; + foreach ($details as $key => $value) { + if($value['chx'] == '1'){ + $segment = strtolower(str_replace(" ","_",$value['segment_name'])); + $data_insert = array( + 'order_id' => $order_header_id, + 'code' => $value['id_code'], + 'label' => $value['label'], + 'note' => $value['value'], + 'segment' => $segment, + 'category' => $value['table_name'] + ); + $this->insert_data_etl($data_insert,$userid); + $rst[] = $data_insert; + } + //$this->insert_code($value['id_code'],$value['label']." | ".$segment); + } + } + } + + return $rst; + } + + function low_back_pain_screening_test($id,$userid){ + $rst = []; + $sql = "SELECT * + FROM fisik_template + JOIN so_resultentry_fisik_umum ON So_ResultEntryFisikUmumFisikTemplateID = FisikTemplateID AND So_ResultEntryFisikUmumSo_ResultEntryID = ? + JOIN so_resultentry ON So_ResultEntryFisikUmumSo_ResultEntryID = So_ResultEntryID + WHERE + FisikTemplateIsActive = 'Y' AND + FisikTemplateTableName = 'low_back_pain_screening_test' + ORDER BY FisikTemplateCode ASC + LIMIT 1 + "; + $qry = $this->db_smartone->query($sql, array($id)); + //echo $this->db_smartone->last_query(); + $datas = $qry->result_array(); + if($datas && count($datas) > 0){ + $order_header_id = $datas[0]['So_ResultEntryT_OrderHeaderID']; + $valdata = json_decode($datas[0]['So_ResultEntryFisikUmumDetails'], true); + $header_details = $valdata['details']; + //print_r($header_details); + foreach ($header_details as $k => $v) { + $details = $v['details']; + foreach ($details as $key => $value) { + if($value['chx'] == '1'){ + $segment = strtolower(str_replace(" ","_",$value['segment_name'])); + $data_insert = array( + 'order_id' => $order_header_id, + 'code' => $value['id_code'], + 'label' => $value['label'], + 'note' => $value['value'], + 'segment' => $segment, + 'category' => $value['table_name'] + ); + $this->insert_data_etl($data_insert,$userid); + $rst[] = $data_insert; + } + //$this->insert_code($value['id_code'],$value['label']." | ".$segment); + } + } + } + + return $rst; + } + + function k3($type,$id,$userid){ + $rst = []; + $sql = "SELECT * + FROM fisik_template + JOIN so_resultentry_fisik_umum ON So_ResultEntryFisikUmumFisikTemplateID = FisikTemplateID AND + So_ResultEntryFisikUmumSo_ResultEntryID = ? + JOIN so_resultentry ON So_ResultEntryFisikUmumSo_ResultEntryID = So_ResultEntryID + WHERE + FisikTemplateIsActive = 'Y' AND + `FisikTemplateType` = 'k3' AND + FisikTemplateTableName = ? + ORDER BY FisikTemplateCode ASC + LIMIT 1 + "; + $qry = $this->db_smartone->query($sql, array($id,$type)); + // echo $this->db_smartone->last_query(); + $datas = $qry->result_array(); + if($datas && count($datas) > 0){ + $order_header_id = $datas[0]['So_ResultEntryT_OrderHeaderID']; + $valdata = json_decode($datas[0]['So_ResultEntryFisikUmumDetails'], true); + $details = $valdata['details']; + foreach ($details as $key => $value) { + if($value['chx'] == '1'){ + $data_insert = array( + 'order_id' => $order_header_id, + 'code' => $value['id_code'], + 'label' => $value['label'], + 'note' => '', + 'segment' => $type, + 'category' => $type + ); + $this->insert_data_etl($data_insert,$userid); + $rst[] = $data_insert; + } + //$this->insert_code($value['id_code'],$value['label'].' | '.$type); + } + } + + return $rst; + } + + function loop_k3($id,$userid){ + $rspn = []; + $arr = ['faktor_fisik','faktor_kimia','faktor_biologi','faktor_ergonomi','faktor_psikologi']; + foreach ($arr as $key => $value) { + $rtn = $this->k3($value,$id,$userid); + if(count($rtn) > 0) + $rspn[] = $rtn; + } + return $rspn; + } + + function generate_summaries($orderID,$soReID,$userID,$debugID=0){ + $sql = "UPDATE t_kelainan_fisik SET + T_KelainanFiskIsActive = 'N', + T_KelainanFiskDeletedUserID = ? , + T_KelainanFiskDeleted = NOW() + WHERE + T_KelainanFiskT_OrderHeaderID = ? AND + T_KelainanFiskIsActive = 'Y'"; + $query = $this->db_smartone->query($sql,[ + $userID, + $orderID + ]); + $kelainanrst = []; + $sql = "SELECT * + FROM mcu_fisiksummary + JOIN mcu_kelainan ON Mcu_kelainanID = Mcu_FisikSummaryMcu_KelainanID + WHERE Mcu_FisikSummaryIsActive = 'Y'"; + $query = $this->db_smartone->query($sql); + $rumus_summaries = $query->result_array(); + //print_r($rumus_summaries); + + foreach ($rumus_summaries as $key => $value) { + //echo $value['Mcu_KelainanName']; + $results = []; + $sql = "SELECT * + FROM mcu_fisiksummarydetail + WHERE + Mcu_FisikSummaryDetailMcu_FisikSummaryID = ? AND + Mcu_FisikSummaryDetailIsActive = 'Y'"; + + $query = $this->db_smartone->query($sql,[$value['Mcu_FisikSummaryID']]); + $details = $query->result_array(); + foreach ($details as $k => $v) { + if($v['Mcu_FisikSummaryDetailType'] == 'VK'){ + $sql = "SELECT * + FROM mcu_fisikvalue + WHERE + Mcu_FisikValueT_OrderHeaderID = ? AND + Mcu_FisikValueIsActive = 'Y' AND + Mcu_FisikValueCode = ? AND + Mcu_FisikValueNote = ?"; + $query = $this->db_smartone->query($sql,[$orderID,$v['Mcu_FisikSummaryDetailCode'],$value['Mcu_KelainanName']]); + /*if($value['Mcu_FisikSummaryID'] == 2){ + echo $this->db_smartone->last_query(); + }*/ + $exist_rows = $query->result_array(); + $return_x = false; + if(count($exist_rows) > 0){ + $return_x = true; + } + $results[] = $return_x; + } + + if($v['Mcu_FisikSummaryDetailType'] == 'V'){ + $sql = "SELECT * + FROM mcu_fisikvalue + JOIN mcu_fisiksummarydetail + ON Mcu_FisikSummaryDetailIsActive = 'Y' + AND Mcu_FisikSummaryDetailCode = Mcu_FisikValueCode + AND Mcu_FisikValueCode = ? + AND Mcu_FisikSummaryDetailType = 'V' + JOIN mcu_fisiksummary + ON Mcu_FisikSummaryDetailMcu_FisikSummaryID = Mcu_FisikSummaryID + AND Mcu_FisikSummaryMcu_KelainanID = ? + WHERE Mcu_FisikValueT_OrderHeaderID = ? + AND Mcu_FisikValueIsActive = 'Y' + AND Mcu_FisikSummaryDetailValue REGEXP CONCAT('(^|, )', TRIM(Mcu_FisikValueNote), '(,|$)')"; + $query = $this->db_smartone->query($sql,[$v['Mcu_FisikSummaryDetailCode'],$value['Mcu_KelainanID'],$orderID]); + if($value['Mcu_FisikSummaryID'] == $debugID){ + echo $this->db_smartone->last_query(); + } + $exist_rows = $query->result_array(); + $return_x = false; + if(count($exist_rows) > 0){ + $return_x = true; + } + $results[] = $return_x; + } + + if($v['Mcu_FisikSummaryDetailType'] == 'C'){ + $sql = "SELECT * + FROM mcu_fisikvalue + WHERE + Mcu_FisikValueT_OrderHeaderID = ? AND + Mcu_FisikValueIsActive = 'Y' AND + Mcu_FisikValueCode = ?"; + $query = $this->db_smartone->query($sql,[$orderID,$v['Mcu_FisikSummaryDetailCode']]); + if($value['Mcu_FisikSummaryID'] == $debugID){ + echo $this->db_smartone->last_query(); + } + + $exist_rows = $query->result_array(); + $return_x = false; + if(count($exist_rows) > 0){ + $return_x = true; + } + $results[] = $return_x; + } + } + //if($value['Mcu_FisikSummaryID'] == 2) + //print_r($results); + + $is_kelainan = false; + if($value['Mcu_FisikSummaryType'] == "AND"){ + if(!in_array(false,$results)) + $is_kelainan = true; + + //if($value['Mcu_FisikSummaryID'] == $debugID){ + // echo "AND"; + // print_r($results); +//} + + } + if($value['Mcu_FisikSummaryType'] == "OR"){ + if(in_array(true,$results)) + $is_kelainan = true; + + //if($value['Mcu_FisikSummaryID'] == $debugID){ + // echo "OR"; + // print_r($results); + //} + } + + //if($value['Mcu_FisikSummaryMcu_KelainanID'] == 27) + // echo $this->db_smartone->last_query(); + if($is_kelainan){ + + //if($value['Mcu_FisikSummaryID'] == 2){ + // echo "IHIR"; + //} + $sql = "INSERT INTO t_kelainan_fisik( + T_KelainanFiskSo_ResultEntryID, + T_KelainanFiskT_OrderHeaderID, + T_KelainanFiskMcu_KelainanID, + T_KelainanFiskMcu_FisikSummaryID, + T_KelainanFiskCreatedUserID, + T_KelainanFiskCreated + ) VALUES(?,?,?,?,?,NOW())"; + $query = $this->db_smartone->query($sql,[ + $soReID, + $orderID, + $value['Mcu_FisikSummaryMcu_KelainanID'], + $value['Mcu_FisikSummaryID'], + $userID + ]); + $kelainanrst[] = array( + 'id' => $value['Mcu_FisikSummaryMcu_KelainanID'], + 'name' => $value['Mcu_KelainanName'] + ); + } + + } + } + + function translate_word($word,$langid=1){ + if($langid == 1){ + return $word; + } + else{ + $sql = "SELECT * FROM translate_word WHERE Translate_WordIsActive = 'Y' AND Translate_WordFrom = '{$word}'"; + //echo $sql; + $qry = $this->db_smartone->query($sql); + if (! $qry) { + return $word; + } + + $rows = $qry->result_array(); + if(count($rows) > 0){ + return $rows[0]["Translate_WordTo"]; + }else{ + return $word; + } + } + } + + function translate_multiline_text($text, $langid = 1) { + // Split the text into lines + $lines = explode("\n", $text); + + // Translate each line + $translated_lines = array_map(function($line) use ($langid) { + // Remove the leading "- " and translate the rest + $trimmed_line = ltrim($line, "- "); + return "- " . $this->translate_sentence($trimmed_line, $langid); + }, $lines); + + // Join the translated lines back into a multiline string + return implode("\n", $translated_lines); + } + + function translate_sentence($sentence, $langid = 1) { + // Split the sentence into words + $words = preg_split('/[\s-]+/', $sentence); + + // Translate each word + $translated_words = array_map(function($word) use ($langid) { + return $this->translate_word($word, $langid); + }, $words); + + // Join the translated words back into a sentence + return implode(' ', $translated_words); + } + +} diff --git a/application/libraries/Excel.php b/application/libraries/Excel.php new file mode 100644 index 00000000..a2ff4d7d --- /dev/null +++ b/application/libraries/Excel.php @@ -0,0 +1,14 @@ + + diff --git a/application/libraries/Generateqrreport.php b/application/libraries/Generateqrreport.php new file mode 100644 index 00000000..fa64d2b3 --- /dev/null +++ b/application/libraries/Generateqrreport.php @@ -0,0 +1,638 @@ +=3)', + `QR_PrintOutRetryCount` int(11) NOT NULL DEFAULT 0 + COMMENT 'Berapa kali sudah dicoba upload, maksimal 3', + `QR_PrintOutLastRetryAt` datetime DEFAULT NULL + COMMENT 'Waktu percobaan upload terakhir yang gagal', + `QR_PrintOutUploadedAt` datetime DEFAULT NULL + COMMENT 'Waktu upload PDF ke dedicated server berhasil', + `QR_PrintOutCreatedAt` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP + COMMENT 'Waktu token QR dibuat', + `QR_PrintOutCreatedByUserID` int(11) NOT NULL DEFAULT 0 + COMMENT 'UserID yang mencetak laporan', + `QR_PrintOutIsActive` tinyint(1) NOT NULL DEFAULT 1 + COMMENT '1=aktif, 0=dinonaktifkan (mis. hasil direvisi)', + PRIMARY KEY (`QR_PrintOutID`), + UNIQUE KEY `uq_qr_uuid` (`QR_PrintOutUUID`), + KEY `idx_order_header` (`QR_PrintOutT_OrderHeaderID`), + KEY `idx_upload_status` (`QR_PrintOutUploadStatus`), + KEY `idx_retry` (`QR_PrintOutUploadStatus`, `QR_PrintOutRetryCount`) +) ENGINE=InnoDB DEFAULT CHARSET=latin1 + COMMENT='Token QR Code untuk verifikasi keaslian laporan hasil laboratorium'; + */ +/** + * Generateqrreport Library + * + * Library untuk generate QR Code pada laporan hasil laboratorium. + * QR Code berisi URL langsung ke file PDF di dedicated server. + * Saat QR di-scan, browser langsung membuka file PDF tersebut. + * + * Arsitektur: + * + * ┌─ PHP App (ini) ──────────────────────────────────────────────┐ + * │ 1. saveQRPrintout(verifyBaseURL='https://ds.com/files') │ + * │ → UUID + verifyURL = https://ds.com/files/{uuid}.pdf │ + * │ verifyURL = URL final PDF = yang di-encode ke QR Code │ + * │ 2. generateQRImageBase64(verifyURL) → embed QR ke PDF cetak │ + * │ 3. saveTempPDF() → simpan PDF sementara di /tmp/ │ + * └──────────────────────────────────────────────────────────────┘ + * │ + * ▼ + * ┌─ Golang Upload Tool ─────────────────────────────────────────┐ + * │ - Poll PHP API: getPendingUploads() │ + * │ - Ambil TempFilePath dari row │ + * │ - Upload PDF ke dedicated server pada path sesuai verifyURL │ + * │ - Berhasil → callback confirmUpload($uuid) │ + * │ - Gagal → callback incrementRetry($uuid) │ + * └──────────────────────────────────────────────────────────────┘ + * + * ┌─ Dedicated Server ───────────────────────────────────────────┐ + * │ - Serve file PDF statis │ + * │ - URL: https://ds.com/files/{uuid}.pdf │ + * │ - Saat QR di-scan → browser langsung buka PDF ini │ + * └──────────────────────────────────────────────────────────────┘ + * + * Tabel yang digunakan: qr_printout + * (lihat: sql/qr_printout_updated.sql untuk DDL lengkap) + */ +class Generateqrreport +{ + /** @var CI_DB_driver */ + protected $db_smartone; + + /** @var CI_DB_driver */ + protected $db_onedev; + + function __construct() + { + $CI = & get_instance(); + $this->db_smartone = $CI->load->database("default", true); + $this->db_onedev = $CI->load->database("default", true); + + $this->_loadQRLib(); + } + + // ========================================================================= + // PRIVATE HELPERS + // ========================================================================= + + /** + * Load phpqrcode library jika belum di-include. + */ + private function _loadQRLib() + { + if (!class_exists('QRcode', false)) { + $libPath = APPPATH . 'libraries/qrcode/'; + if (!defined('QR_CACHEABLE')) + define('QR_CACHEABLE', false); + if (!defined('QR_CACHE_DIR')) + define('QR_CACHE_DIR', APPPATH . 'cache/'); + if (!defined('QR_LOG_DIR')) + define('QR_LOG_DIR', APPPATH . 'logs/'); + if (!defined('QR_FIND_BEST_MASK')) + define('QR_FIND_BEST_MASK', true); + if (!defined('QR_FIND_FROM_RANDOM')) + define('QR_FIND_FROM_RANDOM', false); + if (!defined('QR_PNG_MAXIMUM_SIZE')) + define('QR_PNG_MAXIMUM_SIZE', 1024); + + include_once $libPath . 'phpqrcode.php'; + } + } + + /** + * Generate UUID v4. + * + * @param bool $withHyphens true → 36 char 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx' + * false → 32 char hex tanpa tanda hubung + * @return string + */ + private function _generateUUID($withHyphens = true) + { + $data = random_bytes(16); + $data[6] = chr(ord($data[6]) & 0x0f | 0x40); // version 4 + $data[8] = chr(ord($data[8]) & 0x3f | 0x80); // variant bits + + $uuid = vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex($data), 4)); + return $withHyphens ? $uuid : str_replace('-', '', $uuid); + } + + /** + * Normalisasi UUID: konversi 32-char (tanpa hyphen) ke format 36-char standar. + * + * @param string $uuid + * @return string lowercase 36-char UUID + */ + private function _normalizeUUID($uuid) + { + $uuid = trim($uuid); + if (strlen($uuid) === 32 && strpos($uuid, '-') === false) { + $uuid = substr($uuid, 0, 8) . '-' + . substr($uuid, 8, 4) . '-' + . substr($uuid, 12, 4) . '-' + . substr($uuid, 16, 4) . '-' + . substr($uuid, 20); + } + return strtolower($uuid); + } + + /** + * Validasi format UUID v4 (8-4-4-4-12). + * + * @param string $uuid + * @return bool + */ + private function _validateUUIDFormat($uuid) + { + return (bool)preg_match( + '/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/', + strtolower($uuid) + ); + } + + // ========================================================================= + // PUBLIC METHODS — QR TOKEN + // ========================================================================= + + /** + * Buat record QR baru di tabel qr_printout. + * + * verifyURL = URL LANGSUNG ke file PDF di dedicated server. + * URL ini yang di-encode ke gambar QR Code. + * Golang tool akan upload PDF ke path/URL ini. + * + * Contoh: + * verifyBaseURL = 'https://files.lab.rs.com/reports' + * verifyURL = 'https://files.lab.rs.com/reports/{uuid}.pdf' + * + * @param array $params Wajib: + * - orderHeaderID (int) FK ke t_orderheader + * - groupResultName (string) Label group, mis: 'HEMATOLOGI' + * - verifyBaseURL (string) Base URL folder PDF di dedicated server, + * contoh: 'https://files.lab.rs.com/reports' + * Hasilnya: {verifyBaseURL}/{uuid}.pdf + * Opsional: + * - groupResultID (int) default 0 + * - testID (int) default 0 + * - createdByUserID (int) default 0 + * @return array [ + * 'success' => bool, + * 'uuid' => string|null, // 36-char dengan hyphen + * 'uuid_short' => string|null, // 32-char tanpa hyphen + * 'verifyURL' => string|null, // URL PDF final = yang di-encode ke QR Code + * 'qr_printout_id' => int|null, + * 'message' => string + * ] + */ + public function saveQRPrintout(array $params) + { + $required = ['orderHeaderID', 'groupResultName', 'verifyBaseURL', 'QR_PrintOutReportURL']; + foreach ($required as $field) { + if (empty($params[$field])) { + return [ + 'success' => false, + 'uuid' => null, + 'uuid_short' => null, + 'verifyURL' => null, + 'qr_printout_id' => null, + 'message' => "Parameter '{$field}' wajib diisi.", + ]; + } + } + + $uuid = $this->_generateUUID(true); + $uuidShort = str_replace('-', '', $uuid); + + // verifyURL = URL langsung ke PDF: {base}/{uuid}.pdf + // Golang akan upload PDF ke path ini di dedicated server + $verifyURL = rtrim($params['verifyBaseURL'], '/') . '/' . str_replace('-', '', $uuid) . '.pdf'; + + $data = [ + 'QR_PrintOutT_OrderHeaderID' => (int)$params['orderHeaderID'], + 'QR_PrintOutGroup_ResultID' => (int)($params['groupResultID'] ?? 0), + 'QR_PrintOutT_TestID' => (int)($params['testID'] ?? 0), + 'QR_PrintOutGroup_ResultName' => $params['groupResultName'], + 'QR_PrintOutUUID' => $uuid, + 'QR_PrintOutVerifyURL' => $verifyURL, // URL final PDF = yang di-encode ke QR Code + 'QR_PrintOutReportURL' => $params['QR_PrintOutReportURL'], // URL sumber PDF di PHP server (Golang fetch dari sini) + 'QR_PrintOutTempFilePath' => '', + 'QR_PrintOutUploadStatus' => 'pending', + 'QR_PrintOutRetryCount' => 0, + 'QR_PrintOutLastRetryAt' => null, + 'QR_PrintOutUploadedAt' => null, + 'QR_PrintOutCreatedAt' => date('Y-m-d H:i:s'), + 'QR_PrintOutCreatedByUserID' => (int)($params['createdByUserID'] ?? 0), + 'QR_PrintOutIsActive' => 1, + ]; + + $this->db_smartone->insert('qr_printout', $data); + + if ($this->db_smartone->affected_rows() === 0) { + return [ + 'success' => false, + 'uuid' => null, + 'uuid_short' => null, + 'verifyURL' => null, + 'qr_printout_id' => null, + 'message' => 'Gagal menyimpan data QR Printout ke database.', + ]; + } + + return [ + 'success' => true, + 'uuid' => $uuid, + 'uuid_short' => $uuidShort, + 'verifyURL' => $verifyURL, // ini yang di-encode ke gambar QR Code + 'qr_printout_id' => $this->db_smartone->insert_id(), + 'message' => 'OK', + ]; + } + + /** + * Nonaktifkan QR Code (misal karena hasil direvisi dan QR lama tidak boleh diakses). + * + * @param string $uuid + * @return bool + */ + public function deactivateQR($uuid) + { + $uuid = $this->_normalizeUUID($uuid); + $this->db_smartone->where('QR_PrintOutUUID', $uuid) + ->update('qr_printout', ['QR_PrintOutIsActive' => 0]); + return $this->db_smartone->affected_rows() > 0; + } + + // ========================================================================= + // PUBLIC METHODS — QR IMAGE + // ========================================================================= + + /** + * Generate QR Code sebagai Base64 PNG string. + * Hasil bisa langsung di-embed ke HTML/PDF: + * + * @param string $url URL yang akan di-encode (verifyURL dari saveQRPrintout) + * @param int $pixelSize Ukuran pixel per modul (1–10), default 5 + * @param string $errorLevel Koreksi error: L, M, Q, H (default H) + * @return string "data:image/png;base64,..." atau '' jika gagal + */ + public function generateQRImageBase64($url, $pixelSize = 5, $errorLevel = 'H') + { + $errorLevel = in_array($errorLevel, ['L', 'M', 'Q', 'H']) ? $errorLevel : 'H'; + $pixelSize = min(max((int)$pixelSize, 1), 10); + + ob_start(); + QRcode::png($url, false, $errorLevel, $pixelSize, 2); + $imgData = ob_get_clean(); + + return empty($imgData) ? '' : 'data:image/png;base64,' . base64_encode($imgData); + } + + /** + * Generate QR Code dan simpan sebagai file PNG di disk. + * + * @param string $url URL yang akan di-encode + * @param string $savePath Path lengkap tujuan, misal: FCPATH.'qrcodes/abc.png' + * @param int $pixelSize Ukuran pixel per modul (1–10), default 5 + * @param string $errorLevel Koreksi error: L, M, Q, H (default H) + * @return bool true jika berhasil disimpan + */ + public function generateQRImageFile($url, $savePath, $pixelSize = 5, $errorLevel = 'H') + { + $errorLevel = in_array($errorLevel, ['L', 'M', 'Q', 'H']) ? $errorLevel : 'H'; + $pixelSize = min(max((int)$pixelSize, 1), 10); + + $dir = dirname($savePath); + if (!is_dir($dir)) { + mkdir($dir, 0755, true); + } + + QRcode::png($url, $savePath, $errorLevel, $pixelSize, 2); + return file_exists($savePath); + } + + // ========================================================================= + // PUBLIC METHODS — PDF TEMP & GOLANG CALLBACK + // ========================================================================= + + // ========================================================================= + // PUBLIC METHODS — GOLANG UPLOAD TOOL SUPPORT + // ========================================================================= + + /** + * Ambil daftar record yang BELUM diupload ke dedicated server. + * Dipakai oleh Golang upload tool sebagai polling. + * + * Hanya mengambil record dengan: + * - UploadStatus = 'pending' ATAU 'failed' (masih bisa retry) + * - RetryCount < 3 + * - IsActive = 1 + * - QR_PrintOutReportURL tidak kosong (PDF sudah tersedia di PHP server) + * + * Field penting untuk Golang dari setiap row: + * - QR_PrintOutUUID : identifier + * - QR_PrintOutVerifyURL : URL TUJUAN upload di dedicated server + * - QR_PrintOutReportURL : URL SUMBER PDF di PHP server (Golang fetch dari sini) + * - QR_PrintOutTempFilePath: path lokal file PDF (opsional, jika Golang akses lokal) + * + * @param int $limit Jumlah maksimal record (default 10) + * @return array + */ + public function getPendingUploads($limit = 10) + { + return $this->db_smartone + ->where_in('QR_PrintOutUploadStatus', ['pending', 'failed']) + ->where('QR_PrintOutRetryCount <', 3) + ->where('QR_PrintOutIsActive', 1) + ->where('QR_PrintOutReportURL !=', '') // pastikan PDF sudah siap + ->order_by('QR_PrintOutCreatedAt', 'ASC') + ->limit((int)$limit) + ->get('qr_printout') + ->result_array(); + } + + /** + * Catat bahwa satu percobaan upload gagal dan tambah retry count. + * + * - Jika RetryCount setelah increment < 3 → status tetap 'failed' (akan dicoba lagi) + * - Jika RetryCount setelah increment >= 3 → status menjadi 'failed_permanent' + * (tidak akan diambil oleh getPendingUploads() lagi) + * + * Dipanggil oleh Golang tool saat upload ke dedicated server gagal. + * + * @param string $uuid + * @return array [ + * 'success' => bool, + * 'retry_count' => int, // retry count setelah increment + * 'is_permanent' => bool, // true = sudah melebihi batas, tidak akan di-retry lagi + * 'message' => string + * ] + */ + public function incrementRetry($uuid) + { + $uuid = $this->_normalizeUUID($uuid); + + if (!$this->_validateUUIDFormat($uuid)) { + return ['success' => false, 'retry_count' => 0, 'is_permanent' => false, + 'message' => 'Format UUID tidak valid.']; + } + + $qrRow = $this->db_smartone + ->select('QR_PrintOutRetryCount, QR_PrintOutUploadStatus') + ->where('QR_PrintOutUUID', $uuid) + ->get('qr_printout') + ->row_array(); + + if (!$qrRow) { + return ['success' => false, 'retry_count' => 0, 'is_permanent' => false, + 'message' => 'UUID tidak ditemukan.']; + } + + $newRetryCount = (int)$qrRow['QR_PrintOutRetryCount'] + 1; + $isPermanent = $newRetryCount >= 3; + $newStatus = $isPermanent ? 'failed_permanent' : 'failed'; + + $this->db_smartone->where('QR_PrintOutUUID', $uuid) + ->update('qr_printout', [ + 'QR_PrintOutRetryCount' => $newRetryCount, + 'QR_PrintOutLastRetryAt' => date('Y-m-d H:i:s'), + 'QR_PrintOutUploadStatus' => $newStatus, + ]); + + return [ + 'success' => true, + 'retry_count' => $newRetryCount, + 'is_permanent' => $isPermanent, + 'message' => $isPermanent + ? "Retry count mencapai {$newRetryCount}. Status menjadi 'failed_permanent'. Upload otomatis dihentikan." + : "Retry count: {$newRetryCount}/3. Akan dicoba kembali.", + ]; + } + + /** + * Minta upload ulang (re-upload) untuk satu record. + * + * Gunakan fungsi ini ketika: + * (a) File PDF di dedicated server sudah dihapus / kadaluarsa, ATAU + * (b) Record sebelumnya 'failed_permanent' dan ingin dicoba ulang secara manual + * + * Fungsi ini akan: + * - Reset UploadStatus → 'pending' + * - Reset RetryCount → 0 + * - Kosongkan ReportURL (file lama di dedicated server sudah tidak valid) + * - Wajib diikuti dengan saveTempPDF() untuk menyiapkan file PDF baru + * + * @param string $uuid + * @return array ['success' => bool, 'message' => string] + */ + public function requestReUpload($uuid) + { + $uuid = $this->_normalizeUUID($uuid); + + if (!$this->_validateUUIDFormat($uuid)) { + return ['success' => false, 'message' => 'Format UUID tidak valid.']; + } + + $exists = $this->db_smartone + ->where('QR_PrintOutUUID', $uuid) + ->count_all_results('qr_printout'); + + if ($exists === 0) { + return ['success' => false, 'message' => 'UUID tidak ditemukan.']; + } + + $this->db_smartone->where('QR_PrintOutUUID', $uuid) + ->update('qr_printout', [ + 'QR_PrintOutUploadStatus' => 'pending', + 'QR_PrintOutRetryCount' => 0, + 'QR_PrintOutLastRetryAt' => null, + 'QR_PrintOutUploadedAt' => null, + 'QR_PrintOutTempFilePath' => '', // harus diisi ulang via saveTempPDF() + ]); + + if ($this->db_smartone->affected_rows() === 0) { + return ['success' => false, 'message' => 'Gagal update database.']; + } + + return [ + 'success' => true, + 'message' => 'Record di-reset ke pending. Panggil saveTempPDF() untuk menyiapkan PDF baru.', + ]; + } + + + + /** + * Konfirmasi bahwa Golang berhasil upload PDF ke dedicated server. + * + * URL QR_PrintOutVerifyURL tidak berubah (sudah fix sejak saveQRPrintout). + * Fungsi ini hanya mengubah status → 'uploaded'. + * + * Alur Golang: + * 1. Poll getPendingUploads() → dapat row dengan: + * QR_PrintOutReportURL (fetch PDF dari PHP server via HTTP) + * QR_PrintOutVerifyURL (upload PDF ke dedicated server di path ini) + * 2. Download PDF dari QR_PrintOutReportURL + * 3. Upload ke dedicated server sesuai QR_PrintOutVerifyURL + * 4. Callback PHP: confirmUpload($uuid) + * + * @param string $uuid UUID record qr_printout + * @return array ['success' => bool, 'message' => string] + */ + public function confirmUpload($uuid) + { + $uuid = $this->_normalizeUUID($uuid); + + if (!$this->_validateUUIDFormat($uuid)) { + return ['success' => false, 'message' => 'Format UUID tidak valid.']; + } + + $exists = $this->db_smartone + ->where('QR_PrintOutUUID', $uuid) + ->count_all_results('qr_printout'); + + if ($exists === 0) { + return ['success' => false, 'message' => 'UUID tidak ditemukan di database.']; + } + + $this->db_smartone->where('QR_PrintOutUUID', $uuid) + ->update('qr_printout', [ + 'QR_PrintOutUploadStatus' => 'uploaded', + 'QR_PrintOutUploadedAt' => date('Y-m-d H:i:s'), + ]); + + if ($this->db_smartone->affected_rows() === 0) { + return ['success' => false, 'message' => 'Gagal update database.']; + } + + return ['success' => true, 'message' => 'OK']; + } + + /** + * Tandai upload gagal permanen tanpa menambah retry count. + * Gunakan ini hanya untuk override manual (mis. admin force-fail). + * Untuk kasus normal, gunakan incrementRetry() agar retry count terlacak. + * + * @param string $uuid + * @return bool + */ + public function markUploadFailed($uuid) + { + $uuid = $this->_normalizeUUID($uuid); + $this->db_smartone->where('QR_PrintOutUUID', $uuid) + ->update('qr_printout', [ + 'QR_PrintOutUploadStatus' => 'failed_permanent', + 'QR_PrintOutRetryCount' => 3, + ]); + return $this->db_smartone->affected_rows() > 0; + } + + /** + * Reset URL report (untuk upload ulang jika laporan direvisi). + * @deprecated Gunakan requestReUpload() yang lebih lengkap. + * + * @param string $uuid + * @return array ['success' => bool, 'message' => string] + */ + public function resetReportURL($uuid) + { + return $this->requestReUpload($uuid); + } + + // ========================================================================= + // PUBLIC METHODS — VERIFIKASI (dipakai dedicated server / controller publik) + // ========================================================================= + + /** + * Ambil URL PDF report berdasarkan UUID. + * + * Dipakai jika PHP app perlu tahu URL PDF (mis. untuk redirect). + * Scan tracking dihandle oleh dedicated server. + * + * @param string $uuid UUID (36 atau 32 char) + * @return array [ + * 'success' => bool, + * 'report_url' => string|null, + * 'qr_info' => array|null, + * 'message' => string + * ] + */ + public function getReportURL($uuid) + { + $uuid = $this->_normalizeUUID($uuid); + + if (!$this->_validateUUIDFormat($uuid)) { + return ['success' => false, 'report_url' => null, 'qr_info' => null, + 'message' => 'Format UUID tidak valid.']; + } + + $qrRow = $this->db_smartone + ->where('QR_PrintOutUUID', $uuid) + ->where('QR_PrintOutIsActive', 1) + ->get('qr_printout') + ->row_array(); + + if (!$qrRow) { + return ['success' => false, 'report_url' => null, 'qr_info' => null, + 'message' => 'QR Code tidak ditemukan atau sudah tidak aktif.']; + } + + // verifyURL = URL langsung ke PDF, hanya valid jika sudah ter-upload + if ($qrRow['QR_PrintOutUploadStatus'] !== 'uploaded') { + $status = $qrRow['QR_PrintOutUploadStatus']; + $msg = $status === 'failed_permanent' + ? 'Upload PDF gagal permanen. Hubungi admin laboratorium.' + : 'Report PDF sedang diproses. Coba beberapa saat lagi.'; + return ['success' => false, 'report_url' => null, 'qr_info' => $qrRow, 'message' => $msg]; + } + + return [ + 'success' => true, + 'report_url' => $qrRow['QR_PrintOutVerifyURL'], // URL langsung ke PDF + 'qr_info' => $qrRow, + 'message' => 'OK', + ]; + } + + // ========================================================================= + // LEGACY / UTILITY + // ========================================================================= + + function clean_mysqli_connection($dbc) + { + while (mysqli_more_results($dbc)) { + if (mysqli_next_result($dbc)) { + $result = mysqli_use_result($dbc); + if (get_class($result) == 'mysqli_stmt') { + mysqli_stmt_free_result($result); + } + else { + unset($result); + } + } + } + } +} \ No newline at end of file diff --git a/application/libraries/Genkelainan.php b/application/libraries/Genkelainan.php new file mode 100644 index 00000000..bd7e9dd7 --- /dev/null +++ b/application/libraries/Genkelainan.php @@ -0,0 +1,3250 @@ +db_smartone = $CI->load->database("default", true); + $this->db_smartone = $CI->load->database("default", true); + } + + function clean_mysqli_connection($dbc) + { + while (mysqli_more_results($dbc)) { + if (mysqli_next_result($dbc)) { + $result = mysqli_use_result($dbc); + + if (get_class($result) == 'mysqli_stmt') { + mysqli_stmt_free_result($result); + } + else { + unset($result); + } + } + } + } + + function dynamic_comparison($varleft, $op, $varright) + { + + switch ($op) { + case "=": + return $varleft == $varright; + case "!=": + return $varleft != $varright; + case ">=": + return $varleft >= $varright; + case "<=": + return $varleft <= $varright; + case ">": + return $varleft > $varright; + case "<": + return $varleft < $varright; + default: + return true; + } + } + + function generate_kelainan_lab($orderid = 0, $orderdetailID = 0, $userID = 0) + { + $errors = []; + if ($orderid != 0) { + $filterOrderID = " AND T_OrderHeaderID = {$orderid}"; + } + else { + $filterOrderID = ""; + } + if ($orderdetailID != 0) { + $filterDetailID = " AND T_OrderDetailID = {$orderdetailID}"; + } + else { + $filterDetailID = ""; + } + $sql = "SELECT + T_OrderHeaderID,T_OrderHeaderLabNumber, + T_TestName, T_OrderDetailID, T_OrderDetailResult, T_OrderDetailNat_MethodeID, + T_OrderDetailNat_MethodeID, T_OrderDetailNat_MethodeName, + T_OrderDetailMinValue, T_OrderDetailMaxValue, T_OrderDetailMinValueInclusive, + T_OrderDetailMaxValueInclusive, + Mcu_SummaryLabID, + Mcu_SummaryLabValue, + Mcu_SummaryLabNat_MethodeID, + Mcu_SummaryLabWithMethode, + Mcu_SummaryLabType, + Mcu_SummaryLabIsNormalValue, + Mcu_SummaryLabIsRange, + Mcu_SummaryLabMinInclusive, + Mcu_SummaryLabMinValue, + Mcu_SummaryLabMaxInclusive, + Mcu_SummaryLabMaxValue, + Mcu_KelainanID, Mcu_KelainanName, Mcu_KelainanClasification, + Nat_TestID, + Nat_TestCode, + mcu_kelainangroup.* + from t_orderdetail + join t_orderheader on T_OrderHeaderID = T_OrderDetailT_OrderHeaderID {$filterOrderID} {$filterDetailID} + and T_OrderHeaderID = T_OrderDetailT_OrderHeaderID + and T_OrderDetailIsActive = 'Y' + JOIN m_patient + ON T_OrderHeaderM_PatientID = M_PatientID + JOIN m_sex ON M_PatientM_SexID = M_SexID + join t_test + on T_OrderDetailT_TestID = T_TestID + join nat_test ON T_TestNat_TestID = Nat_TestID + join mcu_summarylab on T_TestNat_TestID = Mcu_SummaryLabNat_TestID AND Mcu_SummaryLabIsActive = 'Y' + AND (Mcu_SummaryLabGender = 'A' OR (Mcu_SummaryLabGender <> 'A' AND Mcu_SummaryLabGender = CASE + WHEN LOWER(M_SexNameLang) = 'male' THEN 'M' + WHEN LOWER(M_SexNameLang) = 'female' THEN 'F' + else '' + END)) + join mcu_kelainan on Mcu_SummaryLabMcu_KelainanID = Mcu_KelainanID + join mcu_kelainangroup on Mcu_KelainanMcu_KelainanGroupID = Mcu_KelainanGroupID"; + //echo $sql; + $qry = $this->db_smartone->query($sql); + if (!$qry) { + + $prm_log = ['SELECT_T_ORDERDETAIL_KELAINAN_LAB_1', 'kelainanlab/generate_kelainan_lab']; + $xsql = $this->db_smartone->last_query(); + $log_error = $this->insert_log_error($xsql, $prm_log, json_encode($errors)); + $errors[] = "SELECT_T_ORDERDETAIL_KELAINAN_LAB_1"; + } + + $rows = $qry->result_array(); + $results = []; + + + + foreach ($rows as $r) { + $result_value = $r['T_OrderDetailResult']; + + $value_comparison = 0; + //echo $r['Mcu_SummaryLabIsNormalValue']; + $kelainan = []; + $notavailable = []; + if (trim($result_value) == 'NA') { + $notavailable = $r; + } + elseif ($r['Mcu_SummaryLabIsNormalValue'] == 'Y') { + if ($r['Mcu_SummaryLabType'] == '<' || $r['Mcu_SummaryLabType'] == '<=') { + $value_comparison = $r['T_OrderDetailMinValue']; + } + if ($r['Mcu_SummaryLabType'] == '>' || $r['Mcu_SummaryLabType'] == '>=') { + $value_comparison = $r['T_OrderDetailMaxValue']; + } + //echo "Y"; + if ($r['Mcu_SummaryLabWithMethode'] == 'N' && $this->dynamic_comparison($result_value, $r['Mcu_SummaryLabType'], $value_comparison)) { + //echo $r['T_TestName']." : ".$r['Mcu_KelainanName'].", "; + $kelainan = $r; + $results[] = array('test' => $r['T_TestName'], 'nat_test' => $r['Nat_TestCode'], 'kelainan' => $r['Mcu_KelainanName'], 'orderdetailID' => $r['T_OrderDetailID'], 'orderheaderID' => $r['T_OrderHeaderID'], 'nat_testID' => $r['Nat_TestID'], 'mcu_summarylabID' => $r['Mcu_SummaryLabID']); + } + } + else if ($r['Mcu_SummaryLabIsRange'] == 'Y') { + // Mcu_SummaryLabIsNormalValue, + // Mcu_SummaryLabIsRange, + // Mcu_SummaryLabMinInclusive, + // Mcu_SummaryLabMinValue, + // Mcu_SummaryLabMaxInclusive, + // Mcu_SummaryLabMaxValue, + $isWithinMin = $r['Mcu_SummaryLabMinInclusive'] === 'Y' ? floatval($result_value) >= floatval($r['Mcu_SummaryLabMinValue']) : floatval($result_value) > floatval($r['Mcu_SummaryLabMinValue']); + $isWithinMax = $r['Mcu_SummaryLabMaxInclusive'] === 'Y' ? floatval($result_value) <= floatval($r['Mcu_SummaryLabMaxValue']) : floatval($result_value) < floatval($r['Mcu_SummaryLabMaxValue']); + + if ($isWithinMax && $isWithinMin) { + $kelainan = $r; + $results[] = array('test' => $r['T_TestName'], 'nat_test' => $r['Nat_TestCode'], 'kelainan' => $r['Mcu_KelainanName'], 'orderdetailID' => $r['T_OrderDetailID'], 'orderheaderID' => $r['T_OrderHeaderID'], 'nat_testID' => $r['Nat_TestID'], 'mcu_summarylabID' => $r['Mcu_SummaryLabID']); + } + } + else { + $value_comparison = $r['Mcu_SummaryLabValue']; + if ($r['Mcu_SummaryLabType'] == '!=' || $r['Mcu_SummaryLabType'] == '==') { + if ($this->dynamic_comparison($result_value, $r['Mcu_SummaryLabType'], $value_comparison)) { + //echo $r['T_TestName']." : ".$r['Mcu_KelainanName'].", "; + $kelainan = $r; + $results[] = array('test' => $r['T_TestName'], 'nat_test' => $r['Nat_TestCode'], 'kelainan' => $r['Mcu_KelainanName'], 'orderdetailID' => $r['T_OrderDetailID'], 'orderheaderID' => $r['T_OrderHeaderID'], 'nat_testID' => $r['Nat_TestID'], 'mcu_summarylabID' => $r['Mcu_SummaryLabID']); + } + } + else { + if (is_numeric($result_value) && $this->dynamic_comparison($result_value, $r['Mcu_SummaryLabType'], $value_comparison)) { + //echo $r['T_TestName']." : ".$r['Mcu_KelainanName'].", "; + $kelainan = $r; + $results[] = array('test' => $r['T_TestName'], 'nat_test' => $r['Nat_TestCode'], 'kelainan' => $r['Mcu_KelainanName'], 'orderdetailID' => $r['T_OrderDetailID'], 'orderheaderID' => $r['T_OrderHeaderID'], 'nat_testID' => $r['Nat_TestID'], 'mcu_summarylabID' => $r['Mcu_SummaryLabID']); + } + } + } + + if (count($results) > 0) { + $sql_update_kel = ""; + if ($orderdetailID != 0) { + $sql_update_kel = "UPDATE t_kelainan_lab + SET T_KelainanLabIsActive = 'N' + WHERE + T_KelainanLabT_OrderDetailID = {$orderdetailID}"; + } + else { + $sql_update_kel = "UPDATE t_kelainan_lab + SET T_KelainanLabIsActive = 'N' + WHERE + T_KelainanLabT_OrderHeaderID = {$orderid}"; + + } + $qry_update_kel = $this->db_smartone->query($sql_update_kel); + if (!$qry_update_kel) { + $prm_log = ['UPDATE_T_KELAINAN_LAB_N', 'kelainanlab/generate_kelainan_lab']; + $xsql = $this->db_smartone->last_query(); + $log_error = $this->insert_log_error($xsql, $prm_log, json_encode(['orderid' => $orderid, 'orderdetailID' => $orderdetailID])); + $errors[] = "UPDATE_T_KELAINAN_LAB_N"; + } + + foreach ($results as $v_result) { + $sql_kel_lab = "SELECT * + FROM t_kelainan_lab + WHERE T_KelainanLabT_OrderDetailID = ? + GROUP BY T_KelainanLabT_OrderDetailID"; + $qry_kel_lab = $this->db_smartone->query($sql_kel_lab, array($v_result['orderdetailID'])); + if ($qry_kel_lab) { + $rows_kel = $qry_kel_lab->result_array(); + } + else { + $prm_log = ['SELECT_T_KELAINAN_LAB', 'kelainanlab/generate_kelainan_lab']; + $xsql = $this->db_smartone->last_query(); + $log_error = $this->insert_log_error($xsql, $prm_log, json_encode($v_result)); + $errors[] = "SELECT_T_KELAINAN_LAB"; + } + + if (count($rows_kel) > 0) { + + // print_r($v_result['orderdetailID']); + // exit; + + $sql_update_kel = "UPDATE t_kelainan_lab + SET T_KelainanLabT_OrderDetailID = {$v_result['orderdetailID']}, + T_KelainanLabT_OrderHeaderID = {$v_result['orderheaderID']}, + T_KelainanLabNat_TestID = {$v_result['nat_testID']}, + T_KelainanLabMcu_SummaryLabID = {$v_result['mcu_summarylabID']}, + T_KelainanLabCreatedUserID = {$userID}, + T_KelainanLabIsActive = 'Y', + T_KelainanLabCreated = NOW() + WHERE T_KelainanLabID = {$rows_kel[0]['T_KelainanLabID']}"; + $qry_update_kel = $this->db_smartone->query($sql_update_kel); + if (!$qry_update_kel) { + $prm_log = ['UPDATE_T_KELAINAN_LAB', 'kelainanlab/generate_kelainan_lab']; + $xsql = $this->db_smartone->last_query(); + $log_error = $this->insert_log_error($xsql, $prm_log, json_encode($v_result)); + $errors[] = "UPDATE_T_KELAINAN_LAB"; + } + } + else { + // print_r('insert'); + // exit; + $sql_insert_lab = "INSERT INTO t_kelainan_lab( + T_KelainanLabT_OrderDetailID, + T_KelainanLabT_OrderHeaderID, + T_KelainanLabNat_TestID, + T_KelainanLabMcu_SummaryLabID, + T_KelainanLabCreatedUserID, + T_KelainanLabCreated) + VALUES( + '{$v_result['orderdetailID']}', + '{$v_result['orderheaderID']}', + '{$v_result['nat_testID']}', + '{$v_result['mcu_summarylabID']}', + {$userID}, + NOW())"; + $qry_insert_lab = $this->db_smartone->query($sql_insert_lab); + + if (!$qry_insert_lab) { + $prm_log = ['INSERT_T_KELAINAN_LAB', 'kelainanlab/generate_kelainan_lab']; + $xsql = $this->db_smartone->last_query(); + $log_error = $this->insert_log_error($xsql, $prm_log, json_encode($v_result)); + $errors[] = "INSERT_T_KELAINAN_LAB"; + } + } + } + } + } + + return $errors; + } + + function generate_kelainan_nonlab($orderID = 0, $so_resultentryID = 0, $userID = 0) + { + $errors = []; + if ($orderID != 0) { + $filterOrderID = " AND T_OrderHeaderID = {$orderID}"; + } + else { + $filterOrderID = ""; + } + if ($so_resultentryID != 0) { + $filterSoResultEntryID = " AND So_ResultEntryID = {$so_resultentryID}"; + } + else { + $filterSoResultEntryID = ""; + } + $sql = "SELECT So_ResultEntryID, T_OrderHeaderID, T_TestNat_TestID, Mcu_SummaryNonlabID, Mcu_SummaryNonlabMcu_KelainanID, Mcu_SummaryNonlabID + FROM so_resultentry_category_result + JOIN so_resultentry ON So_ResultEntryCategoryResultSo_ResultEntryID = So_ResultEntryID AND + So_ResultEntryStatus <> 'NEW' AND So_ResultEntryIsActive = 'Y' {$filterSoResultEntryID} + JOIN t_orderheader ON So_ResultEntryT_OrderHeaderID = T_OrderHeaderID AND T_OrderHeaderIsActive = 'Y' + {$filterOrderID} + JOIN t_orderdetail ON So_ResultEntryT_OrderDetailID = T_OrderDetailID AND T_OrderDetailIsActive = 'Y' + JOIN t_test ON T_OrderDetailT_TestID = T_TestID + JOIN mcu_summarynonlab ON Mcu_SummaryNonlabNat_TestID = T_TestNat_TestID AND + Mcu_SummaryNonlabIsActive = 'Y' AND So_ResultEntryCategoryNonlabConclusionDetailID IN (Mcu_SummaryNonlabConclusionDetailIDs) + WHERE + So_ResultEntryCategoryResultIsActive = 'Y'"; + + $qry = $this->db_smartone->query($sql, array($orderID)); + if (!$qry) { + $prm_log = ['SELECT_T_KELAINAN_NONLAB_1', 'genkelainan/generate_kelainan_nonlab']; + $xsql = $this->db_smartone->last_query(); + $log_error = $this->insert_log_error($xsql, $prm_log, json_encode(['orderID' => $orderID, 'so_resultentryID' => $so_resultentryID])); + $errors[] = "SELECT_T_KELAINAN_NONLAB_1"; + } + + $rows = $qry->result_array(); + if ($orderID != 0) { + $sql = "UPDATE t_kelainan_nonlab SET + T_KelainanNonLabIsActive = 'N' + WHERE + T_KelainanNonLabT_OrderHeaderID = {$orderID} AND + T_KelainanNonLabIsActive = 'Y' + "; + } + else { + $sql = "UPDATE t_kelainan_nonlab SET + T_KelainanNonLabIsActive = 'N' + WHERE + T_KelainanNonLabSo_ResultEntryID = {$so_resultentryID} AND + T_KelainanNonLabIsActive = 'Y' + "; + } + $qry = $this->db_smartone->query($sql); + if (!$qry) { + $prm_log = ['UPDATE_T_KELAINAN_NONLAB_N', 'genkelainan/generate_kelainan_nonlab']; + $xsql = $this->db_smartone->last_query(); + $log_error = $this->insert_log_error($xsql, $prm_log, json_encode(['orderID' => $orderID, 'so_resultentryID' => $so_resultentryID])); + $errors[] = "UPDATE_T_KELAINAN_NONLAB_N"; + } + + foreach ($rows as $key => $value) { + + + $sql = "INSERT INTO t_kelainan_nonlab ( + T_KelainanNonLabSo_ResultEntryID, + T_KelainanNonLabT_OrderHeaderID, + T_KelainanNonLabNat_TestID, + T_KelainanNonLabMcu_SummaryNonlabID, + T_KelainanNonLabCreatedUserID, + T_KelainanLabNonCreated + ) VALUES(?,?,?,?,?,NOW())"; + $qry = $this->db_smartone->query($sql, [ + $value['So_ResultEntryID'], + $value['T_OrderHeaderID'], + $value['T_TestNat_TestID'], + $value['Mcu_SummaryNonlabID'], + $userID + ]); + if (!$qry) { + $prm_log = ['INSERT_T_KELAINAN_NONLAB', 'genkelainan/generate_kelainan_nonlab']; + $xsql = $this->db_smartone->last_query(); + $log_error = $this->insert_log_error($xsql, $prm_log, json_encode($value)); + $errors[] = "INSERT_T_KELAINAN_NONLAB"; + } + } + + return $errors; + + } + + function generate_all_fisik($orderID, $userid) + { + $errors = []; + $errors = array_merge($errors, $this->status_gizi($orderID, $userid)); + $errors = array_merge($errors, $this->persepsi_warna($orderID, $userid)); + $errors = array_merge($errors, $this->visus($orderID, $userid)); + $errors = array_merge($errors, $this->keluhan($orderID, $userid)); + $errors = array_merge($errors, $this->riwayat_penyakit($orderID, $userid)); + $errors = array_merge($errors, $this->penyakit_keluarga($orderID, $userid)); + $errors = array_merge($errors, $this->kebiasaan_hidup($orderID, $userid)); + $errors = array_merge($errors, $this->fisik_konsumsiobatteratur($orderID, $userid)); + $errors = array_merge($errors, $this->imunasi($orderID, $userid)); + $errors = array_merge($errors, $this->vital_sign($orderID, $userid)); + + $errors = array_merge($errors, $this->keadaan_umum($orderID, $userid)); + $errors = array_merge($errors, $this->kepala_wajah($orderID, $userid)); + $errors = array_merge($errors, $this->mata($orderID, $userid)); + $errors = array_merge($errors, $this->lapang_pandang($orderID, $userid)); + $errors = array_merge($errors, $this->telinga($orderID, $userid)); + $errors = array_merge($errors, $this->hidung($orderID, $userid)); + $errors = array_merge($errors, $this->gigi($orderID, $userid)); + $errors = array_merge($errors, $this->mulut($orderID, $userid)); + $errors = array_merge($errors, $this->leher($orderID, $userid)); + $errors = array_merge($errors, $this->thorax($orderID, $userid)); + $errors = array_merge($errors, $this->paru($orderID, $userid)); + $errors = array_merge($errors, $this->jantung($orderID, $userid)); + $errors = array_merge($errors, $this->perut($orderID, $userid)); + $errors = array_merge($errors, $this->sistem_integumen($orderID, $userid)); + $errors = array_merge($errors, $this->genitourinaria($orderID, $userid)); + $errors = array_merge($errors, $this->anggota_gerak($orderID, $userid)); + $errors = array_merge($errors, $this->sistem_persyarafan($orderID, $userid)); + $errors = array_merge($errors, $this->smell_test($orderID, $userid)); + $errors = array_merge($errors, $this->low_back_pain_screening_test($orderID, $userid)); + $errors = array_merge($errors, $this->loop_k3($orderID, $userid)); + + $this->generate_summaries($orderID, $userid); + + return $errors; + } + + + + function status_gizi($id, $userid) + { + $errors = []; + $sql = "SELECT * + FROM t_samplingso_additional_fisik_bbtb + WHERE + T_SamplingAdditionalFisikBBTBT_OrderHeaderID = ? AND + T_SamplingAdditionalFisikBBTBIsActive = 'Y' + LIMIT 1"; + $qry = $this->db_smartone->query($sql, array($id)); + if (!$qry) { + $prm_log = ['SELECT_T_SAMPLINGSO_ADDITIONAL_FISIK_BBTB', 'genkelainan/status_gizi']; + $xsql = $this->db_smartone->last_query(); + $log_error = $this->insert_log_error($xsql, $prm_log, json_encode(['id' => $id])); + $errors[] = "SELECT_T_SAMPLINGSO_ADDITIONAL_FISIK_BBTB"; + } + //echo $this->db_smartone->last_query(); + $row_results = $qry->result_array(); + //print_r($row_result); + if (count($row_results) > 0) { + $row_result = $row_results[0]; + $status_gizi = array(); + $bb = $row_result["T_SamplingAdditionalFisikBBTBValueBB"]; + $tb = $row_result["T_SamplingAdditionalFisikBBTBValueTB"]; + $standart_bmi = $row_result["T_SamplingAdditionalFisikBBTBStandart"]; + $get_bmi = $this->hitung_bmi($bb, $tb, $standart_bmi); + $bmi = $get_bmi['bmi']; + + $classification = $get_bmi['class']; + //echo $classification; + + $data_insert_tb = array( + 'code' => 'tb', + 'label' => $tb, + 'note' => $tb, + 'segment' => 'status_gizi', + 'category' => '', + 'order_id' => $id + ); + $errors = array_merge($errors, $this->insert_data_etl($data_insert_tb, $userid)); + //$this->insert_code('tb',$tb); + + $data_insert_bb = array( + 'code' => 'bb', + 'label' => $bb, + 'note' => $bb, + 'segment' => 'status_gizi', + 'category' => '', + 'order_id' => $id + ); + $errors = array_merge($errors, $this->insert_data_etl($data_insert_bb, $userid)); + //$this->insert_code('bb',$bb); + + $data_insert_bmi = array( + 'code' => 'bmi', + 'label' => $bmi, + 'note' => $bmi, + 'segment' => 'status_gizi', + 'category' => $standart_bmi, + 'order_id' => $id + ); + $errors = array_merge($errors, $this->insert_data_etl($data_insert_bmi, $userid)); + //$this->insert_code('bmi',$bmi); + + $data_insert_bmi_class = array( + 'code' => 'bmi_classification_' . $standart_bmi, + 'label' => $classification, + 'note' => $classification, + 'segment' => 'status_gizi', + 'category' => $standart_bmi, + 'order_id' => $id + ); + //print_r($data_insert_bmi_class); + $errors = array_merge($errors, $this->insert_data_etl($data_insert_bmi_class, $userid)); + //$this->insert_code('bmi_classification_'.$standart_bmi,$classification); + } + + return $errors; + } + + function persepsi_warna($id, $userid) + { + $errors = []; + $sql = "SELECT IFNULL(T_SamplingAdditionalFisikBWPWValue,'Z') as result, + IFNULL(T_SamplingAdditionalFisikBWPWVAngka,'') as angka + FROM t_samplingso_additional_fisik_bw + WHERE + T_SamplingAdditionalFisikBWT_OrderHeaderID = ? + LIMIT 1"; + $qry = $this->db_smartone->query($sql, array($id)); + if (!$qry) { + $prm_log = ['SELECT_T_SAMPLINGSO_ADDITIONAL_FISIK_BWPW', 'genkelainan/persepsi_warna']; + $xsql = $this->db_smartone->last_query(); + $log_error = $this->insert_log_error($xsql, $prm_log, json_encode(['id' => $id])); + $errors[] = "SELECT_T_SAMPLINGSO_ADDITIONAL_FISIK_BWPW"; + } + + + $row_results = $qry->result_array(); + if (count($row_results) > 0) { + $row_result = $row_results[0]; + $hasil = 'Bahan belum'; + if ($row_result['result'] == 'BW') { + $hasil = 'Red Green Deficiency'; + } + if ($row_result['result'] == 'N') { + $hasil = 'Normal'; + } + if ($row_result['result'] == 'X') { + $hasil = 'Tidak dilakukan'; + } + $data_insert_bw = array( + 'code' => 'bw', + 'label' => $row_result['result'], + 'note' => $hasil, + 'segment' => 'mata', + 'category' => '', + 'order_id' => $id + ); + $errors = array_merge($errors, $this->insert_data_etl($data_insert_bw, $userid)); + //$this->insert_code('bw',$row_result['result']); + + $data_insert_bwv = array( + 'code' => 'bw_value', + 'label' => $row_result['angka'], + 'note' => $row_result['angka'], + 'segment' => 'mata', + 'category' => '', + 'order_id' => $id + ); + $errors = array_merge($errors, $this->insert_data_etl($data_insert_bwv, $userid)); + //$this->insert_code('bw_value',$row_result['angka']); + } + + + return $errors; + } + + + + function hitung_bmi($bb, $tb, $standart_bmi) + { + $tb = $tb / 100; + $bmi = ''; + $classs = ""; + $bmi_valuex = 0; + if (intval($bb) != 0 && intval($tb) != 0) { + $bmi = $bb / ($tb * $tb); + $bmi_valuex = number_format($bmi, 2); + + if ($standart_bmi === 'asia_pacific') { + if ($bmi_valuex < 18.5) + $classs = 'Underweight'; + + if ($bmi_valuex >= 18.5 && $bmi_valuex < 23) + $classs = 'Normal'; + + if ($bmi_valuex >= 23 && $bmi_valuex < 25) + $classs = 'Overweight'; + + if ($bmi_valuex >= 25 && $bmi_valuex < 30) + $classs = 'Obese I'; + + if ($bmi_valuex >= 30) + $classs = 'Obese II'; + } + + if ($standart_bmi === 'who') { + if ($bmi_valuex < 18.5) + $classs = 'Underweight'; + + if ($bmi_valuex >= 18.5 && $bmi_valuex < 25) { + $classs = 'Normal'; + } + + if ($bmi_valuex >= 25 && $bmi_valuex < 30) { + $classs = 'Overweight'; + } + + if ($bmi_valuex >= 30) + $classs = 'Obese'; + } + + if ($standart_bmi === 'kemenkes') { + if ($bmi_valuex < 18.5) + $classs = 'Underweight'; + + if ($bmi_valuex >= 18.5 && $bmi_valuex < 25.1) + $classs = 'Normal'; + + if ($bmi_valuex >= 25.1 && $bmi_valuex < 27) + $classs = 'Overweight'; + + if ($bmi_valuex >= 27) + $classs = 'Obese'; + } + } + + + + + + return array( + 'bmi' => $bmi_valuex, + 'class' => $classs + ); + } + + function visus($orderID, $userid) + { + $errors = []; + $ret_array = []; + + $sql = " SELECT * , T_SamplingAdditionalFisikVisusID as visus_id + FROM t_samplingso_additional_fisik_visus + WHERE + T_SamplingAdditionalFisikVisusT_OrderHeaderID = ? LIMIT 1"; + $qry = $this->db_smartone->query($sql, array($orderID)); + if (!$qry) { + $prm_log = ['SELECT_T_SAMPLINGSO_ADDITIONAL_FISIK_VISUS', 'genkelainan/visus']; + $xsql = $this->db_smartone->last_query(); + $log_error = $this->insert_log_error($xsql, $prm_log, json_encode(['orderID' => $orderID])); + $errors[] = "SELECT_T_SAMPLINGSO_ADDITIONAL_FISIK_VISUS"; + } + + $row_result = $qry->row_array(); + //echo $this->db_smartone->last_query(); + + + if ($row_result && intval($row_result['visus_id']) > 0) { + + + + $visus = array(); + $visus_kiri = ""; + $visus_kanan = ""; + $visus_kesimpulan = ""; + $normal = array("20/20", "20/25", "6/6", "6/7.5", "6/7,5"); + $miopia_od = false; + $miopia_os = false; + $miopia_od_value = ''; + $miopia_os_value = ''; + $astigmatismus_od = false; + $astigmatismus_os = false; + $astigmatismus_od_value = ''; + $astigmatismus_os_value = ''; + $presbiopia_ods = false; + $presbiopia_ods_value = ''; + $x_od = false; + $x_os = false; + $x_od_value = ""; + $x_os_value = ""; + $od_visus = "20/20"; + $os_visus = "20/20"; + if ($row_result['T_SamplingAdditionalFisikVisusTKODV'] == '6/7,5' || $row_result['T_SamplingAdditionalFisikVisusTKODV'] == '6/6' || $row_result['T_SamplingAdditionalFisikVisusTKODV'] == '6/7.5') + $od_visus = $row_result['T_SamplingAdditionalFisikVisusTKODV']; + + if ($row_result['T_SamplingAdditionalFisikVisusTKOSV'] == '6/7,5' || $row_result['T_SamplingAdditionalFisikVisusTKOSV'] == '6/6' || $row_result['T_SamplingAdditionalFisikVisusTKOSV'] == '6/7.5') + $os_visus = $row_result['T_SamplingAdditionalFisikVisusTKOSV']; + + + + if ((strtolower($row_result['T_SamplingAdditionalFisikVisusTKODV']) != "normal" && $row_result['T_SamplingAdditionalFisikVisusTKODV'] != "" && $row_result['T_SamplingAdditionalFisikVisusTKODV'] != "-") && ($row_result['T_SamplingAdditionalFisikVisusTKOSV'] != "" && $row_result['T_SamplingAdditionalFisikVisusTKOSV'] != "-" && strtolower($row_result['T_SamplingAdditionalFisikVisusTKODV']) != "normal" && strtolower($row_result['T_SamplingAdditionalFisikVisusTKOSV']) != "normal")) { + $visus[] = array( + "xx1" => "Tanpa Kacamata", + "xx2" => "OD : ", + "xx3" => $row_result['T_SamplingAdditionalFisikVisusTKODV'] + ); + + $visus[] = array( + "xx1" => "Tanpa Kacamata", + "xx2" => "OS", + "xx3" => $row_result['T_SamplingAdditionalFisikVisusTKOSV'] + ); + + + $rst['kelainan'] = "Kelainan refraksi (tanpa kacamata)"; + + if (!in_array($row_result['T_SamplingAdditionalFisikVisusTKODV'], $normal)) { + $value_koreksi_od = ""; + $od_sph = $row_result['T_SamplingAdditionalFisikVisusODSPH']; + if ($od_sph != "" && $od_sph != "-" && $od_sph != "--" && $od_sph != "/-" && $od_sph != "/" && $od_sph != "-/" && strtolower(trim($od_sph)) != 'plano') { + if ($visus_kanan != "") + $visus_kanan .= ", "; + $visus_kanan .= $od_sph . " (Miopia)"; + + $miopia_od = true; + $miopia_od_value = $od_sph; + } + + + $od_cyl = $row_result['T_SamplingAdditionalFisikVisusODCYL']; + + //$od_cyl = $row_result['T_SamplingAdditionalFisikVisusODCYL']; + if ($od_cyl != "" && $od_cyl != "-" && $od_cyl != "--" && $od_cyl != "/-" && $od_cyl != "/" && $od_cyl != "-/") { + if ($visus_kanan != "") + $visus_kanan .= ", "; + $visus_kanan .= "Cyl " . $od_cyl; + + $astigmatismus_od = true; + $astigmatismus_od_value = $od_cyl; + } + + + $od_x = $row_result['T_SamplingAdditionalFisikVisusODX']; + //echo $od_x; + if ($od_x != "" && $od_x != "-" && $od_x != "--" && $od_x != "/-" && $od_x != "/" && $od_x != "-/") { + $visus_kanan .= " axis " . $od_x . " (Astigmatismus)"; + $x_od = true; + $x_od = $od_x; + } + else { + if ($od_cyl != "" && $od_cyl != "-" && $od_cyl != "--" && $od_cyl != "/-" && $od_cyl != "/" && $od_cyl != "-/") + $visus_kanan .= " (Astigmatismus)"; + } + //$value_koreksi_od .= "X (".$od_x.") "; + + + + } + + if (!in_array($row_result['T_SamplingAdditionalFisikVisusTKOSV'], $normal)) { + $value_koreksi_os = ""; + $os_sph = $row_result['T_SamplingAdditionalFisikVisusOSSPH']; + if (strtolower(trim($os_sph)) != "tidak terkoreksi" && strtolower(trim($os_sph)) != "tidak dapat dinilai" && $os_sph != "" && $os_sph != "-" && $os_sph != "--" && $os_sph != "/-" && $os_sph != "/" && $os_sph != "-/" && strtolower(trim($os_sph)) != 'plano') { + if ($visus_kiri != "") + $visus_kiri .= ", "; + $visus_kiri .= $os_sph . " (Miopia)"; + + $miopia_os = true; + $miopia_os_value = $os_sph; + } + + $os_cyl = $row_result['T_SamplingAdditionalFisikVisusOSCYL']; + + if (strtolower(trim($os_cyl)) != "tidak terkoreksi" && strtolower(trim($os_cyl)) != "tidak dapat dinilai" && $os_cyl != "" && $os_cyl != "-" && $os_cyl != "--" && $os_cyl != "/-" && $os_cyl != "/" && $os_cyl != "-/") { + if ($visus_kiri != "") + $visus_kiri .= ", "; + $visus_kiri .= "Cyl " . $os_cyl; + + $astigmatismus_os = true; + $astigmatismus_os_value = $os_cyl; + } + + + $os_x = $row_result['T_SamplingAdditionalFisikVisusOSX']; + + if (strtolower(trim($os_x)) != "tidak terkoreksi" && strtolower(trim($os_x)) != "tidak dapat dinilai" && $os_x != "" && $os_x != "-" && $os_x != "--" && $os_x != "/-" && $os_x != "/" && $os_x != "-/") { + //if ($visus_kiri != "") $visus_kiri .= ", "; + $visus_kiri .= " axis " . $os_x . " (Astigmatismus)"; + $x_os = true; + $x_os = $os_x; + } + else { + if ($os_cyl != "" && $os_cyl != "-") + $visus_kiri .= " (Astigmatismus)"; + } + + } + + } + + if ((strtolower($row_result['T_SamplingAdditionalFisikVisusDKODV']) != "normal" && $row_result['T_SamplingAdditionalFisikVisusDKODV'] != "" && $row_result['T_SamplingAdditionalFisikVisusDKODV'] != "-") && ($row_result['T_SamplingAdditionalFisikVisusDKOSV'] != "" && $row_result['T_SamplingAdditionalFisikVisusDKOSV'] != "-" && strtolower($row_result['T_SamplingAdditionalFisikVisusDKODV']) != "normal" && strtolower($row_result['T_SamplingAdditionalFisikVisusDKOSV']) != "normal")) { + $visus[] = array( + "xx1" => "Dengan Kacamata", + "xx2" => "OD : ", + "xx3" => $row_result['T_SamplingAdditionalFisikVisusDKODV'] + ); + + $visus[] = array( + "xx1" => "Dengan Kacamata", + "xx2" => "OS", + "xx3" => $row_result['T_SamplingAdditionalFisikVisusDKOSV'] + ); + + $rst['kelainan'] = "Kelainan refraksi (dengan kacamata)"; + $od_visus = $row_result['T_SamplingAdditionalFisikVisusDKODV']; + $os_visus = $row_result['T_SamplingAdditionalFisikVisusDKOSV']; + + + $value_koreksi_od = ""; + $od_sph = $row_result['T_SamplingAdditionalFisikVisusODSPH']; + if (strtolower(trim($od_sph)) != "tidak terkoreksi" && strtolower(trim($od_sph)) != "tidak dapat dinilai" && $od_sph != "" && $od_sph != "-" && $od_sph != "--" && $od_sph != "/-" && $od_sph != "/" && $od_sph != "-/" && strtolower(trim($od_sph)) != 'plano') { + if ($visus_kanan != "") + $visus_kanan .= ", "; + $visus_kanan .= $od_sph . " (Miopia)"; + + $miopia_od = true; + $miopia_od_value = $od_sph; + } + + $od_cyl = $row_result['T_SamplingAdditionalFisikVisusODCYL']; + + if (strtolower(trim($od_cyl)) != "tidak terkoreksi" && strtolower(trim($od_cyl)) != "tidak dapat dinilai" && $od_cyl != "" && $od_cyl != "-" && $od_cyl != "--" && $od_cyl != "/-" && $od_cyl != "/" && $od_cyl != "-/") { + if ($visus_kanan != "") + $visus_kanan .= ", "; + $visus_kanan .= "Cyl " . $od_cyl; + + $astigmatismus_od = true; + $astigmatismus_od_value = $od_cyl; + } + + $od_x = $row_result['T_SamplingAdditionalFisikVisusODX']; + if (strtolower(trim($od_x)) != "tidak terkoreksi" && strtolower(trim($od_x)) != "tidak dapat dinilai" && $od_x != "" && $od_x != "-" && $od_x != "--" && $od_x != "/-" && $od_x != "/" && $od_x != "-/") { + //if ($visus_kanan != "") $visus_kanan .= ", "; + $visus_kanan .= " axis " . $od_x . " (Astigmatismus)"; + $x_od = true; + $x_od = $od_x; + } + else { + if ($od_cyl != "" && $od_cyl != "-" && $od_cyl != "--" && $od_cyl != "/-" && $od_cyl != "/" && $od_cyl != "-/") + $visus_kanan .= " (Astigmatismus)"; + } + //$value_koreksi_od .= "X (".$od_x.") "; + + + + + + $value_koreksi_os = ""; + $os_sph = $row_result['T_SamplingAdditionalFisikVisusOSSPH']; + if (strtolower(trim($os_sph)) != "tidak terkoreksi" && strtolower(trim($os_sph)) != "tidak dapat dinilai" && $os_sph != "" && $os_sph != "-" && $os_sph != "--" && $os_sph != "/-" && $os_sph != "/" && $os_sph != "-/" && strtolower(trim($os_sph)) != 'plano') { + if ($visus_kiri != "") + $visus_kiri .= ", "; + $visus_kiri .= $os_sph . " (Miopia)"; + + $miopia_os = true; + $miopia_os_value = $os_sph; + } + + $os_cyl = $row_result['T_SamplingAdditionalFisikVisusOSCYL']; + + if (strtolower(trim($os_cyl)) != "tidak terkoreksi" && strtolower(trim($os_cyl)) != "tidak dapat dinilai" && $os_cyl != "" && $os_cyl != "-" && $os_cyl != "--" && $os_cyl != "/-" && $os_cyl != "/" && $os_cyl != "-/") { + if ($visus_kiri != "") + $visus_kiri .= ", "; + $visus_kiri .= "Cyl " . $os_cyl; + + $astigmatismus_os = true; + $astigmatismus_os_value = $os_cyl; + } + + $os_x = $row_result['T_SamplingAdditionalFisikVisusOSX']; + + if (strtolower(trim($os_x)) != "tidak terkoreksi" && strtolower(trim($os_x)) != "tidak dapat dinilai" && $os_x != "" && $os_x != "-" && $os_x != "--" && $os_x != "/-" && $os_x != "/" && $os_x != "-/") { + $visus_kiri .= " axis " . $os_x . " (Astigmatismus)"; + $x_os = true; + $x_os = $os_x; + } + else { + if ($os_cyl != "" && $os_cyl != "-" && $os_cyl != "--" && $os_cyl != "/-" && $os_cyl != "/" && $os_cyl != "-/") + $visus_kiri .= " (Astigmatismus)"; + } + //$value_koreksi_os .= "X (".$os_x.") "; + + + } + + if (($row_result['T_SamplingAdditionalFisikVisusTKODV'] != "" && $row_result['T_SamplingAdditionalFisikVisusTKODV'] != "-") && ($row_result['T_SamplingAdditionalFisikVisusTKOSV'] != "" && $row_result['T_SamplingAdditionalFisikVisusTKOSV'] != "-")) { + if (!in_array($row_result['T_SamplingAdditionalFisikVisusTKODV'], $normal) && $visus_kanan == '') { + $visus_kanan = "Miopia"; + $miopia_od = true; + $miopia_od_value = ""; + } + + if (!in_array($row_result['T_SamplingAdditionalFisikVisusTKOSV'], $normal) && $visus_kiri == '') { + $visus_kiri = "Miopia"; + $miopia_os = true; + $miopia_os_value = ""; + } + } + + if (($row_result['T_SamplingAdditionalFisikVisusDKODV'] != "" && $row_result['T_SamplingAdditionalFisikVisusDKODV'] != "-") && ($row_result['T_SamplingAdditionalFisikVisusDKOSV'] != "" && $row_result['T_SamplingAdditionalFisikVisusDKOSV'] != "-")) { + if (!in_array($row_result['T_SamplingAdditionalFisikVisusDKODV'], $normal) && $visus_kanan == '') { + $visus_kanan = "Miopia"; + $miopia_od = true; + $miopia_od_value = ""; + } + + if (!in_array($row_result['T_SamplingAdditionalFisikVisusDKOSV'], $normal) && $visus_kiri == '') { + $visus_kiri = "Miopia"; + $miopia_os = true; + $miopia_os_value = ""; + } + } + + $od_add = $row_result['T_SamplingAdditionalFisikVisusADD']; + if ($od_add != "" && $od_add != "-" && $od_add != "--" && $od_add != "/-" && $od_add != "/" && $od_add != "-/") { + if ($visus_kanan != "") + $visus_kanan .= ", "; + $visus_kanan .= $od_add . " (Presbiopia)"; + + if ($visus_kiri != "") + $visus_kiri .= ", "; + $visus_kiri .= $od_add . " (Presbiopia)"; + + + $presbiopia_ods = true; + $presbiopia_ods_value = $od_add; + } + + + + } + + $data_insert = array( + 'code' => 'visus', + 'label' => 'visus', + 'note' => $rst['kelainan'], + 'segment' => 'visus', + 'category' => 'mata', + 'order_id' => $orderID + ); + $errors = array_merge($errors, $this->insert_data_etl($data_insert, $userid)); + //$this->insert_code('visus','visus'); + + if ($miopia_od) { + $data_insert = array( + 'code' => 'visus_miopia_od', + 'label' => 'visus Miopia OD', + 'note' => $miopia_od_value, + 'segment' => 'visus', + 'category' => 'mata', + 'order_id' => $orderID + ); + $errors = array_merge($errors, $this->insert_data_etl($data_insert, $userid)); + //$this->insert_code('visus_miopia_od','visus Miopia OD'); + } + if ($miopia_os) { + $data_insert = array( + 'code' => 'visus_miopia_os', + 'label' => 'visus Miopia OS', + 'note' => $miopia_os_value, + 'segment' => 'visus', + 'category' => 'mata', + 'order_id' => $orderID + ); + $errors = array_merge($errors, $this->insert_data_etl($data_insert, $userid)); + //$this->insert_code('visus_miopia_os','visus Miopia OS'); + } + if ($miopia_od) { + $in_value = ["20/30", "20/40"]; + $exp_value_od = explode("/", $od_visus); + if (isset($exp_value_od[1]) && intval($exp_value_od[1]) < 50) { + $data_insert = array( + 'code' => 'visus_miopia_od_30_40', + 'label' => 'visus Miopia OD 20/30 20/40', + 'note' => $miopia_od_value, + 'segment' => 'visus', + 'category' => 'mata', + 'order_id' => $orderID + ); + $errors = array_merge($errors, $this->insert_data_etl($data_insert, $userid)); + //$this->insert_code('visus_miopia_od_30_40','visus Miopia OD 20/30 20/40'); + } + if (isset($exp_value_od[1]) && intval($exp_value_od[1]) > 50) { + $data_insert = array( + 'code' => 'visus_miopia_od_over_50', + 'label' => 'visus Miopia OD > 20/50', + 'note' => $miopia_od_value, + 'segment' => 'visus', + 'category' => 'mata', + 'order_id' => $orderID + ); + $errors = array_merge($errors, $this->insert_data_etl($data_insert, $userid)); + //$this->insert_code('visus_miopia_ods_over_50','visus Miopia ODS > 20/50'); + } + } + + if ($miopia_os) { + + $in_value = ["20/30", "20/40"]; + $exp_value_os = explode("/", $os_visus); + //print_r($exp_value_os); + if (isset($exp_value_os[1]) && intval($exp_value_os[1]) < 50) { + $data_insert = array( + 'code' => 'visus_miopia_os_30_40', + 'label' => 'visus Miopia OS 20/30 20/40', + 'note' => $miopia_os_value, + 'segment' => 'visus', + 'category' => 'mata', + 'order_id' => $orderID + ); + $errors = array_merge($errors, $this->insert_data_etl($data_insert, $userid)); + //$this->insert_code('visus_miopia_od_30_40','visus Miopia OD 20/30 20/40'); + } + if (isset($exp_value_os[1]) && intval($exp_value_os[1]) > 50) { + $data_insert = array( + 'code' => 'visus_miopia_os_over_50', + 'label' => 'visus Miopia OS > 20/50', + 'note' => $miopia_os_value, + 'segment' => 'visus', + 'category' => 'mata', + 'order_id' => $orderID + ); + $errors = array_merge($errors, $this->insert_data_etl($data_insert, $userid)); + //$this->insert_code('visus_miopia_ods_over_50','visus Miopia ODS > 20/50'); + } + } + + if ($astigmatismus_od) { + $data_insert = array( + 'code' => 'visus_astigmatismus_od', + 'label' => 'visus Astigmatismus OD', + 'note' => $astigmatismus_od_value, + 'segment' => 'visus', + 'category' => 'mata', + 'order_id' => $orderID + ); + $errors = array_merge($errors, $this->insert_data_etl($data_insert, $userid)); + //$this->insert_code('visus_astigmatismus_od','visus Astigmatismus OD'); + } + if ($astigmatismus_os) { + $data_insert = array( + 'code' => 'visus_astigmatismus_os', + 'label' => 'visus Astigmatismus OS', + 'note' => $astigmatismus_os_value, + 'segment' => 'visus', + 'category' => 'mata', + 'order_id' => $orderID + ); + $errors = array_merge($errors, $this->insert_data_etl($data_insert, $userid)); + //$this->insert_code('visus_astigmatismus_os','visus Astigmatismus OS'); + } + if ($astigmatismus_od && $astigmatismus_os) { + $data_insert = array( + 'code' => 'visus_astigmatismus_ods', + 'label' => 'visus Astigmatismus ODS', + 'note' => $astigmatismus_os_value, + 'segment' => 'visus', + 'category' => 'mata', + 'order_id' => $orderID + ); + $errors = array_merge($errors, $this->insert_data_etl($data_insert, $userid)); + //$this->insert_code('visus_astigmatismus_ods','visus Astigmatismus ODS'); + } + if ($x_od) { + $data_insert = array( + 'code' => 'visus_x_od', + 'label' => 'visus X OD', + 'note' => $x_od_value, + 'segment' => 'visus', + 'category' => 'mata', + 'order_id' => $orderID + ); + $errors = array_merge($errors, $this->insert_data_etl($data_insert, $userid)); + //$this->insert_code('visus_x_od','visus X OD'); + } + if ($x_os) { + $data_insert = array( + 'code' => 'visus_x_os', + 'label' => 'visus X OS', + 'note' => $x_od_value, + 'segment' => 'visus', + 'category' => 'mata', + 'order_id' => $orderID + ); + $errors = array_merge($errors, $this->insert_data_etl($data_insert, $userid)); + //$this->insert_code('visus_x_os','visus X OS'); + } + if ($presbiopia_ods) { + $data_insert = array( + 'code' => 'visus_presbiopia_ods', + 'label' => 'visus Presbiopia ODS', + 'note' => $presbiopia_ods_value, + 'segment' => 'visus', + 'category' => 'mata', + 'order_id' => $orderID + ); + $errors = array_merge($errors, $this->insert_data_etl($data_insert, $userid)); + //$this->insert_code('visus_presbiopia_ods','visus Presbiopia ODS'); + } + return $errors; + } + + function keluhan($id, $userid) + { + $errors = []; + $rst = []; + $sql = "SELECT * + FROM fisik_template + JOIN so_resultentry_fisik_umum ON So_ResultEntryFisikUmumFisikTemplateID = FisikTemplateID AND + So_ResultEntryFisikUmumT_OrderHeaderID = ? AND So_ResultEntryFisikUmumIsActive = 'Y' + WHERE + FisikTemplateIsActive = 'Y' AND + FisikTemplateTableName = 'fisik_keluhan' + ORDER BY FisikTemplateCode ASC + LIMIT 1 + "; + $qry = $this->db_smartone->query($sql, array($id)); + if (!$qry) { + $prm_log = ['SELECT_FISIK_TEMPLATE', 'genkelainan/keluhan']; + $xsql = $this->db_smartone->last_query(); + $log_error = $this->insert_log_error($xsql, $prm_log, json_encode(['id' => $id])); + $errors[] = "SELECT_FISIK_TEMPLATE"; + } + // echo $this->db_smartone->last_query(); + $datas = $qry->result_array(); + if ($datas && count($datas) > 0) { + $order_header_id = $datas[0]['So_ResultEntryFisikUmumT_OrderHeaderID']; + $valdata = json_decode($datas[0]['So_ResultEntryFisikUmumDetails'], true); + $details = $valdata['details']; + foreach ($details as $key => $value) { + if ($value['chx'] == '1') { + $data_insert = array( + 'order_id' => $order_header_id, + 'code' => $value['id_code'], + 'label' => $value['label'], + 'note' => $value['value'], + 'segment' => 'fisik_keluhan', + 'category' => '' + ); + $errors = array_merge($errors, $this->insert_data_etl($data_insert, $userid)); + $rst[] = $data_insert; + } + //$this->insert_code($value['id_code'],$value['label']); + + } + } + + return $errors; + } + + function riwayat_penyakit($id, $userid) + { + $errors = []; + $rst = []; + $sql = "SELECT * + FROM fisik_template + JOIN so_resultentry_fisik_umum ON So_ResultEntryFisikUmumFisikTemplateID = FisikTemplateID AND + So_ResultEntryFisikUmumT_OrderHeaderID = ? AND So_ResultEntryFisikUmumIsActive = 'Y' + WHERE + FisikTemplateIsActive = 'Y' AND + FisikTemplateTableName = 'fisik_penyakit' + ORDER BY FisikTemplateCode ASC + LIMIT 1 + "; + $qry = $this->db_smartone->query($sql, array($id)); + if (!$qry) { + $prm_log = ['SELECT_FISIK_TEMPLATE', 'genkelainan/riwayat_penyakit']; + $xsql = $this->db_smartone->last_query(); + $log_error = $this->insert_log_error($xsql, $prm_log, json_encode(['id' => $id])); + $errors[] = "SELECT_FISIK_TEMPLATE"; + } + // echo $this->db_smartone->last_query(); + $datas = $qry->result_array(); + if ($datas && count($datas) > 0) { + $order_header_id = $datas[0]['So_ResultEntryFisikUmumT_OrderHeaderID']; + $valdata = json_decode($datas[0]['So_ResultEntryFisikUmumDetails'], true); + $header_details = $valdata['details']; + foreach ($header_details as $k => $v) { + $details = $v['details']; + foreach ($details as $key => $value) { + if ($value['chx'] == '1') { + $data_insert = array( + 'order_id' => $order_header_id, + 'code' => $value['id_code'], + 'label' => $value['label'], + 'note' => $value['value'], + 'segment' => $value['segment_name'], + 'category' => $value['table_name'] + ); + $errors = array_merge($errors, $this->insert_data_etl($data_insert, $userid)); + $rst[] = $data_insert; + } + //$this->insert_code($value['id_code'],$value['label']." | ".$value['segment_name']); + + } + } + } + + return $errors; + } + + function penyakit_keluarga($id, $userid) + { + $errors = []; + $rst = []; + $sql = "SELECT * + FROM fisik_template + JOIN so_resultentry_fisik_umum ON So_ResultEntryFisikUmumFisikTemplateID = FisikTemplateID AND + So_ResultEntryFisikUmumT_OrderHeaderID = ? AND So_ResultEntryFisikUmumIsActive = 'Y' + WHERE + FisikTemplateIsActive = 'Y' AND + FisikTemplateTableName = 'fisik_penyakitkeluarga' + ORDER BY FisikTemplateCode ASC + LIMIT 1 + "; + $qry = $this->db_smartone->query($sql, array($id)); + if (!$qry) { + $prm_log = ['SELECT_FISIK_TEMPLATE', 'genkelainan/penyakit_keluarga']; + $xsql = $this->db_smartone->last_query(); + $log_error = $this->insert_log_error($xsql, $prm_log, json_encode(['id' => $id])); + $errors[] = "SELECT_FISIK_TEMPLATE"; + } + // echo $this->db_smartone->last_query(); + $datas = $qry->result_array(); + if ($datas && count($datas) > 0) { + $order_header_id = $datas[0]['So_ResultEntryFisikUmumT_OrderHeaderID']; + $valdata = json_decode($datas[0]['So_ResultEntryFisikUmumDetails'], true); + $details = $valdata['details']; + foreach ($details as $key => $value) { + $results = []; + $options = $value['options']; + foreach ($options as $ko => $vo) { + if ($vo['selected'] == '1') + $results[] = $vo['label']; + } + + if (count($results) > 0) { + $data_insert = array( + 'order_id' => $order_header_id, + 'code' => $value['id_code'], + 'label' => $value['label'], + 'note' => join(", ", $results), + 'segment' => $value['table_name'], + 'category' => $value['table_name'], + ); + $errors = array_merge($errors, $this->insert_data_etl($data_insert, $userid)); + $rst[] = $data_insert; + } + //$this->insert_code($value['id_code'],$value['label']); + + } + } + + return $errors; + } + + + function kebiasaan_hidup($id, $userid) + { + $errors = []; + $rst = []; + $sql = "SELECT * + FROM fisik_template + JOIN so_resultentry_fisik_umum ON So_ResultEntryFisikUmumFisikTemplateID = FisikTemplateID AND + So_ResultEntryFisikUmumT_OrderHeaderID = ? AND So_ResultEntryFisikUmumIsActive = 'Y' + WHERE + FisikTemplateIsActive = 'Y' AND + FisikTemplateTableName = 'fisik_kebiasaanhidup' + ORDER BY FisikTemplateCode ASC + LIMIT 1 + "; + $qry = $this->db_smartone->query($sql, array($id)); + // echo $this->db_smartone->last_query(); + $datas = $qry->result_array(); + if ($datas && count($datas) > 0) { + $order_header_id = $datas[0]['So_ResultEntryFisikUmumT_OrderHeaderID']; + $valdata = json_decode($datas[0]['So_ResultEntryFisikUmumDetails'], true); + $header_details = $valdata['details']; + foreach ($header_details as $k => $v) { + $details = $v['details']; + foreach ($details as $key => $value) { + if ($value['chx'] == '1') { + $data_insert = array( + 'order_id' => $order_header_id, + 'code' => $value['id_code'], + 'label' => $value['label'], + 'note' => $value['value'], + 'segment' => $value['segment_name'], + 'category' => $value['table_name'] + ); + $errors = array_merge($errors, $this->insert_data_etl($data_insert, $userid)); + $rst[] = $data_insert; + } + //$this->insert_code($value['id_code'],$value['label']." | ".$value['segment_name']); + } + } + } + + return $errors; + } + + function fisik_konsumsiobatteratur($id, $userid) + { + $rst = []; + $sql = "SELECT * + FROM fisik_template + JOIN so_resultentry_fisik_umum ON So_ResultEntryFisikUmumFisikTemplateID = FisikTemplateID AND + So_ResultEntryFisikUmumT_OrderHeaderID = ? AND So_ResultEntryFisikUmumIsActive = 'Y' + WHERE + FisikTemplateIsActive = 'Y' AND + FisikTemplateTableName = 'fisik_konsumsiobatteratur' + ORDER BY FisikTemplateCode ASC + LIMIT 1 + "; + $qry = $this->db_smartone->query($sql, array($id)); + if (!$qry) { + $prm_log = ['SELECT_FISIK_TEMPLATE', 'genkelainan/fisik_konsumsiobatteratur']; + $xsql = $this->db_smartone->last_query(); + $log_error = $this->insert_log_error($xsql, $prm_log, json_encode(['id' => $id])); + $errors[] = "SELECT_FISIK_TEMPLATE"; + } + // echo $this->db_smartone->last_query(); + $datas = $qry->result_array(); + if ($datas && count($datas) > 0) { + $order_header_id = $datas[0]['So_ResultEntryFisikUmumT_OrderHeaderID']; + $valdata = json_decode($datas[0]['So_ResultEntryFisikUmumDetails'], true); + $details = $valdata['details']; + foreach ($details as $key => $value) { + if ($value['chx'] == '1') { + $data_insert = array( + 'order_id' => $order_header_id, + 'code' => $value['id_code'], + 'label' => $value['label'], + 'note' => $value['value'], + 'segment' => $value['table_name'], + 'category' => $value['table_name'] + ); + $this->insert_data_etl($data_insert, $userid); + $rst[] = $data_insert; + } + //$this->insert_code($value['id_code'],$value['label']); + } + } + + return $errors; + } + + + function imunasi($id, $userid) + { + $errors = []; + $rst = []; + $sql = "SELECT * + FROM fisik_template + JOIN so_resultentry_fisik_umum ON So_ResultEntryFisikUmumFisikTemplateID = FisikTemplateID AND + So_ResultEntryFisikUmumT_OrderHeaderID = ? AND So_ResultEntryFisikUmumIsActive = 'Y' + WHERE + FisikTemplateIsActive = 'Y' AND + FisikTemplateTableName = 'fisik_riwayatimunisasi' + ORDER BY FisikTemplateCode ASC + LIMIT 1 + "; + $qry = $this->db_smartone->query($sql, array($id)); + if (!$qry) { + $prm_log = ['SELECT_FISIK_TEMPLATE', 'genkelainan/imunasi']; + $xsql = $this->db_smartone->last_query(); + $log_error = $this->insert_log_error($xsql, $prm_log, json_encode(['id' => $id])); + $errors[] = "SELECT_FISIK_TEMPLATE"; + } + // echo $this->db_smartone->last_query(); + $datas = $qry->result_array(); + if ($datas && count($datas) > 0) { + $order_header_id = $datas[0]['So_ResultEntryFisikUmumT_OrderHeaderID']; + $valdata = json_decode($datas[0]['So_ResultEntryFisikUmumDetails'], true); + $header_details = $valdata['details']; + foreach ($header_details as $k => $v) { + $details = $v['details']; + foreach ($details as $key => $value) { + if ($value['chx'] == '1') { + $data_insert = array( + 'order_id' => $order_header_id, + 'code' => $value['id_code'], + 'label' => $value['label'], + 'note' => $value['value'], + 'segment' => $value['segment_name'], + 'category' => $value['table_name'] + ); + $errors = array_merge($errors, $this->insert_data_etl($data_insert, $userid)); + $rst[] = $data_insert; + } + //$this->insert_code($value['id_code'],$value['label']." | ".$value['segment_name']); + } + } + } + + return $errors; + } + + function vital_sign($id, $userid) + { + + $errors = []; + $rst = []; + $sql = "SELECT * + FROM fisik_template + JOIN so_resultentry_fisik_umum ON So_ResultEntryFisikUmumFisikTemplateID = FisikTemplateID AND + So_ResultEntryFisikUmumT_OrderHeaderID = ? AND So_ResultEntryFisikUmumIsActive = 'Y' + WHERE + FisikTemplateIsActive = 'Y' AND + FisikTemplateTableName = 'tanda_vital' + ORDER BY FisikTemplateCode ASC + LIMIT 1 + "; + $qry = $this->db_smartone->query($sql, array($id)); + if (!$qry) { + $prm_log = ['SELECT_FISIK_TEMPLATE', 'genkelainan/vital_sign']; + $xsql = $this->db_smartone->last_query(); + $log_error = $this->insert_log_error($xsql, $prm_log, json_encode(['id' => $id])); + $errors[] = "SELECT_FISIK_TEMPLATE"; + } + // echo $this->db_smartone->last_query(); + $datas = $qry->result_array(); + //return $datas; + //exit; + if ($datas && count($datas) > 0) { + $order_header_id = $datas[0]['So_ResultEntryFisikUmumT_OrderHeaderID']; + $valdata = json_decode($datas[0]['So_ResultEntryFisikUmumDetails'], true); + $details = $valdata['details']; + foreach ($details as $key => $value) { + if ($value['id_code'] == 'tanda_vital_5') { + $data_insert = array( + 'order_id' => $order_header_id, + 'code' => $value['id_code'] . '_1', + 'label' => $value['label_x'], + 'note' => $value['value_x'], + 'segment' => 'tekanan_darah', + 'category' => $value['table_name'] + ); + $errors = array_merge($errors, $this->insert_data_etl($data_insert, $userid)); + //$this->insert_code($value['id_code'].'_1',$value['label_x']); + $rst[] = $data_insert; + $data_insert = array( + 'order_id' => $order_header_id, + 'code' => $value['id_code'] . '_2', + 'label' => $value['label_y'], + 'note' => $value['value_y'], + 'segment' => 'tekanan_darah', + 'category' => $value['table_name'] + ); + $errors = array_merge($errors, $this->insert_data_etl($data_insert, $userid)); + //$this->insert_code($value['id_code'].'_2',$value['label_y']); + $rst[] = $data_insert; + $data_insert = array( + 'order_id' => $order_header_id, + 'code' => 'tekanan_darah_conclusion', + 'label' => $value['standart'], + 'note' => $value['value'], + 'segment' => 'tekanan_darah', + 'category' => $value['table_name'] + ); + //echo 'tekanan_darah_conclusion: '.$value['value']; + //exit; + $errors = array_merge($errors, $this->insert_data_etl($data_insert, $userid)); + //$this->insert_code('tekanan_darah_conclusion',$value['label_y']); + $rst[] = $data_insert; + } + + if ($value['id_code'] == 'tanda_vital_6') { + $data_insert = array( + 'order_id' => $order_header_id, + 'code' => $value['id_code'], + 'label' => $value['chx_y'] == '1' ? $value['label_y'] : $value['label_x'], + 'note' => $value['value'], + 'segment' => 'suhu', + 'category' => $value['table_name'] + ); + $errors = array_merge($errors, $this->insert_data_etl($data_insert, $userid)); + //$this->insert_code($value['id_code'],'Suhu'); + $rst[] = $data_insert; + } + + if ($value['id_code'] == 'tanda_vital_1') { + $data_insert = array( + 'order_id' => $order_header_id, + 'code' => $value['id_code'], + 'label' => $value['label'], + 'note' => $value['value'], + 'segment' => 'denyut_nadi', + 'category' => $value['table_name'] + ); + $errors = array_merge($errors, $this->insert_data_etl($data_insert, $userid)); + //$this->insert_code($value['id_code'],$value['label']); + $rst[] = $data_insert; + } + + if ($value['id_code'] == 'tanda_vital_2') { + $data_insert = array( + 'order_id' => $order_header_id, + 'code' => $value['id_code'], + 'label' => $value['chx_y'] == '1' ? $value['label_y'] : $value['label_x'], + 'note' => $value['value'], + 'segment' => 'ritme_denyut_nadi', + 'category' => $value['table_name'] + ); + $errors = array_merge($errors, $this->insert_data_etl($data_insert, $userid)); + //$this->insert_code($value['id_code'],'Denyut Nadi'); + $rst[] = $data_insert; + } + + if ($value['id_code'] == 'tanda_vital_3') { + $data_insert = array( + 'order_id' => $order_header_id, + 'code' => $value['id_code'], + 'label' => $value['label'], + 'note' => $value['value'], + 'segment' => 'laju_pernafasan', + 'category' => $value['table_name'] + ); + $errors = array_merge($errors, $this->insert_data_etl($data_insert, $userid)); + //$this->insert_code($value['id_code'],$value['label']); + $rst[] = $data_insert; + } + + if ($value['id_code'] == 'tanda_vital_4') { + $data_insert = array( + 'order_id' => $order_header_id, + 'code' => $value['id_code'], + 'label' => $value['chx_y'] == '1' ? $value['label_y'] : $value['label_x'], + 'note' => $value['value'], + 'segment' => 'pola_nafas', + 'category' => $value['table_name'] + ); + $errors = array_merge($errors, $this->insert_data_etl($data_insert, $userid)); + //$this->insert_code($value['id_code'],'Pola Nafas'); + $rst[] = $data_insert; + } + + } + } + + //echo json_encode($rst); + //exit; + + return $errors; + } + + + function keadaan_umum($id, $userid) + { + $errors = []; + $rst = []; + $sql = "SELECT * + FROM fisik_template + JOIN so_resultentry_fisik_umum ON So_ResultEntryFisikUmumFisikTemplateID = FisikTemplateID AND + So_ResultEntryFisikUmumT_OrderHeaderID = ? AND So_ResultEntryFisikUmumIsActive = 'Y' + WHERE + FisikTemplateIsActive = 'Y' AND + FisikTemplateTableName = 'keadaan_umum' + ORDER BY FisikTemplateCode ASC + LIMIT 1 + "; + $qry = $this->db_smartone->query($sql, array($id)); + if (!$qry) { + $prm_log = ['SELECT_FISIK_TEMPLATE', 'genkelainan/keadaan_umum']; + $xsql = $this->db_smartone->last_query(); + $log_error = $this->insert_log_error($xsql, $prm_log, json_encode(['id' => $id])); + $errors[] = "SELECT_FISIK_TEMPLATE"; + } + // echo $this->db_smartone->last_query(); + $datas = $qry->result_array(); + if ($datas && count($datas) > 0) { + $order_header_id = $datas[0]['So_ResultEntryFisikUmumT_OrderHeaderID']; + $valdata = json_decode($datas[0]['So_ResultEntryFisikUmumDetails'], true); + $details = $valdata['details']; + foreach ($details as $key => $value) { + if ($value['chx_x'] == '1') { + $data_insert = array( + 'order_id' => $order_header_id, + 'code' => $value['id_code'] + '_x', + 'label' => $value['label_x'], + 'note' => $value['value'], + 'segment' => $value['table_name'], + 'category' => $value['table_name'] + ); + $errors = array_merge($errors, $this->insert_data_etl($data_insert, $userid)); + } + if ($value['chx_y'] == '1') { + $data_insert = array( + 'order_id' => $order_header_id, + 'code' => $value['id_code'] . '_y', + 'label' => $value['label_y'], + 'note' => $value['value'], + 'segment' => $value['table_name'], + 'category' => $value['table_name'] + ); + $errors = array_merge($errors, $this->insert_data_etl($data_insert, $userid)); + } + + ////$this->insert_code($value['id_code'],'Keadaan Umum'); + $rst[] = $data_insert; + } + } + + return $errors; + } + + function kepala_wajah($id, $userid) + { + $errors = []; + $rst = []; + $sql = "SELECT * + FROM fisik_template + JOIN so_resultentry_fisik_umum ON So_ResultEntryFisikUmumFisikTemplateID = FisikTemplateID AND + So_ResultEntryFisikUmumT_OrderHeaderID = ? AND So_ResultEntryFisikUmumIsActive = 'Y' + WHERE + FisikTemplateIsActive = 'Y' AND + FisikTemplateTableName = 'kepala_wajah' + ORDER BY FisikTemplateCode ASC + LIMIT 1 + "; + $qry = $this->db_smartone->query($sql, array($id)); + if (!$qry) { + $prm_log = ['SELECT_FISIK_TEMPLATE', 'genkelainan/kepala_wajah']; + $xsql = $this->db_smartone->last_query(); + $log_error = $this->insert_log_error($xsql, $prm_log, json_encode(['id' => $id])); + $errors[] = "SELECT_FISIK_TEMPLATE"; + } + // echo $this->db_smartone->last_query(); + $datas = $qry->result_array(); + if ($datas && count($datas) > 0) { + $order_header_id = $datas[0]['So_ResultEntryFisikUmumT_OrderHeaderID']; + $valdata = json_decode($datas[0]['So_ResultEntryFisikUmumDetails'], true); + $details = $valdata['details']; + foreach ($details as $key => $value) { + if ($value['chx'] == '1' && $value['is_normal'] == 'N') { + $data_insert = array( + 'order_id' => $order_header_id, + 'code' => $value['id_code'], + 'label' => $value['label'], + 'note' => $value['value'], + 'segment' => $value['table_name'], + 'category' => $value['table_name'] + ); + $errors = array_merge($errors, $this->insert_data_etl($data_insert, $userid)); + $rst[] = $data_insert; + } + //$this->insert_code($value['id_code'],$value['label'].' | '.$value['table_name']); + } + } + + return $errors; + } + + function mata($id, $userid) + { + $errors = []; + $rst = []; + $sql = "SELECT * + FROM fisik_template + JOIN so_resultentry_fisik_umum ON So_ResultEntryFisikUmumFisikTemplateID = FisikTemplateID AND + So_ResultEntryFisikUmumT_OrderHeaderID = ? AND So_ResultEntryFisikUmumIsActive = 'Y' + WHERE + FisikTemplateIsActive = 'Y' AND + FisikTemplateTableName = 'mata' + ORDER BY FisikTemplateCode ASC + LIMIT 1 + "; + $qry = $this->db_smartone->query($sql, array($id)); + if (!$qry) { + $prm_log = ['SELECT_FISIK_TEMPLATE', 'genkelainan/mata']; + $xsql = $this->db_smartone->last_query(); + $log_error = $this->insert_log_error($xsql, $prm_log, json_encode(['id' => $id])); + $errors[] = "SELECT_FISIK_TEMPLATE"; + } + // echo $this->db_smartone->last_query(); + $datas = $qry->result_array(); + if ($datas && count($datas) > 0) { + $order_header_id = $datas[0]['So_ResultEntryFisikUmumT_OrderHeaderID']; + $valdata = json_decode($datas[0]['So_ResultEntryFisikUmumDetails'], true); + $details = $valdata['details']; + foreach ($details as $key => $value) { + if ($value['chx'] == '1') { + $data_insert = array( + 'order_id' => $order_header_id, + 'code' => $value['id_code'], + 'label' => $value['label'], + 'note' => $value['value'], + 'segment' => 'mata', + 'category' => 'mata' + ); + $errors = array_merge($errors, $this->insert_data_etl($data_insert, $userid)); + $rst[] = $data_insert; + } + //$this->insert_code($value['id_code'],$value['label']." | Mata"); + + } + } + + return $errors; + } + + function lapang_pandang($id, $userid) + { + $errors = []; + $rst = []; + $sql = "SELECT * + FROM fisik_template + JOIN so_resultentry_fisik_umum ON So_ResultEntryFisikUmumFisikTemplateID = FisikTemplateID AND + So_ResultEntryFisikUmumT_OrderHeaderID = ? AND So_ResultEntryFisikUmumIsActive = 'Y' + WHERE + FisikTemplateIsActive = 'Y' AND + FisikTemplateTableName = 'lapang_pandang' + ORDER BY FisikTemplateCode ASC + LIMIT 1 + "; + $qry = $this->db_smartone->query($sql, array($id)); + if (!$qry) { + $prm_log = ['SELECT_FISIK_TEMPLATE', 'genkelainan/lapang_pandang']; + $xsql = $this->db_smartone->last_query(); + $log_error = $this->insert_log_error($xsql, $prm_log, json_encode(['id' => $id])); + $errors[] = "SELECT_FISIK_TEMPLATE"; + } + // echo $this->db_smartone->last_query(); + $datas = $qry->result_array(); + if ($datas && count($datas) > 0) { + $order_header_id = $datas[0]['So_ResultEntryFisikUmumT_OrderHeaderID']; + $valdata = json_decode($datas[0]['So_ResultEntryFisikUmumDetails'], true); + $details = $valdata['details']; + $value_data = $details[0]; + + if ($value_data['chx_x'] == '1') { + $data_insert = array( + 'order_id' => $order_header_id, + 'code' => 'lapang_pandang_x', + 'label' => $value_data['label_x'], + 'note' => $value_data['value'], + 'segment' => 'lapang_pandang', + 'category' => 'lapang_pandang' + ); + $errors = array_merge($errors, $this->insert_data_etl($data_insert, $userid)); + + $rst[] = $data_insert; + } + + if ($value_data['chx_y'] == '1') { + $data_insert = array( + 'order_id' => $order_header_id, + 'code' => 'lapang_pandang_y', + 'label' => $value_data['label_y'], + 'note' => $value_data['value'], + 'segment' => 'lapang_pandang', + 'category' => 'lapang_pandang' + ); + $errors = array_merge($errors, $this->insert_data_etl($data_insert, $userid)); + + $rst[] = $data_insert; + } + //$this->insert_code('lapang_pandang_x','Lapang Pandang Tidak Normal'); + //$this->insert_code('lapang_pandang_y','Lapang Pandang Normal'); + } + + return $errors; + } + + function telinga($id, $userid) + { + $errors = []; + $rst = []; + $sql = "SELECT * + FROM fisik_template + JOIN so_resultentry_fisik_umum ON So_ResultEntryFisikUmumFisikTemplateID = FisikTemplateID AND + So_ResultEntryFisikUmumT_OrderHeaderID = ? AND So_ResultEntryFisikUmumIsActive = 'Y' + WHERE + FisikTemplateIsActive = 'Y' AND + FisikTemplateTableName = 'telinga' + ORDER BY FisikTemplateCode ASC + LIMIT 1 + "; + $qry = $this->db_smartone->query($sql, array($id)); + if (!$qry) { + $prm_log = ['SELECT_FISIK_TEMPLATE', 'genkelainan/telinga']; + $xsql = $this->db_smartone->last_query(); + $log_error = $this->insert_log_error($xsql, $prm_log, json_encode(['id' => $id])); + $errors[] = "SELECT_FISIK_TEMPLATE"; + } + // echo $this->db_smartone->last_query(); + $datas = $qry->result_array(); + if ($datas && count($datas) > 0) { + $order_header_id = $datas[0]['So_ResultEntryFisikUmumT_OrderHeaderID']; + $valdata = json_decode($datas[0]['So_ResultEntryFisikUmumDetails'], true); + $details = $valdata['details']; + foreach ($details as $key => $value) { + if ($value['chx'] == '1') { + $data_insert = array( + 'order_id' => $order_header_id, + 'code' => $value['id_code'], + 'label' => $value['label'], + 'note' => $value['value'], + 'segment' => 'telinga', + 'category' => 'telinga' + ); + $errors = array_merge($errors, $this->insert_data_etl($data_insert, $userid)); + $rst[] = $data_insert; + } + //$this->insert_code($value['id_code'],$value['label'].' | Telinga'); + } + } + + return $errors; + } + + function hidung($id, $userid) + { + $errors = []; + $rst = []; + $sql = "SELECT * + FROM fisik_template + JOIN so_resultentry_fisik_umum ON So_ResultEntryFisikUmumFisikTemplateID = FisikTemplateID AND + So_ResultEntryFisikUmumT_OrderHeaderID = ? AND So_ResultEntryFisikUmumIsActive = 'Y' + WHERE + FisikTemplateIsActive = 'Y' AND + FisikTemplateTableName = 'hidung' + ORDER BY FisikTemplateCode ASC + LIMIT 1 + "; + $qry = $this->db_smartone->query($sql, array($id)); + if (!$qry) { + $prm_log = ['SELECT_FISIK_TEMPLATE', 'genkelainan/hidung']; + $xsql = $this->db_smartone->last_query(); + $log_error = $this->insert_log_error($xsql, $prm_log, json_encode(['id' => $id])); + $errors[] = "SELECT_FISIK_TEMPLATE"; + } + // echo $this->db_smartone->last_query(); + $datas = $qry->result_array(); + if ($datas && count($datas) > 0) { + $order_header_id = $datas[0]['So_ResultEntryFisikUmumT_OrderHeaderID']; + $valdata = json_decode($datas[0]['So_ResultEntryFisikUmumDetails'], true); + $details = $valdata['details']; + foreach ($details as $key => $value) { + if ($value['chx'] == '1') { + $data_insert = array( + 'order_id' => $order_header_id, + 'code' => $value['id_code'], + 'label' => $value['label'], + 'note' => $value['value'], + 'segment' => 'hidung', + 'category' => 'hidung' + ); + $errors = array_merge($errors, $this->insert_data_etl($data_insert, $userid)); + $rst[] = $data_insert; + } + //$this->insert_code($value['id_code'],$value['label'].' | Hidung'); + } + } + + return $errors; + } + + function gigi($id, $userid) + { + $errors = []; + $rst = []; + $sql = "SELECT * + FROM fisik_template + JOIN so_resultentry_fisik_umum ON So_ResultEntryFisikUmumFisikTemplateID = FisikTemplateID AND + So_ResultEntryFisikUmumT_OrderHeaderID = ? AND So_ResultEntryFisikUmumIsActive = 'Y' + WHERE + FisikTemplateIsActive = 'Y' AND + FisikTemplateTableName = 'gigi' + ORDER BY FisikTemplateCode ASC + LIMIT 1 + "; + $qry = $this->db_smartone->query($sql, array($id)); + if (!$qry) { + $prm_log = ['SELECT_FISIK_TEMPLATE', 'genkelainan/gigi']; + $xsql = $this->db_smartone->last_query(); + $log_error = $this->insert_log_error($xsql, $prm_log, json_encode(['id' => $id])); + $errors[] = "SELECT_FISIK_TEMPLATE"; + } + // echo $this->db_smartone->last_query(); + $datas = $qry->result_array(); + if ($datas && count($datas) > 0) { + $order_header_id = $datas[0]['So_ResultEntryFisikUmumT_OrderHeaderID']; + $valdata = json_decode($datas[0]['So_ResultEntryFisikUmumDetails'], true); + $details = $valdata['details']; + foreach ($details as $key => $value) { + if ($value['chx'] == '1') { + $data_insert = array( + 'order_id' => $order_header_id, + 'code' => $value['id_code'], + 'label' => $value['label'], + 'note' => $value['value'], + 'segment' => 'gigi', + 'category' => 'gigi' + ); + $errors = array_merge($errors, $this->insert_data_etl($data_insert, $userid)); + $rst[] = $data_insert; + } + //$this->insert_code($value['id_code'],$value['label'].' | Gigi'); + + } + } + + return $errors; + } + + function mulut($id, $userid) + { + $errors = []; + $rst = []; + $sql = "SELECT * + FROM fisik_template + JOIN so_resultentry_fisik_umum ON So_ResultEntryFisikUmumFisikTemplateID = FisikTemplateID AND + So_ResultEntryFisikUmumT_OrderHeaderID = ? AND So_ResultEntryFisikUmumIsActive = 'Y' + WHERE + FisikTemplateIsActive = 'Y' AND + FisikTemplateTableName = 'mukosa_rongga_mulut' + ORDER BY FisikTemplateCode ASC + LIMIT 1 + "; + $qry = $this->db_smartone->query($sql, array($id)); + if (!$qry) { + $prm_log = ['SELECT_FISIK_TEMPLATE', 'genkelainan/mulut']; + $xsql = $this->db_smartone->last_query(); + $log_error = $this->insert_log_error($xsql, $prm_log, json_encode(['id' => $id])); + $errors[] = "SELECT_FISIK_TEMPLATE"; + } + //echo $this->db_smartone->last_query(); + $datas = $qry->result_array(); + if ($datas && count($datas) > 0) { + $order_header_id = $datas[0]['So_ResultEntryFisikUmumT_OrderHeaderID']; + $valdata = json_decode($datas[0]['So_ResultEntryFisikUmumDetails'], true); + $header_details = $valdata['details']; + //print_r($header_details); + foreach ($header_details as $k => $v) { + $details = $v['details']; + foreach ($details as $key => $value) { + $segment = strtolower(str_replace(" ", "_", $value['segment_name'])); + if ($value['chx'] == '1') { + $data_insert = array( + 'order_id' => $order_header_id, + 'code' => $value['id_code'], + 'label' => $value['label'], + 'note' => $value['value'], + 'segment' => $segment, + 'category' => $value['table_name'] + ); + $errors = array_merge($errors, $this->insert_data_etl($data_insert, $userid)); + $rst[] = $data_insert; + } + //$this->insert_code($value['id_code'],$value['label']." | ".$segment); + + } + } + } + + return $errors; + } + + function leher($id, $userid) + { + $errors = []; + $rst = []; + $sql = "SELECT * + FROM fisik_template + JOIN so_resultentry_fisik_umum ON So_ResultEntryFisikUmumFisikTemplateID = FisikTemplateID AND + So_ResultEntryFisikUmumT_OrderHeaderID = ? AND So_ResultEntryFisikUmumIsActive = 'Y' + WHERE + FisikTemplateIsActive = 'Y' AND + FisikTemplateTableName = 'leher' + ORDER BY FisikTemplateCode ASC + LIMIT 1 + "; + $qry = $this->db_smartone->query($sql, array($id)); + if (!$qry) { + $prm_log = ['SELECT_FISIK_TEMPLATE', 'genkelainan/leher']; + $xsql = $this->db_smartone->last_query(); + $log_error = $this->insert_log_error($xsql, $prm_log, json_encode(['id' => $id])); + $errors[] = "SELECT_FISIK_TEMPLATE"; + } + // echo $this->db_smartone->last_query(); + $datas = $qry->result_array(); + if ($datas && count($datas) > 0) { + $order_header_id = $datas[0]['So_ResultEntryFisikUmumT_OrderHeaderID']; + $valdata = json_decode($datas[0]['So_ResultEntryFisikUmumDetails'], true); + $details = $valdata['details']; + foreach ($details as $key => $value) { + if ($value['chx'] == '1') { + $data_insert = array( + 'order_id' => $order_header_id, + 'code' => $value['id_code'], + 'label' => $value['label'], + 'note' => $value['value'], + 'segment' => 'leher', + 'category' => 'leher' + ); + $errors = array_merge($errors, $this->insert_data_etl($data_insert, $userid)); + $rst[] = $data_insert; + } + //$this->insert_code($value['id_code'],$value['label'].' | Leher'); + } + } + + return $errors; + } + + function thorax($id, $userid) + { + $errors = []; + $rst = []; + $sql = "SELECT * + FROM fisik_template + JOIN so_resultentry_fisik_umum ON So_ResultEntryFisikUmumFisikTemplateID = FisikTemplateID AND + So_ResultEntryFisikUmumT_OrderHeaderID = ? AND So_ResultEntryFisikUmumIsActive = 'Y' + WHERE + FisikTemplateIsActive = 'Y' AND + FisikTemplateTableName = 'thorax' + ORDER BY FisikTemplateCode ASC + LIMIT 1 + "; + $qry = $this->db_smartone->query($sql, array($id)); + if (!$qry) { + $prm_log = ['SELECT_FISIK_TEMPLATE', 'genkelainan/thorax']; + $xsql = $this->db_smartone->last_query(); + $log_error = $this->insert_log_error($xsql, $prm_log, json_encode(['id' => $id])); + $errors[] = "SELECT_FISIK_TEMPLATE"; + } + // echo $this->db_smartone->last_query(); + $datas = $qry->result_array(); + if ($datas && count($datas) > 0) { + $order_header_id = $datas[0]['So_ResultEntryFisikUmumT_OrderHeaderID']; + $valdata = json_decode($datas[0]['So_ResultEntryFisikUmumDetails'], true); + $details = $valdata['details']; + foreach ($details as $key => $value) { + if ($value['chx'] == '1') { + $data_insert = array( + 'order_id' => $order_header_id, + 'code' => $value['id_code'], + 'label' => $value['label'], + 'note' => $value['value'], + 'segment' => 'thorax', + 'category' => 'thorax' + ); + $errors = array_merge($errors, $this->insert_data_etl($data_insert, $userid)); + $rst[] = $data_insert; + } + //$this->insert_code($value['id_code'],$value['label'].' | Thorax'); + } + } + + return $errors; + } + + function paru($id, $userid) + { + $errors = []; + $rst = []; + $sql = "SELECT * + FROM fisik_template + JOIN so_resultentry_fisik_umum ON So_ResultEntryFisikUmumFisikTemplateID = FisikTemplateID AND + So_ResultEntryFisikUmumT_OrderHeaderID = ? AND So_ResultEntryFisikUmumIsActive = 'Y' + WHERE + FisikTemplateIsActive = 'Y' AND + FisikTemplateTableName = 'paru' + ORDER BY FisikTemplateCode ASC + LIMIT 1 + "; + $qry = $this->db_smartone->query($sql, array($id)); + if (!$qry) { + $prm_log = ['SELECT_FISIK_TEMPLATE', 'genkelainan/paru']; + $xsql = $this->db_smartone->last_query(); + $log_error = $this->insert_log_error($xsql, $prm_log, json_encode(['id' => $id])); + $errors[] = "SELECT_FISIK_TEMPLATE"; + } + // echo $this->db_smartone->last_query(); + $datas = $qry->result_array(); + if ($datas && count($datas) > 0) { + $order_header_id = $datas[0]['So_ResultEntryFisikUmumT_OrderHeaderID']; + $valdata = json_decode($datas[0]['So_ResultEntryFisikUmumDetails'], true); + $details = $valdata['details']; + foreach ($details as $key => $value) { + if ($value['chx'] == '1') { + $data_insert = array( + 'order_id' => $order_header_id, + 'code' => $value['id_code'], + 'label' => $value['label'], + 'note' => $value['value'], + 'segment' => 'paru', + 'category' => 'paru' + ); + $errors = array_merge($errors, $this->insert_data_etl($data_insert, $userid)); + $rst[] = $data_insert; + } + //$this->insert_code($value['id_code'],$value['label'].' | Paru'); + } + } + + return $errors; + } + + function jantung($id, $userid) + { + $errors = []; + $rst = []; + $sql = "SELECT * + FROM fisik_template + JOIN so_resultentry_fisik_umum ON So_ResultEntryFisikUmumFisikTemplateID = FisikTemplateID AND + So_ResultEntryFisikUmumT_OrderHeaderID = ? AND So_ResultEntryFisikUmumIsActive = 'Y' + WHERE + FisikTemplateIsActive = 'Y' AND + FisikTemplateTableName = 'jantung' + ORDER BY FisikTemplateCode ASC + LIMIT 1 + "; + $qry = $this->db_smartone->query($sql, array($id)); + + if (!$qry) { + $prm_log = ['SELECT_FISIK_TEMPLATE', 'genkelainan/jantung']; + $xsql = $this->db_smartone->last_query(); + $log_error = $this->insert_log_error($xsql, $prm_log, json_encode(['id' => $id])); + $errors[] = "SELECT_FISIK_TEMPLATE"; + } + //echo $this->db_smartone->last_query(); + $datas = $qry->result_array(); + if ($datas && count($datas) > 0) { + $order_header_id = $datas[0]['So_ResultEntryFisikUmumT_OrderHeaderID']; + $valdata = json_decode($datas[0]['So_ResultEntryFisikUmumDetails'], true); + $header_details = $valdata['details']; + //print_r($header_details); + foreach ($header_details as $k => $v) { + $details = $v['details']; + foreach ($details as $key => $value) { + $segment = strtolower(str_replace(" ", "_", str_replace("/", "", $value['segment_name']))); + if ($value['chx'] == '1') { + + $data_insert = array( + 'order_id' => $order_header_id, + 'code' => $value['id_code'], + 'label' => $value['label'], + 'note' => $value['value'], + 'segment' => $segment, + 'category' => $value['table_name'] + ); + $errors = array_merge($errors, $this->insert_data_etl($data_insert, $userid)); + $rst[] = $data_insert; + } + //$this->insert_code($value['id_code'],$value['label']." | ".$segment); + } + } + } + + return $errors; + } + + function perut($id, $userid) + { + $errors = []; + $rst = []; + $sql = "SELECT * + FROM fisik_template + JOIN so_resultentry_fisik_umum ON So_ResultEntryFisikUmumFisikTemplateID = FisikTemplateID AND + So_ResultEntryFisikUmumT_OrderHeaderID = ? AND So_ResultEntryFisikUmumIsActive = 'Y' + WHERE + FisikTemplateIsActive = 'Y' AND + FisikTemplateTableName = 'perut' + ORDER BY FisikTemplateCode ASC + LIMIT 1 + "; + $qry = $this->db_smartone->query($sql, array($id)); + if (!$qry) { + $prm_log = ['SELECT_FISIK_TEMPLATE', 'genkelainan/perut']; + $xsql = $this->db_smartone->last_query(); + $log_error = $this->insert_log_error($xsql, $prm_log, json_encode(['id' => $id])); + $errors[] = "SELECT_FISIK_TEMPLATE"; + } + //echo $this->db_smartone->last_query(); + $datas = $qry->result_array(); + if ($datas && count($datas) > 0) { + $order_header_id = $datas[0]['So_ResultEntryFisikUmumT_OrderHeaderID']; + $valdata = json_decode($datas[0]['So_ResultEntryFisikUmumDetails'], true); + $header_details = $valdata['details']; + //print_r($header_details); + foreach ($header_details as $k => $v) { + if ($v['name'] != 'Hernia' && $v['name'] != 'Pengukuran') { + $details = $v['details']; + foreach ($details as $key => $value) { + $segment = strtolower(str_replace(" ", "_", $v['name'])); + if ($value['chx'] == '1') { + + $data_insert = array( + 'order_id' => $order_header_id, + 'code' => $value['id_code'], + 'label' => $value['label'], + 'note' => $value['value'], + 'segment' => $segment, + 'category' => $value['table_name'] + ); + $errors = array_merge($errors, $this->insert_data_etl($data_insert, $userid)); + $rst[] = $data_insert; + } + //$this->insert_code($value['id_code'],$value['label']." | ".$segment); + } + } + + if ($v['name'] == 'Hernia') { + $details = $v['details']; + foreach ($details as $key => $value) { + if ($value['id_code'] == 'perut_13') { + if ($value['chx'] == '1') { + $segment = strtolower(str_replace(" ", "_", $v['name'])); + $data_insert = array( + 'order_id' => $order_header_id, + 'code' => $value['id_code'], + 'label' => $value['label'], + 'note' => $value['value'], + 'segment' => $segment, + 'category' => $value['table_name'] + ); + $errors = array_merge($errors, $this->insert_data_etl($data_insert, $userid)); + $rst[] = $data_insert; + } + //$this->insert_code($value['id_code'],$value['label'].' | Hernia '.$segment); + } + + if ($value['id_code'] == 'perut_14') { + $segment = strtolower(str_replace(" ", "_", $v['name'])); + if ($value['chx'] == '1') { + $child_details = $value['details']; + foreach ($child_details as $kx => $vx) { + if ($vx['id_code'] == 'perut_14_1') { + if ($vx['chx_value'] == '1') { + $data_insert = array( + 'order_id' => $order_header_id, + 'code' => $vx['id_code'], + 'label' => $vx['label'], + 'note' => '', + 'segment' => $segment, + 'category' => $value['table_name'] + ); + $errors = array_merge($errors, $this->insert_data_etl($data_insert, $userid)); + $rst[] = $data_insert; + } + //$this->insert_code($value['id_code'],$value['label'].' | Hernia '.$segment); + } + + if ($vx['id_code'] != 'perut_14_1') { + if ($vx['chx_a_value'] == '1') { + $data_insert = array( + 'order_id' => $order_header_id, + 'code' => $vx['id_code'] . '_' . $vx['chx_a_label'], + 'label' => $vx['label'], + 'note' => $vx['chx_a_label'], + 'segment' => $segment, + 'category' => $value['table_name'] + ); + $errors = array_merge($errors, $this->insert_data_etl($data_insert, $userid)); + $rst[] = $data_insert; + } + + if ($vx['chx_b_value'] == '1') { + $data_insert = array( + 'order_id' => $order_header_id, + 'code' => $vx['id_code'] . '_' . $vx['chx_b_label'], + 'label' => $vx['label'], + 'note' => $vx['chx_b_label'], + 'segment' => $segment, + 'category' => $value['table_name'] + ); + $errors = array_merge($errors, $this->insert_data_etl($data_insert, $userid)); + $rst[] = $data_insert; + } + //$this->insert_code($vx['id_code'].'_'.$vx['chx_a_label'],$value['label'].' | Hernia '.$segment); + //$this->insert_code($vx['id_code'].'_'.$vx['chx_b_label'],$value['label'].' | Hernia '.$segment); + } + + } + } + //$this->insert_code($value['id_code'],$value['label']); + } + + + } + } + + if ($v['name'] == 'Hernia') { + $details = $v['details']; + } + + } + } + + return $errors; + } + + function sistem_integumen($id, $userid) + { + $errors = []; + $rst = []; + $sql = "SELECT * + FROM fisik_template + JOIN so_resultentry_fisik_umum ON So_ResultEntryFisikUmumFisikTemplateID = FisikTemplateID AND + So_ResultEntryFisikUmumT_OrderHeaderID = ? AND So_ResultEntryFisikUmumIsActive = 'Y' + WHERE + FisikTemplateIsActive = 'Y' AND + FisikTemplateTableName = 'sistem_integumen' + ORDER BY FisikTemplateCode ASC + LIMIT 1 + "; + $qry = $this->db_smartone->query($sql, array($id)); + if (!$qry) { + $prm_log = ['SELECT_FISIK_TEMPLATE', 'genkelainan/sistem_integumen']; + $xsql = $this->db_smartone->last_query(); + $log_error = $this->insert_log_error($xsql, $prm_log, json_encode(['id' => $id])); + $errors[] = "SELECT_FISIK_TEMPLATE"; + } + //echo $this->db_smartone->last_query(); + $datas = $qry->result_array(); + if ($datas && count($datas) > 0) { + $order_header_id = $datas[0]['So_ResultEntryFisikUmumT_OrderHeaderID']; + $valdata = json_decode($datas[0]['So_ResultEntryFisikUmumDetails'], true); + $header_details = $valdata['details']; + //print_r($header_details); + foreach ($header_details as $k => $v) { + $details = $v['details']; + foreach ($details as $key => $value) { + $segment = strtolower(str_replace(" ", "_", $value['segment_name'])); + if ($value['chx'] == '1') { + + $data_insert = array( + 'order_id' => $order_header_id, + 'code' => $value['id_code'], + 'label' => $value['label'], + 'note' => $value['value'], + 'segment' => $segment, + 'category' => $value['table_name'] + ); + $errors = array_merge($errors, $this->insert_data_etl($data_insert, $userid)); + + $rst[] = $data_insert; + } + //$this->insert_code($value['id_code'],$value['label']." | ".$segment); + } + } + } + + return $errors; + } + + function genitourinaria($id, $userid) + { + $errors = []; + $rst = []; + $sql = "SELECT * + FROM fisik_template + JOIN so_resultentry_fisik_umum ON So_ResultEntryFisikUmumFisikTemplateID = FisikTemplateID AND + So_ResultEntryFisikUmumT_OrderHeaderID = ? AND So_ResultEntryFisikUmumIsActive = 'Y' + WHERE + FisikTemplateIsActive = 'Y' AND + FisikTemplateTableName = 'genitourinaria' + ORDER BY FisikTemplateCode ASC + LIMIT 1 + "; + $qry = $this->db_smartone->query($sql, array($id)); + if (!$qry) { + $prm_log = ['SELECT_FISIK_TEMPLATE', 'genkelainan/genitourinaria']; + $xsql = $this->db_smartone->last_query(); + $log_error = $this->insert_log_error($xsql, $prm_log, json_encode(['id' => $id])); + $errors[] = "SELECT_FISIK_TEMPLATE"; + } + // echo $this->db_smartone->last_query(); + $datas = $qry->result_array(); + if ($datas && count($datas) > 0) { + $order_header_id = $datas[0]['So_ResultEntryFisikUmumT_OrderHeaderID']; + $valdata = json_decode($datas[0]['So_ResultEntryFisikUmumDetails'], true); + $details = $valdata['details']; + foreach ($details as $key => $value) { + if ($value['chx'] == '1') { + $data_insert = array( + 'order_id' => $order_header_id, + 'code' => $value['id_code'], + 'label' => $value['label'], + 'note' => $value['value'], + 'segment' => 'genitourinaria', + 'category' => 'genitourinaria' + ); + $errors = array_merge($errors, $this->insert_data_etl($data_insert, $userid)); + $rst[] = $data_insert; + } + //$this->insert_code($value['id_code'],$value['label'].' Genitourinaria'); + } + } + + return $errors; + } + + function anggota_gerak($id, $userid) + { + $errors = []; + $rst = []; + $sql = "SELECT * + FROM fisik_template + JOIN so_resultentry_fisik_umum ON So_ResultEntryFisikUmumFisikTemplateID = FisikTemplateID AND + So_ResultEntryFisikUmumT_OrderHeaderID = ? AND So_ResultEntryFisikUmumIsActive = 'Y' + WHERE + FisikTemplateIsActive = 'Y' AND + FisikTemplateTableName = 'anggota_gerak' + ORDER BY FisikTemplateCode ASC + LIMIT 1 + "; + $qry = $this->db_smartone->query($sql, array($id)); + if (!$qry) { + $prm_log = ['SELECT_FISIK_TEMPLATE', 'genkelainan/anggota_gerak']; + $xsql = $this->db_smartone->last_query(); + $log_error = $this->insert_log_error($xsql, $prm_log, json_encode(['id' => $id])); + $errors[] = "SELECT_FISIK_TEMPLATE"; + } + //echo $this->db_smartone->last_query(); + $datas = $qry->result_array(); + if ($datas && count($datas) > 0) { + $order_header_id = $datas[0]['So_ResultEntryFisikUmumT_OrderHeaderID']; + $valdata = json_decode($datas[0]['So_ResultEntryFisikUmumDetails'], true); + $header_details = $valdata['details']; + //print_r($header_details); + foreach ($header_details as $k => $v) { + $details = $v['details']; + foreach ($details as $key => $value) { + if ($value['chx'] == '1') { + $segment = strtolower(str_replace(" ", "_", str_replace("/", "", $value['segment_name']))); + $data_insert = array( + 'order_id' => $order_header_id, + 'code' => $value['id_code'], + 'label' => $value['label'], + 'note' => $value['value'], + 'segment' => $segment, + 'category' => $value['table_name'] + ); + $errors = array_merge($errors, $this->insert_data_etl($data_insert, $userid)); + $rst[] = $data_insert; + } + //$this->insert_code($value['id_code'],$value['label']." | ".$segment); + } + } + } + + return $errors; + } + + function sistem_persyarafan($id, $userid) + { + $errors = []; + $rst = []; + $sql = "SELECT * + FROM fisik_template + JOIN so_resultentry_fisik_umum ON So_ResultEntryFisikUmumFisikTemplateID = FisikTemplateID AND + So_ResultEntryFisikUmumT_OrderHeaderID = ? AND So_ResultEntryFisikUmumIsActive = 'Y' + WHERE + FisikTemplateIsActive = 'Y' AND + FisikTemplateTableName = 'sistem_persyarafan' + ORDER BY FisikTemplateCode ASC + LIMIT 1 + "; + $qry = $this->db_smartone->query($sql, array($id)); + if (!$qry) { + $prm_log = ['SELECT_FISIK_TEMPLATE', 'genkelainan/sistem_persyarafan']; + $xsql = $this->db_smartone->last_query(); + $log_error = $this->insert_log_error($xsql, $prm_log, json_encode(['id' => $id])); + $errors[] = "SELECT_FISIK_TEMPLATE"; + } + //echo $this->db_smartone->last_query(); + $datas = $qry->result_array(); + if ($datas && count($datas) > 0) { + $order_header_id = $datas[0]['So_ResultEntryFisikUmumT_OrderHeaderID']; + $valdata = json_decode($datas[0]['So_ResultEntryFisikUmumDetails'], true); + $header_details = $valdata['details']; + //print_r($header_details); + foreach ($header_details as $k => $v) { + $details = $v['details']; + foreach ($details as $key => $value) { + if ($value['chx'] == '1') { + $segment = strtolower(str_replace(" ", "_", str_replace("&", "", $value['segment_name']))); + $data_insert = array( + 'order_id' => $order_header_id, + 'code' => $value['id_code'], + 'label' => $value['label'], + 'note' => $value['value'], + 'segment' => $segment, + 'category' => $value['table_name'] + ); + $errors = array_merge($errors, $this->insert_data_etl($data_insert, $userid)); + $rst[] = $data_insert; + } + //$this->insert_code($value['id_code'],$value['label']." | ".$segment); + } + } + } + + return $errors; + } + + function smell_test($id, $userid) + { + $errors = []; + $rst = []; + $sql = "SELECT * + FROM fisik_template + JOIN so_resultentry_fisik_umum ON So_ResultEntryFisikUmumFisikTemplateID = FisikTemplateID AND + So_ResultEntryFisikUmumT_OrderHeaderID = ? AND So_ResultEntryFisikUmumIsActive = 'Y' + WHERE + FisikTemplateIsActive = 'Y' AND + FisikTemplateTableName = 'smell_test' + ORDER BY FisikTemplateCode ASC + LIMIT 1 + "; + $qry = $this->db_smartone->query($sql, array($id)); + if (!$qry) { + $prm_log = ['SELECT_FISIK_TEMPLATE', 'genkelainan/smell_test']; + $xsql = $this->db_smartone->last_query(); + $log_error = $this->insert_log_error($xsql, $prm_log, json_encode(['id' => $id])); + $errors[] = "SELECT_FISIK_TEMPLATE"; + } + //echo $this->db_smartone->last_query(); + $datas = $qry->result_array(); + if ($datas && count($datas) > 0) { + $order_header_id = $datas[0]['So_ResultEntryFisikUmumT_OrderHeaderID']; + $valdata = json_decode($datas[0]['So_ResultEntryFisikUmumDetails'], true); + $header_details = $valdata['details']; + //print_r($header_details); + foreach ($header_details as $k => $v) { + $details = $v['details']; + foreach ($details as $key => $value) { + if ($value['chx'] == '1') { + $segment = strtolower(str_replace(" ", "_", $value['segment_name'])); + $data_insert = array( + 'order_id' => $order_header_id, + 'code' => $value['id_code'], + 'label' => $value['label'], + 'note' => $value['value'], + 'segment' => $segment, + 'category' => $value['table_name'] + ); + $errors = array_merge($errors, $this->insert_data_etl($data_insert, $userid)); + $rst[] = $data_insert; + } + //$this->insert_code($value['id_code'],$value['label']." | ".$segment); + } + } + } + + return $errors; + } + + function low_back_pain_screening_test($id, $userid) + { + $errors = []; + $rst = []; + $sql = "SELECT * + FROM fisik_template + JOIN so_resultentry_fisik_umum ON So_ResultEntryFisikUmumFisikTemplateID = FisikTemplateID AND + So_ResultEntryFisikUmumT_OrderHeaderID = ? AND So_ResultEntryFisikUmumIsActive = 'Y' + WHERE + FisikTemplateIsActive = 'Y' AND + FisikTemplateTableName = 'low_back_pain_screening_test' + ORDER BY FisikTemplateCode ASC + LIMIT 1 + "; + $qry = $this->db_smartone->query($sql, array($id)); + if (!$qry) { + $prm_log = ['SELECT_FISIK_TEMPLATE', 'genkelainan/low_back_pain_screening_test']; + $xsql = $this->db_smartone->last_query(); + $log_error = $this->insert_log_error($xsql, $prm_log, json_encode(['id' => $id])); + $errors[] = "SELECT_FISIK_TEMPLATE"; + } + //echo $this->db_smartone->last_query(); + $datas = $qry->result_array(); + if ($datas && count($datas) > 0) { + $order_header_id = $datas[0]['So_ResultEntryFisikUmumT_OrderHeaderID']; + $valdata = json_decode($datas[0]['So_ResultEntryFisikUmumDetails'], true); + $header_details = $valdata['details']; + //print_r($header_details); + foreach ($header_details as $k => $v) { + $details = $v['details']; + foreach ($details as $key => $value) { + if ($value['chx'] == '1') { + $segment = strtolower(str_replace(" ", "_", $value['segment_name'])); + $data_insert = array( + 'order_id' => $order_header_id, + 'code' => $value['id_code'], + 'label' => $value['label'], + 'note' => $value['value'], + 'segment' => $segment, + 'category' => $value['table_name'] + ); + $errors = array_merge($errors, $this->insert_data_etl($data_insert, $userid)); + $rst[] = $data_insert; + } + //$this->insert_code($value['id_code'],$value['label']." | ".$segment); + } + } + } + + return $errors; + } + + function k3($type, $id, $userid) + { + $errors = []; + $rst = []; + $sql = "SELECT * + FROM fisik_template + JOIN so_resultentry_fisik_umum ON So_ResultEntryFisikUmumFisikTemplateID = FisikTemplateID AND + So_ResultEntryFisikUmumT_OrderHeaderID = ? AND So_ResultEntryFisikUmumIsActive = 'Y' + WHERE + FisikTemplateIsActive = 'Y' AND + `FisikTemplateType` = 'k3' AND + FisikTemplateTableName = ? + ORDER BY FisikTemplateCode ASC + LIMIT 1 + "; + $qry = $this->db_smartone->query($sql, array($id, $type)); + if (!$qry) { + $prm_log = ['SELECT_FISIK_TEMPLATE', 'genkelainan/k3']; + $xsql = $this->db_smartone->last_query(); + $log_error = $this->insert_log_error($xsql, $prm_log, json_encode(['id' => $id])); + $errors[] = "SELECT_FISIK_TEMPLATE"; + } + // echo $this->db_smartone->last_query(); + $datas = $qry->result_array(); + if ($datas && count($datas) > 0) { + $order_header_id = $datas[0]['So_ResultEntryFisikUmumT_OrderHeaderID']; + $valdata = json_decode($datas[0]['So_ResultEntryFisikUmumDetails'], true); + $details = $valdata['details']; + foreach ($details as $key => $value) { + if ($value['chx'] == '1') { + $data_insert = array( + 'order_id' => $order_header_id, + 'code' => $value['id_code'], + 'label' => $value['label'], + 'note' => '', + 'segment' => $type, + 'category' => $type + ); + $errors = array_merge($errors, $this->insert_data_etl($data_insert, $userid)); + $rst[] = $data_insert; + } + //$this->insert_code($value['id_code'],$value['label'].' | '.$type); + } + } + + return $errors; + } + + function loop_k3($id, $userid) + { + $errors = []; + $rspn = []; + $arr = ['faktor_fisik', 'faktor_kimia', 'faktor_biologi', 'faktor_ergonomi', 'faktor_psikologi']; + foreach ($arr as $key => $value) { + $rtn = $this->k3($value, $id, $userid); + if (count($rtn) > 0) + $errors = array_merge($errors, $rtn); + } + return $errors; + } + + function generate_summaries($orderID, $userID, $debugID = 0) + { + $errors = []; + $sql = "UPDATE t_kelainan_fisik SET + T_KelainanFiskIsActive = 'N', + T_KelainanFiskDeletedUserID = ? , + T_KelainanFiskDeleted = NOW() + WHERE + T_KelainanFiskT_OrderHeaderID = ? AND + T_KelainanFiskIsActive = 'Y'"; + $query = $this->db_smartone->query($sql, [ + $userID, + $orderID + ]); + if (!$query) { + $prm_log = ['UPDATE_T_KELAINAN_FISIK', 'genkelainan/generate_summaries']; + $xsql = $this->db_smartone->last_query(); + $log_error = $this->insert_log_error($xsql, $prm_log, json_encode(['orderID' => $orderID])); + $errors[] = "UPDATE_T_KELAINAN_FISIK"; + } + $kelainanrst = []; + $sql = "SELECT * + FROM mcu_fisiksummary + JOIN mcu_kelainan ON Mcu_kelainanID = Mcu_FisikSummaryMcu_KelainanID + WHERE Mcu_FisikSummaryIsActive = 'Y'"; + $query = $this->db_smartone->query($sql); + if (!$query) { + $prm_log = ['SELECT_MCU_FISIKSUMMARY', 'genkelainan/generate_summaries']; + $xsql = $this->db_smartone->last_query(); + $log_error = $this->insert_log_error($xsql, $prm_log, json_encode(['orderID' => $orderID])); + $errors[] = "SELECT_MCU_FISIKSUMMARY"; + } + $rumus_summaries = $query->result_array(); + + foreach ($rumus_summaries as $key => $value) { + $results = []; + $sql = "SELECT * + FROM mcu_fisiksummarydetail + WHERE + Mcu_FisikSummaryDetailMcu_FisikSummaryID = ? AND + Mcu_FisikSummaryDetailIsActive = 'Y'"; + + $query = $this->db_smartone->query($sql, [$value['Mcu_FisikSummaryID']]); + if (!$query) { + $prm_log = ['SELECT_MCU_FISIKSUMMARYDETAIL', 'genkelainan/generate_summaries']; + $xsql = $this->db_smartone->last_query(); + $log_error = $this->insert_log_error($xsql, $prm_log, json_encode(['orderID' => $orderID])); + $errors[] = "SELECT_MCU_FISIKSUMMARYDETAIL"; + } + $details = $query->result_array(); + foreach ($details as $k => $v) { + if ($v['Mcu_FisikSummaryDetailType'] == 'VK') { + $sql = "SELECT * + FROM mcu_fisikvalue + WHERE + Mcu_FisikValueT_OrderHeaderID = ? AND + Mcu_FisikValueIsActive = 'Y' AND + Mcu_FisikValueCode = ? AND + Mcu_FisikValueNote = ?"; + $query = $this->db_smartone->query($sql, [$orderID, $v['Mcu_FisikSummaryDetailCode'], $value['Mcu_KelainanName']]); + if (!$query) { + $prm_log = ['SELECT_MCU_FISIKVALUE', 'genkelainan/generate_summaries']; + $xsql = $this->db_smartone->last_query(); + $log_error = $this->insert_log_error($xsql, $prm_log, json_encode(['orderID' => $orderID])); + $errors[] = "SELECT_MCU_FISIKVALUE"; + } + + $exist_rows = $query->result_array(); + $return_x = false; + if (count($exist_rows) > 0) { + $return_x = true; + } + $results[] = $return_x; + } + + if ($v['Mcu_FisikSummaryDetailType'] == 'V') { + $sql = "SELECT * + FROM mcu_fisikvalue + JOIN mcu_fisiksummarydetail + ON Mcu_FisikSummaryDetailIsActive = 'Y' + AND Mcu_FisikSummaryDetailCode = Mcu_FisikValueCode + AND Mcu_FisikValueCode = ? + AND Mcu_FisikSummaryDetailType = 'V' + JOIN mcu_fisiksummary + ON Mcu_FisikSummaryDetailMcu_FisikSummaryID = Mcu_FisikSummaryID + AND Mcu_FisikSummaryMcu_KelainanID = ? + WHERE Mcu_FisikValueT_OrderHeaderID = ? + AND Mcu_FisikValueIsActive = 'Y' + AND Mcu_FisikSummaryDetailValue REGEXP CONCAT('(^|, )', TRIM(Mcu_FisikValueNote), '(,|$)')"; + $query = $this->db_smartone->query($sql, [$v['Mcu_FisikSummaryDetailCode'], $value['Mcu_KelainanID'], $orderID]); + if (!$query) { + $prm_log = ['SELECT_MCU_FISIKVALUE', 'genkelainan/generate_summaries']; + $xsql = $this->db_smartone->last_query(); + $log_error = $this->insert_log_error($xsql, $prm_log, json_encode(['orderID' => $orderID])); + $errors[] = "SELECT_MCU_FISIKVALUE"; + } + if ($value['Mcu_FisikSummaryID'] == $debugID) { + echo $this->db_smartone->last_query(); + } + $exist_rows = $query->result_array(); + $return_x = false; + if (count($exist_rows) > 0) { + $return_x = true; + } + $results[] = $return_x; + } + + if ($v['Mcu_FisikSummaryDetailType'] == 'C') { + $sql = "SELECT * + FROM mcu_fisikvalue + WHERE + Mcu_FisikValueT_OrderHeaderID = ? AND + Mcu_FisikValueIsActive = 'Y' AND + Mcu_FisikValueCode = ?"; + $query = $this->db_smartone->query($sql, [$orderID, $v['Mcu_FisikSummaryDetailCode']]); + if (!$query) { + $prm_log = ['SELECT_MCU_FISIKVALUE', 'genkelainan/generate_summaries']; + $xsql = $this->db_smartone->last_query(); + $log_error = $this->insert_log_error($xsql, $prm_log, json_encode(['orderID' => $orderID])); + $errors[] = "SELECT_MCU_FISIKVALUE"; + } + if ($value['Mcu_FisikSummaryID'] == $debugID) { + echo $this->db_smartone->last_query(); + } + + $exist_rows = $query->result_array(); + $return_x = false; + if (count($exist_rows) > 0) { + $return_x = true; + } + $results[] = $return_x; + } + } + + $is_kelainan = false; + if ($value['Mcu_FisikSummaryType'] == "AND") { + if (!in_array(false, $results)) + $is_kelainan = true; + + } + if ($value['Mcu_FisikSummaryType'] == "OR") { + if (in_array(true, $results)) + $is_kelainan = true; + + } + + if ($is_kelainan) { + + $sql = "INSERT INTO t_kelainan_fisik( + T_KelainanFiskT_OrderHeaderID, + T_KelainanFiskMcu_KelainanID, + T_KelainanFiskMcu_FisikSummaryID, + T_KelainanFiskCreatedUserID, + T_KelainanFiskCreated + ) VALUES(?,?,?,?,NOW())"; + $query = $this->db_smartone->query($sql, [ + $orderID, + $value['Mcu_FisikSummaryMcu_KelainanID'], + $value['Mcu_FisikSummaryID'], + $userID + ]); + if (!$query) { + $prm_log = ['INSERT_T_KELAINAN_FISIK', 'genkelainan/generate_summaries']; + $xsql = $this->db_smartone->last_query(); + $log_error = $this->insert_log_error($xsql, $prm_log, json_encode(['orderID' => $orderID])); + $errors[] = "INSERT_T_KELAINAN_FISIK"; + } + $kelainanrst[] = array( + 'id' => $value['Mcu_FisikSummaryMcu_KelainanID'], + 'name' => $value['Mcu_KelainanName'] + ); + } + + } + } + + function generateKesimpulanSaran($id, $debug = 'N') + { + //get kelainan nonlab + $sql = "SELECT + T_KelainanNonLabID AS kelainanNonlabID, + T_KelainanNonLabT_OrderHeaderID as orderID, + Mcu_KelainanID as kelainanID, + T_KelainanNonLabMcu_SummaryNonlabID As summaryID, + Mcu_KelainanName as kelainanName, + fn_get_translate_word_separator_comma(Mcu_KelainanName,2) as kelainanNameEng, + 'NONLAB' as type + FROM + t_kelainan_nonlab + JOIN mcu_summarynonlab + ON T_KelainanNonLabMcu_SummaryNonlabID = Mcu_SummaryNonlabID + AND T_KelainanNonLabT_OrderHeaderID = ? + AND T_KelainanNonLabIsActive = 'Y' + JOIN mcu_kelainan + ON Mcu_SummaryNonlabMcu_KelainanID = Mcu_KelainanID + AND Mcu_KelainanIsActive = 'Y' + GROUP BY Mcu_KelainanID + "; + $query = $this->db_smartone->query($sql, [$id]); + if (!$query) { + $prm_log = ['SELECT_T_KELAINAN_NONLAB', 'genkelainan/generate_summaries']; + $xsql = $this->db_smartone->last_query(); + $log_error = $this->insert_log_error($xsql, $prm_log, json_encode(['orderID' => $orderID])); + $errors[] = "SELECT_T_KELAINAN_NONLAB"; + } + + $kelainanNonlab = $query->result_array(); + + //get kelainan lab + $sql = "SELECT + T_KelainanLabID as kelainanLabID, + T_KelainanLabT_OrderHeaderID as orderID, + Mcu_KelainanID as kelainanID, + Mcu_SummaryLabID as summaryID, + Mcu_KelainanName as kelainanName, + fn_get_translate_word_separator_comma(Mcu_KelainanName,2) as kelainanNameEng, + 'LAB' as type + FROM t_kelainan_lab + JOIN mcu_summarylab + ON T_KelainanLabMcu_SummaryLabID = Mcu_SummaryLabID + AND Mcu_SummaryLabIsActive = 'Y' + AND T_KelainanLabT_OrderHeaderID = ? + JOIN mcu_kelainan + ON Mcu_summaryLabMcu_KelainanID = Mcu_KelainanID + AND Mcu_KelainanIsActive = 'Y' + AND T_KelainanLabIsActive = 'Y' + GROUP BY Mcu_KelainanID + "; + $query = $this->db_smartone->query($sql, [$id]); + if (!$query) { + $prm_log = ['SELECT_T_KELAINAN_LAB', 'genkelainan/generate_summaries']; + $xsql = $this->db_smartone->last_query(); + $log_error = $this->insert_log_error($xsql, $prm_log, json_encode(['orderID' => $orderID])); + $errors[] = "SELECT_T_KELAINAN_LAB"; + } + $kelainanLab = $query->result_array(); + + //get kelainan fisik + $sql = "SELECT + T_KelainanFiskID as kelainanFisikID, + T_KelainanFiskT_OrderHeaderID orderID, + Mcu_FisikSummaryID summaryID, + Mcu_KelainanID as kelainanID , + Mcu_KelainanName as kelainanName, + fn_get_translate_word_separator_comma(Mcu_KelainanName,2) as kelainanNameEng, + 'FISIK' as type + FROM t_kelainan_fisik + JOIN mcu_fisiksummary + ON T_KelainanFiskMcu_FisikSummaryID = Mcu_FisikSummaryID + AND Mcu_FisikSummaryIsActive = 'Y' + AND T_KelainanFiskT_OrderHeaderID = ? + AND T_KelainanFiskIsActive = 'Y' + JOIN mcu_kelainan + ON Mcu_FisikSummaryMcu_KelainanID = Mcu_KelainanID + AND Mcu_KelainanIsActive = 'Y' + GROUP BY Mcu_KelainanID + "; + $query = $this->db_smartone->query($sql, [$id]); + if (!$query) { + $prm_log = ['SELECT_T_KELAINAN_FISIK', 'genkelainan/generate_summaries']; + $xsql = $this->db_smartone->last_query(); + $log_error = $this->insert_log_error($xsql, $prm_log, json_encode(['orderID' => $orderID])); + $errors[] = "SELECT_T_KELAINAN_FISIK"; + } + $kelainanFisik = $query->result_array(); + + $arrMcuKelainanID = array(); + $arrMcuKelainanIDEng = array(); + $kesimpulan = ""; + $counterKesimpulan = 1; + $conclusion = ""; + $counterConclusion = 1; + for ($i = 0; $i < count($kelainanNonlab); $i++) { + $kesimpulan .= "- " . $kelainanNonlab[$i]['kelainanName'] . "\n"; + $counterKesimpulan += 1; + array_push($arrMcuKelainanID, $kelainanNonlab[$i]['kelainanID']); + + $conclusion .= "- " . $kelainanNonlab[$i]['kelainanNameEng'] . "\n"; + $counterConclusion += 1; + array_push($arrMcuKelainanIDEng, $kelainanNonlab[$i]['kelainanNameEng']); + } + for ($i = 0; $i < count($kelainanLab); $i++) { + $kesimpulan .= "- " . $kelainanLab[$i]['kelainanName'] . "\n"; + $counterKesimpulan += 1; + array_push($arrMcuKelainanID, $kelainanLab[$i]['kelainanID']); + + $conclusion .= "- " . $kelainanLab[$i]['kelainanNameEng'] . "\n"; + $counterConclusion += 1; + array_push($arrMcuKelainanIDEng, $kelainanLab[$i]['kelainanNameEng']); + } + for ($i = 0; $i < count($kelainanFisik); $i++) { + $kesimpulan .= "- " . $kelainanFisik[$i]['kelainanName'] . "\n"; + $counterKesimpulan += 1; + array_push($arrMcuKelainanID, $kelainanFisik[$i]['kelainanID']); + + $conclusion .= "- " . $kelainanFisik[$i]['kelainanNameEng'] . "\n"; + $counterConclusion += 1; + array_push($arrMcuKelainanIDEng, $kelainanFisik[$i]['kelainanNameEng']); + } + //get kelainan saran nonlab + $sql = "SELECT + Nat_AdvicekelainanID adviceID, + Nat_AdvicekelainanMcu_KelainanID mcuKelainanID, + Nat_AdviceIna saranIna, + IF(Nat_AdviceEng = '',Nat_AdviceIna, Nat_AdviceEng) saranEng, + fn_get_translate_word_separator_comma(Nat_AdviceIna,2) as translate_eng + FROM nat_advice_kelainan + JOIN nat_advice + ON Nat_AdvicekelainanNat_AdviceID = Nat_AdviceID + AND Nat_AdvicekelainanMcu_KelainanID IN ? + AND Nat_AdviceIsActive = 'Y' + AND Nat_AdvicekelainanIsActive = 'Y' + group by Nat_AdviceIna + "; + + $query = $this->db_smartone->query($sql, [$arrMcuKelainanID]); + //echo $this->db_smartone->last_query(); + if (!$query) { + $prm_log = ['SELECT_NAT_ADVICE_KELAINAN', 'genkelainan/generate_summaries']; + $xsql = $this->db_smartone->last_query(); + $log_error = $this->insert_log_error($xsql, $prm_log, json_encode(['orderID' => $orderID])); + $errors[] = "SELECT_NAT_ADVICE_KELAINAN"; + } + $arrSaran = $query->result_array(); + if (count($arrSaran) > 0) { + foreach ($arrSaran as $key => $value) { + $adv = $value['saranEng']; + if (trim($adv) == '' || $adv == $value['saranIna']) { + $adv = $value['translate_eng']; + } + $arrSaran[$key]['saranEng'] = $adv; + } + } + + $saran = ""; + $counterSaran = 1; + $advice = ""; + $counterAdvice = 1; + for ($i = 0; $i < count($arrSaran); $i++) { + $saran .= "- " . $arrSaran[$i]['saranIna'] . "\n"; + $counterSaran += 1; + $advice .= "- " . $arrSaran[$i]['saranEng'] . "\n"; + $counterAdvice += 1; + } + if ($debug == 'Y') { + $this->sys_ok(array( + "kesimpulan" => $kesimpulan, + "saran" => $saran, + "advice" => $advice, + "conclusion" => $conclusion, + )); + } + else { + return array( + "kesimpulan" => $kesimpulan, + "saran" => $saran, + "advice" => $advice, + "conclusion" => $conclusion, + ); + } + } + + function generate_fitness_category($orderID) + { + $sql = " SELECT 'lab' as type, + T_KelainanLabID, + Mcu_KelainanName, + fn_get_translate_word_separator_comma(Mcu_KelainanName,2) as Mcu_KelainanNameEng, + Mcu_FitnessCategoryID, + Mcu_FitnessCategoryName, + Mcu_FitnessCategoryEng, + Mcu_FitnessCategoryLevel, + Nat_TestName + FROM t_kelainan_lab + JOIN mcu_summarylab ON T_KelainanLabMcu_SummaryLabID = Mcu_SummaryLabID + JOIN mcu_kelainan ON Mcu_summaryLabMcu_KelainanID = Mcu_KelainanID + JOIN mcu_fitness_category ON Mcu_SummaryLabMcu_FitnessCategoryID = Mcu_FitnessCategoryID + JOIN nat_test ON Mcu_SummaryLabNat_TestID = Nat_TestID + WHERE + T_KelainanLabT_OrderHeaderID = ? AND + T_KelainanLabIsActive= 'Y' + UNION + SELECT 'nonlab' as type, + T_KelainanNonLabID, + Mcu_KelainanName, + fn_get_translate_word_separator_comma(Mcu_KelainanName,2) as Mcu_KelainanNameEng, + Mcu_FitnessCategoryID, + Mcu_FitnessCategoryName, + Mcu_FitnessCategoryEng, + Mcu_FitnessCategoryLevel, + Nat_TestName + FROM t_kelainan_nonlab + JOIN mcu_summarynonlab ON T_KelainanNonLabMcu_SummaryNonlabID = Mcu_SummaryNonlabID + JOIN mcu_kelainan ON Mcu_SummaryNonlabMcu_KelainanID = Mcu_KelainanID + JOIN mcu_fitness_category ON Mcu_SummaryNonlabMcu_FitnessCategoryID = Mcu_FitnessCategoryID + JOIN nat_test ON Mcu_SummaryNonlabNat_TestID = Nat_TestID + WHERE + T_KelainanNonLabT_OrderHeaderID = ? AND + T_KelainanNonLabIsActive= 'Y' + UNION + SELECT 'fisik' as type, + T_KelainanFiskID, + Mcu_KelainanName, + fn_get_translate_word_separator_comma(Mcu_KelainanName,2) as Mcu_KelainanNameEng, + Mcu_FitnessCategoryID, + Mcu_FitnessCategoryName, + Mcu_FitnessCategoryEng, + Mcu_FitnessCategoryLevel, + GROUP_CONCAT(CONCAT(Mcu_FisikValueLabel,'|',Mcu_FisikValueSegment,'|',Mcu_FisikValueCategory)) as Nat_TestName + FROM t_kelainan_fisik + JOIN mcu_fisiksummary ON T_KelainanFiskMcu_FisikSummaryID = Mcu_FisikSummaryID + JOIN mcu_kelainan ON Mcu_FisikSummaryMcu_KelainanID = Mcu_KelainanID + JOIN mcu_fitness_category ON Mcu_FisikSummaryMcu_FitnessCategoryID = Mcu_FitnessCategoryID + JOIN mcu_fisiksummarydetail ON Mcu_FisikSummaryDetailMcu_FisikSummaryID = Mcu_FisikSummaryID AND + Mcu_FisikSummaryDetailIsActive = 'Y' + JOIN mcu_fisikvalue ON Mcu_FisikValueT_OrderHeaderID = T_KelainanFiskT_OrderHeaderID AND + Mcu_FisikSummaryDetailCode = Mcu_FisikValueCode AND Mcu_FisikValueIsActive = 'Y' + WHERE + T_KelainanFiskT_OrderHeaderID = ? AND + T_KelainanFiskIsActive = 'Y' + GROUP BY T_KelainanFiskID"; + $query = $this->db_smartone->query($sql, array($orderID, $orderID, $orderID)); + //echo $this->db_smartone->last_query(); + $rtn = $query->result_array(); + $status = array("id" => "1", "name" => "BAIK", "name_eng" => "FIT FOR WORK", "level" => "1"); + if (count($rtn) > 0) { + $max = 0; + foreach ($rtn as $key => $value) { + if (intval($value['Mcu_FitnessCategoryLevel']) > $max) { + $max = intval($value['Mcu_FitnessCategoryLevel']); + $status = array("id" => $value['Mcu_FitnessCategoryID'], "name" => $value['Mcu_FitnessCategoryName'], "name_eng" => $value['Mcu_FitnessCategoryEng'], "level" => $value['Mcu_FitnessCategoryLevel']); + } + + } + } + + return array("status" => $status, "data" => $rtn); + } + + function translate_word($word, $langid = 1) + { + if ($langid == 1) { + return $word; + } + else { + $sql = "SELECT * FROM translate_word WHERE Translate_WordIsActive = 'Y' AND Translate_WordFrom = '{$word}'"; + //echo $sql; + $qry = $this->db_smartone->query($sql); + if (!$qry) { + return $word; + } + + $rows = $qry->result_array(); + if (count($rows) > 0) { + return $rows[0]["Translate_WordTo"]; + } + else { + return $word; + } + } + } + + function translate_multiline_text($text, $langid = 1) + { + // Split the text into lines + $lines = explode("\n", $text); + + // Translate each line + $translated_lines = array_map(function ($line) use ($langid) { + // Remove the leading "- " and translate the rest + $trimmed_line = ltrim($line, "- "); + return "- " . $this->translate_sentence($trimmed_line, $langid); + }, $lines); + + // Join the translated lines back into a multiline string + return implode("\n", $translated_lines); + } + + function translate_sentence($sentence, $langid = 1) + { + // Split the sentence into words + $words = preg_split('/[\s-]+/', $sentence); + + // Translate each word + $translated_words = array_map(function ($word) use ($langid) { + return $this->translate_word($word, $langid); + }, $words); + + // Join the translated words back into a sentence + return implode(' ', $translated_words); + } + + function insert_data_etl($data, $userid) + { + $errors = []; + if ($data) { + + /*$sql = "UPDATE mcu_fisikvalue SET + Mcu_FisikValueIsActive = 'N', + Mcu_FisikValueLastUpdated = NOW() , + Mcu_FisikValueLastUpdatedUserID = ? + WHERE + Mcu_FisikValueT_OrderHeaderID = ? AND + Mcu_FisikValueCode = ? AND + Mcu_FisikValueIsActive = 'Y'"; + $qry = $this->db_smartone->query($sql,array($userid,$data['order_id'],$data['code'])); + if (! $qry) { + return false; + }*/ + + $sql = "SELECT COUNT(*) as xcount, Mcu_FisikValueID as id + FROM mcu_fisikvalue + WHERE + Mcu_FisikValueT_OrderHeaderID = ? AND + Mcu_FisikValueCode = ? + LIMIT 1 + "; + $qry = $this->db_smartone->query($sql, array($data['order_id'], $data['code'])); + if (!$qry) { + $prm_log = ['SELECT_MCU_FISIKVALUE', 'genkelainan/insert_data_etl']; + $xsql = $this->db_smartone->last_query(); + $log_error = $this->insert_log_error($xsql, $prm_log, json_encode($data)); + $errors[] = "SELECT_MCU_FISIKVALUE"; + + } + + //echo $this->db_smartone->last_query(); + //print_r($data); + //echo $data['code']; + /*if($data['code'] == 'bmi_classification_asia_pacific'){ + echo $this->db_smartone->last_query(); + }*/ + + $exist_dt = $qry->row_array(); + /*if($data['code'] == 'bmi_classification_asia_pacific'){ + print_r($exist_dt); + }*/ + + if ($exist_dt['xcount'] > 0) { + $sql = "UPDATE mcu_fisikvalue SET + Mcu_FisikValueIsActive = 'Y', + Mcu_FisikValueLastUpdated = NOW() , + Mcu_FisikValueLastUpdatedUserID = ?, + Mcu_FisikValueLabel = ?, + Mcu_FisikValueNote = ?, + Mcu_FisikValueSegment = ?, + Mcu_FisikValueCategory = ? + WHERE + Mcu_FisikValueID = ? + "; + $qry = $this->db_smartone->query($sql, array($userid, $data['label'], $data['note'], $data['segment'], $data['category'], $exist_dt['id'])); + if (!$qry) { + $prm_log = ['UPDATE_MCU_FISIKVALUE', 'genkelainan/insert_data_etl']; + $xsql = $this->db_smartone->last_query(); + $log_error = $this->insert_log_error($xsql, $prm_log, json_encode($data)); + $errors[] = "UPDATE_MCU_FISIKVALUE"; + } + } + else { + $sql = "INSERT INTO mcu_fisikvalue ( + `Mcu_FisikValueT_OrderHeaderID`, + `Mcu_FisikValueCode`, + `Mcu_FisikValueLabel`, + `Mcu_FisikValueNote`, + `Mcu_FisikValueSegment`, + `Mcu_FisikValueCategory`, + `Mcu_FisikValueCreated`, + `Mcu_FisikValueCreatedUserID` + ) VALUES(?,?,?,?,?,?,NOW(),?)"; + $qry = $this->db_smartone->query($sql, array( + $data['order_id'], + $data['code'], + $data['label'], + $data['note'], + $data['segment'], + $data['category'], + $userid + )); + if (!$qry) { + $prm_log = ['INSERT_MCU_FISIKVALUE', 'genkelainan/insert_data_etl']; + $xsql = $this->db_smartone->last_query(); + $log_error = $this->insert_log_error($xsql, $prm_log, json_encode($data)); + $errors[] = "INSERT_MCU_FISIKVALUE"; + } + } + } + return $errors; + } + + function insert_log_error($log_sql, $params, $data = '') + { + // Membersihkan SQL dari \r\n dan whitespace berlebih + //$clean_log_sql = trim(str_replace(["\r\n", "\r", "\n"], ' ', $log_sql)); + + $sql = "INSERT INTO one_lab_log.error_log( + ErrorLogCode, + ErrorLogName, + ErrorLogDescription, + ErrorLogData, + ErrorLogOrderCreated + ) + VALUES( + ?,?,?,?,NOW() + )"; + + $query = $this->db_smartone->query($sql, [$params[0], $params[1], $log_sql, json_encode($data)]); + // echo $this->db_log->last_query(); + if (!$query) { + return false; + } + return true; + } +} \ No newline at end of file diff --git a/application/libraries/Genreportfisik.php b/application/libraries/Genreportfisik.php new file mode 100644 index 00000000..2d1a78fe --- /dev/null +++ b/application/libraries/Genreportfisik.php @@ -0,0 +1,1050 @@ +db_smartone = $CI->load->database("default", true); + } + + function clean_mysqli_connection($dbc) + { + while (mysqli_more_results($dbc)) { + if (mysqli_next_result($dbc)) { + $result = mysqli_use_result($dbc); + if (get_class($result) == 'mysqli_stmt') { + mysqli_stmt_free_result($result); + } + else { + unset($result); + } + } + } + } + + // ============================================================ + // ENTRY POINT UTAMA (GET) + // Parameter : $order_header_id = T_OrderHeaderID + // Mengembalikan JSON object berisi semua data fisik yang sudah + // diproses, termasuk dukungan bilingual jika + // T_OrderHeaderAddOnSecondM_LangID > 0 + // ============================================================ + function get_data($order_header_id) + { + $order_header_id = intval($order_header_id); + if ($order_header_id <= 0) { + echo json_encode(['error' => 'Invalid T_OrderHeaderID']); + return; + } + + // -- Cek apakah perlu bilingual -- + $sql = "SELECT T_OrderHeaderAddOnSecondM_LangID + FROM t_orderheaderaddon + WHERE T_OrderHeaderAddOnT_OrderHeaderID = ? + AND T_OrderHeaderAddOnIsActive = 'Y' + LIMIT 1"; + $qry = $this->db_smartone->query($sql, [$order_header_id]); + $addon_row = $qry ? $qry->row_array() : []; + $second_langid = isset($addon_row['T_OrderHeaderAddOnSecondM_LangID']) + ? intval($addon_row['T_OrderHeaderAddOnSecondM_LangID']) + : 0; + + $result = []; + + $result['tanda_vital'] = $this->get_tanda_vital($order_header_id); + $result['status_gizi'] = $this->get_status_gizi($order_header_id); + $result['persepsi_warna'] = $this->get_persepsi_warna($order_header_id); + $result['visus'] = $this->get_visus($order_header_id); + $result['body_fat'] = $this->get_body_fat($order_header_id); + + if ($second_langid > 0) { + $result['tanda_vital_lang2'] = $this->get_tanda_vital($order_header_id, $second_langid); + $result['status_gizi_lang2'] = $this->get_status_gizi($order_header_id, $second_langid); + $result['persepsi_warna_lang2'] = $this->get_persepsi_warna($order_header_id, $second_langid); + $result['visus_lang2'] = $this->get_visus($order_header_id, $second_langid); + } + + $result['second_langid'] = $second_langid; + + echo json_encode($result); + } + + // ============================================================ + // ENTRY POINT UTAMA (SAVE) + // Membaca semua row so_resultentry_fisik_umum untuk 1 order, + // lalu INSERT ke so_resultentry_fisik_summary (1 tabel). + // • tanda_vital → 1 baris per item pengukuran + // • template lain → 1 baris per item yang abnormal (dicentang+tidak normal) + // + // Idempotent: hapus dulu data lama (IsActive='Y') sebelum insert. + // + // @param int $order_header_id T_OrderHeaderID + // @param int $user_id M_UserID + // @return array ['success'=>bool, 'saved'=>int, 'errors'=>array] + // ============================================================ + function save_data($order_header_id, $user_id = 0) + { + $order_header_id = intval($order_header_id); + $result = [ + 'success' => false, + 'saved' => 0, + 'errors' => [], + ]; + + if ($order_header_id <= 0) { + $result['errors'][] = 'Invalid T_OrderHeaderID'; + return $result; + } + + // -- 1. Ambil semua template yang sudah diisi untuk order ini -- + $sql = "SELECT + srfu.*, + ft.FisikTemplateCode, + ft.FisikTemplateType, + ft.FisikTemplateTableName, + ft.FisikTemplateTitle + FROM so_resultentry_fisik_umum srfu + JOIN fisik_template ft + ON srfu.So_ResultEntryFisikUmumFisikTemplateID = ft.FisikTemplateID + AND ft.FisikTemplateIsActive = 'Y' + WHERE srfu.So_ResultEntryFisikUmumT_OrderHeaderID = ? + AND srfu.So_ResultEntryFisikUmumIsActive = 'Y'"; + $qry = $this->db_smartone->query($sql, [$order_header_id]); + if (!$qry) { + $result['errors'][] = 'Query so_resultentry_fisik_umum gagal'; + return $result; + } + $rows = $qry->result_array(); + if (count($rows) == 0) { + $result['errors'][] = 'Tidak ada data fisik untuk order ini'; + return $result; + } + + // -- 2. Hapus data lama (soft-delete dulu, lalu truncate baris lama) -- + // Gunakan hard-delete (DELETE) untuk idempotent yang bersih, + // karena data lama sudah di-soft-delete saat unval1. + $this->db_smartone->query( + "DELETE FROM so_resultentry_fisik_summary + WHERE So_ResultEntryFisikSummaryT_OrderHeaderID = ?", + [$order_header_id] + ); + + $now = date('Y-m-d H:i:s'); + + // -- 3. Proses tiap template -- + foreach ($rows as $row) { + $json_str = $row['So_ResultEntryFisikUmumDetails']; + $template_id = intval($row['So_ResultEntryFisikUmumFisikTemplateID']); + $tmpl_code = $row['FisikTemplateCode']; + $tmpl_title = $row['FisikTemplateTitle']; + $tmpl_table = $row['FisikTemplateTableName']; + + $d = json_decode($json_str, true); + if (!$d) { + $result['errors'][] = "JSON invalid untuk template {$tmpl_code}"; + continue; + } + + $type_form = strtoupper($d['type_form'] ?? ''); + + $is_tanda_vital = ( + $tmpl_table === 'tanda_vital' || + strtoupper($tmpl_title) === 'TANDA VITAL' || + in_array($tmpl_code, ['FI00', 'FI00.TD']) + ); + + if ($is_tanda_vital) { + // -- Tanda Vital: 1 baris per item pengukuran -- + $tv_items = $this->build_tanda_vital_rows($d); + foreach ($tv_items as $tv) { + $ok = $this->insert_summary_row( + $order_header_id, $template_id, $tmpl_code, $tmpl_table, + $tv['id_code'], $tv['label'], $tv['label'], + $tv['value'], $tv['value2'], + $tv['value_numeric'], $tv['value2_numeric'], + null, null, null, + 'tanda_vital', + $user_id, $now + ); + if ($ok) $result['saved']++; + } + continue; + } + + // -- Template lain: simpan semua item yang dicentang -- + // Aturan: + // • is_normal='Y' + chx=true → type='normal' + // • is_normal='N' + chx=true → type='kelainan' + // • XXV chx_y=true → type='normal' + // • XXV chx_x=true → type='kelainan' + // • Riwayat/K3: chx=true → type='kelainan' + // • Riwayat/K3: tidak ada yg dicentang → 1 baris 'Tidak Ada' type='normal' + $details = $d['details'] ?? []; + $tmpl_type = strtoupper($d['type_form'] ?? ''); + $is_riwayat = in_array($tmpl_type, ['XV', 'XVS', 'XO', 'XD', 'XVS-LXX']) + && !isset($d['flag_normal']) // Fisik punya flag_normal, Riwayat tidak + && ($tmpl_type !== 'XV' || !$this->has_is_normal_field($details)); + // Lebih tepat: Riwayat tidak punya is_normal di items-nya + $is_riwayat_or_k3 = $this->is_riwayat_or_k3_template($details, $tmpl_type); + + $any_checked = false; + $saved_in_tmpl = 0; + + foreach ($details as $item) { + if (isset($item['details']) && is_array($item['details'])) { + $segment = $item['name'] ?? ($item['segment_name'] ?? null); + foreach ($item['details'] as $sub_item) { + $sub_item['_segment'] = $segment; + $saved = $this->save_item_by_rule( + $order_header_id, $template_id, $tmpl_code, + $tmpl_table, $tmpl_type, $tmpl_title, $sub_item, $user_id, $now + ); + if ($saved) { $result['saved']++; $saved_in_tmpl++; $any_checked = true; } + } + } + else { + $saved = $this->save_item_by_rule( + $order_header_id, $template_id, $tmpl_code, + $tmpl_table, $tmpl_type, $tmpl_title, $item, $user_id, $now + ); + if ($saved) { $result['saved']++; $saved_in_tmpl++; $any_checked = true; } + } + } + + // -- Jika Riwayat/K3 tidak ada yang dicentang → simpan 'Tidak Ada' -- + if ($is_riwayat_or_k3 && !$any_checked) { + $ok = $this->insert_summary_row( + $order_header_id, $template_id, $tmpl_code, $tmpl_table, + 'tidak_ada', 'Tidak Ada', 'Tidak Ada', + null, null, null, null, + null, null, null, + 'normal', + $user_id, $now + ); + if ($ok) $result['saved']++; + } + } + + $result['success'] = true; + return $result; + } + + // ============================================================ + // Helper: cek apakah template ini Riwayat atau K3 + // (bedanya dengan Fisik: items tidak punya is_normal) + // ============================================================ + private function is_riwayat_or_k3_template($details, $type_form) + { + if ($type_form === 'XVV') return true; // K3 selalu XVV + + // Cek apakah ada item dengan is_normal → berarti Fisik, bukan Riwayat + foreach ($details as $item) { + if (isset($item['is_normal'])) return false; + if (isset($item['details'])) { + foreach ($item['details'] as $sub) { + if (isset($sub['is_normal'])) return false; + } + } + } + return true; // tidak ada is_normal → Riwayat + } + + // ============================================================ + // Helper: cek apakah detail punya field is_normal (Fisik) + // ============================================================ + private function has_is_normal_field($details) + { + foreach ($details as $item) { + if (isset($item['is_normal'])) return true; + if (isset($item['details'])) { + foreach ($item['details'] as $sub) { + if (isset($sub['is_normal'])) return true; + } + } + } + return false; + } + + // ============================================================ + // SAVE ITEM BY RULE + // Tentukan summary_type berdasarkan is_normal + chx + // Hanya simpan jika item dicentang (chx=true / chx_x / chx_y) + // $tmpl_title dipakai untuk LabelDisplay: "JantungTitle : segment" + // ============================================================ + private function save_item_by_rule( + $order_header_id, $template_id, $tmpl_code, + $tmpl_table, $type_form, $tmpl_title, $item, $user_id, $now + ) { + $chx = !empty($item['chx']) || $item['chx'] === 1 || $item['chx'] === '1' || $item['chx'] === true; + $chx_x = !empty($item['chx_x']) || $item['chx_x'] === 1 || $item['chx_x'] === '1' || $item['chx_x'] === true; + $chx_y = !empty($item['chx_y']) || $item['chx_y'] === 1 || $item['chx_y'] === '1' || $item['chx_y'] === true; + $is_normal_field = isset($item['is_normal']) ? strtoupper($item['is_normal']) : null; + + $summary_type = null; + + // Skip tipe yang tidak masuk summary + $skip_types = ['VXX+', 'VXX', 'V', 'T', 'XXVWL']; + if (in_array($type_form, $skip_types)) return false; + + if ($type_form === 'XXV') { + // chx_y = Normal, chx_x = Tidak Normal + if ($chx_y) $summary_type = 'normal'; + elseif ($chx_x) $summary_type = 'kelainan'; + else return false; + } + elseif ($type_form === 'XVV') { + // K3: chx = ada paparan = kelainan + if (!$chx) return false; + $summary_type = 'kelainan'; + } + elseif ($type_form === 'TOOTH') { + if (!$chx) return false; + $summary_type = 'kelainan'; + } + else { + // XV, XVS, XVS-LXX, XO, XD, X, Riwayat ... + if (!$chx) return false; + if ($is_normal_field === 'Y') $summary_type = 'normal'; + elseif ($is_normal_field === 'N') $summary_type = 'kelainan'; + else $summary_type = 'kelainan'; // Riwayat (tidak ada is_normal) → kelainan + } + + $id_code = $item['id_code'] ?? ''; + $label = $item['label'] ?? ''; + $value = $item['value'] ?? null; + $segment = $item['segment_name'] ?? ($item['_segment'] ?? null); + $value_sumber = $item['value_sumber'] ?? null; + $value_lama = $item['value_lama'] ?? null; + + // -- Bangun LabelDisplay & Value -- + // + // Pola universal: + // Fisik ber-segment → "Jantung : Apex" + // Fisik tanpa segment → "Deformitas" (label saja) + // XO (Penyakit Keluarga) → "Riwayat Penyakit Keluarga : Diabetes Melitus" + // Value = "Ayah, Ibu" (dari options.selected) + // XD (Imunisasi) → "Riwayat Imunisasi : Hepatitis A" + // XVS Riwayat ber-segment → "Riwayat Kebiasaan Hidup : Minum alkohol" + // XV Riwayat tanpa segment → "Riwayat Penyakit : Gastritis (maag)" + // + // Cara membedakan Riwayat vs Fisik: is_normal ada → Fisik, tidak ada → Riwayat + + $title_clean = ucwords(strtolower(trim($tmpl_title))); + $is_riwayat_item = ($is_normal_field === null) + && !in_array($type_form, ['XXV', 'XVV', 'TOOTH']); + + if ($type_form === 'XO') { + // LabelDisplay = "Riwayat Penyakit Keluarga : Diabetes Melitus" + // Value = "Ayah, Ibu" + $label_display = $title_clean . ' : ' . $label; + if (!empty($item['options'])) { + $selected_opts = []; + foreach ($item['options'] as $opt) { + if (!empty($opt['selected'])) { + $selected_opts[] = $opt['label']; + } + } + if (count($selected_opts) > 0) { + $value = implode(', ', $selected_opts); + } + } + } + elseif ($is_riwayat_item && $segment) { + // Riwayat ber-segment: "Riwayat Kebiasaan Hidup : Minum alkohol" + $label_display = $title_clean . ' : ' . $segment; + } + elseif ($is_riwayat_item) { + // Riwayat tanpa segment: "Riwayat Penyakit : Gastritis (maag)" + $label_display = $title_clean . ' : ' . $label; + } + elseif ($segment) { + // Fisik ber-segment (is_normal ada): "Jantung : Apex" + $label_display = $title_clean . ' : ' . $segment; + } + else { + // Fisik tanpa segment: "Deformitas" + $label_display = $label; + } + + return $this->insert_summary_row( + $order_header_id, $template_id, $tmpl_code, $tmpl_table, + $id_code, $label, $label_display, + $value, null, null, null, + $segment, $value_sumber, $value_lama, + $summary_type, + $user_id, $now + ); + } + + // ============================================================ + // BUILD TANDA VITAL ROWS + // Dari JSON detail tanda vital, buat array item siap INSERT + // id_code: tanda_vital_5 → TD (sistole + diastole) + // tanda_vital_6 → Suhu + // tanda_vital_1 → Nadi + // tanda_vital_2 → Ritme nadi + // tanda_vital_3 → Laju nafas + // tanda_vital_4 → Pola nafas + // ============================================================ + private function build_tanda_vital_rows($d) + { + $rows = []; + foreach ($d['details'] as $item) { + $code = $item['id_code'] ?? ''; + + // Tekanan Darah: value_x=sistole, value_y=diastole + if ($code === 'tanda_vital_5') { + $sistole = $item['value_x'] ?? null; + $diastole = $item['value_y'] ?? null; + $rows[] = [ + 'id_code' => 'tanda_vital_5', + 'label' => 'Tekanan Darah', + 'value' => $sistole, + 'value2' => $diastole, + 'value_numeric' => is_numeric($sistole) ? floatval($sistole) : null, + 'value2_numeric' => is_numeric($diastole) ? floatval($diastole) : null, + ]; + } + + // Suhu: value=angka, chx_x/chx_y → label ket (Febrile/Afebrile) + if ($code === 'tanda_vital_6') { + $suhu_val = $item['value'] ?? null; + if (!empty($item['chx_x'])) { + $ket = $item['label_x'] ?? null; + } + elseif (!empty($item['chx_y'])) { + $ket = $item['label_y'] ?? null; + } + else { + $ket = null; + } + $rows[] = [ + 'id_code' => 'tanda_vital_6', + 'label' => 'Suhu', + 'value' => $ket, + 'value2' => $suhu_val, + 'value_numeric' => null, + 'value2_numeric' => is_numeric($suhu_val) ? floatval($suhu_val) : null, + ]; + } + + // Denyut Nadi + if ($code === 'tanda_vital_1') { + $val = $item['value'] ?? null; + $rows[] = [ + 'id_code' => 'tanda_vital_1', + 'label' => 'Denyut Nadi', + 'value' => $val, + 'value2' => null, + 'value_numeric' => is_numeric($val) ? floatval($val) : null, + 'value2_numeric' => null, + ]; + } + + // Ritme Nadi: chx_y=Reguler, chx_x=Ireguler + if ($code === 'tanda_vital_2') { + if (!empty($item['chx_y'])) { + $ritme = $item['label_y'] ?? 'Reguler'; + } + elseif (!empty($item['chx_x'])) { + $ritme = $item['label_x'] ?? 'Ireguler'; + } + else { + $ritme = null; + } + $rows[] = [ + 'id_code' => 'tanda_vital_2', + 'label' => 'Ritme Nadi', + 'value' => $ritme, + 'value2' => null, + 'value_numeric' => null, + 'value2_numeric' => null, + ]; + } + + // Laju Pernafasan + if ($code === 'tanda_vital_3') { + $val = $item['value'] ?? null; + $rows[] = [ + 'id_code' => 'tanda_vital_3', + 'label' => 'Laju Pernafasan', + 'value' => $val, + 'value2' => null, + 'value_numeric' => is_numeric($val) ? floatval($val) : null, + 'value2_numeric' => null, + ]; + } + + // Pola Nafas + if ($code === 'tanda_vital_4') { + if (!empty($item['chx_y'])) { + $pola = $item['label_y'] ?? 'Normal'; + } + elseif (!empty($item['chx_x'])) { + $pola = $item['label_x'] ?? 'Tidak normal'; + } + else { + $pola = null; + } + $rows[] = [ + 'id_code' => 'tanda_vital_4', + 'label' => 'Pola Nafas', + 'value' => $pola, + 'value2' => null, + 'value_numeric' => null, + 'value2_numeric' => null, + ]; + } + } + return $rows; + } + + // ============================================================ + // SAVE KELAINAN ITEM (legacy - masih dipakai oleh is_item_abnormal) + // ============================================================ + private function save_kelainan_item( + $order_header_id, $template_id, $tmpl_code, + $tmpl_table, $type_form, $item, $user_id, $now + ) { + if (!$this->is_item_abnormal($type_form, $item)) { + return false; + } + + $id_code = $item['id_code'] ?? ''; + $label = $item['label'] ?? ''; + $value = $item['value'] ?? null; + $segment = $item['segment_name'] ?? ($item['_segment'] ?? null); + $value_sumber = $item['value_sumber'] ?? null; + $value_lama = $item['value_lama'] ?? null; + + return $this->insert_summary_row( + $order_header_id, $template_id, $tmpl_code, $tmpl_table, + $id_code, $label, + $value, null, null, null, + $segment, $value_sumber, $value_lama, + 'kelainan', + $user_id, $now + ); + } + + // ============================================================ + // INSERT KE so_resultentry_fisik_summary + // Satu fungsi INSERT untuk semua tipe baris + // $label_display = teks siap tampil (Jantung : Apex, DM (Ayah), dst) + // ============================================================ + private function insert_summary_row( + $order_header_id, $template_id, $tmpl_code, $tmpl_table, + $id_code, $label, $label_display, + $value, $value2, $value_numeric, $value2_numeric, + $segment, $value_sumber, $value_lama, + $summary_type, + $user_id, $now + ) { + $sql = "INSERT INTO so_resultentry_fisik_summary ( + So_ResultEntryFisikSummaryT_OrderHeaderID, + So_ResultEntryFisikSummaryFisikTemplateID, + So_ResultEntryFisikSummaryFisikTemplateCode, + So_ResultEntryFisikSummaryTableName, + So_ResultEntryFisikSummaryIdCode, + So_ResultEntryFisikSummaryLabel, + So_ResultEntryFisikSummaryLabelDisplay, + So_ResultEntryFisikSummarySegment, + So_ResultEntryFisikSummaryValue, + So_ResultEntryFisikSummaryValue2, + So_ResultEntryFisikSummaryValueNumeric, + So_ResultEntryFisikSummaryValue2Numeric, + So_ResultEntryFisikSummaryValueSumber, + So_ResultEntryFisikSummaryValueLama, + So_ResultEntryFisikSummaryType, + So_ResultEntryFisikSummaryIsActive, + So_ResultEntryFisikSummaryCreated, + So_ResultEntryFisikSummaryCreatedUserID, + So_ResultEntryFisikSummaryLastUpdated, + So_ResultEntryFisikSummaryLastUpdatedUserID + ) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,'Y',?,?,?,?)"; + + $qry = $this->db_smartone->query($sql, [ + $order_header_id, + $template_id, + $tmpl_code, + $tmpl_table, + $id_code, + $label, + $label_display, + $segment, + $value, + $value2, + $value_numeric, + $value2_numeric, + $value_sumber, + $value_lama, + $summary_type, + $now, + $user_id, + $now, + $user_id, + ]); + + return (bool)$qry; + } + + // ============================================================ + // IS ITEM ABNORMAL? + // Lihat comment lengkap di versi sebelumnya + // ============================================================ + private function is_item_abnormal($type_form, $item) + { + $chx = !empty($item['chx']) || $item['chx'] === 1 || $item['chx'] === '1' || $item['chx'] === true; + $chx_x = !empty($item['chx_x']) || $item['chx_x'] === 1 || $item['chx_x'] === '1' || $item['chx_x'] === true; + $is_normal = isset($item['is_normal']) ? strtoupper($item['is_normal']) : null; + + $skip_types = ['VXX+', 'VXX', 'V', 'T', 'XXVWL', 'XVS3R']; + if (in_array($type_form, $skip_types)) return false; + + if ($type_form === 'XXV') return $chx_x; + if ($type_form === 'XVV') return $chx; + if ($type_form === 'TOOTH') return $chx; + + if (in_array($type_form, ['XV', 'XVS', 'XVS-LXX', 'XD', 'XO'])) { + if ($is_normal !== null) { + return ($chx && $is_normal === 'N'); + } + return $chx; + } + + if ($type_form === 'X') return $chx; + + return $chx; + } + + // ============================================================ + // GET TANDA VITAL + // Baca dari so_resultentry_fisik_summary (type='tanda_vital') + // Fallback ke so_resultentry_fisik_umum jika summary belum ada + // ============================================================ + function get_tanda_vital($order_header_id, $langid = 1) + { + $empty = [ + 'td_sistole' => 'NaN', + 'td_diastole' => 'NaN', + 'td_nilai' => 'NaN', + 'td_standart' => 'NaN', + 'suhu' => 'NaN', + 'suhu_ket' => 'NaN', + 'nadi' => 'NaN', + 'ritme_nadi' => 'NaN', + 'laju_nafas' => 'NaN', + 'pola_nafas' => 'NaN', + ]; + + // -- Coba baca dari summary dulu (sudah diproses) -- + $sql = "SELECT So_ResultEntryFisikSummaryIdCode as id_code, + So_ResultEntryFisikSummaryValue as val, + So_ResultEntryFisikSummaryValue2 as val2 + FROM so_resultentry_fisik_summary + WHERE So_ResultEntryFisikSummaryT_OrderHeaderID = ? + AND So_ResultEntryFisikSummaryType = 'tanda_vital' + AND So_ResultEntryFisikSummaryIsActive = 'Y'"; + $qry = $this->db_smartone->query($sql, [$order_header_id]); + + if ($qry && count($qry->result_array()) > 0) { + $out = $empty; + foreach ($qry->result_array() as $r) { + switch ($r['id_code']) { + case 'tanda_vital_5': + $out['td_sistole'] = $r['val'] ?? ''; + $out['td_diastole'] = $r['val2'] ?? ''; + break; + case 'tanda_vital_6': + $out['suhu_ket'] = $this->translate_word($r['val'] ?? '', $langid); + $out['suhu'] = $r['val2'] ?? ''; + break; + case 'tanda_vital_1': + $out['nadi'] = ($r['val'] !== null) + ? $r['val'] . ' ' . $this->translate_word('x/menit', $langid) + : ''; + break; + case 'tanda_vital_2': + $out['ritme_nadi'] = $this->translate_word($r['val'] ?? '', $langid); + break; + case 'tanda_vital_3': + $out['laju_nafas'] = ($r['val'] !== null) + ? $r['val'] . ' ' . $this->translate_word('x/menit', $langid) + : ''; + break; + case 'tanda_vital_4': + $out['pola_nafas'] = $this->translate_word($r['val'] ?? '', $langid); + break; + } + } + return $out; + } + + // -- Fallback: baca dari so_resultentry_fisik_umum (JSON) -- + $table = ($langid == 2) ? 'so_resultentry_fisik_umum_eng' : 'so_resultentry_fisik_umum'; + $sql = "SELECT * + FROM {$table} + JOIN fisik_template + ON So_ResultEntryFisikUmumFisikTemplateID = FisikTemplateID + AND FisikTemplateIsActive = 'Y' + AND FisikTemplateTitle = 'TANDA VITAL' + WHERE So_ResultEntryFisikUmumT_OrderHeaderID = ? + AND So_ResultEntryFisikUmumIsActive = 'Y' + LIMIT 1"; + $qry = $this->db_smartone->query($sql, [$order_header_id]); + if (!$qry) return $empty; + + $rows = $qry->result_array(); + if (count($rows) == 0) return $empty; + + $d = json_decode($rows[0]['So_ResultEntryFisikUmumDetails'], true); + if (!$d || $d['title'] != 'TANDA VITAL') return $empty; + + $out = $empty; + foreach ($d['details'] as $item) { + $code = $item['id_code'] ?? ''; + if ($code === 'tanda_vital_5') { + $out['td_sistole'] = $item['value_x'] ?? ''; + $out['td_diastole'] = $item['value_y'] ?? ''; + $out['td_nilai'] = $item['value'] ?? ''; + $out['td_standart'] = $item['standart'] ?? ''; + } + if ($code === 'tanda_vital_6') { + $out['suhu'] = $item['value'] ?? ''; + if (!empty($item['chx_x'])) + $out['suhu_ket'] = $this->translate_word($item['label_x'] ?? '', $langid); + elseif (!empty($item['chx_y'])) + $out['suhu_ket'] = $this->translate_word($item['label_y'] ?? '', $langid); + } + if ($code === 'tanda_vital_1') { + $v = $item['value'] ?? ''; + $out['nadi'] = $v !== '' ? $v . ' ' . $this->translate_word('x/menit', $langid) : ''; + } + if ($code === 'tanda_vital_2') { + if (!empty($item['chx_y'])) + $out['ritme_nadi'] = $this->translate_word($item['label_y'] ?? 'Reguler', $langid); + elseif (!empty($item['chx_x'])) + $out['ritme_nadi'] = $this->translate_word($item['label_x'] ?? 'Ireguler', $langid); + } + if ($code === 'tanda_vital_3') { + $v = $item['value'] ?? ''; + $out['laju_nafas'] = $v !== '' ? $v . ' ' . $this->translate_word('x/menit', $langid) : ''; + } + if ($code === 'tanda_vital_4') { + if (!empty($item['chx_y'])) + $out['pola_nafas'] = $this->translate_word($item['label_y'] ?? 'Normal', $langid); + elseif (!empty($item['chx_x'])) + $out['pola_nafas'] = $this->translate_word($item['label_x'] ?? 'Tidak normal', $langid); + } + } + return $out; + } + + // ============================================================ + // STATUS GIZI + // ============================================================ + function get_status_gizi($order_header_id, $langid = 1) + { + $empty = [ + 'bb' => 'NaN', + 'tb' => 'NaN', + 'body_fat' => 'NaN', + 'bmi' => 'NaN', + 'bmi_classification' => 'NaN', + 'bmi_standard' => 'NaN', + ]; + + $sql = "SELECT * + FROM t_samplingso_additional_fisik_bbtb + WHERE T_SamplingAdditionalFisikBBTBT_OrderHeaderID = ? + LIMIT 1"; + $qry = $this->db_smartone->query($sql, [$order_header_id]); + if (!$qry) return $empty; + + $row = $qry->row_array(); + if (!$row) return $empty; + + $bb = $row['T_SamplingAdditionalFisikBBTBValueBB']; + $tb = $row['T_SamplingAdditionalFisikBBTBValueTB']; + $standart_bmi = $row['T_SamplingAdditionalFisikBBTBStandart']; + $bodyfat_raw = $row['T_SamplingAdditionalFisikBBTBBodyFat']; + + if (intval($bb) == 0 && intval($tb) == 0) return $empty; + + $bodyfat = ($bodyfat_raw == -1) + ? $this->translate_word('Tidak dilakukan', $langid) + : $bodyfat_raw; + + $get_bmi = $this->hitung_bmi($bb, $tb, $standart_bmi); + $bmi_class = $this->translate_word($get_bmi['class'], $langid); + + return [ + 'bb' => $bb, + 'tb' => $tb, + 'body_fat' => $bodyfat, + 'bmi' => $get_bmi['bmi'], + 'bmi_classification' => $bmi_class, + 'bmi_standard' => ucwords(str_replace('_', ' ', $standart_bmi)), + ]; + } + + // ============================================================ + // PERSEPSI WARNA + // ============================================================ + function get_persepsi_warna($order_header_id, $langid = 1) + { + $empty = ['result' => 'NaN', 'angka' => '']; + + $sql = "SELECT T_OrderDetailID FROM t_orderdetail + WHERE T_OrderDetailT_OrderHeaderID = ? + AND T_OrderDetailT_TestCode = '40111200' + AND T_OrderDetailIsActive = 'Y' LIMIT 1"; + $qry = $this->db_smartone->query($sql, [$order_header_id]); + if (!$qry || count($qry->result_array()) == 0) return $empty; + + $sql = "SELECT IFNULL(T_SamplingAdditionalFisikBWPWValue,'Z') as result, + IFNULL(T_SamplingAdditionalFisikBWPWVAngka,'') as angka + FROM t_samplingso_additional_fisik_bw + WHERE T_SamplingAdditionalFisikBWT_OrderHeaderID = ? LIMIT 1"; + $qry = $this->db_smartone->query($sql, [$order_header_id]); + if (!$qry) return $empty; + + $row = $qry->row_array(); + if (!$row) return $empty; + + if ($row['result'] == 'BW') + $result_text = 'Red Green Deficiency'; + elseif ($row['result'] == 'N') + $result_text = 'Normal'; + elseif ($row['result'] == 'X') + $result_text = $this->translate_word('Tidak dilakukan', $langid); + else + $result_text = $this->translate_word('Bahan Belum', $langid); + + return ['result' => $result_text, 'angka' => $row['angka']]; + } + + // ============================================================ + // VISUS + // ============================================================ + function get_visus($order_header_id, $langid = 1) + { + $empty = [ + 'visus_kanan' => 'NaN', 'visus_kiri' => 'NaN', + 'tk_od' => 'NaN', 'tk_os' => 'NaN', + 'dk_od' => 'NaN', 'dk_os' => 'NaN', + 'od_sph' => '-', 'od_cyl' => '-', 'od_x' => '-', + 'os_sph' => '-', 'os_cyl' => '-', 'os_x' => '-', + 'add' => '-', 'kelainan_kanan' => '', 'kelainan_kiri' => '', + ]; + + $sql = "SELECT T_OrderDetailID FROM t_orderdetail + WHERE T_OrderDetailT_OrderHeaderID = ? + AND T_OrderDetailT_TestCode = '40111000' + AND T_OrderDetailIsActive = 'Y' LIMIT 1"; + $qry = $this->db_smartone->query($sql, [$order_header_id]); + if (!$qry || count($qry->result_array()) == 0) return $empty; + + $sql = "SELECT *, IFNULL(T_SamplingAdditionalFisikVisusID, 0) as visus_id + FROM t_samplingso_additional_fisik_visus + WHERE T_SamplingAdditionalFisikVisusT_OrderHeaderID = ? LIMIT 1"; + $qry = $this->db_smartone->query($sql, [$order_header_id]); + if (!$qry) return $empty; + + $row = $qry->row_array(); + if (!$row || intval($row['visus_id']) == 0) { + return array_merge($empty, [ + 'visus_kanan' => $this->translate_word('Bahan belum', $langid), + 'visus_kiri' => $this->translate_word('Bahan belum', $langid), + ]); + } + + $normal = ['20/20', '20/25', '6/6', '6/7.5', '6/7,5']; + $tk_od = $row['T_SamplingAdditionalFisikVisusTKODV']; + $tk_os = $row['T_SamplingAdditionalFisikVisusTKOSV']; + $dk_od = $row['T_SamplingAdditionalFisikVisusDKODV']; + $dk_os = $row['T_SamplingAdditionalFisikVisusDKOSV']; + $od_sph = $row['T_SamplingAdditionalFisikVisusODSPH']; + $od_cyl = $row['T_SamplingAdditionalFisikVisusODCYL']; + $od_x = $row['T_SamplingAdditionalFisikVisusODX']; + $os_sph = trim($row['T_SamplingAdditionalFisikVisusOSSPH']); + $os_cyl = $row['T_SamplingAdditionalFisikVisusOSCYL']; + $os_x = $row['T_SamplingAdditionalFisikVisusOSX']; + $od_add = $row['T_SamplingAdditionalFisikVisusADD']; + + $is_valid = function ($v) { + $v = trim($v); + return $v !== '' && $v !== '-' && $v !== '--' && $v !== '/-' + && $v !== '/' && $v !== '-/' && strtolower($v) !== 'plano' + && strtolower($v) !== 'tidak terkoreksi' + && strtolower($v) !== 'tidak dapat dinilai'; + }; + + $kelainan_kanan = ''; + if ($is_valid($od_sph)) $kelainan_kanan .= $od_sph . ' (' . $this->translate_word('Miopia', $langid) . ')'; + if ($is_valid($od_cyl)) { + if ($kelainan_kanan != '') $kelainan_kanan .= ', '; + $kelainan_kanan .= 'Cyl ' . $od_cyl; + $kelainan_kanan .= $is_valid($od_x) + ? ' axis ' . $od_x . ' (' . $this->translate_word('Astigmatismus', $langid) . ')' + : ' (' . $this->translate_word('Astigmatismus', $langid) . ')'; + } + if ($is_valid($od_add)) { + if ($kelainan_kanan != '') $kelainan_kanan .= ', '; + $kelainan_kanan .= $od_add . ' (' . $this->translate_word('Presbiopia', $langid) . ')'; + } + + $kelainan_kiri = ''; + if ($is_valid($os_sph)) $kelainan_kiri .= $os_sph . ' (' . $this->translate_word('Miopia', $langid) . ')'; + if ($is_valid($os_cyl)) { + if ($kelainan_kiri != '') $kelainan_kiri .= ', '; + $kelainan_kiri .= 'Cyl ' . $os_cyl; + $kelainan_kiri .= $is_valid($os_x) + ? ' axis ' . $os_x . ' (' . $this->translate_word('Astigmatismus', $langid) . ')' + : ' (' . $this->translate_word('Astigmatismus', $langid) . ')'; + } + if ($is_valid($od_add)) { + if ($kelainan_kiri != '') $kelainan_kiri .= ', '; + $kelainan_kiri .= $od_add . ' (' . $this->translate_word('Presbiopia', $langid) . ')'; + } + + // Teks ringkas kanan + if ($tk_od == 'OFF' && $dk_od == 'OFF') { + $visus_kanan = $kelainan_kanan ?: 'Normal'; + } + else { + $normal_kanan = (in_array($tk_od, $normal) || in_array($dk_od, $normal)) ? '(Normal)' : ''; + $v_od = ($dk_od != '' && $dk_od != '-' && $dk_od != 'OFF') ? $dk_od : (($tk_od != '' && $tk_od != '-' && $tk_od != 'OFF') ? $tk_od : '20/20'); + $st_od = ($dk_od != '' && $dk_od != '-' && $dk_od != 'OFF') ? $this->translate_word('dengan kacamata', $langid) : $this->translate_word('tanpa kacamata', $langid); + if (!in_array($v_od, $normal) && $kelainan_kanan == '') $kelainan_kanan = $this->translate_word('Miopia', $langid); + $pre = trim($v_od . ' ' . strtolower($st_od) . ' ' . $normal_kanan); + $visus_kanan = $kelainan_kanan == '' ? $pre : $pre . '; ' . $kelainan_kanan; + } + + // Teks ringkas kiri + if ($tk_os == 'OFF' && $dk_os == 'OFF') { + $visus_kiri = $kelainan_kiri ?: 'Normal'; + } + else { + $normal_kiri = (in_array($tk_os, $normal) || in_array($dk_os, $normal)) ? '(Normal)' : ''; + $v_os = ($dk_os != '' && $dk_os != '-' && $dk_os != 'OFF') ? $dk_os : (($tk_os != '' && $tk_os != '-' && $tk_os != 'OFF') ? $tk_os : '20/20'); + $st_os = ($dk_os != '' && $dk_os != '-' && $dk_os != 'OFF') ? $this->translate_word('dengan kacamata', $langid) : $this->translate_word('tanpa kacamata', $langid); + if (!in_array($v_os, $normal) && $kelainan_kiri == '') $kelainan_kiri = $this->translate_word('Miopia', $langid); + $pre = trim($v_os . ' ' . strtolower($st_os) . ' ' . $normal_kiri); + $visus_kiri = $kelainan_kiri == '' ? $pre : $pre . '; ' . $kelainan_kiri; + } + + return [ + 'visus_kanan' => $visus_kanan, 'visus_kiri' => $visus_kiri, + 'tk_od' => $tk_od ?: '-', 'tk_os' => $tk_os ?: '-', + 'dk_od' => $dk_od ?: '-', 'dk_os' => $dk_os ?: '-', + 'od_sph' => $od_sph ?: '-', 'od_cyl' => $od_cyl ?: '-', 'od_x' => $od_x ?: '-', + 'os_sph' => $os_sph ?: '-', 'os_cyl' => $os_cyl ?: '-', 'os_x' => $os_x ?: '-', + 'add' => $od_add ?: '-', + 'kelainan_kanan' => $kelainan_kanan, 'kelainan_kiri' => $kelainan_kiri, + ]; + } + + // ============================================================ + // BODY FAT + // ============================================================ + function get_body_fat($order_header_id, $langid = 1) + { + $sql = "SELECT T_SamplingAdditionalFisikBBTBBodyFat as body_fat + FROM t_samplingso_additional_fisik_bbtb + WHERE T_SamplingAdditionalFisikBBTBT_OrderHeaderID = ? LIMIT 1"; + $qry = $this->db_smartone->query($sql, [$order_header_id]); + if (!$qry) return ['body_fat' => 'NaN', 'body_fat_display' => 'NaN']; + + $row = $qry->row_array(); + if (!$row) return ['body_fat' => 'NaN', 'body_fat_display' => 'NaN']; + + $val = $row['body_fat']; + if ($val === null || $val === '') return ['body_fat' => 'NaN', 'body_fat_display' => 'NaN']; + if ($val == -1) return ['body_fat' => 'NaN', 'body_fat_display' => $this->translate_word('Tidak dilakukan', $langid)]; + return ['body_fat' => $val, 'body_fat_display' => $val . '%']; + } + + // ============================================================ + // HITUNG BMI + // ============================================================ + function hitung_bmi($bb, $tb, $standart_bmi) + { + if (floatval($tb) <= 0) return ['bmi' => 'NaN', 'class' => 'Undefined']; + + $tb_m = floatval($tb) / 100; + $bmi = floatval($bb) / ($tb_m * $tb_m); + $bmi_v = number_format($bmi, 2); + $class = 'Undefined'; + + if ($standart_bmi === 'asia_pacific') { + if ($bmi_v < 18.5) $class = 'Underweight'; + if ($bmi_v >= 18.5 && $bmi_v < 23) $class = 'Normal'; + if ($bmi_v >= 23 && $bmi_v < 25) $class = 'Overweight'; + if ($bmi_v >= 25 && $bmi_v < 30) $class = 'Obese I'; + if ($bmi_v >= 30) $class = 'Obese II'; + } + if ($standart_bmi === 'who') { + if ($bmi_v < 18.5) $class = 'Underweight'; + if ($bmi_v >= 18.5 && $bmi_v < 25) $class = 'Normal'; + if ($bmi_v >= 25 && $bmi_v < 30) $class = 'Overweight'; + if ($bmi_v >= 30) $class = 'Obese'; + } + if ($standart_bmi === 'kemenkes') { + if ($bmi_v < 18.5) $class = 'Underweight'; + if ($bmi_v >= 18.5 && $bmi_v < 25.1) $class = 'Normal'; + if ($bmi_v >= 25.1 && $bmi_v < 27) $class = 'Overweight'; + if ($bmi_v >= 27) $class = 'Obese'; + } + return ['bmi' => $bmi_v, 'class' => $class]; + } + + // ============================================================ + // TRANSLATE + // ============================================================ + function translate_word($word, $langid = 1) + { + if ($langid == 1) return $word; + $sql = "SELECT Translate_WordTo FROM translate_word + WHERE Translate_WordIsActive = 'Y' AND Translate_WordFrom = '{$word}' LIMIT 1"; + $qry = $this->db_smartone->query($sql); + if (!$qry) return $word; + $rows = $qry->result_array(); + return (count($rows) > 0) ? $rows[0]['Translate_WordTo'] : $word; + } + + function translate_sentence($sentence, $langid = 1) + { + $words = preg_split('/[\s-]+/', $sentence); + return implode(' ', array_map(function ($w) use ($langid) { + return $this->translate_word($w, $langid); + }, $words)); + } + + function translate_multiline_text($text, $langid = 1) + { + $lines = explode("\n", $text); + return implode("\n", array_map(function ($line) use ($langid) { + return '- ' . $this->translate_sentence(ltrim($line, '- '), $langid); + }, $lines)); + } + + // ============================================================ + // LOG ERROR + // ============================================================ + function insert_log_error($log_sql, $params, $data = '') + { + $sql = "INSERT INTO one_lab_log.error_log( + ErrorLogCode, ErrorLogName, ErrorLogDescription, + ErrorLogData, ErrorLogOrderCreated + ) VALUES(?,?,?,?,NOW())"; + $query = $this->db_smartone->query($sql, [ + $params[0], $params[1], $log_sql, json_encode($data), + ]); + return (bool)$query; + } +} \ No newline at end of file diff --git a/application/libraries/Genresultfisik.php b/application/libraries/Genresultfisik.php new file mode 100644 index 00000000..f83f8f72 --- /dev/null +++ b/application/libraries/Genresultfisik.php @@ -0,0 +1,3967 @@ +db_smartone = $CI->load->database("default", true); + $this->db_onedev = $CI->load->database("default", true); + } + + function clean_mysqli_connection($dbc) + { + while (mysqli_more_results($dbc)) { + if (mysqli_next_result($dbc)) { + $result = mysqli_use_result($dbc); + + if (get_class($result) == 'mysqli_stmt') { + mysqli_stmt_free_result($result); + } else { + unset($result); + } + } + } + } + + function pribadi($id) + { + //$id = So_ResultEntryID + $sql = "select +DATE_FORMAT(T_OrderHeaderDate, '%d-%m-%Y') as T_OrderHeaderDate , +T_OrderHeaderLabNumber , + concat(M_TitleName ,'. ' , M_PatientName) as M_PatientName, +M_SexName as Gender, +M_PatientNoReg, +M_PatientDOB, +T_OrderHeaderM_PatientAge, +M_CompanyName as CorporateName, +(SELECT concat(M_PatientAddressDescription, ' ' , M_DistrictName, ' ' ,M_CityName) from m_patientaddress AS p +left join m_kelurahan on p.M_PatientAddressM_KelurahanID = M_KelurahanID +left join m_district on M_KelurahanM_DistrictID = M_DistrictID +left join m_city on M_DistrictM_CityID = M_CityID + + WHERE M_PatientAddressM_PatientID = M_PatientID + ORDER BY M_PatientAddressM_PatientID + LIMIT 1) as M_PatientAddress, +M_PatientHp , +M_PatientEmail, +'' as M_PatientAddressCity, +'' as M_PatientAddressState, +M_CompanyAddress as CorporateAddress, +M_CompanyEmail as CorporateEmail , +M_CompanyPhone CorporatePhone, +'' as CorporateAddressCity, + '' as CorporateAddressState, +CONCAT(ifnull(M_DoctorPrefix,''),' ',ifnull(M_DoctorPrefix2,''),' ',M_DoctorName,' ',ifnull(M_DoctorSufix,''),' ',ifnull(M_DoctorSufix2,'') ) AS M_DoctorName , +CONCAT(DATE_FORMAT(M_PatientDOB, '%d-%m-%Y') ,' / ',T_OrderHeaderM_PatientAge) AS Umur, +NOW() as tanggalsekarang, +concat(M_PatientDepartement ,' - ' ,M_PatientNIP ) as M_PatientDepartement + +from so_resultentry +join t_orderheader on So_ResultEntryT_OrderHeaderID = T_OrderHeaderID +left join m_patient ON T_OrderHeaderM_PatientID = M_PatientID AND M_PatientIsActive = 'Y' +left join m_title ON M_PatientM_TitleID = M_TitleID AND M_TitleIsActive = 'Y' +left join m_company ON T_OrderHeaderM_CompanyID = M_CompanyID and M_CompanyIsActive = 'Y' +left join m_doctorpj ON T_OrderHeaderPjM_DoctorID = M_DoctorPjID and M_DoctorPjIsDefaultPJ = 'Y' + left join m_doctor ON So_ResultEntryM_DoctorID = M_DoctorID AND M_DoctorIsActive = 'Y' + left join m_sex ON M_PatientM_SexID = M_SexID +where + So_ResultEntryID = ? + and T_OrderHeaderIsActive = 'Y' group by T_OrderHeaderID"; + $qry = $this->db_smartone->query($sql, array($id)); + if ($qry) { + $rows = $qry->result_array(); + + //Baru + // $langid = 1; + + // foreach($rows as $idx => $r ) { + // $rows[$idx]["kesimpulan"] = $this->kesimpulanv4($id,$langid); + + // } + + echo json_encode($rows); + } + else { + echo json_encode(array()); + } + } + + function translate_word($word, $langid = 1) + { + if ($langid == 1) { + return $word; + } + else { + $sql = "SELECT * FROM translate_word WHERE Translate_WordIsActive = 'Y' AND Translate_WordFrom = '{$word}'"; + //echo $sql; + $qry = $this->db_smartone->query($sql); + if (!$qry) { + return $word; + } + + $rows = $qry->result_array(); + if (count($rows) > 0) { + return $rows[0]["Translate_WordTo"]; + } + else { + return $word; + } + } + } + + + function keluhan_saat_ini($id, $langid = 1) + { + $return_data = "Err"; + + $sql = "SELECT * + FROM so_resultentry_fisik_umum + JOIN fisik_template ON So_ResultEntryFisikUmumFisikTemplateID = FisikTemplateID AND FisikTemplateIsActive = 'Y' AND FisikTemplateTitle = 'KELUHAN SAAT INI' + WHERE + So_ResultEntryFisikUmumT_OrderHeaderID = ? AND So_ResultEntryFisikUmumIsActive = 'Y' AND So_ResultEntryFisikUmumFisikTemplateID = FisikTemplateID"; + $qry = $this->db_smartone->query($sql, array($id)); + if (!$qry) { + return "Err"; + } + $rows = $qry->result_array(); + if(count($rows) == 0) { + return "Err"; + } + if (count($rows) > 0) { + $d = json_decode($rows[0]["So_ResultEntryFisikUmumDetails"], true); + + $keluhan_saat_ini = ""; + $arr_keluhan = []; + if ($d["title"] == "KELUHAN SAAT INI") { + if ($d["flag_normal"] == "Y") { + $keluhan_saat_ini = ""; + } + else { + foreach ($d["details"] as $xd) { + if ($xd["chx"] == "1") { + $arr_keluhan[] = $this->translate_word($xd["label"], $langid) . " " . $this->translate_word($xd["value"], $langid); + if ($keluhan_saat_ini != "") + $keluhan_saat_ini .= ", "; + $keluhan_saat_ini .= $this->translate_word($xd["label"], $langid); + } + } + } + } + + $return_data = $keluhan_saat_ini; + }else{ + $return_data = 'NaN'; + } + + + return $return_data ; + } + + function riwayat_phobia($id, $langid = 1) + { + $return_data = "Err"; + $table_fisik_umum = "so_resultentry_fisik_umum"; + if ($langid == 2) { + $table_fisik_umum = "so_resultentry_fisik_umum_eng"; + } + + $sql = "SELECT * + FROM {$table_fisik_umum} + JOIN fisik_template ON So_ResultEntryFisikUmumFisikTemplateID = FisikTemplateID AND FisikTemplateIsActive = 'Y' AND FisikTemplateTitle = 'RIWAYAT POBIA' + WHERE + So_ResultEntryFisikUmumT_OrderHeaderID = ? AND So_ResultEntryFisikUmumIsActive = 'Y'"; + $qry = $this->db_smartone->query($sql, array($id)); + if (!$qry) { + return "Err"; + } + $rows = $qry->result_array(); + if(count($rows) == 0) { + return "Err"; + } + if (count($rows) > 0) { + $d = json_decode($rows[0]["So_ResultEntryFisikUmumDetails"], true); + //keluhan saat ini + $riwayat_phobia = array(); + + if ($d["title"] == "RIWAYAT POBIA") { + if ($d["flag_normal"] == "Y") { + $riwayat_phobia = array(); + + } + else { + foreach ($d["details"] as $gp) { + if ($gp["chx"] == 1) { + $arr_result[] = array($gp["label"], $gp["value"]); + $riwayat_phobia[] = $this->translate_word($gp["label"], $langid); + } + } + + } + } + + $return_data = join(", ", $riwayat_phobia); + if($return_data == ""){ + $return_data = "Tidak ada"; + } + } + else { + $return_data = 'NaN'; + } + + return $return_data; + } + + function etnis($id, $langid = 1) + { + $table_fisik_umum = "so_resultentry_fisik_umum"; + if ($langid == 2) { + $table_fisik_umum = "so_resultentry_fisik_umum_eng"; + } + $return_data = "Err"; + $sql = "SELECT * + FROM {$table_fisik_umum} + JOIN fisik_template ON So_ResultEntryFisikUmumFisikTemplateID = FisikTemplateID AND FisikTemplateIsActive = 'Y' AND FisikTemplateTitle = 'ETNIS' + WHERE + So_ResultEntryFisikUmumT_OrderHeaderID = ? AND So_ResultEntryFisikUmumIsActive = 'Y'"; + $qry = $this->db_smartone->query($sql, array($id)); + if (!$qry) { + return "Err"; + } + $rows = $qry->result_array(); + if(count($rows) == 0) { + return "Err"; + } + if (count($rows) > 0) { + $d = json_decode($rows[0]["So_ResultEntryFisikUmumDetails"], true); + //keluhan saat ini + $etnis = array(); + + //echo $d["title"]; + if ($d["title"] == "ETNIS") { + if ($d["flag_normal"] == "Y") { + $etnis = array(); + } + else { + foreach ($d["details"] as $gp) { + if ($gp["chx"] == 1) { + $return_data = $this->translate_word($gp["label"], $langid) . " " . $this->translate_word($gp["value"], $langid) . ""; + } + } + + } + } + } + else { + $return_data = 'NaN'; + } + return $return_data; + } + + + function bodyfatmonitoring($id, $langid = 1, $type = "fisik") + { + $return_data = "Err"; + $sql = " SELECT * + FROM t_samplingso_additional_fisik_bbtb + WHERE + T_SamplingAdditionalFisikBBTBT_OrderHeaderID = ? + AND T_SamplingAdditionalFisikBBTBIsActive = 'Y'"; + $qry = $this->db_smartone->query($sql, array($id)); + if (!$qry) { + $return_data = 'Err'; + //$return_data = $this->db_smartone->last_query(); + return $return_data; + } + $rows = $qry->result_array(); + if (count($rows) == 0) { + $return_data = 'Err'; + + return $return_data; + } + $d = $rows[0]["T_SamplingAdditionalFisikBBTBBodyFat"]; + $return_data = $d . "%"; + + return $return_data; + } + + function riwayat_penyakit($id, $langid = 1) + { + $return_data = "Err"; + + $table_fisik_umum = "so_resultentry_fisik_umum"; + if ($langid == 2) { + $table_fisik_umum = "so_resultentry_fisik_umum_eng"; + } + + $sql = "SELECT * + FROM {$table_fisik_umum} + JOIN fisik_template ON So_ResultEntryFisikUmumFisikTemplateID = FisikTemplateID AND FisikTemplateIsActive = 'Y' AND FisikTemplateTitle = 'RIWAYAT PENYAKIT' + WHERE + So_ResultEntryFisikUmumT_OrderHeaderID = ? AND So_ResultEntryFisikUmumIsActive = 'Y'"; + $qry = $this->db_smartone->query($sql, array($id)); + if (!$qry) { + $return_data = 'Err'; + return $return_data; + } + $rows = $qry->result_array(); + if(count($rows) == 0) { + return "Err"; + } + if (count($rows) > 0) { + $d = json_decode($rows[0]["So_ResultEntryFisikUmumDetails"], true); + //keluhan saat ini + $riwayat_penyakit = array(); + + + if ($d["title"] == "RIWAYAT PENYAKIT") { + if ($d["flag_normal"] == "Y") { + $riwayat_penyakit = array(); + } + else { + foreach ($d["details"] as $gp) { + if ($gp['name'] != "Allergi") { + foreach ($gp["details"] as $xd) { + + if ($xd["chx"] == 1) { + //print_r($xd); + $hasil = str_replace("Militus", "Melitus", $xd["label"]); + $hasil = $this->translate_word($hasil, $langid); + if ($xd["value"] != ''){ + $special_labels = [ + "Lain-lain ( Penyakit lainnya )", + "Epilepsi (ayan), kejang, pingsan", + "Kecelakaan / cidera / trauma / luka parah", + "Lain-lain ( Kulit & Sistem Reproduksi )" + ]; + + if (in_array($xd["label"], $special_labels)) { + $hasil = $this->translate_word($xd["value"], $langid); + } + else { + $hasil = $this->translate_word($xd["label"], $langid) . " " . $this->translate_word($xd["value"], $langid) . ""; + } + ; + } + + $arr_result[] = array($xd["label"], $xd["value"], $xd["segment_name"], $xd["id"]); + if ($xd["label"] !== "Lain-lain ( Sistem Pencernaan )" && + $xd["label"] !== "Lain-lain ( Sistem Pernafasan )" && + $xd["label"] !== "Lain-lain ( Sistem Cardiovaskuler )*" && + $xd["label"] !== "Lain-lain ( Sistem Syaraf )" && + $xd["label"] !== "Lain-lain ( Sistem Penglihatan )" && + $xd["label"] !== "Lain-lain ( Sistem Pendengaran/THT )" && + $xd["label"] !== "Lain-lain ( Ginjal & Saluran Kemih )" && + $xd["label"] !== "Lain-lain ( Tulang, Sendi & Otot )" && + $xd["label"] !== "Lain-lain ( Kulit & Sistem Reproduksi )" && + $xd["label"] !== "Lain-lain ( Sistem Endokrin )" && + $xd["label"] !== "Lain-lain ( Penyakit daerah tropis )" && + $xd["label"] !== "Lain-lain ( Penyakit lainnya )" + ) { + $riwayat_penyakit[] = $hasil; + } + else { + $riwayat_penyakit[] = $hasil; + } + + } + } + } + } + + } + } + + if (count($riwayat_penyakit) > 0) + $return_data = join("\r\n", str_replace("*", "", $riwayat_penyakit)); + else + $return_data = "-"; + } + else { + $return_data = 'NaN'; + } + + return $return_data; + } + + + + function alergi($id, $langid = 1) + { + $ret_array = []; + $return_data = "Err"; + + $table_fisik_umum = "so_resultentry_fisik_umum"; + if ($langid == 2) { + $table_fisik_umum = "so_resultentry_fisik_umum_eng"; + } + + $sql = "SELECT * + FROM {$table_fisik_umum} + JOIN fisik_template ON So_ResultEntryFisikUmumFisikTemplateID = FisikTemplateID AND FisikTemplateIsActive = 'Y' AND FisikTemplateTitle = 'RIWAYAT PENYAKIT' + WHERE + So_ResultEntryFisikUmumT_OrderHeaderID = ? AND So_ResultEntryFisikUmumIsActive = 'Y'"; + $qry = $this->db_smartone->query($sql, array($id)); + if (!$qry) { +$return_data = 'Err'; + return $return_data; + } + $rows = $qry->result_array(); + if(count($rows) == 0) { + return "Err"; + } + if (count($rows) > 0) { + $d = json_decode($rows[0]["So_ResultEntryFisikUmumDetails"], true); + //keluhan saat ini + $riwayat_penyakit = array(); + + + if ($d["title"] == "RIWAYAT PENYAKIT") { + if ($d["flag_normal"] == "Y") { + $riwayat_penyakit = array(); + //$d["label_flag_normal"]; + // exit; + } + else { + foreach ($d["details"] as $gp) { + if ($gp['name'] == "Allergi") { + foreach ($gp["details"] as $xd) { + if ($xd["chx"] == 1 && $xd['id_code'] != 'fisik_penyakit_64') { + $arr_result[] = array($xd["label"], $xd["value"], $xd["segment_name"], $xd["id"]); + $hasil = $this->translate_word($xd["label"], $langid); + if ($xd['value'] != '') + $hasil = $this->translate_word($xd["label"], $langid) . " (" . $xd["value"] . ")"; + + $riwayat_penyakit[] = $hasil; + } + if ($xd["chx"] == 1 && $xd['id_code'] == 'fisik_penyakit_64') { + //echo $xd['id_code']; + $arr_result[] = array($xd["label"], $xd["value"], $xd["segment_name"], $xd["id"]); + $hasil = $this->translate_word($xd["label"], $langid); + if ($xd['value'] != '') + $hasil = $this->translate_word($xd["label"], $langid) . " (" . $this->translate_word($xd["value"], $langid) . ")"; + $riwayat_penyakit[] = $hasil; + } + } + } + } + + } + } + + if (count($riwayat_penyakit) > 0) + $return_data = join(", ", $riwayat_penyakit); + else + $return_data = "-"; + } + else { + $return_data = 'NaN'; + } + + return $return_data; + } + + function riwayat_keluarga($id, $langid = 1) + { + $ret_array = [ + 'ayah' => '', + 'ibu' => '' + ]; + + $table_fisik_umum = "so_resultentry_fisik_umum"; + if ($langid == 2) { + $table_fisik_umum = "so_resultentry_fisik_umum_eng"; + } + + $sql = "SELECT * + FROM {$table_fisik_umum} + JOIN fisik_template ON So_ResultEntryFisikUmumFisikTemplateID = FisikTemplateID AND FisikTemplateIsActive = 'Y' AND FisikTemplateTitle = 'RIWAYAT PENYAKIT KELUARGA' + WHERE + So_ResultEntryFisikUmumT_OrderHeaderID = ? AND So_ResultEntryFisikUmumIsActive = 'Y'"; + $qry = $this->db_smartone->query($sql, array($id)); + if (!$qry) { + return "Err"; + } + $rows = $qry->result_array(); + if (count($rows) == 0) { + return "Err"; + } + $d = json_decode($rows[0]["So_ResultEntryFisikUmumDetails"], true); + //keluhan saat ini + $riwayat_keluarga = array(); + $ayah = []; + $ibu = []; + + if ($d["title"] == "RIWAYAT PENYAKIT KELUARGA") { + if ($d["flag_normal"] == "Y") { + + $string_ayah = count($ayah) > 0 ? join(", ", $ayah) : "-"; + $string_ibu = count($ibu) > 0 ? join(", ", $ibu) : "-"; + if ($string_ibu == '') + $string_ibu = "-"; + + if ($string_ayah == '') + $string_ayah = "-"; + + $ret_array['ayah'] = $string_ayah; + $ret_array['ibu'] = $string_ibu; + } + else { + //print_r($d["details"]); + + foreach ($d["details"] as $gp) { + if (true || $gp["chx"] == 1) { + //print_r($gp["options"]); + $arr_result[] = array($gp["label"], $gp["value"], $gp["id"]); + foreach ($gp["options"] as $k => $gpd) { + if ($gpd["selected"] == 1) { + $label = $gp["label"]; + if ($label == "Diabetes Millitus") { + $label = "Diabetes Melitus"; + } + if ($label == "Hypertensi") { + $label = "Hipertensi"; + } + $label = $this->translate_word($label, $langid); + if ($k == 0) { + $ayah[] = $label; + } + else { + $ibu[] = $label; + } + } + } + } + } + //echo count($ibu); + $string_ayah = count($ayah) > 0 ? join(", ", $ayah) : "-"; + $string_ibu = count($ibu) > 0 ? join(", ", $ibu) : "-"; + if ($string_ibu == '') + $string_ibu = "-"; + + if ($string_ayah == '') + $string_ayah = "-"; + //echo $string_ibu; + $ret_array['ayah'] = $string_ayah; + $ret_array['ibu'] = $string_ibu; + } + } + + return count($ret_array) > 0 ? $ret_array : "Err"; + } + + function merokok($id, $langid = 1) + { + $ret_array = []; + $return_data = "Err"; + $table_fisik_umum = "so_resultentry_fisik_umum"; + if ($langid == 2) { + $table_fisik_umum = "so_resultentry_fisik_umum_eng"; + } + + $orderid = $id; + $sql = "SELECT * + FROM {$table_fisik_umum} + JOIN fisik_template ON So_ResultEntryFisikUmumFisikTemplateID = FisikTemplateID AND FisikTemplateIsActive = 'Y' AND FisikTemplateTitle = 'RIWAYAT KEBIASAAN HIDUP' + WHERE + So_ResultEntryFisikUmumT_OrderHeaderID = ? AND So_ResultEntryFisikUmumIsActive = 'Y'"; + $qry = $this->db_smartone->query($sql, array($id)); + if (!$qry) { + return "Err"; + } + $rows = $qry->result_array(); + if (count($rows) == 0) { + $return_data = 'Err'; + return $return_data; + } + $d = json_decode($rows[0]["So_ResultEntryFisikUmumDetails"], true); + //keluhan saat ini + $riwayat_hidup = array(); + + if ($d["title"] == "RIWAYAT KEBIASAAN HIDUP") { + if ($d["flag_normal"] == "Y") { + $return_data = "-"; + } + else { + foreach ($d["details"] as $gp) { + if ($gp['name'] == 'Merokok') { + foreach ($gp["details"] as $xd) { + if ($xd["chx"] == 1) { + $arr_result[] = array($xd["segment_name"], $xd["label"], $xd["value"]); + if ($xd['id_code'] != 'fisik_kebiasaanhidup_4') { + $hasil = $this->translate_word($xd['label'], $langid); + if ($xd['value'] != '') + $hasil = $this->translate_word($xd['label'], $langid) . ', ' . $this->translate_word($xd["value"], $langid); + $riwayat_hidup[] = $hasil; + } + else { + $hasil = $this->translate_word($xd["label"], $langid); + if ($xd['value'] != '') + $hasil = $this->translate_word($xd['label'], $langid) . ', ' . $this->translate_word($xd["value"], $langid); + if ($xd['suffix'] != '') + $hasil = $hasil . ' ' . $this->translate_word($xd['suffix'], $langid); + $riwayat_hidup[] = $hasil; + } + + } + } + } + + } + + } + } + + if (count($riwayat_hidup) > 0) { + $return_data = join(", ", $riwayat_hidup); + } + else { + $return_data = "-"; + } + + return $return_data; + } + + function alkohol($id, $langid = 1) + { + $ret_array = []; + $return_data = "Err"; + + $orderid = $id; + + $table_fisik_umum = "so_resultentry_fisik_umum"; + if ($langid == 2) { + $table_fisik_umum = "so_resultentry_fisik_umum_eng"; + } + + $sql = "SELECT * + FROM {$table_fisik_umum} + JOIN fisik_template ON So_ResultEntryFisikUmumFisikTemplateID = FisikTemplateID AND FisikTemplateIsActive = 'Y' AND FisikTemplateTitle = 'RIWAYAT KEBIASAAN HIDUP' + WHERE + So_ResultEntryFisikUmumT_OrderHeaderID = ? AND So_ResultEntryFisikUmumIsActive = 'Y'"; + $qry = $this->db_smartone->query($sql, array($id)); + if (!$qry) { + return "Err"; + } + $rows = $qry->result_array(); + if (count($rows) == 0) { + $return_data = 'Err'; + return $return_data; + } + $d = json_decode($rows[0]["So_ResultEntryFisikUmumDetails"], true); + //keluhan saat ini + $riwayat_hidup = array(); + + if ($d["title"] == "RIWAYAT KEBIASAAN HIDUP") { + if ($d["flag_normal"] == "Y") { + $return_data = "-"; + } + else { + foreach ($d["details"] as $gp) { + if ($gp['name'] == 'Minum alkohol') { + foreach ($gp["details"] as $xd) { + if ($xd["chx"] == 1) { + $arr_result[] = array($xd["segment_name"], $xd["label"], $xd["value"]); + if ($xd['id_code'] != 'fisik_kebiasaanhidup_4') { + $hasil = $this->translate_word($xd['label'], $langid); + if ($xd['value'] != '') + $hasil = $this->translate_word($xd['label'], $langid) . ', ' . $this->translate_word($xd["value"], $langid); + $riwayat_hidup[] = $hasil; + } + else { + $hasil = $this->translate_word($xd["label"], $langid); + if ($xd['value'] != '') + $hasil = $this->translate_word($xd['label'], $langid) . ', ' . $this->translate_word($xd["value"], $langid); + if ($xd['suffix'] != '') + $hasil = $hasil . ' ' . $this->translate_word($xd['suffix'], $langid); + $riwayat_hidup[] = $hasil; + } + + } + } + } + + } + + } + } + + if (count($riwayat_hidup) > 0) { + $return_data = join(", ", $riwayat_hidup); + } + else { + $return_data = "-"; + } + + return $return_data; + } + + function olahraga($id, $langid = 1) + { + $ret_array = []; + $return_data = "Err"; + + $table_fisik_umum = "so_resultentry_fisik_umum"; + if ($langid == 2) { + $table_fisik_umum = "so_resultentry_fisik_umum_eng"; + } + + $sql = "SELECT * + FROM {$table_fisik_umum} + JOIN fisik_template ON So_ResultEntryFisikUmumFisikTemplateID = FisikTemplateID AND FisikTemplateIsActive = 'Y' AND FisikTemplateTitle = 'RIWAYAT KEBIASAAN HIDUP' + WHERE + So_ResultEntryFisikUmumT_OrderHeaderID = ? AND So_ResultEntryFisikUmumIsActive = 'Y'"; + $qry = $this->db_smartone->query($sql, array($id)); + if (!$qry) { + $return_data = 'Err'; + return $return_data; + } + $rows = $qry->result_array(); + if (count($rows) == 0) { + $return_data = 'Err'; + return $return_data; + } + $d = json_decode($rows[0]["So_ResultEntryFisikUmumDetails"], true); + //keluhan saat ini + $riwayat_hidup = array(); + + if ($d["title"] == "RIWAYAT KEBIASAAN HIDUP") { + if ($d["flag_normal"] == "Y") { + $riwayat_hidup = array(); + //$d["label_flag_normal"]; + //exit; + } + else { + foreach ($d["details"] as $gp) { + if ($gp['name'] == 'Olahraga') { + foreach ($gp["details"] as $xd) { + if ($xd["chx"] == 1) { + $arr_result[] = array($xd["segment_name"], $xd["label"], $xd["value"]); + if ($xd['id_code'] != 'fisik_kebiasaanhidup_4') { + $hasil = $this->translate_word($xd['label'], $langid); + if ($xd['value'] != '') + $hasil = $this->translate_word($xd['label'], $langid) . ', ' . $this->translate_word($xd["value"], $langid); + $riwayat_hidup[] = $hasil; + } + else { + $jumlah_olahraga = ""; + if ($xd["value"] != '') + $jumlah_olahraga = $this->translate_word($xd["value"], $langid) . ' ' . $this->translate_word($xd['suffix'], $langid); + + $hasil = $this->translate_word($xd["label"], $langid); + if ($xd['value'] != '') + $hasil = $this->translate_word($xd['label'], $langid) . ', ' . $this->translate_word($xd["value"], $langid); + if ($xd['suffix'] != '') + $hasil = $hasil . ' ' . $this->translate_word($xd['suffix'], $langid); + $riwayat_hidup[] = $hasil; + } + + } + } + } + + } + + } + } + + if (count($riwayat_hidup) > 0) { + $return_data = join(", ", $riwayat_hidup); + } + else { + $return_data = "-"; + } + + return $return_data; + } + + function riwayat_obat($id, $langid = 1) + { + $ret_array = []; + $return_data = "Err"; + $table_fisik_umum = "so_resultentry_fisik_umum"; + if ($langid == 2) { + $table_fisik_umum = "so_resultentry_fisik_umum_eng"; + } + + $sql = "SELECT * + FROM {$table_fisik_umum} + JOIN fisik_template ON So_ResultEntryFisikUmumFisikTemplateID = FisikTemplateID AND FisikTemplateIsActive = 'Y' + AND FisikTemplateTitle = 'RIWAYAT KONSUMSI OBAT TERATUR' + WHERE + So_ResultEntryFisikUmumT_OrderHeaderID = ? AND So_ResultEntryFisikUmumIsActive = 'Y'"; + $qry = $this->db_smartone->query($sql, array($id)); + if (!$qry) { + return "Err"; + } + $rows = $qry->result_array(); + if (count($rows) == 0) { + $return_data = 'NaN'; + return $return_data; + } + $d = json_decode($rows[0]["So_ResultEntryFisikUmumDetails"], true); + //keluhan saat ini + $riwayat_obat = array(); + + + if ($d["title"] == "RIWAYAT KONSUMSI OBAT TERATUR") { + if ($d["flag_normal"] == "Y") { + $riwayat_obat = array(); + //$d["label_flag_normal"]; + // exit; + } + else { + foreach ($d["details"] as $gp) { + if ($gp["chx"] == 1) { + $arr_result[] = array($gp["label"], $gp["value"]); + $hasil = $this->translate_word($gp["label"], $langid); + if ($gp["value"] != '') + $hasil = $this->translate_word($gp["label"], $langid) . " : " . $this->translate_word($gp["value"], $langid); + $riwayat_obat[] = $hasil; + } + } + + } + } + + $string_obat = count($riwayat_obat) > 0 ? join(", ", $riwayat_obat) : "-"; + $return_data = $string_obat; + return $return_data; + } + + + + function riwayat_imunisasi($id, $langid = 1) + { + + $return_data = "Err"; + + $table_fisik_umum = "so_resultentry_fisik_umum"; + if ($langid == 2) { + $table_fisik_umum = "so_resultentry_fisik_umum_eng"; + } + + $sql = "SELECT * + FROM {$table_fisik_umum} + JOIN fisik_template ON So_ResultEntryFisikUmumFisikTemplateID = FisikTemplateID AND FisikTemplateIsActive = 'Y' AND FisikTemplateTitle = 'RIWAYAT IMUNISASI' + WHERE + So_ResultEntryFisikUmumT_OrderHeaderID = ? AND So_ResultEntryFisikUmumIsActive = 'Y'"; + $qry = $this->db_smartone->query($sql, array($id)); + if (!$qry) { + $return_data = 'Err'; + //$return_data = $this->db_smartone->last_query(); + return $return_data; + } + $rows = $qry->result_array(); + if (count($rows) == 0) { + $return_data = 'Err'; + + return $return_data; + } + $d = json_decode($rows[0]["So_ResultEntryFisikUmumDetails"], true); + //keluhan saat ini + $riwayat_imunisasi = array(); + + + if ($d["title"] == "RIWAYAT IMUNISASI") { + if ($d["flag_normal"] == "Y") { + $riwayat_imunisasi = array(); + //$d["label_flag_normal"]; + + } + else { + foreach ($d["details"] as $gp) { + foreach ($gp["details"] as $xd) { + if ($xd["chx"] == 1) { + if ($xd["label"] == 'Pernah') + $riwayat_imunisasi[] = str_replace(",", " ", $this->translate_word($xd["segment_name"], $langid)) . ' ' . $this->translate_word($xd["value"], $langid); + } + } + } + + } + } + $string_obat = count($riwayat_imunisasi) > 0 ? join(", ", $riwayat_imunisasi) : "-"; + $return_data = $string_obat; + return $return_data; + } + + + + + //pemeriksaan Fisik + function tanda_vital_xxx($id, $langid = 1, $type = "fisik") + { + $tanda_vital = array(); + + $table_fisik_umum = "so_resultentry_fisik_umum"; + if ($langid == 2) { + $table_fisik_umum = "so_resultentry_fisik_umum_eng"; + } + + $sql = "SELECT * + FROM {$table_fisik_umum} + JOIN fisik_template ON So_ResultEntryFisikUmumFisikTemplateID = FisikTemplateID AND FisikTemplateIsActive = 'Y' AND FisikTemplateTitle = 'TANDA VITAL' + WHERE + So_ResultEntryFisikUmumT_OrderHeaderID = ? AND So_ResultEntryFisikUmumIsActive = 'Y'"; + $qry = $this->db_smartone->query($sql, array($id)); + if (!$qry) { + return "Err"; + } + $rows = $qry->result_array(); + if (count($rows) == 0) { + return "Err"; + } + $d = json_decode($rows[0]["So_ResultEntryFisikUmumDetails"], true); + //keluhan saat ini + + + if ($d["title"] == "TANDA VITAL") { + + foreach ($d["details"] as $gp) { + if ($gp['id_code'] != 'tanda_vital_5') { + $value = $gp["value"] . ' ' . $gp["unit"]; + if ($gp["chx_y"] == "1") + $value = $gp["label_y"]; + + if ($gp["chx_x"] == "1") + $value = $gp["label_x"] . ' ' . $gp["value"] . ' ' . $gp["unit"]; + + + if($gp["value_x"] != '') + $value = $value . ' ( ' . ucwords(strtolower($gp["value_x"])).' )'; + $tanda_vital[] = array( + "label" => $this->translate_word($gp["label"], $langid), + "value" => $value + ); + } + else { + $kesimpulan = str_replace("Stadium", "Stage", $gp["value"]); + $value = $gp["value_x"] . '/' . $gp["value_y"] . ' ' . $gp["unit"]; + + $kesimpulan = ucwords(strtolower($this->translate_word($kesimpulan, $langid))); + if($kesimpulan != '') + $value = $value . ' ( ' . $kesimpulan.' )'; + $tanda_vital[] = array( + "label" => $this->translate_word($gp["label"], $langid), + "value" => $value + ); + } + + } + } + + return count($tanda_vital) > 0 ? $tanda_vital : "Err"; + } + + function tbbbbodyfat($id, $type, $langid = 1) + { + $ret_array = []; + $sql = "SELECT * + FROM t_samplingso_additional_fisik_bbtb + WHERE + T_SamplingAdditionalFisikBBTBT_OrderHeaderID = $id AND + T_SamplingAdditionalFisikBBTBIsActive = 'Y' + LIMIT 1"; + //echo $sql; + $qry = $this->db_smartone->query($sql); + if (!$qry) { + return "Err"; + } + //echo $this->db_smartone->last_query(); + $row_s = $qry->result_array(); + if(count($row_s) == 0) { + return "Err"; + } + $row_result = $row_s[0]; + + $bb = $row_result["T_SamplingAdditionalFisikBBTBValueBB"] == 0 ? "NaN" : $row_result["T_SamplingAdditionalFisikBBTBValueBB"]; + $tb = $row_result["T_SamplingAdditionalFisikBBTBValueTB"] == 0 ? "NaN" : $row_result["T_SamplingAdditionalFisikBBTBValueTB"]; + $bodyfat = $row_result["T_SamplingAdditionalFisikBBTBBodyFat"] == 0 ? "NaN" : $row_result["T_SamplingAdditionalFisikBBTBBodyFat"] . "%"; + $standart_bmi = $row_result["T_SamplingAdditionalFisikBBTBStandart"]; + if($bb != "NaN" && $tb != "NaN") { + $get_bmi = $this->hitung_bmi($bb, $tb, $standart_bmi); + $bmi = $get_bmi['bmi']; + $standart_text = "Standart " . ucwords(str_replace("_", " ", $standart_bmi)); + $show_standart = $row_result["Mgm_McuShowStandartBMI"]; + $classification = $get_bmi['class']; + $ret_array['BMI'] = $bmi . " " . $classification; + } + + + $ret_array['TB'] = $tb != "NaN" ? $tb . " cm" : "NaN"; + $ret_array['BB'] = $bb != "NaN" ? $bb . " kg" : "NaN"; + $ret_array['BodyFat'] = $bodyfat != "NaN" ? $bodyfat : "NaN"; + + return count($ret_array) > 0 ? $ret_array : "Err"; + } + + function tekanan_darah($id,$langid = 1) + { + + $return_data = []; + $table_fisik_umum = "so_resultentry_fisik_umum"; + if ($langid == 2) { + $table_fisik_umum = "so_resultentry_fisik_umum_eng"; + } + + $sql = "SELECT * + FROM {$table_fisik_umum} + JOIN fisik_template ON So_ResultEntryFisikUmumFisikTemplateID = FisikTemplateID AND FisikTemplateIsActive = 'Y' AND ( FisikTemplateTitle = 'TEKANAN DARAH' OR FisikTemplateTitle = 'TANDA VITAL' ) + WHERE + So_ResultEntryFisikUmumT_OrderHeaderID = ? AND So_ResultEntryFisikUmumIsActive = 'Y'"; + $qry = $this->db_smartone->query($sql, array($id)); + if (!$qry) { + return "Err"; + } + $rows = $qry->result_array(); + //echo $this->db_smartone->last_query(); + if (count($rows) == 0) { + return "Err"; + } + $d = json_decode($rows[0]["So_ResultEntryFisikUmumDetails"], true); + //print_r($d); + //keluhan saat ini + $tanda_vital = array(); + + if ($d["title"] == "TEKANAN DARAH" || $d["title"] == "TANDA VITAL") { + + foreach ($d["details"] as $gp) { + if ($gp['id_code'] == 'tanda_vital_5') { + $return_data[$gp['label_x']] = $gp['value_x'] . " mmHg"; + $return_data[$gp['label_y']] = $gp['value_y'] . " mmHg"; + $return_data['standart_tensi'] = $gp['standart']; + $return_data['conclusion_tensi'] = $gp['value']; + if($langid == 2) { + $return_data['conclusion_tensi'] = $this->translate_word($gp['value'], $langid); + } + } + + } + } + + return $return_data; + } + + function laju_pernafasan($id, $langid = 1) + { + + $return_data = "Err"; + + $table_fisik_umum = "so_resultentry_fisik_umum"; + if ($langid == 2) { + $table_fisik_umum = "so_resultentry_fisik_umum_eng"; + } + + $sql = "SELECT * + FROM {$table_fisik_umum} + JOIN fisik_template ON So_ResultEntryFisikUmumFisikTemplateID = FisikTemplateID AND FisikTemplateIsActive = 'Y' AND FisikTemplateTitle = 'TANDA VITAL' + WHERE + So_ResultEntryFisikUmumT_OrderHeaderID = ? AND So_ResultEntryFisikUmumIsActive = 'Y'"; + $qry = $this->db_smartone->query($sql, array($id)); + if (!$qry) { + return "Err"; + } + $rows = $qry->result_array(); + if (count($rows) == 0) { + return "Err"; + } + if (count($rows) > 0) { + $d = json_decode($rows[0]["So_ResultEntryFisikUmumDetails"], true); + //keluhan saat ini + $return_data = 'NaN'; + if ($d["title"] == "TANDA VITAL") { + foreach ($d["details"] as $gp) { + if ($gp['id_code'] == 'tanda_vital_3') { + $return_data = $gp['value'] . " " . $this->translate_word($gp['unit'], $langid); + } + + } + } + } + + return $return_data; + } + + function denyut_nadi($id, $langid = 1) + { + $return_data = "Err"; + + $table_fisik_umum = "so_resultentry_fisik_umum"; + if ($langid == 2) { + $table_fisik_umum = "so_resultentry_fisik_umum_eng"; + } + + $sql = "SELECT * + FROM {$table_fisik_umum} + JOIN fisik_template ON So_ResultEntryFisikUmumFisikTemplateID = FisikTemplateID AND FisikTemplateIsActive = 'Y' AND FisikTemplateTitle = 'TANDA VITAL' + WHERE + So_ResultEntryFisikUmumT_OrderHeaderID = ? AND So_ResultEntryFisikUmumIsActive = 'Y'"; + $qry = $this->db_smartone->query($sql, array($id)); + if (!$qry) { + return "Err"; + } + $rows = $qry->result_array(); + if (count($rows) == 0) { + return "Err"; + } + if (count($rows) > 0) { + $d = json_decode($rows[0]["So_ResultEntryFisikUmumDetails"], true); + //keluhan saat ini + $tanda_vital = array(); + $return_data = 'NaN'; + if ($d["title"] == "TANDA VITAL") { + + foreach ($d["details"] as $gp) { + if ($gp['id_code'] == 'tanda_vital_1') { + $return_data = $gp['value'] . " " . $this->translate_word('x/menit', $langid); + } + + } + } + } + + + return $return_data; + } + + function ritme_denyut_nadi($id, $langid = 1) + { + $return_data = "Err"; + + $table_fisik_umum = "so_resultentry_fisik_umum"; + if ($langid == 2) { + $table_fisik_umum = "so_resultentry_fisik_umum_eng"; + } + + $sql = "SELECT * + FROM {$table_fisik_umum} + JOIN fisik_template ON So_ResultEntryFisikUmumFisikTemplateID = FisikTemplateID AND FisikTemplateIsActive = 'Y' AND FisikTemplateTitle = 'TANDA VITAL' + WHERE + So_ResultEntryFisikUmumT_OrderHeaderID = ? AND So_ResultEntryFisikUmumIsActive = 'Y'"; + $qry = $this->db_smartone->query($sql, array($id)); + if (!$qry) { + return "Err"; + } + $rows = $qry->result_array(); + if (count($rows) == 0) { + return "Err"; + } + if (count($rows) > 0) { + $d = json_decode($rows[0]["So_ResultEntryFisikUmumDetails"], true); + //keluhan saat ini + $tanda_vital = array(); + $return_data = 'NaN'; + if ($d["title"] == "TANDA VITAL") { + + foreach ($d["details"] as $gp) { + if ($gp['id_code'] == 'tanda_vital_2') { + if($gp['chx_y'] == 1) + $return_data = $this->translate_word($gp['label_y'], $langid); + else + $return_data = $this->translate_word($gp['label_x'], $langid); + } + + } + } + } + + + return $return_data; + } + + function pola_nafas($id, $langid = 1) + { + $return_data = "Err"; + + $table_fisik_umum = "so_resultentry_fisik_umum"; + if ($langid == 2) { + $table_fisik_umum = "so_resultentry_fisik_umum_eng"; + } + + $sql = "SELECT * + FROM {$table_fisik_umum} + JOIN fisik_template ON So_ResultEntryFisikUmumFisikTemplateID = FisikTemplateID AND FisikTemplateIsActive = 'Y' AND FisikTemplateTitle = 'TANDA VITAL' + WHERE + So_ResultEntryFisikUmumT_OrderHeaderID = ? AND So_ResultEntryFisikUmumIsActive = 'Y'"; + $qry = $this->db_smartone->query($sql, array($id)); + if (!$qry) { + return "Err"; + } + $rows = $qry->result_array(); + if (count($rows) == 0) { + return "Err"; + } + if (count($rows) > 0) { + $d = json_decode($rows[0]["So_ResultEntryFisikUmumDetails"], true); + //keluhan saat ini + $tanda_vital = array(); + $return_data = 'NaN'; + if ($d["title"] == "TANDA VITAL") { + + foreach ($d["details"] as $gp) { + if ($gp['id_code'] == 'tanda_vital_4') { + if($gp['chx_y'] == 1) + $return_data = $this->translate_word($gp['label_y'], $langid); + else + $return_data = $this->translate_word($gp['label_x'], $langid); + } + + } + } + } + + + return $return_data; + } + + + function suhu($id, $langid = 1) + { + $return_data = "Err"; + + $table_fisik_umum = "so_resultentry_fisik_umum"; + if ($langid == 2) { + $table_fisik_umum = "so_resultentry_fisik_umum_eng"; + } + + $sql = "SELECT * + FROM {$table_fisik_umum} + JOIN fisik_template ON So_ResultEntryFisikUmumFisikTemplateID = FisikTemplateID AND FisikTemplateIsActive = 'Y' AND FisikTemplateTitle = 'TANDA VITAL' + WHERE + So_ResultEntryFisikUmumT_OrderHeaderID = ? AND So_ResultEntryFisikUmumIsActive = 'Y'"; + $qry = $this->db_smartone->query($sql, array($id)); + if (!$qry) { + $return_data = 'Err'; + //$return_data = $this->db_smartone->last_query(); + return $return_data; + } + $rows = $qry->result_array(); + if (count($rows) == 0) { + return "Err"; + } + if (count($rows) > 0) { + $d = json_decode($rows[0]["So_ResultEntryFisikUmumDetails"], true); + //keluhan saat ini + $tanda_vital = array(); + $return_data = 'NaN'; + if ($d["title"] == "TANDA VITAL") { + + foreach ($d["details"] as $gp) { + if ($gp['id_code'] == 'tanda_vital_6') { + if ($gp['chx_x'] == 1) + $return_data = $this->translate_word($gp['label_x'], $langid); + if ($gp['chx_y'] == 1) + $return_data = $this->translate_word($gp['label_y'], $langid); + } + + } + } + } + + return $return_data; + } + + function status_gizi($id, $langid = 1, $type = "fisik") + { + $sql = "SELECT * + FROM t_samplingso_additional_fisik_bbtb + WHERE + T_SamplingAdditionalFisikBBTBT_OrderHeaderID = $id AND + T_SamplingAdditionalFisikBBTBIsActive = 'Y' + LIMIT 1"; + //echo $sql; + $qry = $this->db_smartone->query($sql); + if (!$qry) { + return "Err"; + } + //echo $this->db_smartone->last_query(); + $row_s = $qry->result_array(); + if(count($row_s) == 0) { + return "Err"; + } + $row_result = $row_s[0]; + + $status_gizi = array(); + $bb = $row_result["T_SamplingAdditionalFisikBBTBValueBB"] == 0 ? "Err" : $row_result["T_SamplingAdditionalFisikBBTBValueBB"]; + $tb = $row_result["T_SamplingAdditionalFisikBBTBValueTB"] == 0 ? "Err" : $row_result["T_SamplingAdditionalFisikBBTBValueTB"]; + $bodyfat = $row_result["T_SamplingAdditionalFisikBBTBBodyFat"] == 0 ? "Err" : $row_result["T_SamplingAdditionalFisikBBTBBodyFat"] . "%"; + $standart_bmi = $row_result["T_SamplingAdditionalFisikBBTBStandart"]; + $get_bmi = $this->hitung_bmi($bb, $tb, $standart_bmi); + $bmi = $get_bmi['bmi']; + $classification = $get_bmi['class']; + + $standart_text = ucwords(str_replace("_", " ", $standart_bmi)); + if ($bb == "Err" && $tb == "Err") { + $bodyfat = 'Err'; + $standart_bmi = 'Err'; + $bmi = 'Err'; + $classification = 'Err'; + $standart_text = 'Err'; + } + + $status_gizi['TB'] = $tb != "Err" ? $tb . " cm" : "Err"; + $status_gizi['BB'] = $bb != "Err" ? $bb . " kg" : "Err"; + $status_gizi['BodyFat'] = $bodyfat != "Err" ? $bodyfat : "Err"; + $status_gizi['BMI'] = $bmi != "Err" ? $bmi . " " . $classification : "Err"; + $status_gizi['Standart_BMI'] = $standart_text != "Err" ? $standart_text : "Err"; + + + + return $status_gizi; + } + + function lapang_pandang($id, $langid = 1) + { + + $table_fisik_umum = "so_resultentry_fisik_umum"; + if ($langid == 2) { + $table_fisik_umum = "so_resultentry_fisik_umum_eng"; + } + + $sql = "SELECT * + FROM {$table_fisik_umum} + JOIN fisik_template ON So_ResultEntryFisikUmumFisikTemplateID = FisikTemplateID AND FisikTemplateIsActive = 'Y' AND FisikTemplateTitle = 'LAPANG PANDANG' + WHERE + So_ResultEntryFisikUmumT_OrderHeaderID = ? AND So_ResultEntryFisikUmumIsActive = 'Y'"; + $qry = $this->db_smartone->query($sql, array($id)); + if (!$qry) { + return "Err"; + } + + $rows = $qry->result_array(); + if (count($rows) == 0) { + return "Err"; + } + $d = json_decode($rows[0]["So_ResultEntryFisikUmumDetails"], true); + //keluhan saat ini + $return_data = "Err"; + + if (strtolower($d["title"]) == strtolower("LAPANG PANDANG")) { + foreach ($d["details"] as $gp) { + if ($gp["chx_y"] == "1") + $value = $this->translate_word($gp["label_y"], $langid); + + if ($gp["chx_x"] == "1") + $value = $this->translate_word($gp["label_x"], $langid); + + if ($gp['value'] != '') + $value = $value . " (" . $gp['value'] . ")"; + + $return_data = $value; + + + } + } + + return $return_data; + } + + function klasifikasi_bmi($bmi, $standart_bmi) + { + $bmi_valuex = number_format($bmi, 2); + $classs = "Undefined"; + if ($standart_bmi === 'asia_pacific') { + if ($bmi_valuex < 18.5) + $classs = 'Underweight'; + + if ($bmi_valuex >= 18.5 && $bmi_valuex < 23) + $classs = 'Normal'; + + if ($bmi_valuex >= 23 && $bmi_valuex < 25) + $classs = 'Overweight'; + + if ($bmi_valuex >= 25 && $bmi_valuex < 30) + $classs = 'Obese I'; + + if ($bmi_valuex >= 30) + $classs = 'Obese II'; + } + + if ($standart_bmi === 'who') { + if ($bmi_valuex < 18.5) + $classs = 'Underweight'; + + if ($bmi_valuex >= 18.5 && $bmi_valuex < 25) { + $classs = 'Normal'; + } + + if ($bmi_valuex >= 25 && $bmi_valuex < 30) { + $classs = 'Overweight'; + } + + if ($bmi_valuex >= 30) + $classs = 'Obese'; + } + + if ($standart_bmi === 'kemenkes') { + if ($bmi_valuex < 18.5) + $classs = 'Underweight'; + + if ($bmi_valuex >= 18.5 && $bmi_valuex < 25.1) + $classs = 'Normal'; + + if ($bmi_valuex >= 25.1 && $bmi_valuex < 27) + $classs = 'Overweight'; + + if ($bmi_valuex >= 27) + $classs = 'Obese'; + } + + return $classs; + } + + function hitung_bmi($bb, $tb, $standart_bmi) + { + $tb = $tb / 100; + $bmi = ''; + $bmi = $bb / ($tb * $tb); + $bmi_valuex = number_format($bmi, 2); + $classs = "Undefined"; + + if ($standart_bmi === 'asia_pacific') { + if ($bmi_valuex < 18.5) + $classs = 'Underweight'; + + if ($bmi_valuex >= 18.5 && $bmi_valuex < 23) + $classs = 'Normal'; + + if ($bmi_valuex >= 23 && $bmi_valuex < 25) + $classs = 'Overweight'; + + if ($bmi_valuex >= 25 && $bmi_valuex < 30) + $classs = 'Obese I'; + + if ($bmi_valuex >= 30) + $classs = 'Obese II'; + } + + if ($standart_bmi === 'who') { + if ($bmi_valuex < 18.5) + $classs = 'Underweight'; + + if ($bmi_valuex >= 18.5 && $bmi_valuex < 25) { + $classs = 'Normal'; + } + + if ($bmi_valuex >= 25 && $bmi_valuex < 30) { + $classs = 'Overweight'; + } + + if ($bmi_valuex >= 30) + $classs = 'Obese'; + } + + if ($standart_bmi === 'kemenkes') { + if ($bmi_valuex < 18.5) + $classs = 'Underweight'; + + if ($bmi_valuex >= 18.5 && $bmi_valuex < 25.1) + $classs = 'Normal'; + + if ($bmi_valuex >= 25.1 && $bmi_valuex < 27) + $classs = 'Overweight'; + + if ($bmi_valuex >= 27) + $classs = 'Obese'; + } + + return array( + 'bmi' => $bmi_valuex, + 'class' => $classs + ); + } + + function keadaan_umum($id, $langid = 1) + { + $ret_array = []; + $table_fisik_umum = "so_resultentry_fisik_umum"; + if ($langid == 2) { + $table_fisik_umum = "so_resultentry_fisik_umum_eng"; + } + + $sql = "SELECT * + FROM {$table_fisik_umum} + JOIN fisik_template ON So_ResultEntryFisikUmumFisikTemplateID = FisikTemplateID AND FisikTemplateIsActive = 'Y' AND FisikTemplateTitle = 'KEADAAN UMUM' + WHERE + So_ResultEntryFisikUmumT_OrderHeaderID = ? AND So_ResultEntryFisikUmumIsActive = 'Y'"; + $qry = $this->db_smartone->query($sql, array($id)); + if (!$qry) { + return "Err"; + } + $rows = $qry->result_array(); + if(count($rows) == 0) { + return "Err"; + } + $d = json_decode($rows[0]["So_ResultEntryFisikUmumDetails"], true); + + if ($d["title"] == "KEADAAN UMUM") { + foreach ($d["details"] as $gp) { + $value = $gp["value"]; + if ($gp["chx_x"] == "1") $value = $gp["label_x"]; + if ($gp["chx_y"] == "1") $value = $gp["label_y"]; + + $ret_array[] = array( + "label" => $this->translate_word($gp["label"], $langid), + "value" => $this->translate_word($value, $langid). " " . $this->translate_word($gp["unit"], $langid) + ); + } + } + + return count($ret_array) > 0 ? $ret_array : "Err"; + } + + + function kepala_wajah($id, $langid = 1, $type = "fisik") + { + $ret_array = []; + $table_fisik_umum = "so_resultentry_fisik_umum"; + if ($langid == 2) { + $table_fisik_umum = "so_resultentry_fisik_umum_eng"; + } + + $sql = "SELECT * + FROM so_resultentry + WHERE + So_ResultEntryID = ?"; + $qry = $this->db_smartone->query($sql, array($id)); + if (!$qry) { + return "Err"; + } + $row = $qry->row(); + if (!$row) { + return "Err"; + } + $orderid = $row->So_ResultEntryT_OrderHeaderID; + + $sql = "SELECT * + FROM {$table_fisik_umum} + JOIN fisik_template ON So_ResultEntryFisikUmumFisikTemplateID = FisikTemplateID AND FisikTemplateIsActive = 'Y' AND FisikTemplateTitle = 'KEPALA WAJAH' + WHERE + So_ResultEntryFisikUmumT_OrderHeaderID = ? AND So_ResultEntryFisikUmumIsActive = 'Y'"; + $qry = $this->db_smartone->query($sql, array($id)); + if (!$qry) { + return "Err"; + } + $rows = $qry->result_array(); + if (count($rows) == 0) { + return 'Err'; + } + $d = json_decode($rows[0]["So_ResultEntryFisikUmumDetails"], true); + //keluhan saat ini + $kepala_wajah = array(); + + + if ($d["title"] == "KEPALA WAJAH") { + + foreach ($d["details"] as $gp) { + if ($gp["chx"] == 1) { + $hasil = $this->translate_word($gp["label"], $langid); + if ($gp["value"] != '') + $hasil = $this->translate_word($gp["label"], $langid) . " : " . $this->translate_word($gp["value"], $langid); + $kepala_wajah[] = $hasil; + } + } + } + + if(count($kepala_wajah) == 0) { + return "Err"; + } + $return_data = join(", ", $kepala_wajah); + return $return_data; + } + + + function persepsi_warna($id, $langid = 1) + { + $return_data = "Err"; + + $sql = "SELECT IFNULL(T_SamplingAdditionalFisikBWPWValue,'Z') as result, + IFNULL(T_SamplingAdditionalFisikBWPWVAngka,'') as angka + FROM t_samplingso_additional_fisik_bw + WHERE + T_SamplingAdditionalFisikBWT_OrderHeaderID = ? + LIMIT 1 "; + $qry = $this->db_smartone->query($sql, array($id)); + + if (!$qry) { + return "Err"; + } + $row_s = $qry->result_array(); + if(count($row_s) == 0) { + return "Err"; + } + $row_result = $row_s[0]; + $result = $this->translate_word("Bahan Belum", $langid); + if ($row_result) { + if ($row_result['result'] == 'BW') + $result = $this->translate_word("Red Green Deficiency", $langid) . " ( " . $this->translate_word($row_result['angka'], $langid) . " )"; + if ($row_result['result'] == 'N') + $result = $this->translate_word("Normal", $langid); + if ($row_result['result'] == 'X') + $result = $this->translate_word("Tidak dilakukan", $langid); + } + + $return_data = $result; + + return $return_data; + } + + + function doctor($id) + { + $return_data = "Err"; + + + $sql = "SELECT concat(if(M_DoctorPrefix is null, '',CONCAT(M_DoctorPrefix,' ')),if(M_DoctorPrefix2 is null, '',CONCAT(M_DoctorPrefix2,' ')),M_DoctorName) as doctor + FROM so_resultentry_fisik_umum JOIN so_resultentry ON So_ResultEntryFisikUmumT_OrderHeaderID = So_ResultEntryT_OrderHeaderID AND +So_ResultEntryNonlab_TemplateID = 27 + JOIN m_doctor ON M_DOctorID = So_ResultEntryM_DoctorID + WHERE So_ResultEntryFisikUmumT_OrderHeaderID = ? AND So_ResultEntryFisikUmumIsActive = 'Y' + LIMIT 1"; + $qry = $this->db_smartone->query($sql, array($id)); + if (!$qry) { + $return_data = 'Err'; + $return_data = $this->db_smartone->last_query(); + return $return_data; + } + $rows = $qry->result_array(); + if (count($rows) == 0) { + return "Err"; + } + $row_result = $rows[0]; + $return_data = $row_result["doctor"]; + if (trim((string)$return_data) === '') { + return "Err"; + } + + return $return_data; + } + + function konjuktiva_sklera($id, $langid = 1) + { + $return_data = "Err"; + + $table_fisik_umum = "so_resultentry_fisik_umum"; + if ($langid == 2) { + $table_fisik_umum = "so_resultentry_fisik_umum_eng"; + } + + $sql = "SELECT * + FROM {$table_fisik_umum} + JOIN fisik_template ON So_ResultEntryFisikUmumFisikTemplateID = FisikTemplateID AND FisikTemplateIsActive = 'Y' AND + FisikTemplateTitle = 'MATA' + WHERE + So_ResultEntryFisikUmumT_OrderHeaderID = ? AND So_ResultEntryFisikUmumIsActive = 'Y'"; + $qry = $this->db_smartone->query($sql, array($id)); + if (!$qry) { + return "Err"; + } + $rows = $qry->result_array(); + if (count($rows) == 0) { + return "Err"; + } + $row_result = $rows[0]; + $d = json_decode($row_result["So_ResultEntryFisikUmumDetails"], true); + + $mata = array(); + + if ($d["title"] == "MATA") { + + foreach ($d["details"] as $gp) { + if ($gp["chx"] == 1) { + $hasil = $this->translate_word($gp["label"], $langid); + if ($gp["value"] != '') + $hasil = $this->translate_word($gp["label"], $langid) . " (" . $this->translate_word($gp["value"], $langid) . ")"; + $mata[] = $hasil; + } + } + + } + + $string_mata = count($mata) > 0 ? join(", ", $mata) : "-"; + $return_data = $string_mata; + + + + return $return_data; + } + + + function telinga($id, $langid = 1) + { + $ret_array = []; + + + $table_fisik_umum = "so_resultentry_fisik_umum"; + if ($langid == 2) { + $table_fisik_umum = "so_resultentry_fisik_umum_eng"; + } + + $sql = "SELECT * + FROM {$table_fisik_umum} + JOIN fisik_template ON So_ResultEntryFisikUmumFisikTemplateID = FisikTemplateID AND FisikTemplateIsActive = 'Y' AND FisikTemplateTitle = 'TELINGA' + WHERE + So_ResultEntryFisikUmumT_OrderHeaderID = ? AND So_ResultEntryFisikUmumIsActive = 'Y'"; + $qry = $this->db_smartone->query($sql, array($id)); + + if (!$qry) { + return "Err"; + } + $rows = $qry->result_array(); + if (count($rows) == 0) { + return "Err"; + } + $row_result = $rows[0]; + $d = json_decode($row_result["So_ResultEntryFisikUmumDetails"], true); + //keluhan saat ini + $telinga = array(); + + + if ($d["title"] == "TELINGA") { + + foreach ($d["details"] as $gp) { + if ($gp["chx"] == 1) { + $arr_result[] = array($gp["label"], $gp["value"]); + $hasil = $this->translate_word($gp["label"], $langid); + if ($gp["value"] != '') + $hasil = $this->translate_word($gp["label"], $langid) . " : " . $this->translate_word($gp["value"], $langid); + $telinga[] = $hasil; + } + } + + } + + $string_telinga = count($telinga) > 0 ? join(", ", $telinga) : "-"; + $return_data = $string_telinga; + + return $return_data; + } + + function visus($id, $type, $langid = 1) + { + $ret_array = []; + + + $sql = "SELECT * + FROM t_orderdetail + JOIN so_resultentry ON So_ResultEntryT_OrderHeaderID = + T_OrderDetailT_OrderHeaderID AND So_ResultEntryT_OrderHeaderID = {$id} + WHERE T_OrderDetailT_TestCode = '40111000' + AND T_OrderDetailIsActive = 'Y' LIMIT 1"; + $qry = $this->db_smartone->query($sql); + + + $check_exist_test = $qry->result_array(); + + $ret_array = []; + if (intval($id) == 0 || count($check_exist_test) == 0) { + $return_data = 'Err'; + //$return_data = $this->db_smartone->last_query(); + return $return_data; + } + + + $sql = " SELECT * , T_SamplingAdditionalFisikVisusID as visus_id + FROM t_samplingso_additional_fisik_visus + WHERE + T_SamplingAdditionalFisikVisusT_OrderHeaderID = ? AND + T_SamplingAdditionalFisikVisusIsActive = 'Y' + LIMIT 1"; + $qry = $this->db_smartone->query($sql, array($id)); + if (!$qry) { + $return_data = 'Err'; + // $return_data = $this->db_smartone->last_query(); + return $return_data; + } + + //$return_data = $this->db_smartone->last_query(); + //return $return_data; + + $rows = $qry->result_array(); + // return $rows; + if (count($rows) == 0) { + return "Err"; + } + $row_result = $rows[0]; + $ret_array['a2'] = ""; + + if ($row_result && intval($row_result['visus_id']) > 0) { + + $visus = array(); + $visus_kiri = ""; + $visus_kanan = ""; + $visus_kesimpulan = ""; + $normal = array("20/20", "20/25", "6/6", "6/7.5", "6/7,5"); + + $value_visus_od = "20/20"; + $value_visus_os = "20/20"; + $status_kcmt = $this->translate_word("tanpa kacamata", $langid); + + $normal_kanan = ""; + if (in_array($row_result['T_SamplingAdditionalFisikVisusTKODV'], $normal) || in_array($row_result['T_SamplingAdditionalFisikVisusDKODV'], $normal)) + $normal_kanan = "(Normal)"; + + $normal_kiri = ""; + if (in_array($row_result['T_SamplingAdditionalFisikVisusTKOSV'], $normal) || in_array($row_result['T_SamplingAdditionalFisikVisusDKOSV'], $normal)) + $normal_kiri = "(Normal)"; + + if ($row_result['T_SamplingAdditionalFisikVisusTKODV'] == '6/7,5' || $row_result['T_SamplingAdditionalFisikVisusTKODV'] == '6/6' || $row_result['T_SamplingAdditionalFisikVisusTKODV'] == '6/7.5') + $value_visus_od = $row_result['T_SamplingAdditionalFisikVisusTKODV']; + + if ($row_result['T_SamplingAdditionalFisikVisusTKOSV'] == '6/7,5' || $row_result['T_SamplingAdditionalFisikVisusTKOSV'] == '6/6' || $row_result['T_SamplingAdditionalFisikVisusTKOSV'] == '6/7.5') + $value_visus_os = $row_result['T_SamplingAdditionalFisikVisusTKOSV']; + + + if ((strtolower($row_result['T_SamplingAdditionalFisikVisusTKODV']) != "normal" && $row_result['T_SamplingAdditionalFisikVisusTKODV'] != "" && $row_result['T_SamplingAdditionalFisikVisusTKODV'] != "-") && ($row_result['T_SamplingAdditionalFisikVisusTKOSV'] != "" && $row_result['T_SamplingAdditionalFisikVisusTKOSV'] != "-")) { + $visus_kiri = ""; + $visus_kanan = ""; + + $visus[] = array( + "xx1" => $row_result['T_SamplingAdditionalFisikVisusTKODV'] == 'OFF' ? '' : $this->translate_word("Tanpa Kacamata", $langid), + "xx2" => "OD : ", + "xx3" => $row_result['T_SamplingAdditionalFisikVisusTKODV'] == 'OFF' ? '' : $row_result['T_SamplingAdditionalFisikVisusTKODV'] + ); + + $visus[] = array( + "xx1" => $row_result['T_SamplingAdditionalFisikVisusTKOSV'] == 'OFF' ? '' : $this->translate_word("Tanpa Kacamata", $langid), + "xx2" => "OS", + "xx3" => $row_result['T_SamplingAdditionalFisikVisusTKOSV'] == 'OFF' ? '' : $row_result['T_SamplingAdditionalFisikVisusTKOSV'] + ); + + $rst['kelainan'] = $this->translate_word("Kelainan refraksi (tanpa kacamata)", $langid); + $value_visus_od = $row_result['T_SamplingAdditionalFisikVisusTKODV'] == 'OFF' ? '' : $row_result['T_SamplingAdditionalFisikVisusTKODV']; + $value_visus_os = $row_result['T_SamplingAdditionalFisikVisusTKOSV'] == 'OFF' ? '' : $row_result['T_SamplingAdditionalFisikVisusTKOSV']; + $status_kcmt = $row_result['T_SamplingAdditionalFisikVisusTKODV'] == 'OFF' ? '' : $this->translate_word("tanpa kacamata", $langid); + + + if (!in_array($row_result['T_SamplingAdditionalFisikVisusTKODV'], $normal)) { + + $value_koreksi_od = ""; + $od_sph = $row_result['T_SamplingAdditionalFisikVisusODSPH']; + if ($od_sph != "" && $od_sph != "-" && $od_sph != "--" && $od_sph != "/-" && $od_sph != "/" && $od_sph != "-/" && strtolower(trim($od_sph)) != 'plano') { + if ($visus_kanan != "") + $visus_kanan .= ", "; + $visus_kanan .= $od_sph . " (" . $this->translate_word("Miopia", $langid) . ")"; + } + + + $od_cyl = $row_result['T_SamplingAdditionalFisikVisusODCYL']; + + //$od_cyl = $row_result['T_SamplingAdditionalFisikVisusODCYL']; + if ($od_cyl != "" && $od_cyl != "-" && $od_cyl != "--" && $od_cyl != "/-" && $od_cyl != "/" && $od_cyl != "-/") { + if ($visus_kanan != "") + $visus_kanan .= ", "; + $visus_kanan .= "Cyl " . $od_cyl; + } + + + $od_x = $row_result['T_SamplingAdditionalFisikVisusODX']; + //echo $od_x; + if ($od_x != "" && $od_x != "-" && $od_x != "--" && $od_x != "/-" && $od_x != "/" && $od_x != "-/") { + //if ($visus_kanan != "") $visus_kanan .= ", "; + $visus_kanan .= " axis " . $od_x . " (" . $this->translate_word("Astigmatismus", $langid) . ")"; + } + else { + if ($od_cyl != "" && $od_cyl != "-" && $od_cyl != "--" && $od_cyl != "/-" && $od_cyl != "/" && $od_cyl != "-/") + $visus_kanan .= " (" . $this->translate_word("Astigmatismus", $langid) . ")"; + } + //$value_koreksi_od .= "X (".$od_x.") "; + + + + } + + if (!in_array($row_result['T_SamplingAdditionalFisikVisusTKOSV'], $normal)) { + $value_koreksi_os = ""; + $os_sph = trim($row_result['T_SamplingAdditionalFisikVisusOSSPH']); + //echo $os_sph; + if (trim($os_sph) != " " && strtolower(trim($os_sph)) != "tidak terkoreksi" && strtolower(trim($os_sph)) != "tidak dapat dinilai" && $os_sph != "" && $os_sph != "-" && $os_sph != "--" && $os_sph != "/-" && $os_sph != "/" && $os_sph != "-/" && strtolower(trim($os_sph)) != 'plano') { + if ($visus_kiri != "") + $visus_kiri .= ", "; + $visus_kiri .= $os_sph . " (" . $this->translate_word("Miopia", $langid) . ")"; + //return $langid; + } + + + $os_cyl = $row_result['T_SamplingAdditionalFisikVisusOSCYL']; + + if (strtolower(trim($os_cyl)) != "tidak terkoreksi" && strtolower(trim($os_cyl)) != "tidak dapat dinilai" && $os_cyl != "" && $os_cyl != "-" && $os_cyl != "--" && $os_cyl != "/-" && $os_cyl != "/" && $os_cyl != "-/") { + if ($visus_kiri != "") + $visus_kiri .= ", "; + $visus_kiri .= "Cyl " . $os_cyl; + } + + + $os_x = $row_result['T_SamplingAdditionalFisikVisusOSX']; + + if (strtolower(trim($os_x)) != "tidak terkoreksi" && strtolower(trim($os_x)) != "tidak dapat dinilai" && $os_x != "" && $os_x != "-" && $os_x != "--" && $os_x != "/-" && $os_x != "/" && $os_x != "-/") { + //if ($visus_kiri != "") $visus_kiri .= ", "; + $visus_kiri .= " axis " . $os_x . " (" . $this->translate_word("Astigmatismus", $langid) . ")"; + } + else { + if ($os_cyl != "" && $os_cyl != "-") + $visus_kiri .= " (" . $this->translate_word("Astigmatismus", $langid) . ")"; + } + + + } + + + + } + + //return $visus_kiri; + + + if (($row_result['T_SamplingAdditionalFisikVisusDKODV'] != "" && $row_result['T_SamplingAdditionalFisikVisusDKODV'] != "-") && ($row_result['T_SamplingAdditionalFisikVisusDKOSV'] != "" && $row_result['T_SamplingAdditionalFisikVisusDKOSV'] != "-")) { + + $visus_kiri = ""; + $visus_kanan = ""; + $visus[] = array( + "xx1" => $row_result['T_SamplingAdditionalFisikVisusDKODV'] == 'OFF' ? '' : $this->translate_word("Dengan Kacamata", $langid), + "xx2" => "OD : ", + "xx3" => $row_result['T_SamplingAdditionalFisikVisusDKODV'] == 'OFF' ? '' : $row_result['T_SamplingAdditionalFisikVisusDKODV'] + ); + + $visus[] = array( + "xx1" => $row_result['T_SamplingAdditionalFisikVisusDKOSV'] == 'OFF' ? '' : $this->translate_word("Dengan Kacamata", $langid), + "xx2" => "OS", + "xx3" => $row_result['T_SamplingAdditionalFisikVisusDKOSV'] == 'OFF' ? '' : $row_result['T_SamplingAdditionalFisikVisusDKOSV'] + ); + + $rst['kelainan'] = $this->translate_word("Kelainan refraksi (dengan kacamata)", $langid); + $value_visus_od = $row_result['T_SamplingAdditionalFisikVisusDKODV'] == 'OFF' ? '' : $row_result['T_SamplingAdditionalFisikVisusDKODV']; + $value_visus_os = $row_result['T_SamplingAdditionalFisikVisusDKOSV'] == 'OFF' ? '' : $row_result['T_SamplingAdditionalFisikVisusDKOSV']; + $status_kcmt = $row_result['T_SamplingAdditionalFisikVisusDKODV'] == 'OFF' ? '' : $this->translate_word("dengan kacamata", $langid); + + //if (!in_array($row_result['T_SamplingAdditionalFisikVisusDKODV'], $normal)){ + $value_koreksi_od = ""; + $od_sph = $row_result['T_SamplingAdditionalFisikVisusODSPH']; + if ($od_sph != "" && $od_sph != "-" && $od_sph != "--" && $od_sph != "/-" && $od_sph != "/" && $od_sph != "-/" && strtolower(trim($od_sph)) != 'plano') { + if ($visus_kanan != "") + $visus_kanan .= ", "; + $visus_kanan .= $od_sph . " (" . $this->translate_word("Miopia", $langid) . ")"; + } + + + $od_cyl = $row_result['T_SamplingAdditionalFisikVisusODCYL']; + + //$od_cyl = $row_result['T_SamplingAdditionalFisikVisusODCYL']; + if ($od_cyl != "" && $od_cyl != "-" && $od_cyl != "--" && $od_cyl != "/-" && $od_cyl != "/" && $od_cyl != "-/") { + if ($visus_kanan != "") + $visus_kanan .= ", "; + $visus_kanan .= "Cyl " . $od_cyl; + } + + + $od_x = $row_result['T_SamplingAdditionalFisikVisusODX']; + //echo $od_x; + if ($od_x != "" && $od_x != "-" && $od_x != "--" && $od_x != "/-" && $od_x != "/" && $od_x != "-/") { + //if ($visus_kanan != "") $visus_kanan .= ", "; + $visus_kanan .= " axis " . $od_x . " (" . $this->translate_word("Astigmatismus", $langid) . ")"; + } + else { + if ($od_cyl != "" && $od_cyl != "-" && $od_cyl != "--" && $od_cyl != "/-" && $od_cyl != "/" && $od_cyl != "-/") + $visus_kanan .= " (" . $this->translate_word("Astigmatismus", $langid) . ")"; + } + //$value_koreksi_od .= "X (".$od_x.") "; + + + // } + + //if (!in_array($row_result['T_SamplingAdditionalFisikVisusDKOSV'], $normal)){ + $value_koreksi_os = ""; + $os_sph = trim($row_result['T_SamplingAdditionalFisikVisusOSSPH']); + //echo $os_sph; + if (trim($os_sph) != " " && strtolower(trim($os_sph)) != "tidak terkoreksi" && strtolower(trim($os_sph)) != "tidak dapat dinilai" && $os_sph != "" && $os_sph != "-" && $os_sph != "--" && $os_sph != "/-" && $os_sph != "/" && $os_sph != "-/" && strtolower(trim($os_sph)) != 'plano') { + if ($visus_kiri != "") + $visus_kiri .= ", "; + $visus_kiri .= $os_sph . " (" . $this->translate_word("Miopia", $langid) . ")"; + } + + $os_cyl = $row_result['T_SamplingAdditionalFisikVisusOSCYL']; + + if (strtolower(trim($os_cyl)) != "tidak terkoreksi" && strtolower(trim($os_cyl)) != "tidak dapat dinilai" && $os_cyl != "" && $os_cyl != "-" && $os_cyl != "--" && $os_cyl != "/-" && $os_cyl != "/" && $os_cyl != "-/") { + if ($visus_kiri != "") + $visus_kiri .= ", "; + $visus_kiri .= "Cyl " . $os_cyl; + } + + + $os_x = $row_result['T_SamplingAdditionalFisikVisusOSX']; + + if (strtolower(trim($os_x)) != "tidak terkoreksi" && strtolower(trim($os_x)) != "tidak dapat dinilai" && $os_x != "" && $os_x != "-" && $os_x != "--" && $os_x != "/-" && $os_x != "/" && $os_x != "-/") { + //if ($visus_kiri != "") $visus_kiri .= ", "; + $visus_kiri .= " axis " . $os_x . " (" . $this->translate_word("Astigmatismus", $langid) . ")"; + } + else { + if ($os_cyl != "" && $os_cyl != "-") + $visus_kiri .= " (" . $this->translate_word("Astigmatismus", $langid) . ")"; + } + + + //} + + + } + + if (($row_result['T_SamplingAdditionalFisikVisusTKODV'] != "" && $row_result['T_SamplingAdditionalFisikVisusTKODV'] != "-") && ($row_result['T_SamplingAdditionalFisikVisusTKOSV'] != "" && $row_result['T_SamplingAdditionalFisikVisusTKOSV'] != "-")) { + if (!in_array($row_result['T_SamplingAdditionalFisikVisusTKODV'], $normal) && $visus_kanan == '' && $row_result['T_SamplingAdditionalFisikVisusTKODV'] != 'OFF') { + $visus_kanan = "Miopia"; + } + + if (!in_array($row_result['T_SamplingAdditionalFisikVisusTKOSV'], $normal) && $visus_kiri == '' && $row_result['T_SamplingAdditionalFisikVisusTKOSV'] != 'OFF') { + $visus_kiri = "Miopia"; + } + } + + if (($row_result['T_SamplingAdditionalFisikVisusDKODV'] != "" && $row_result['T_SamplingAdditionalFisikVisusDKODV'] != "-") && ($row_result['T_SamplingAdditionalFisikVisusDKOSV'] != "" && $row_result['T_SamplingAdditionalFisikVisusDKOSV'] != "-")) { + if (!in_array($row_result['T_SamplingAdditionalFisikVisusDKODV'], $normal) && $visus_kanan == '' && $row_result['T_SamplingAdditionalFisikVisusDKODV'] != 'OFF') { + $visus_kanan = "Miopia"; + } + + if (!in_array($row_result['T_SamplingAdditionalFisikVisusDKOSV'], $normal) && $visus_kiri == '' && $row_result['T_SamplingAdditionalFisikVisusDKOSV'] != 'OFF') { + $visus_kiri = "Miopia"; + } + } + + $od_add = $row_result['T_SamplingAdditionalFisikVisusADD']; + if ($od_add != "" && $od_add != "-" && $od_add != "--" && $od_add != "/-" && $od_add != "/" && $od_add != "-/") { + if ($visus_kanan != "") + $visus_kanan .= ", "; + $visus_kanan .= $od_add . " (" . $this->translate_word("Presbiopia", $langid) . ")"; + + if ($visus_kiri != "") + $visus_kiri .= ", "; + $visus_kiri .= $od_add . " (" . $this->translate_word("Presbiopia", $langid) . ")"; + } + + + if ($row_result['T_SamplingAdditionalFisikVisusTKODV'] != 'OFF' && + $row_result['T_SamplingAdditionalFisikVisusTKOSV'] != 'OFF' && + $row_result['T_SamplingAdditionalFisikVisusDKODV'] != 'OFF' && + $row_result['T_SamplingAdditionalFisikVisusDKOSV'] != 'OFF') { + + $pre_result_od = $value_visus_od . " " . strtolower($this->translate_word($status_kcmt, $langid)) . " " . $normal_kanan; + $pre_result_os = $value_visus_os . " " . strtolower($this->translate_word($status_kcmt, $langid)) . " " . $normal_kiri; + + if ($type == 'left') + $ret_array['a2'] = $visus_kiri == "" ? $pre_result_os : $pre_result_os . ";" . $visus_kiri; + + if ($type == 'right') + $ret_array['a2'] = $visus_kanan == "" ? $pre_result_od : $pre_result_od . ";" . $visus_kanan; + + } + + //return $ret_array['a2']; + if ($row_result['T_SamplingAdditionalFisikVisusTKODV'] == 'OFF' && + $row_result['T_SamplingAdditionalFisikVisusTKOSV'] == 'OFF' && + $row_result['T_SamplingAdditionalFisikVisusDKODV'] == 'OFF' && + $row_result['T_SamplingAdditionalFisikVisusDKOSV'] == 'OFF') { + if ($type == 'left') + $ret_array['a2'] = $visus_kiri == "" ? "Normal" : $visus_kiri; + + if ($type == 'right') + $ret_array['a2'] = $visus_kanan == "" ? "Normal" : $visus_kanan; + } + + } + else { + $ret_array['a2'] = $this->translate_word("Bahan belum", $langid); + } + + $return_data = $ret_array['a2']; + + return $return_data; + } + + + function hidung($id, $langid = 1) + { + $ret_array = []; + + $table_fisik_umum = "so_resultentry_fisik_umum"; + if ($langid == 2) { + $table_fisik_umum = "so_resultentry_fisik_umum_eng"; + } + + $sql = "SELECT * + FROM {$table_fisik_umum} + JOIN fisik_template ON So_ResultEntryFisikUmumFisikTemplateID = FisikTemplateID AND FisikTemplateIsActive = 'Y' AND FisikTemplateTitle = 'HIDUNG' + WHERE + So_ResultEntryFisikUmumT_OrderHeaderID = ? AND So_ResultEntryFisikUmumIsActive = 'Y'"; + $qry = $this->db_smartone->query($sql, array($id)); + if (!$qry) { + return "Err"; + } + $rows = $qry->result_array(); + if (count($rows) == 0) { + return "Err"; + } + $row_result = $rows[0]; + $d = json_decode($rows[0]["So_ResultEntryFisikUmumDetails"], true); + //keluhan saat ini + $hidung = array(); + + + if ($d["title"] == "HIDUNG") { + + foreach ($d["details"] as $gp) { + if ($gp["chx"] == 1) { + $arr_result[] = array($gp["label"], $gp["value"]); + $hasil = $this->translate_word($gp["label"], $langid); + if ($gp["value"] != '') + $hasil = $this->translate_word($gp["label"], $langid) . " : " . $this->translate_word($gp["value"], $langid); + $hidung[] = $hasil; + } + } + + } + $string_hidung = count($hidung) > 0 ? join(", ", $hidung) : "-"; + $return_data = $string_hidung; + + return $return_data; + } + + function leher($id, $langid = 1) + { + $return_data = "Err"; + + $table_fisik_umum = "so_resultentry_fisik_umum"; + if ($langid == 2) { + $table_fisik_umum = "so_resultentry_fisik_umum_eng"; + } + + $sql = "SELECT * + FROM {$table_fisik_umum} + JOIN fisik_template ON So_ResultEntryFisikUmumFisikTemplateID = FisikTemplateID AND FisikTemplateIsActive = 'Y' AND FisikTemplateTitle = 'LEHER' + WHERE + So_ResultEntryFisikUmumT_OrderHeaderID = ? AND So_ResultEntryFisikUmumIsActive = 'Y'"; + $qry = $this->db_smartone->query($sql, array($id)); + if (!$qry) { + return "Err"; + } + $rows = $qry->result_array(); + if (count($rows) == 0) { + return "Err"; + } + $row_result = $rows[0]; + $d = json_decode($rows[0]["So_ResultEntryFisikUmumDetails"], true); + //keluhan saat ini + $leher = array(); + + + if ($d["title"] == "LEHER") { + + foreach ($d["details"] as $gp) { + if ($gp["chx"] == 1) { + $arr_result[] = array($gp["label"], $gp["value"]); + $hasil = $this->translate_word($gp["label"], $langid); + if ($gp["value"] != '') + $hasil = $this->translate_word($gp["label"], $langid) . " : " . $this->translate_word($gp["value"], $langid); + $leher[] = $hasil; + } + } + + } + + $string_leher = count($leher) > 0 ? join(", ", $leher) : "Normal"; + $return_data = $string_leher; + + return $return_data; + } + + function thorax($id, $langid = 1) + { + $return_data = "Err"; + + $table_fisik_umum = "so_resultentry_fisik_umum"; + if ($langid == 2) { + $table_fisik_umum = "so_resultentry_fisik_umum_eng"; + } + + $sql = "SELECT * + FROM {$table_fisik_umum} + JOIN fisik_template ON So_ResultEntryFisikUmumFisikTemplateID = FisikTemplateID AND FisikTemplateIsActive = 'Y' AND + FisikTemplateTitle = 'THORAX / DADA' + WHERE + So_ResultEntryFisikUmumT_OrderHeaderID = ? AND So_ResultEntryFisikUmumIsActive = 'Y'"; + $qry = $this->db_smartone->query($sql, array($id)); + //echo $this->db_smartone->last_query(); + if (!$qry) { + return "Err"; + } + $rows = $qry->result_array(); + if (count($rows) == 0) { + return "Err"; + } + $row_result = $rows[0]; + $d = json_decode($rows[0]["So_ResultEntryFisikUmumDetails"], true); + //keluhan saat ini + $leher = array(); + + + if ($d["title"] == "THORAX / DADA") { + + foreach ($d["details"] as $gp) { + if ($gp["chx"] == 1) { + $arr_result[] = array($gp["label"], $gp["value"]); + $hasil = $this->translate_word($gp["label"], $langid); + if ($gp["value"] != '') + $hasil = $this->translate_word($gp["label"], $langid) . " : " . $this->translate_word($gp["value"], $langid); + $leher[] = $hasil; + } + } + + } + + $string_leher = count($leher) > 0 ? join(", ", $leher) : "Normal"; + $return_data = $string_leher; + + return $return_data; + } + + function mulut($id, $langid = 1) + { + $return_data = "Err"; + + + $table_fisik_umum = "so_resultentry_fisik_umum"; + if ($langid == 2) { + $table_fisik_umum = "so_resultentry_fisik_umum_eng"; + } + + $sql = "SELECT * + FROM {$table_fisik_umum} + JOIN fisik_template ON So_ResultEntryFisikUmumFisikTemplateID = FisikTemplateID AND FisikTemplateIsActive = 'Y' AND + ( FisikTemplateTitle = 'MULUT' ) + WHERE + So_ResultEntryFisikUmumT_OrderHeaderID = ? AND So_ResultEntryFisikUmumIsActive = 'Y'"; + $qry = $this->db_smartone->query($sql, array($id)); + if (!$qry) { + return "Err"; + } + $rows = $qry->result_array(); + if (count($rows) == 0) { + return "Err"; + } + $d = json_decode($rows[0]["So_ResultEntryFisikUmumDetails"], true); + //print_r($d); + //echo $d["title"]; + //keluhan saat ini + $mulut = array(); + + if ($d["title"] == "MULUT") { + //print_r($d['details']); + foreach ($d["details"] as $gp) { + if ($gp['name'] == "Mukosa rongga mulut") { + //print_r($gp["details"]); + foreach ($gp["details"] as $xd) { + if ($xd["chx"] == 1 && $xd["label"] != 'Normal') { + $arr_result[] = array($gp["name"], $xd["label"], $xd["value"]); + // Convert to lowercase first, then capitalize first letter + $hasil = ucfirst(strtolower($this->translate_word($xd["label"], $langid))); + if ($xd["value"] != '') + $hasil = ucfirst(strtolower($this->translate_word($xd["label"], $langid))) . " : " . ucfirst(strtolower($this->translate_word($xd["value"], $langid))); + + //echo $hasil; + $mulut[] = $hasil; + } + } + } + + } + } + + $string_mulut = count($mulut) > 0 ? join(", ", $mulut) : "Normal"; + $return_data = $string_mulut; + + + + + return $return_data; + } + + function tenggorokan($id, $langid = 1) + { + $return_data = "Err"; + + $table_fisik_umum = "so_resultentry_fisik_umum"; + if ($langid == 2) { + $table_fisik_umum = "so_resultentry_fisik_umum_eng"; + } + + $sql = "SELECT * + FROM {$table_fisik_umum} + JOIN fisik_template ON So_ResultEntryFisikUmumFisikTemplateID = FisikTemplateID AND FisikTemplateIsActive = 'Y' AND FisikTemplateTitle = 'MULUT' + WHERE + So_ResultEntryFisikUmumT_OrderHeaderID = ? AND So_ResultEntryFisikUmumIsActive = 'Y'"; + $qry = $this->db_smartone->query($sql, array($id)); + if (!$qry) { + return "Err"; + } + $rows = $qry->result_array(); + if (count($rows) > 0) { + $d = json_decode($rows[0]["So_ResultEntryFisikUmumDetails"], true); + //keluhan saat ini + $mulut = array(); + + + if ($d["title"] == "MULUT") { + + foreach ($d["details"] as $gp) { + if ($gp['name'] == "Tenggorokan") { + foreach ($gp["details"] as $xd) { + if ($xd["chx"] == 1 && $xd["label"] != 'Normal') { + $arr_result[] = array($gp["name"], $xd["label"], $xd["value"]); + $hasil = $this->translate_word($xd["label"], $langid); + if ($xd["value"] != '') + $hasil = $this->translate_word($xd["label"], $langid) . " : " . $this->translate_word($xd["value"], $langid); + $mulut[] = $hasil; + } + } + } + + } + } + + + $string_mulut = count($mulut) > 0 ? join(", ", $mulut) : "Normal"; + $return_data = $string_mulut; + } + + + return $return_data; + } + + function gigi($id, $langid = 1) + { + $return_data = "Err"; + + $sql = "SELECT * + FROM so_resultentry_fisik_umum + JOIN fisik_template ON So_ResultEntryFisikUmumFisikTemplateID = FisikTemplateID AND FisikTemplateIsActive = 'Y' AND FisikTemplateTitle = 'GIGI' + WHERE + So_ResultEntryFisikUmumT_OrderHeaderID = ? AND So_ResultEntryFisikUmumIsActive = 'Y'"; + $qry = $this->db_smartone->query($sql, array($id)); + if (!$qry) { + return "Err"; + } + $rows = $qry->result_array(); + if (count($rows) == 0) { + return "Err"; + } + $d = json_decode($rows[0]["So_ResultEntryFisikUmumDetails"], true); + //keluhan saat ini + $gigi = array(); + + + if ($d["title"] == "GIGI") { + + foreach ($d["details"] as $gp) { + if ($gp["chx"] == 1) { + $arr_result[] = array($gp["label"], $gp["value"]); + $hasil = $this->translate_word($gp["label"], $langid); + if ($gp["value"] != '') + $hasil = $this->translate_word($gp["label"], $langid) . " : " . $this->translate_word($gp["value"], $langid); + $gigi[] = $hasil; + } + } + + } + + $string_gigi = count($gigi) > 0 ? join(", ", $gigi) : "Normal"; + $return_data = $string_gigi; + + return $return_data; + } + + function paru($id, $langid = 1) + { + $ret_array = []; + + $table_fisik_umum = "so_resultentry_fisik_umum"; + if ($langid == 2) { + $table_fisik_umum = "so_resultentry_fisik_umum_eng"; + } + + $sql = "SELECT * + FROM {$table_fisik_umum} + JOIN fisik_template ON So_ResultEntryFisikUmumFisikTemplateID = FisikTemplateID AND FisikTemplateIsActive = 'Y' AND FisikTemplateTitle = 'PARU-PARU' + WHERE + So_ResultEntryFisikUmumT_OrderHeaderID = ? AND So_ResultEntryFisikUmumIsActive = 'Y'"; + $qry = $this->db_smartone->query($sql, array($id)); + if (!$qry) { + return "Err"; + } + $rows = $qry->result_array(); + if (count($rows) == 0) { + return "Err"; + } + $row_result = $rows[0]; + $d = json_decode($rows[0]["So_ResultEntryFisikUmumDetails"], true); + //keluhan saat ini + $paru = array(); + + if ($d["title"] == "PARU-PARU") { + + foreach ($d["details"] as $gp) { + if ($gp["chx"] == 1) { + $arr_result[] = array($gp["label"], $gp["value"]); + $hasil = $this->translate_word($gp["label"], $langid); + if ($gp["value"] != '') + $hasil = $this->translate_word($gp["label"], $langid) . " : " . $this->translate_word($gp["value"], $langid); + $paru[] = $hasil; + } + } + + } + $string_paru = count($paru) > 0 ? join(", ", $paru) : "-"; + $return_data = $string_paru; + + return $return_data; + } + + function jantung($id, $langid = 1) + { + $ret_array = []; + + $table_fisik_umum = "so_resultentry_fisik_umum"; + if ($langid == 2) { + $table_fisik_umum = "so_resultentry_fisik_umum_eng"; + } + + $sql = "SELECT * + FROM {$table_fisik_umum} + JOIN fisik_template ON So_ResultEntryFisikUmumFisikTemplateID = FisikTemplateID AND FisikTemplateIsActive = 'Y' AND FisikTemplateTitle = 'JANTUNG' + WHERE + So_ResultEntryFisikUmumT_OrderHeaderID = ? AND So_ResultEntryFisikUmumIsActive = 'Y'"; + $qry = $this->db_smartone->query($sql, array($id)); + if (!$qry) { + return "Err"; + } + //echo $this->db_smartone->last_query(); + $rows = $qry->result_array(); + if (count($rows) > 0) { + $d = json_decode($rows[0]["So_ResultEntryFisikUmumDetails"], true); + //keluhan saat ini + $jantung = array(); + + + if ($d["title"] == "JANTUNG") { + + foreach ($d["details"] as $gp) { + foreach ($gp["details"] as $xd) { + if ($xd["chx"] == 1 && $xd["label"] != 'Normal') { + $arr_result[] = array($gp["name"], $xd["label"], $xd["value"]); + $hasil = $this->translate_word($xd["label"], $langid); + if ($xd["value"] != '') + $hasil = $this->translate_word($xd["label"], $langid) . " : " . $this->translate_word($xd["value"], $langid); + $jantung[] = $hasil; + } + } + } + + + } + + $string_jantung = count($jantung) > 0 ? join(", ", $jantung) : "Normal"; + $return_data = $string_jantung; + } + + return $return_data; + } + + function anogenital($id, $langid = 1) + { + $ret_array = []; + + $table_fisik_umum = "so_resultentry_fisik_umum"; + if ($langid == 2) { + $table_fisik_umum = "so_resultentry_fisik_umum_eng"; + } + + $sql = "SELECT * + FROM {$table_fisik_umum} + JOIN fisik_template ON So_ResultEntryFisikUmumFisikTemplateID = FisikTemplateID AND FisikTemplateIsActive = 'Y' AND FisikTemplateTitle = 'PERUT / ABDOMEN' + WHERE + So_ResultEntryFisikUmumT_OrderHeaderID = ? AND So_ResultEntryFisikUmumIsActive = 'Y'"; + $qry = $this->db_smartone->query($sql, array($id)); + if (!$qry) { + return "Err"; + } + //echo $this->db_smartone->last_query(); + //exit; + $string_perut = "Err"; + $rows = $qry->result_array(); + if(count($rows) == 0) { + return "Err"; + } + if (count($rows) > 0) { + $d = json_decode($rows[0]["So_ResultEntryFisikUmumDetails"], true); + //keluhan saat ini + $perut = array(); + + + if ($d["title"] == "PERUT / ABDOMEN") { + + foreach ($d["details"] as $gp) { + if ($gp["name"] == 'Hemorroid') { + foreach ($gp["details"] as $xd) { + if ($xd["chx"] == 1 && $xd['id_code'] == 'perut_17') { + $arr_result[] = array($gp["name"], $xd["label"], $xd["value"]); + $hasil = $gp["name"] . " : " . $this->translate_word($xd["label"], $langid); + if ($xd["value"] != '') + $hasil = $gp["name"] . " : " . $this->translate_word($xd["label"], $langid) . " (" . $this->translate_word($xd["value"], $langid) . ")"; + $perut[] = $hasil; + } + if ($xd["chx"] == 1 && $xd['id_code'] == 'perut_15') { + $arr_result[] = array($gp["name"], $xd["label"], $xd["value"]); + $hasil = $this->translate_word($xd["label"], $langid); + if ($xd["value"] != '') + $hasil = $this->translate_word($xd["label"], $langid) . " (" . $this->translate_word($xd["value"], $langid) . ")"; + $perut[] = $hasil; + } + if ($xd["chx"] == 1 && $xd['id_code'] == 'perut_16') { + $arr_result[] = array($gp["name"], $xd["label"], $xd["value"]); + $hasil = $this->translate_word($xd["label"], $langid); + if ($xd["value"] != '') + $hasil = $this->translate_word($xd["label"], $langid) . " (" . $this->translate_word($xd["value"], $langid) . ")"; + $perut[] = $hasil; + } + } + } + + } + + } + + $string_perut = count($perut) > 0 ? join(", ", $perut) : "-"; + $ret_array['a2'] = $string_perut; + } + + $return_data = $string_perut; + + return $return_data; + } + + function pengukuran($id, $langid = 1) + { + $return_data = []; + + $table_fisik_umum = "so_resultentry_fisik_umum"; + if ($langid == 2) { + $table_fisik_umum = "so_resultentry_fisik_umum_eng"; + } + + + $sql = "SELECT * + FROM {$table_fisik_umum} + JOIN fisik_template ON So_ResultEntryFisikUmumFisikTemplateID = FisikTemplateID AND FisikTemplateIsActive = 'Y' AND FisikTemplateTitle = 'PERUT / ABDOMEN' + WHERE + So_ResultEntryFisikUmumT_OrderHeaderID = ? AND So_ResultEntryFisikUmumIsActive = 'Y'"; + $qry = $this->db_smartone->query($sql, array($id)); + if (!$qry) { + return "Err"; + } + $rows = $qry->result_array(); + if (count($rows) == 0) { + return "Err"; + } + if (count($rows) > 0) { + $d = json_decode($rows[0]["So_ResultEntryFisikUmumDetails"], true); + $perut = array(); + + if ($d["title"] == "PERUT / ABDOMEN") { + + foreach ($d["details"] as $gp) { + if ($gp["name"] == 'Pengukuran') { + foreach ($gp["details"] as $xd) { + if ( $xd["id_code"] == 'perut_18') { + if (intval($xd["value"]) > 0) { + $return_data['lingkar_perut'] = $xd["value"] . " " . $xd["unit"]; + } + else { + $return_data['lingkar_perut'] = 'NaN'; + } + } + if ( $xd["id_code"] == 'perut_19') { + if (intval($xd["value"]) > 0) { + $return_data['lingkar_pinggang'] = $xd["value"] . " " . $xd["unit"]; + } + else { + $return_data['lingkar_pinggang'] = 'NaN'; + } + } + } + } + + } + } + } + return $return_data; + } + + + + function tonometri($id, $langid = 1) + { + $return_data = "Err"; + + $table_fisik_umum = "so_resultentry_fisik_umum"; + if ($langid == 2) { + $table_fisik_umum = "so_resultentry_fisik_umum_eng"; + } + + $sql = "SELECT * + FROM {$table_fisik_umum} + JOIN fisik_template ON So_ResultEntryFisikUmumFisikTemplateID = FisikTemplateID AND FisikTemplateIsActive = 'Y' AND FisikTemplateTitle = 'TONOMETRI' + WHERE + So_ResultEntryFisikUmumT_OrderHeaderID = ? AND So_ResultEntryFisikUmumIsActive = 'Y'"; + $qry = $this->db_smartone->query($sql, array($id)); + if (!$qry) { + return "Err"; + } + $rows = $qry->result_array(); + if (count($rows) == 0) { + + $return_data = 'Err'; + return $return_data; + } + $d = json_decode($rows[0]["So_ResultEntryFisikUmumDetails"], true); + if ($d["title"] == "TONOMETRI") { + + foreach ($d["details"] as $gp) { + foreach ($gp["details"] as $xd) { + if ($xd["id_code"] == 'tonometri_od') { + $od = "OD : " . $xd["value"] . " " . $xd["unit"]; + } + if ($xd["id_code"] == 'tonometri_os') { + $os = "OS : " . $xd["value"] . " " . $xd["unit"]; + } + } + + + } + + + } + + $return_data = $od . " ; " . $os; + return $return_data; + } + + function perut($id, $langid = 1) + { + $return_data = "Err"; + + $table_fisik_umum = "so_resultentry_fisik_umum"; + if ($langid == 2) { + $table_fisik_umum = "so_resultentry_fisik_umum_eng"; + } + + $orderid = $id; + + $sql = "SELECT * + FROM {$table_fisik_umum} + JOIN fisik_template ON So_ResultEntryFisikUmumFisikTemplateID = FisikTemplateID AND FisikTemplateIsActive = 'Y' AND FisikTemplateTitle = 'PERUT / ABDOMEN' + WHERE + So_ResultEntryFisikUmumT_OrderHeaderID = ? AND So_ResultEntryFisikUmumIsActive = 'Y'"; + $qry = $this->db_smartone->query($sql, array($id)); + if (!$qry) { + return 'Err'; + } + $rows = $qry->result_array(); + if (count($rows) > 0) { + $d = json_decode($rows[0]["So_ResultEntryFisikUmumDetails"], true); + $perut = array(); + + if ($d["title"] == "PERUT / ABDOMEN") { + foreach ($d["details"] as $gp) { + if ($gp["name"] != 'Hernia' && $gp["name"] != 'Pengukuran' && $gp["name"] != 'Hemorroid') { + foreach ($gp["details"] as $xd) { + if ($xd["chx"] == 1 && $xd["label"] != 'Normal' && $xd["id_code"] !== 'perut_3') { + $arr_result[] = array($gp["name"], $xd["label"], $xd["value"]); + $hasil = $this->translate_word($gp["name"], $langid) . " : " . $this->translate_word($xd["label"], $langid); + if ($xd["value"] != '') + $hasil = $this->translate_word($gp["name"], $langid) . " : " . $this->translate_word($xd["label"], $langid) . " (" . $this->translate_word($xd["value"], $langid) . ")"; + $perut[] = $hasil; + } + } + } + } + } + + $string_perut = count($perut) > 0 ? join(", ", $perut) : "Normal"; + $return_data = $string_perut; + } + + + return $return_data; + } + + function ginjal($id, $langid = 1) + { + $ret_array = []; + + $table_fisik_umum = "so_resultentry_fisik_umum"; + if ($langid == 2) { + $table_fisik_umum = "so_resultentry_fisik_umum_eng"; + } + + $sql = "SELECT * + FROM {$table_fisik_umum} + JOIN fisik_template ON So_ResultEntryFisikUmumFisikTemplateID = FisikTemplateID AND FisikTemplateIsActive = 'Y' AND FisikTemplateTitle = 'PERUT / ABDOMEN' + WHERE + So_ResultEntryFisikUmumT_OrderHeaderID = ? AND So_ResultEntryFisikUmumIsActive = 'Y'"; + $qry = $this->db_smartone->query($sql, array($id)); + if (!$qry) { + return "Err"; + } + $rows = $qry->result_array(); + if (count($rows) == 0) { + return "Err"; + } + if (count($rows) > 0) { + $d = json_decode($rows[0]["So_ResultEntryFisikUmumDetails"], true); + //keluhan saat ini + $perut = []; + + if ($d["title"] == "PERUT / ABDOMEN") { + + foreach ($d["details"] as $gp) { + if ($gp["name"] == 'Abdomen') { + foreach ($gp["details"] as $xd) { + if ($xd["chx"] == 1 && $xd["id_code"] == 'perut_3') { + //$arr_result[] = array($gp["name"],$xd["label"],$xd["value"]) ; + $hasil = $this->translate_word($xd["label"], $langid); + if ($xd["value"] != '') + $hasil = $this->translate_word($xd["label"], $langid) . " (" . $this->translate_word($xd["value"], $langid) . ")"; + $perut[] = $hasil; + } + } + + } + + + } + + + } + + $string_perut = count($perut) > 0 ? join(", ", $perut) : "Normal"; + if ($string_perut == "") + $string_perut = "Normal"; + $return_data = $string_perut; + } + + return $return_data; + } + + function hernia($id, $langid = 1) + { + $ret_array = []; + + + $table_fisik_umum = "so_resultentry_fisik_umum"; + if ($langid == 2) { + $table_fisik_umum = "so_resultentry_fisik_umum_eng"; + } + + $sql = "SELECT * + FROM {$table_fisik_umum} + JOIN fisik_template ON So_ResultEntryFisikUmumFisikTemplateID = FisikTemplateID AND FisikTemplateIsActive = 'Y' AND FisikTemplateTitle = 'PERUT / ABDOMEN' + WHERE + So_ResultEntryFisikUmumT_OrderHeaderID = ? AND So_ResultEntryFisikUmumIsActive = 'Y'"; + $qry = $this->db_smartone->query($sql, array($id)); + if (!$qry) { + return "Err"; + } + $rows = $qry->result_array(); + if(count($rows) == 0) { + return "Err"; + } + if (count($rows) > 0) { + $d = json_decode($rows[0]["So_ResultEntryFisikUmumDetails"], true); + //keluhan saat ini + $perut = ""; + + + if ($d["title"] == "PERUT / ABDOMEN") { + + foreach ($d["details"] as $gp) { + if ($gp["name"] == 'Hernia') { + if ($gp["details"][1]["chx"] == "1") { + + $perut = $this->translate_word($gp["details"][1]["label"], $langid); + + if ($gp["details"][1]["details"][0]["chx_value"] == 1) { + if ($perut != "") + $perut .= " : "; + $perut .= " " . $this->translate_word($gp["details"][1]["details"][0]["label"], $langid); + } + //print_r($gp["details"][1]["details"][1]); + if ($gp["details"][1]["details"][1]["chx_a_value"] == 1 || $gp["details"][1]["details"][1]["chx_b_value"] == 1) { + $ds_hasil = ""; + if ($gp["details"][1]["details"][1]["chx_a_value"] == 1) { + if ($ds_hasil != "") + $ds_hasil .= ", "; + $ds_hasil .= $this->translate_word($gp["details"][1]["details"][1]["chx_a_label"], $langid); + } + + if ($gp["details"][1]["details"][1]["chx_b_value"] == 1) { + if ($ds_hasil != "") + $ds_hasil .= ", "; + $ds_hasil .= $this->translate_word($gp["details"][1]["details"][1]["chx_b_label"], $langid); + } + + if ($perut != "") + $perut .= " : "; + $perut .= " " . $this->translate_word($gp["details"][1]["details"][1]["label"], $langid) . " (" . $ds_hasil . ")"; + } + + if ($gp["details"][1]["details"][2]["chx_a_value"] == 1 || $gp["details"][1]["details"][2]["chx_b_value"] == 1) { + $ds_hasil = ""; + if ($gp["details"][1]["details"][2]["chx_a_value"] == 1) { + if ($ds_hasil != "") + $ds_hasil .= ", "; + $ds_hasil .= $this->translate_word($gp["details"][1]["details"][1]["chx_a_label"], $langid); + } + + if ($gp["details"][1]["details"][2]["chx_b_value"] == 1) { + if ($ds_hasil != "") + $ds_hasil .= ", "; + $ds_hasil .= $this->translate_word($gp["details"][1]["details"][2]["chx_b_label"], $langid); + } + + if ($perut != "") + $perut .= " : "; + $perut .= " " . $this->translate_word($gp["details"][1]["details"][2]["label"], $langid) . " (" . $ds_hasil . ")"; + } + + } + if ($gp["details"][0]["chx"] == "1") { + $perut = $this->translate_word($gp["details"][0]["label"], $langid); + } + } + + + } + + + } + $return_data = $perut; + } + return $return_data; + } + + function kulit($id, $langid = 1) + { + $ret_array = []; + $return_data = "Err"; + + $table_fisik_umum = "so_resultentry_fisik_umum"; + if ($langid == 2) { + $table_fisik_umum = "so_resultentry_fisik_umum_eng"; + } + + $sql = "SELECT * + FROM {$table_fisik_umum} + JOIN fisik_template ON So_ResultEntryFisikUmumFisikTemplateID = FisikTemplateID AND FisikTemplateIsActive = 'Y' AND + FisikTemplateTitle = 'SISTEM INTEGUMEN' + WHERE + So_ResultEntryFisikUmumT_OrderHeaderID = ? AND So_ResultEntryFisikUmumIsActive = 'Y'"; + $qry = $this->db_smartone->query($sql, array($id)); + if (!$qry) { + return "Err"; + } + + $rows = $qry->result_array(); + if(count($rows) == 0) { + return "Err"; + } + if (count($rows) > 0) { + $d = json_decode($rows[0]["So_ResultEntryFisikUmumDetails"], true); + //keluhan saat ini + $perut = array(); + + + if ($d["title"] == "SISTEM INTEGUMEN") { + + foreach ($d["details"] as $gp) { + if ($gp["name"] == 'Kulit') { + //echo "kulit"; + foreach ($gp["details"] as $xd) { + if ($xd["chx"] == 1 && $xd["label"] != 'Lain-lain') { + // echo "IN"; + $arr_result[] = array($gp["name"], $xd["label"], $xd["value"]); + $hasil = $this->translate_word($xd["label"], $langid); + if ($xd["value"] != '') + $hasil = $this->translate_word($xd["label"], $langid) . " : " . $this->translate_word($xd["value"], $langid); + $perut[] = $hasil; + } + + if ($xd["chx"] == 1 && $xd["label"] == 'Lain-lain') { + // echo "lain"; + $arr_result[] = array($gp["name"], $xd["label"], $xd["value"]); + $hasil = $this->translate_word($xd["label"], $langid); + if ($xd["value"] != '') + $hasil = $this->translate_word($xd["label"], $langid) . " : " . $this->translate_word($xd["value"], $langid); + $perut[] = $hasil; + } + } + } + + } + + + } + + $sql = "SELECT * + FROM {$table_fisik_umum} + JOIN fisik_template ON So_ResultEntryFisikUmumFisikTemplateID = FisikTemplateID AND FisikTemplateIsActive = 'Y' AND + FisikTemplateTitle = 'KEPALA WAJAH' + WHERE + So_ResultEntryFisikUmumT_OrderHeaderID = ? AND So_ResultEntryFisikUmumIsActive = 'Y'"; + $qry = $this->db_smartone->query($sql, array($id)); + if (!$qry) { + return 'Err'; + } + + $rows_kepala = $qry->result_array(); + if (count($rows_kepala) > 0) { + $d_kepala = json_decode($rows_kepala[0]["So_ResultEntryFisikUmumDetails"], true); + if ($d_kepala["title"] == "KEPALA WAJAH") { + $kepala_wajah = []; + foreach ($d_kepala["details"] as $xd_kepala) { + if ($xd_kepala["chx"] == 1 && $xd_kepala["is_normal"] == 'N') { + $arr_result[] = array($d_kepala["title"], $xd_kepala["label"], $xd_kepala["value"]); + $hasil = $this->translate_word($xd_kepala["label"], $langid); + if ($xd_kepala["value"] != '') + $hasil = $this->translate_word($xd_kepala["label"], $langid) . " : " . $this->translate_word($xd_kepala["value"], $langid); + $kepala_wajah[] = $hasil; + } + } + if (count($kepala_wajah) > 0) { + $string_kepala_wajah = join(", ", $kepala_wajah); + $perut[] = "Kepala wajah ( ".$string_kepala_wajah." )"; + } + } + } + + $string_perut = count($perut) > 0 ? join(", ", $perut) : "-"; + $return_data = $string_perut; + } + return $return_data; + } + + function extremitas_xxx($id, $langid = 1) + { + $return_data = "Err"; + + $table_fisik_umum = "so_resultentry_fisik_umum"; + if ($langid == 2) { + $table_fisik_umum = "so_resultentry_fisik_umum_eng"; + } + + $sql = "SELECT * + FROM {$table_fisik_umum} + JOIN fisik_template ON So_ResultEntryFisikUmumFisikTemplateID = FisikTemplateID AND FisikTemplateIsActive = 'Y' AND + FisikTemplateTitle = 'ANGGOTA GERAK' + WHERE + So_ResultEntryFisikUmumT_OrderHeaderID = ? AND So_ResultEntryFisikUmumIsActive = 'Y'"; + $qry = $this->db_smartone->query($sql, array($id)); + if (!$qry) { + return "Err"; + } + $rows = $qry->result_array(); + if (count($rows) == 0) { + return "Err"; + } + if (count($rows) > 0) { + $d = json_decode($rows[0]["So_ResultEntryFisikUmumDetails"], true); + $perut = array(); + + + if ($d["title"] == "ANGGOTA GERAK") { + + foreach ($d["details"] as $gp) { + foreach ($gp["details"] as $xd) { + if ($xd["chx"] == 1 && $xd["label"] != 'Lain-lain' && $xd["label"] != 'Normal') { + $arr_result[] = array($gp["name"], $xd["label"], $xd["value"]); + $hasil = $this->translate_word($xd["label"], $langid); + if ($xd["value"] != '') + $hasil = $gp["name"] . " : " . $this->translate_word($xd["label"], $langid) . " (" . $this->translate_word($xd["value"], $langid) . ")"; + $perut[] = $hasil; + } + + if ($xd["chx"] == 1 && $xd["label"] == 'Lain-lain') { + // echo "lain"; + $arr_result[] = array($gp["name"], $xd["label"], $xd["value"]); + $hasil = $this->translate_word($xd["label"], $langid); + if ($xd["value"] != '') + $hasil = $gp["name"] . " : " . $this->translate_word($xd["label"], $langid) . " (" . $this->translate_word($xd["value"], $langid) . ")"; + $perut[] = $hasil; + } + } + } + } + + $string_perut = count($perut) > 0 ? join(", ", $perut) : "Normal"; + $return_data = $string_perut; + } + return $return_data; + } + + function reflek($id, $langid = 1) + { + $ret_array = []; + + + $table_fisik_umum = "so_resultentry_fisik_umum"; + if ($langid == 2) { + $table_fisik_umum = "so_resultentry_fisik_umum_eng"; + } + + $sql = "SELECT * + FROM {$table_fisik_umum} + JOIN fisik_template ON So_ResultEntryFisikUmumFisikTemplateID = FisikTemplateID AND FisikTemplateIsActive = 'Y' AND + FisikTemplateTitle = 'SISTEM PERSYARAFAN' + WHERE + So_ResultEntryFisikUmumT_OrderHeaderID = ? AND So_ResultEntryFisikUmumIsActive = 'Y'"; + $qry = $this->db_smartone->query($sql, array($id)); + if (!$qry) { + return "Err"; + } + $rows = $qry->result_array(); + if (count($rows) == 0) { + return "Err"; + } + if (count($rows) > 0) { + $d = json_decode($rows[0]["So_ResultEntryFisikUmumDetails"], true); + //keluhan saat ini + $fisiologis = array(); + $patologis = array(); + + + if ($d["title"] == "SISTEM PERSYARAFAN") { + + foreach ($d["details"] as $gp) { + if ($gp['name'] == 'Refleks Fisiologis') { + foreach ($gp["details"] as $xd) { + if ($xd["chx"] == 1 && $xd["label"] != 'Lain-lain' && $xd["label"] != 'Normal') { + // echo "IN"; + $arr_result[] = array($gp["name"], $xd["label"], $xd["value"]); + $hasil = $this->translate_word($xd["label"], $langid); + if ($xd["value"] != '') + $hasil = $this->translate_word($xd["label"], $langid) . " (" . $this->translate_word($xd["value"], $langid) . ")"; + $fisiologis[] = $hasil; + } + + if ($xd["chx"] == 1 && $xd["label"] == 'Lain-lain') { + // echo "lain"; + $arr_result[] = array($gp["name"], $xd["label"], $xd["value"]); + $hasil = $this->translate_word($xd["label"], $langid); + if ($xd["value"] != '') + $hasil = $this->translate_word($xd["label"], $langid) . " (" . $this->translate_word($xd["value"], $langid) . ")"; + $fisiologis[] = $hasil; + } + } + } + + + if ($gp['name'] == 'Refleks Pathologis') { + $hasil_rst_lbp = []; + $low_back_pain_inspected = false; + foreach ($gp["details"] as $xd) { + if ($xd["chx"] == 1) { + $sql = "SELECT * + FROM {$table_fisik_umum} + JOIN fisik_template ON So_ResultEntryFisikUmumFisikTemplateID = FisikTemplateID AND FisikTemplateIsActive = 'Y' AND + FisikTemplateTitle = 'LOW BACK PAIN SCREENING TEST' + WHERE + So_ResultEntryFisikUmumT_OrderHeaderID = ? AND + So_ResultEntryFisikUmumIsActive = 'Y'"; + $qry = $this->db_smartone->query($sql, array($id)); + $rows_lbp = $qry->result_array(); + //return $this->db_smartone->last_query(); + if (count($rows_lbp) > 0) { + $d_lbp = json_decode($rows_lbp[0]["So_ResultEntryFisikUmumDetails"], true); + $patologis = array(); + + if ($d_lbp["title"] == "LOW BACK PAIN SCREENING TEST") { + $low_back_pain_inspected = true; + foreach ($d_lbp["details"] as $gp_lbp) { + foreach ($gp_lbp["details"] as $xd_lbp) { + + if ($xd_lbp["chx"] == 1) { + $arr_result[] = array($gp_lbp["name"], $xd["label"], $xd_lbp["value"]); + $hasil = $gp_lbp["name"] . " : " . $xd_lbp["label"]; + if ($xd_lbp["value"] != '') + $hasil = $gp_lbp["name"] . " : " . $xd_lbp["label"] . " (" . $xd_lbp['value'] . ")"; + $patologis[] = $hasil; + } + } + } + } + else { + $arr_result[] = array($gp["name"], $xd["label"], $xd["value"]); + $hasil = $this->translate_word($xd["label"], $langid); + if ($xd["value"] != '') + $hasil = $this->translate_word($xd["label"], $langid) . " : " . $this->translate_word($xd["value"], $langid); + $patologis[] = $hasil; + } + } + } + } + } + } + } + + $string_hasil_fisiologis = count($fisiologis) > 0 ? join(", ", $fisiologis) : "Normal"; + $string_hasil_patologis = count($patologis) > 0 ? join(", ", $patologis) : "Normal"; + + $ret_array['Refleks_Fisiologis'] = $string_hasil_fisiologis; + $ret_array['Refleks_Pathologis'] = $string_hasil_patologis; + } + + + return count($ret_array) > 0 ? $ret_array : "Err"; + } + + function romberg($id, $langid = 1) + { + $return_data = "Err"; + + $table_fisik_umum = "so_resultentry_fisik_umum"; + if ($langid == 2) { + $table_fisik_umum = "so_resultentry_fisik_umum_eng"; + } + + $sql = "SELECT * + FROM {$table_fisik_umum} + JOIN fisik_template ON So_ResultEntryFisikUmumFisikTemplateID = FisikTemplateID AND FisikTemplateIsActive = 'Y' AND + FisikTemplateTitle = 'SISTEM PERSYARAFAN' + WHERE + So_ResultEntryFisikUmumT_OrderHeaderID = ? AND So_ResultEntryFisikUmumIsActive = 'Y'"; + $qry = $this->db_smartone->query($sql, array($id)); + if (!$qry) { + return "Err"; + } + $rows = $qry->result_array(); + if (count($rows) == 0) { + return "Err"; + } + + + if (count($rows) > 0 ) { + $d = json_decode($rows[0]["So_ResultEntryFisikUmumDetails"], true); + $fisiologis = array(); + $patologis = array(); + + if ($d["title"] == "SISTEM PERSYARAFAN") { + foreach ($d["details"] as $gp) { + if ($gp['name'] == 'Keseimbangan & Koordinasi (Romberg)') { + foreach ($gp["details"] as $xd) { + if ($xd["chx"] == 1 && $xd["label"] != 'Lain-lain') { + $arr_result[] = array($gp["name"], $xd["label"], $xd["value"]); + $hasil = $this->translate_word($xd["label"], $langid); + if ($xd["value"] != '') + $hasil = $this->translate_word($xd["label"], $langid) . " (" . $this->translate_word($xd["value"], $langid) . ")"; + $return_data = $hasil; + } + } + } + } + } + } + + return $return_data; + } + + function genitourinaria($id, $langid = 1) + { + $return_data = "Err"; + + $table_fisik_umum = "so_resultentry_fisik_umum"; + if ($langid == 2) { + $table_fisik_umum = "so_resultentry_fisik_umum_eng"; + } + + $sql = "SELECT * + FROM {$table_fisik_umum} + JOIN fisik_template ON So_ResultEntryFisikUmumFisikTemplateID = FisikTemplateID AND FisikTemplateIsActive = 'Y' AND + FisikTemplateTitle = 'GENITOURINARIA' + WHERE + So_ResultEntryFisikUmumT_OrderHeaderID = ? AND So_ResultEntryFisikUmumIsActive = 'Y'"; + $qry = $this->db_smartone->query($sql, array($id)); + if (!$qry) { + $return_data = "Err"; + //$return_data = $this->db_smartone->last_query(); + + return $return_data; + } + $rows = $qry->result_array(); + if (count($rows) == 0) { + return "Err"; + } + $d = json_decode($rows[0]["So_ResultEntryFisikUmumDetails"], true); + //keluhan saat ini + $genitourinaria = array(); + + + if ($d["title"] == "GENITOURINARIA") { + + foreach ($d["details"] as $gp) { + if ($gp["chx"] == 1) { + $arr_result[] = array($gp["label"], $gp["value"]); + $hasil = $this->translate_word($gp["label"], $langid); + if ($gp["value"] != '') + $hasil = $this->translate_word($gp["label"], $langid) . " : " . $this->translate_word($gp["value"], $langid); + $genitourinaria[] = $hasil; + } + } + + } + + if (count($genitourinaria) == 0) { + return "Err"; + } + + $string_genitourinaria = count($genitourinaria) > 0 ? join(", ", $genitourinaria) : "Tidak diperiksa"; + return $string_genitourinaria; + } + + function anggota_gerak($id, $langid = 1) + { + $return_data = ""; + $table_fisik_umum = "so_resultentry_fisik_umum"; + if ($langid == 2) { + $table_fisik_umum = "so_resultentry_fisik_umum_eng"; + } + + $sql = "SELECT * + FROM {$table_fisik_umum} + JOIN fisik_template ON So_ResultEntryFisikUmumFisikTemplateID = FisikTemplateID AND FisikTemplateIsActive = 'Y' AND FisikTemplateTitle = 'ANGGOTA GERAK' + WHERE + So_ResultEntryFisikUmumT_OrderHeaderID = ? AND So_ResultEntryFisikUmumIsActive = 'Y'"; + $qry = $this->db_smartone->query($sql, array($id)); + if (!$qry) { + return "Err"; + } + $rows = $qry->result_array(); + if (count($rows) == 0) { + return "Err"; + } + if (count($rows) > 0) { + $d = json_decode($rows[0]["So_ResultEntryFisikUmumDetails"], true); + //keluhan saat ini + $anggota = array(); + + + if ($d["title"] == "ANGGOTA GERAK") { + foreach ($d["details"] as $gp) { + $anggota[$gp["name"]] = array(); + foreach ($gp["details"] as $xd) { + if ($xd["chx"] == 1) { + $hasil = $this->translate_word($xd["label"], $langid); + if ($xd["value"] != '') + $hasil = $this->translate_word($xd["label"], $langid) . " (" . $this->translate_word($xd["value"], $langid) . ")"; + $anggota[$gp["name"]][] = $hasil; + } + } + } + } + } + + $dt_return = array(); + + if(count($anggota) > 0) { + foreach ($anggota as $key => $value) { + $dt_return[$key] = count($value) > 0 ? join(", ", $value) : "Tidak diperiksa"; + } + + $return_data = ""; + foreach ($dt_return as $key => $value) { + $return_data .= $key . " : " . $value . ", "; + } + $return_data = rtrim($return_data, ", "); + } + else { + $return_data = "Tidak diperiksa"; + } + + return $return_data; + } + + function sistem_persyarafan($id, $langid = 1) + { + $return_data = ""; + $table_fisik_umum = "so_resultentry_fisik_umum"; + if ($langid == 2) { + $table_fisik_umum = "so_resultentry_fisik_umum_eng"; + } + + $sql = "SELECT * + FROM {$table_fisik_umum} + JOIN fisik_template ON So_ResultEntryFisikUmumFisikTemplateID = FisikTemplateID AND FisikTemplateIsActive = 'Y' AND FisikTemplateTitle = 'SISTEM PERSYARAFAN' + WHERE + So_ResultEntryFisikUmumT_OrderHeaderID = ? AND So_ResultEntryFisikUmumIsActive = 'Y'"; + $qry = $this->db_smartone->query($sql, array($id)); + if (!$qry) { + return "Err"; + } + $rows = $qry->result_array(); + if (count($rows) == 0) { + return "Err"; + } + if (count($rows) > 0) { + $d = json_decode($rows[0]["So_ResultEntryFisikUmumDetails"], true); + //keluhan saat ini + $sistem = array(); + + + if ($d["title"] == "SISTEM PERSYARAFAN") { + + foreach ($d["details"] as $gp) { + + if ($gp["name"] != 'Keseimbangan & Koordinasi (Romberg)') { + $gpname = str_replace(" ", "_", $gp["name"]); + $sistem[$gpname] = array(); + foreach ($gp["details"] as $xd) { + if ($xd["chx"] == 1 ) { + $hasil = $this->translate_word($xd["label"], $langid); + if ($xd["value"] != '') + $hasil = $this->translate_word($xd["label"], $langid) . " (" . $this->translate_word($xd["value"], $langid) . ")"; + $sistem[$gpname][] = $hasil; + } + } + } + + } + } + } + + if(count($sistem) > 0) { + foreach ($sistem as $key => $value) { + $dt_return[$key] = count($value) > 0 ? join(", ", $value) : "Tidak diperiksa"; + } + $return_data = $dt_return; + } + else { + $return_data = "Tidak diperiksa"; + } + + return $return_data; + + } + + + function smell_test($id, $langid = 1) + { + $sql = "SELECT * + FROM so_resultentry + WHERE + So_ResultEntryID = ?"; + $qry = $this->db_smartone->query($sql, array($id)); + if(!$qry) { + return "Err"; + } + $row = $qry->row(); + if(!$row) { + return "Err"; + } + $orderid = $qry->row()->So_ResultEntryT_OrderHeaderID; + $table_fisik_umum = "so_resultentry_fisik_umum"; + if ($langid == 2) { + $table_fisik_umum = "so_resultentry_fisik_umum_eng"; + } + + $sql = "SELECT * + FROM {$table_fisik_umum} + JOIN fisik_template ON So_ResultEntryFisikUmumFisikTemplateID = FisikTemplateID AND + FisikTemplateIsActive = 'Y' AND FisikTemplateTitle = 'SMELL TEST' + WHERE + So_ResultEntryFisikUmumT_OrderHeaderID = ? AND So_ResultEntryFisikUmumIsActive = 'Y'"; + $qry = $this->db_smartone->query($sql, array($id)); + if (!$qry) { + return 'Err'; + } + $rows = $qry->result_array(); + $dt_return = array(); + if (count($rows) > 0) { + $d = json_decode($rows[0]["So_ResultEntryFisikUmumDetails"], true); + //keluhan saat ini + $smell = array(); + + + if ($d["title"] == "SMELL TEST") { + + foreach ($d["details"] as $gp) { + //$smell[$gp["name"]] = array(); + foreach ($gp["details"] as $xd) { + if ($xd["chx"] == 1) { + $hasil = $this->translate_word($gp["name"], $langid); + if ($xd["value"] != '') + $hasil = $this->translate_word($xd["label"], $langid) . " : " . $this->translate_word($xd["value"], $langid); + //$smell[$gp["name"]][] = $hasil; + $smell[] = $hasil; + } + } + } + + + } + + if(count($smell) > 0) { + $string_smell = count($smell) > 0 ? join(", ", $smell) : "Tidak diperiksa"; + $dt_return = $string_smell; + } + + + } + return count($dt_return) > 0 ? $dt_return : "Err"; + } + + function rectum_urogenital($id, $langid = 1) + { + $return_data = "Err"; + + $table_fisik_umum = "so_resultentry_fisik_umum"; + if ($langid == 2) { + $table_fisik_umum = "so_resultentry_fisik_umum_eng"; + } + + $sql = "SELECT * + FROM {$table_fisik_umum} + JOIN fisik_template ON So_ResultEntryFisikUmumFisikTemplateID = FisikTemplateID AND FisikTemplateIsActive = 'Y' + AND FisikTemplateTitle = 'PEMERIKSAAN RECTUM DAN UROGENITAL' + WHERE + So_ResultEntryFisikUmumT_OrderHeaderID = ? AND So_ResultEntryFisikUmumIsActive = 'Y'"; + $qry = $this->db_smartone->query($sql, array($id)); + if (!$qry) { + return "Err"; + } + $rows = $qry->result_array(); + if (count($rows) == 0) { + return "Err"; + } + $row_result = $rows[0]; + $d = json_decode($rows[0]["So_ResultEntryFisikUmumDetails"], true); + //keluhan saat ini + $leher = array(); + + + if ($d["title"] == "PEMERIKSAAN RECTUM DAN UROGENITAL") { + + foreach ($d["details"] as $gp) { + if ($gp["chx"] == 1) { + $arr_result[] = array($gp["label"], $gp["value"]); + $hasil = $this->translate_word($gp["label"], $langid); + if ($gp["value"] != '') + $hasil = $this->translate_word($gp["label"], $langid) . " : " . $this->translate_word($gp["value"], $langid); + $leher[] = $hasil; + } + } + + } + + $string_leher = count($leher) > 0 ? join(", ", $leher) : "Normal"; + $return_data = $string_leher; + + return $return_data; + } + + + + function saran($id, $langid) + { + $sql = "select * from so_resultentry_fisik_umum + where So_ResultEntryFisikUmumSo_ResultEntryID= ? + and So_ResultEntryFisikUmumM_LangID=? + and So_ResultEntryFisikUmumType='saran'"; + $qry = $this->db_smartone->query($sql, array($id, $langid)); + $saran = "Err"; + if ($qry) { + $rows = $qry->result_array(); + if (count($rows) > 0) { + $saran = $this->translate_word($rows[0]["So_ResultEntryFisikUmumDetails"], $langid); + } + } + + return trim((string)$saran) === '' ? "Err" : $saran; + } + + function konsul($id, $langid) + { + $sql = "select * from so_resultentry_fisik_umum + where So_ResultEntryFisikUmumSo_ResultEntryID= ? + and So_ResultEntryFisikUmumM_LangID=? + and So_ResultEntryFisikUmumType='konsul'"; + $qry = $this->db_smartone->query($sql, array($id, $langid)); + $konsul = "Err"; + if ($qry) { + $rows = $qry->result_array(); + if (count($rows) > 0) { + $konsul = $this->translate_word($rows[0]["So_ResultEntryFisikUmumDetails"], $langid); + } + } + return trim((string)$konsul) === '' ? "Err" : $konsul; + } + + //k3 + function faktor_fisik($id, $langid = 1) + { + $sql = "SELECT * + FROM so_resultentry_fisik_umum + JOIN fisik_template ON So_ResultEntryFisikUmumFisikTemplateID = FisikTemplateID + AND FisikTemplateIsActive = 'Y' AND FisikTemplateTitle = 'FAKTOR FISIK' + WHERE + So_ResultEntryFisikUmumT_OrderHeaderID = ? AND So_ResultEntryFisikUmumIsActive = 'Y'"; + $qry = $this->db_smartone->query($sql, array ($id)); + if (!$qry) { + return "Err"; + } + $rows = $qry->result_array(); + if (count($rows) == 0) { + return "Err"; + } + $d = json_decode($rows[0]["So_ResultEntryFisikUmumDetails"], true); + //keluhan saat ini + $faktor_fisik = array(); + + + if ($d["title"] == "FAKTOR FISIK") { + + foreach ($d["details"] as $gp) { + // if ($gp["chx"] == 1 ) { + if ($gp["chx"] == 1) { + $faktor_fisik[] = $this->translate_word($gp["label"], $langid); + } + // } + } + + } + + + $return_data = ""; + if (count($faktor_fisik) > 0) { + foreach ($faktor_fisik as $key => $value) { + $return_data .= $value . ", "; + } + $return_data = rtrim($return_data, ", "); + } + else { + $return_data = "Tidak ada"; + } + return $return_data; + } + + function faktor_kimia($id, $langid = 1) + { + $sql = "SELECT * + FROM so_resultentry_fisik_umum + JOIN fisik_template ON So_ResultEntryFisikUmumFisikTemplateID = FisikTemplateID AND FisikTemplateIsActive = 'Y' AND FisikTemplateTitle = 'FAKTOR KIMIA' + WHERE + So_ResultEntryFisikUmumT_OrderHeaderID = ? AND So_ResultEntryFisikUmumIsActive = 'Y'"; + $qry = $this->db_smartone->query($sql, array($id)); + if (!$qry) { + return "Err"; + } + $rows = $qry->result_array(); + if (count($rows) == 0) { + return "Err"; + } + $d = json_decode($rows[0]["So_ResultEntryFisikUmumDetails"], true); + //keluhan saat ini + $faktor_kimia = array(); + + if ($d["title"] == "FAKTOR KIMIA") { + + foreach ($d["details"] as $gp) { + // if ($gp["chx"] == 1 ) { + if ($gp["chx"] == 1) { + $faktor_kimia[] = $this->translate_word($gp["label"], $langid); + } + // } + } + + } + + $return_data = ""; + if (count($faktor_kimia) > 0) { + foreach ($faktor_kimia as $key => $value) { + $return_data .= $value . ", "; + } + $return_data = rtrim($return_data, ", "); + } + else { + $return_data = "Tidak ada"; + } + return $return_data; + } + + function faktor_biologi($id, $langid = 1) + { + $sql = "SELECT * + FROM so_resultentry_fisik_umum + JOIN fisik_template ON So_ResultEntryFisikUmumFisikTemplateID = FisikTemplateID AND FisikTemplateIsActive = 'Y' AND FisikTemplateTitle = 'FAKTOR BIOLOGI' + WHERE + So_ResultEntryFisikUmumT_OrderHeaderID = ? AND So_ResultEntryFisikUmumIsActive = 'Y'"; + $qry = $this->db_smartone->query($sql, array($id)); + if (!$qry) { + return "Err"; + } + $rows = $qry->result_array(); + if (count($rows) == 0) { + return "Err"; + } + $d = json_decode($rows[0]["So_ResultEntryFisikUmumDetails"], true); + //keluhan saat ini + $faktor_biologi = array(); + + + if ($d["title"] == "FAKTOR BIOLOGI") { + + foreach ($d["details"] as $gp) { + // if ($gp["chx"] == 1 ) { + if ($gp["chx"] == 1) { + $faktor_biologi[] = $this->translate_word($gp["label"], $langid); + } + // } + } + + } + + $return_data = ""; + if (count($faktor_biologi) > 0) { + foreach ($faktor_biologi as $key => $value) { + $return_data .= $value . ", "; + } + $return_data = rtrim($return_data, ", "); + } + else { + $return_data = "Tidak ada"; + } + return $return_data; + } + + function faktor_ergonomi($id, $langid = 1) + { + $sql = "SELECT * + FROM so_resultentry_fisik_umum + JOIN fisik_template ON So_ResultEntryFisikUmumFisikTemplateID = FisikTemplateID AND FisikTemplateIsActive = 'Y' AND FisikTemplateTitle = 'FAKTOR ERGONOMI' + WHERE + So_ResultEntryFisikUmumT_OrderHeaderID = ? AND So_ResultEntryFisikUmumIsActive = 'Y'"; + $qry = $this->db_smartone->query($sql, array($id)); + if (!$qry) { + return "Err"; + } + $rows = $qry->result_array(); + if (count($rows) == 0) { + return "Err"; + } + $d = json_decode($rows[0]["So_ResultEntryFisikUmumDetails"], true); + //keluhan saat ini + $faktor_ergonomi = array(); + + + if ($d["title"] == "FAKTOR ERGONOMI") { + + foreach ($d["details"] as $gp) { + // if ($gp["chx"] == 1 ) { + if ($gp["chx"] == 1) { + + $faktor_ergonomi[] = $this->translate_word($gp["label"], $langid); + } + // } + } + + } + + $return_data = ""; + if (count($faktor_ergonomi) > 0) { + foreach ($faktor_ergonomi as $key => $value) { + $return_data .= $value . ", "; + } + $return_data = rtrim($return_data, ", "); + } + else { + $return_data = "Tidak ada"; + } + return $return_data; + } + function faktor_psikologi($id, $langid = 1) + { + $sql = "SELECT * + FROM so_resultentry_fisik_umum + JOIN fisik_template ON So_ResultEntryFisikUmumFisikTemplateID = FisikTemplateID AND FisikTemplateIsActive = 'Y' AND FisikTemplateTitle = 'FAKTOR PSIKOLOGI' + WHERE + So_ResultEntryFisikUmumT_OrderHeaderID = ? AND So_ResultEntryFisikUmumIsActive = 'Y'"; + $qry = $this->db_smartone->query($sql, array($id)); + if (!$qry) { + return "Err"; + } + $rows = $qry->result_array(); + if (count($rows) == 0) { + return "Err"; + } + $d = json_decode($rows[0]["So_ResultEntryFisikUmumDetails"], true); + //keluhan saat ini + $faktor_psikologi = array(); + + + if ($d["title"] == "FAKTOR PSIKOLOGI") { + + foreach ($d["details"] as $gp) { + + if ($gp["chx"] == 1) { + $faktor_psikologi[] = $this->translate_word($gp["label"], $langid); + } + + } + + } + + $return_data = ""; + if (count($faktor_psikologi) > 0) { + foreach ($faktor_psikologi as $key => $value) { + $return_data .= $value . ", "; + } + $return_data = rtrim($return_data, ", "); + } + else { + $return_data = "Tidak ada"; + } + return $return_data; + } + + /** + * Simpan semua hasil pemeriksaan fisik ke tabel result_fisik_umum. + * + * Logika penyimpanan: + * - Jika hasil fungsi berupa string / scalar → 1 row, ResultFisikUmumLabel = nama fungsi + * - Jika hasil berupa array of {label, value} (misal keadaan_umum) → tiap item jadi 1 row, + * ResultFisikUmumLabel = item['label'] + * - Jika hasil berupa associative array (misal status_gizi, pengukuran, reflek, sistem_persyarafan) + * → tiap key jadi 1 row, ResultFisikUmumLabel = key + * + * @param int $orderHeaderId T_OrderHeaderID + * @param int $langid 1 = Indonesia, 2 = Inggris + * @return array ['success', 'orderHeaderId', 'rows_saved'] + */ + function save_result_fisik_umum($orderHeaderId, $langid = 1) + { + /** + * Peta field: + * 'call' → cara memanggil: default | default3 | id_only | visus | tekanan_darah + * 'result_type' → bentuk hasil yang DIHARAPKAN dari fungsi: + * string → nilai tunggal, 1 row, label = nama field + * assoc → associative array, tiap key jadi 1 row + * label_value → array of {label, value}, tiap item jadi 1 row + */ + $field_map = [ + // --- Anamnesis --- + 'keluhan_saat_ini' => ['method' => 'keluhan_saat_ini', 'call' => 'default', 'result_type' => 'string'], + 'riwayat_phobia' => ['method' => 'riwayat_phobia', 'call' => 'default', 'result_type' => 'string'], + 'bodyfatmonitoring' => ['method' => 'bodyfatmonitoring', 'call' => 'default3', 'result_type' => 'string'], + 'riwayat_penyakit' => ['method' => 'riwayat_penyakit', 'call' => 'default', 'result_type' => 'string'], + 'alergi' => ['method' => 'alergi', 'call' => 'default', 'result_type' => 'string'], + 'riwayat_penyakit_keluarga' => ['method' => 'riwayat_penyakit_keluarga', 'call' => 'default', 'result_type' => 'assoc'], + 'merokok' => ['method' => 'merokok', 'call' => 'default', 'result_type' => 'string'], + 'alkohol' => ['method' => 'alkohol', 'call' => 'default', 'result_type' => 'string'], + 'olahraga' => ['method' => 'olahraga', 'call' => 'default', 'result_type' => 'string'], + 'riwayat_obat' => ['method' => 'riwayat_obat', 'call' => 'default', 'result_type' => 'string'], + 'riwayat_imunisasi' => ['method' => 'riwayat_imunisasi', 'call' => 'default', 'result_type' => 'string'], + // --- Tanda Vital --- + 'tekanan_darah' => ['method' => 'tekanan_darah', 'call' => 'tekanan_darah', 'result_type' => 'assoc'], + 'laju_pernafasan' => ['method' => 'laju_pernafasan', 'call' => 'default', 'result_type' => 'string'], + 'denyut_nadi' => ['method' => 'denyut_nadi', 'call' => 'default', 'result_type' => 'string'], + 'suhu' => ['method' => 'suhu', 'call' => 'default', 'result_type' => 'string'], + 'ritme_denyut_nadi' => ['method' => 'ritme_denyut_nadi', 'call' => 'default', 'result_type' => 'string'], + 'pola_nafas' => ['method' => 'pola_nafas', 'call' => 'default', 'result_type' => 'string'], + // --- Status Gizi (object: TB, BB, BodyFat, BMI, Standart) --- + 'status_gizi' => ['method' => 'status_gizi', 'call' => 'default3', 'result_type' => 'assoc'], + // --- Pemeriksaan Fisik --- + 'lapang_pandang' => ['method' => 'lapang_pandang', 'call' => 'default', 'result_type' => 'string'], + 'keadaan_umum' => ['method' => 'keadaan_umum', 'call' => 'default', 'result_type' => 'label_value'], + 'kepala_wajah' => ['method' => 'kepala_wajah', 'call' => 'default3', 'result_type' => 'string'], + 'persepsi_warna' => ['method' => 'persepsi_warna', 'call' => 'default', 'result_type' => 'string'], + 'doctor' => ['method' => 'doctor', 'call' => 'id_only', 'result_type' => 'string'], + 'konjuktiva_sklera' => ['method' => 'konjuktiva_sklera', 'call' => 'id_only', 'result_type' => 'string'], + 'telinga' => ['method' => 'telinga', 'call' => 'default', 'result_type' => 'string'], + 'visus_left' => ['method' => 'visus', 'call' => 'visus', 'result_type' => 'string', 'side' => 'left'], + 'visus_right' => ['method' => 'visus', 'call' => 'visus', 'result_type' => 'string', 'side' => 'right'], + 'hidung' => ['method' => 'hidung', 'call' => 'default', 'result_type' => 'string'], + 'leher' => ['method' => 'leher', 'call' => 'default', 'result_type' => 'string'], + 'thorax' => ['method' => 'thorax', 'call' => 'default', 'result_type' => 'string'], + 'mulut' => ['method' => 'mulut', 'call' => 'default', 'result_type' => 'string'], + 'tenggorokan' => ['method' => 'tenggorokan', 'call' => 'default', 'result_type' => 'string'], + 'paru' => ['method' => 'paru', 'call' => 'default', 'result_type' => 'string'], + 'jantung' => ['method' => 'jantung', 'call' => 'default', 'result_type' => 'string'], + 'anogenital' => ['method' => 'anogenital', 'call' => 'default', 'result_type' => 'string'], + // --- Pengukuran (object: lingkar_perut, lingkar_pinggang) --- + 'pengukuran' => ['method' => 'pengukuran', 'call' => 'default', 'result_type' => 'assoc'], + 'tonometri' => ['method' => 'tonometri', 'call' => 'default', 'result_type' => 'string'], + 'perut' => ['method' => 'perut', 'call' => 'default', 'result_type' => 'string'], + 'ginjal' => ['method' => 'ginjal', 'call' => 'default', 'result_type' => 'string'], + 'hernia' => ['method' => 'hernia', 'call' => 'default', 'result_type' => 'string'], + 'kulit' => ['method' => 'kulit', 'call' => 'default', 'result_type' => 'string'], + // --- Reflek (object: Refleks_Fisiologis, Refleks_Pathologis) --- + 'reflek' => ['method' => 'reflek', 'call' => 'default', 'result_type' => 'assoc'], + 'romberg' => ['method' => 'romberg', 'call' => 'id_only', 'result_type' => 'string'], + 'genitourinaria' => ['method' => 'genitourinaria', 'call' => 'default', 'result_type' => 'string'], + 'anggota_gerak' => ['method' => 'anggota_gerak', 'call' => 'default', 'result_type' => 'string'], + // --- Sistem Persyarafan (object: Refleks_Fisiologis, Refleks_Pathologis, Refleks_Neurologis_Lainnya) --- + 'sistem_persyarafan' => ['method' => 'sistem_persyarafan', 'call' => 'default', 'result_type' => 'assoc'], + 'smell_test' => ['method' => 'smell_test', 'call' => 'default', 'result_type' => 'string'], + 'rectum_urogenital' => ['method' => 'rectum_urogenital', 'call' => 'default', 'result_type' => 'string'], + // --- Faktor Risiko --- + 'faktor_fisik' => ['method' => 'faktor_fisik', 'call' => 'default', 'result_type' => 'string'], + 'faktor_kimia' => ['method' => 'faktor_kimia', 'call' => 'default', 'result_type' => 'string'], + 'faktor_biologi' => ['method' => 'faktor_biologi', 'call' => 'default', 'result_type' => 'string'], + 'faktor_ergonomi' => ['method' => 'faktor_ergonomi', 'call' => 'default', 'result_type' => 'string'], + 'faktor_psikologi' => ['method' => 'faktor_psikologi', 'call' => 'default', 'result_type' => 'string'], + ]; + + $rows_to_insert = []; + $now = date('Y-m-d H:i:s'); + + $order_header_row = $this->db_smartone->select('T_OrderHeaderDate') + ->where('T_OrderHeaderID', $orderHeaderId) + ->get('t_orderheader') + ->row(); + $order_header_date = $order_header_row ? $order_header_row->T_OrderHeaderDate : null; + + foreach ($field_map as $label_key => $config) { + $method = $config['method']; + + if (!method_exists($this, $method)) { + continue; + } + + try { + switch ($config['call']) { + case 'id_only': + $result = $this->{$method}($orderHeaderId); + break; + case 'visus': + $result = $this->visus($orderHeaderId, $config['side'], $langid); + break; + case 'default3': + $result = $this->{$method}($orderHeaderId, $langid, 'fisik'); + break; + case 'tekanan_darah': + $result = $this->tekanan_darah($orderHeaderId, '', $langid); + break; + default: + $result = $this->{$method}($orderHeaderId, $langid); + break; + } + } catch (Throwable $e) { + continue; + } + + // Simpan berdasarkan result_type yang sudah ditentukan eksplisit di field_map + $result_type = $config['result_type']; + + // Jika fungsi mengembalikan error / string saat diharapkan object, fallback ke string + if (!is_array($result)) { + $result_type = 'string'; + } + + switch ($result_type) { + + case 'label_value': + // Array of [{label => '...', value => '...'}, ...] → misal: keadaan_umum + foreach ($result as $item) { + if (!isset($item['label'])) continue; + $rows_to_insert[] = [ + 'ResultFisikUmumLabel' => $item['label'], + 'ResultFisikUmumT_OrderHeaderID' => $orderHeaderId, + 'ResultFisikUmumT_OrderHeaderDate' => $order_header_date, + 'ResultFisikUmumValue' => (string)($item['value'] ?? ''), + 'ResultFisikUmumIsActive' => 'Y', + 'ResultFisikUmumCreated' => $now, + ]; + } + break; + + case 'assoc': + // Associative array → tiap key jadi 1 row + // misal: status_gizi, pengukuran, reflek, sistem_persyarafan, riwayat_penyakit_keluarga + foreach ($result as $key => $val) { + $save_val = is_array($val) ? json_encode($val, JSON_UNESCAPED_UNICODE) : (string)$val; + $rows_to_insert[] = [ + 'ResultFisikUmumLabel' => (string)$key, + 'ResultFisikUmumT_OrderHeaderID' => $orderHeaderId, + 'ResultFisikUmumT_OrderHeaderDate' => $order_header_date, + 'ResultFisikUmumValue' => $save_val, + 'ResultFisikUmumIsActive' => 'Y', + 'ResultFisikUmumCreated' => $now, + ]; + } + break; + + default: // string + $save_val = is_array($result) ? json_encode($result, JSON_UNESCAPED_UNICODE) : (string)$result; + $rows_to_insert[] = [ + 'ResultFisikUmumLabel' => $label_key, + 'ResultFisikUmumT_OrderHeaderID' => $orderHeaderId, + 'ResultFisikUmumT_OrderHeaderDate' => $order_header_date, + 'ResultFisikUmumValue' => $save_val, + 'ResultFisikUmumIsActive' => 'Y', + 'ResultFisikUmumCreated' => $now, + ]; + break; + } + } + + // Non-aktifkan data lama yang masih aktif untuk orderHeaderId ini + $this->db_smartone->where('ResultFisikUmumT_OrderHeaderID', $orderHeaderId); + $this->db_smartone->where('ResultFisikUmumIsActive', 'Y'); + $this->db_smartone->update('result_fisik_umum', ['ResultFisikUmumIsActive' => 'N']); + + if (!empty($rows_to_insert)) { + $this->db_smartone->insert_batch('result_fisik_umum', $rows_to_insert); + } + + return [ + 'success' => true, + 'orderHeaderId' => $orderHeaderId, + 'rows_saved' => count($rows_to_insert), + ]; + } + + function update_unvalidated($t_order_header_id){ + $errors = [ + 'success' => false, + 'orderHeaderId' => $t_order_header_id, + 'message' => 'Error update unvalidated fisik umum genresultfisik', + ]; + try { + $this->db_smartone->where('ResultFisikUmumT_OrderHeaderID', $t_order_header_id); + $this->db_smartone->where('ResultFisikUmumIsActive', 'Y'); + $this->db_smartone->update('result_fisik_umum', ['ResultFisikUmumIsActive' => 'N']); + $this->db_smartone->update('result_fisik_umum', ['ResultFisikUmumLastUpdated' => date('Y-m-d H:i:s')]); + + //echo $this->db_smartone->last_query(); + $errors['success'] = true; + $errors['message'] = 'Data unvalidated fisik umum genresultfisik updated successfully'; + return $errors; + } catch (Throwable $e) { + $errors['message'] = $e->getMessage(); + return $errors; + } + } + +} +?> diff --git a/application/libraries/ImageManipulator.php b/application/libraries/ImageManipulator.php new file mode 100755 index 00000000..3381c91b --- /dev/null +++ b/application/libraries/ImageManipulator.php @@ -0,0 +1,279 @@ +setImageFile($file); + } else { + $this->setImageString($file); + } + } + } + + /** + * Set image resource from file + * + * @param string $file Path to image file + * @return ImageManipulator for a fluent interface + * @throws InvalidArgumentException + */ + public function setImageFile($file) + { + if (!(is_readable($file) && is_file($file))) { + throw new InvalidArgumentException("Image file $file is not readable"); + } + + if (is_resource($this->image)) { + imagedestroy($this->image); + } + + list ($this->width, $this->height, $type) = getimagesize($file); + + switch ($type) { + case IMAGETYPE_GIF : + $this->image = imagecreatefromgif($file); + break; + case IMAGETYPE_JPEG : + $this->image = imagecreatefromjpeg($file); + break; + case IMAGETYPE_PNG : + $this->image = imagecreatefrompng($file); + break; + default : + throw new InvalidArgumentException("Image type $type not supported"); + } + + return $this; + } + + /** + * Set image resource from string data + * + * @param string $data + * @return ImageManipulator for a fluent interface + * @throws RuntimeException + */ + public function setImageString($data) + { + if (is_resource($this->image)) { + imagedestroy($this->image); + } + + if (!$this->image = imagecreatefromstring($data)) { + throw new RuntimeException('Cannot create image from data string'); + } + $this->width = imagesx($this->image); + $this->height = imagesy($this->image); + return $this; + } + + /** + * Resamples the current image + * + * @param int $width New width + * @param int $height New height + * @param bool $constrainProportions Constrain current image proportions when resizing + * @return ImageManipulator for a fluent interface + * @throws RuntimeException + */ + public function resample($width, $height, $constrainProportions = true) + { + if (!is_resource($this->image)) { + throw new RuntimeException('No image set'); + } + if ($constrainProportions) { + if ($this->height >= $this->width) { + $width = round($height / $this->height * $this->width); + } else { + $height = round($width / $this->width * $this->height); + } + } + $temp = imagecreatetruecolor($width, $height); + imagecopyresampled($temp, $this->image, 0, 0, 0, 0, $width, $height, $this->width, $this->height); + return $this->_replace($temp); + } + + /** + * Enlarge canvas + * + * @param int $width Canvas width + * @param int $height Canvas height + * @param array $rgb RGB colour values + * @param int $xpos X-Position of image in new canvas, null for centre + * @param int $ypos Y-Position of image in new canvas, null for centre + * @return ImageManipulator for a fluent interface + * @throws RuntimeException + */ + public function enlargeCanvas($width, $height, array $rgb = array(), $xpos = null, $ypos = null) + { + if (!is_resource($this->image)) { + throw new RuntimeException('No image set'); + } + + $width = max($width, $this->width); + $height = max($height, $this->height); + + $temp = imagecreatetruecolor($width, $height); + if (count($rgb) == 3) { + $bg = imagecolorallocate($temp, $rgb[0], $rgb[1], $rgb[2]); + imagefill($temp, 0, 0, $bg); + } + + if (null === $xpos) { + $xpos = round(($width - $this->width) / 2); + } + if (null === $ypos) { + $ypos = round(($height - $this->height) / 2); + } + + imagecopy($temp, $this->image, (int) $xpos, (int) $ypos, 0, 0, $this->width, $this->height); + return $this->_replace($temp); + } + + /** + * Crop image + * + * @param int|array $x1 Top left x-coordinate of crop box or array of coordinates + * @param int $y1 Top left y-coordinate of crop box + * @param int $x2 Bottom right x-coordinate of crop box + * @param int $y2 Bottom right y-coordinate of crop box + * @return ImageManipulator for a fluent interface + * @throws RuntimeException + */ + public function crop($x1, $y1 = 0, $x2 = 0, $y2 = 0) + { + if (!is_resource($this->image)) { + throw new RuntimeException('No image set'); + } + if (is_array($x1) && 4 == count($x1)) { + list($x1, $y1, $x2, $y2) = $x1; + } + + $x1 = max($x1, 0); + $y1 = max($y1, 0); + + $x2 = min($x2, $this->width); + $y2 = min($y2, $this->height); + + $width = $x2 - $x1; + $height = $y2 - $y1; + + $temp = imagecreatetruecolor($width, $height); + imagecopy($temp, $this->image, 0, 0, $x1, $y1, $width, $height); + + return $this->_replace($temp); + } + + /** + * Replace current image resource with a new one + * + * @param resource $res New image resource + * @return ImageManipulator for a fluent interface + * @throws UnexpectedValueException + */ + protected function _replace($res) + { + if (!is_resource($res)) { + throw new UnexpectedValueException('Invalid resource'); + } + if (is_resource($this->image)) { + imagedestroy($this->image); + } + $this->image = $res; + $this->width = imagesx($res); + $this->height = imagesy($res); + return $this; + } + + /** + * Save current image to file + * + * @param string $fileName + * @return void + * @throws RuntimeException + */ + public function save($fileName, $type = IMAGETYPE_JPEG) + { + $dir = dirname($fileName); + if (!is_dir($dir)) { + if (!mkdir($dir, 0755, true)) { + throw new RuntimeException('Error creating directory ' . $dir); + } + } + + try { + switch ($type) { + case IMAGETYPE_GIF : + if (!imagegif($this->image, $fileName)) { + throw new RuntimeException; + } + break; + case IMAGETYPE_PNG : + if (!imagepng($this->image, $fileName)) { + throw new RuntimeException; + } + break; + case IMAGETYPE_JPEG : + default : + if (!imagejpeg($this->image, $fileName, 95)) { + throw new RuntimeException; + } + } + } catch (Exception $ex) { + throw new RuntimeException('Error saving image file to ' . $fileName); + } + } + + /** + * Returns the GD image resource + * + * @return resource + */ + public function getResource() + { + return $this->image; + } + + /** + * Get current image resource width + * + * @return int + */ + public function getWidth() + { + return $this->width; + } + + /** + * Get current image height + * + * @return int + */ + public function getHeight() + { + return $this->height; + } +} \ No newline at end of file diff --git a/application/libraries/Jwt.php b/application/libraries/Jwt.php new file mode 100755 index 00000000..d8712a48 --- /dev/null +++ b/application/libraries/Jwt.php @@ -0,0 +1,196 @@ + + * @author Anant Narayanan + * @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) { + throw new UnexpectedValueException('Wrong number of segments'); + } + list($headb64, $bodyb64, $cryptob64) = $tks; + if (null === ($header = JWT::jsonDecode(JWT::urlsafeB64Decode($headb64)))) { + throw new UnexpectedValueException('Invalid segment encoding'); + } + if (null === $payload = JWT::jsonDecode(JWT::urlsafeB64Decode($bodyb64))) { + throw new UnexpectedValueException('Invalid segment encoding'); + } + $sig = JWT::urlsafeB64Decode($cryptob64); + if ($verify) { + if (empty($header->alg)) { + 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 + ); + } + +} \ No newline at end of file diff --git a/application/libraries/Kapus.php b/application/libraries/Kapus.php new file mode 100644 index 00000000..d9b3a592 --- /dev/null +++ b/application/libraries/Kapus.php @@ -0,0 +1,162 @@ +db = $CI->load->database("onedev",true); + //cek if current date is posted + $this->db->trans_start(); + $sql = "select * from sys_f_kapus_sum where sysFKapusSumDate = ? + and sysFKapusIsActive = 'Y' "; + $qry = $this->db->query($sql , array($date)); + $sysFKapusSumID = 0; + if ($qry ) { + $rows = $qry->result_array(); + if ( count($rows) > 0 ) { + $sysFKapusSumID = $rows[0]["sysFKapusSumID"]; + if ($rows[0]["sysFKapusSumIsPosted"] == "Y" ) { + return array("status" => "ERR" , "message" => "Kapus at $date already posted"); + } + } + + } + + + + $sql = "select * from sys_kapus limit 0,1"; + $qry = $this->db->query($sql); + if (! $qry ) { + $this->db->trans_rollback(); + return array("status" => "ERR" , "message" => "Invalid Kapus Setting" . print_r($this->db->error(),true)); + } + $rows = $qry->result_array(); + if (count($rows) == 0 ) { + $this->db->trans_rollback(); + return array("status" => "ERR" , "message" => "Invalid Kapus Setting"); + } + $companyID = $rows[0]["sysKaPusM_CompanyID"] . "," . $rows[0]["sysKaPusM_CompanyID2"]; + $paymentTypeID = $rows[0]["sysKaPusM_PaymentTypeID"]; + $targetPct = $rows[0]["sysKaPusPct"]; + // get kapus + $sql = "select sum(F_PaymentDetailAmount) TotalAmount, + sum(F_PaymentDetailAmount - F_PaymentDetailAmount mod 500 ) TotalAmountAfterRounding + from t_orderheader + join f_payment on T_OrderHeaderID = F_PaymentT_OrderHeaderID + and F_PaymentIsActive = 'Y' and T_OrderHeaderIsActive = 'Y' + and date(T_OrderHeaderDate) = date(?) + and F_PaymentDate = date(?) + join f_paymentdetail on F_PaymentID = F_PaymentDetailF_PaymentID + and F_PaymentDetailM_PaymentTypeID = ? + and F_PaymentDetailIsActive = 'Y' "; + $qry = $this->db->query($sql, array($date,$date, $paymentTypeID)); + if (! $qry ) { + $this->db->trans_rollback(); + return array("status" => "ERR" , "message" => "Error get total payment " . print_r($this->db->error(),true)); + } + $rows = $qry->result_array(); + if (count($rows) == 0 ) { + $this->db->trans_rollback(); + return array("status" => "OK" , "message" => "No Payment Type , $paymentTypeID , $date "); + } + // seluruh kas + $totalAmount = $rows[0]["TotalAmount"]; + $totalAmountAfterRounding = $rows[0]["TotalAmountAfterRounding"]; + if ($totalAmount == 0 ) { + $this->db->trans_rollback(); + return array("status" => "OK" , "message" => "Total Amount Zero "); + } + + $sql = "drop table if exists xtmp_kapus"; + $qry = $this->db->query($sql); + if (! $qry ) { + $this->db->trans_rollback(); + return array("status" => "ERR" , "message" => "Drop Tmp table " . print_r($this->db->error(),true)); + } + $sql = " + create temporary table xtmp_kapus + select F_PaymentT_OrderHeaderID, + cast(sum(F_PaymentDetailAmount) as decimal(15,0)) Total + from f_payment + join t_orderheader on F_PaymentT_OrderHeaderID = T_OrderHeaderID and T_OrderHeaderM_CompanyID in ($companyID) + join f_paymentdetail on F_PaymentDetailF_PaymentID = F_PaymentID and F_PaymentDetailIsActive = 'Y' + and F_PaymentIsActive = 'Y' + where F_PaymentDate = ? and F_PaymentDetailM_PaymentTypeID = ? + group by F_PaymentT_OrderHeaderID"; + $qry = $this->db->query($sql, array($date,$paymentTypeID)); + if (! $qry ) { + $this->db->trans_rollback(); + return array("status" => "ERR" , "message" => "Create Tmp table " . print_r($this->db->error(),true)); + } + + $sql = " + select T_OrderHeaderID, + cast(T_OrderHeaderTotal as decimal(15,0) ) as T_OrderHeaderTotal , + cast(T_OrderHeaderTotal - T_OrderHeaderTotal mod 500 as decimal(15,0) ) as T_OrderHeaderTotalAfterRounding + from t_orderheader + join xtmp_kapus on T_OrderHeaderID = F_PaymentT_OrderHeaderID + and Total = T_OrderHeaderTotal + and date(T_OrderHeaderDate) = ? + order by T_OrderHeaderID"; + $qry = $this->db->query($sql, array($date)); + if (! $qry ) { + $this->db->trans_rollback(); + return array("status" => "ERR" , "message" => "Error get detail payment " . print_r($this->db->error(),true)); + } + $rows = $qry->result_array(); + + if ($sysFKapusSumID == 0) { + $sql = "insert into sys_f_kapus_sum(sysFKapusSumDate, sysFKapusSumUserID,sysFKapusSumTargetPct, + sysFKapusSumTotal, sysFKapusSumTotalAfterRounding) values(?,?,?,?,?)"; + $qry = $this->db->query($sql,array($date, $userID, $targetPct, $totalAmount, $totalAmountAfterRounding)); + if (! $qry ) { + $this->db->trans_rollback(); + return array("status" => "ERR" , "message" => "Error create sysFKapusSum " . print_r($this->db->error(),true)); + } + $sysFKapusSumID = $this->db->insert_id(); + } + $qry = $this->db->query("update sys_f_kapus set sysFKapusIsActive='N' where sysFKapusSysFKapusSumID=?", array($sysFKapusSumID)); + if (! $qry ) { + $this->db->trans_rollback(); + return array("status" => "ERR" , "message" => "Error reset sysFKapus " . print_r($this->db->error(),true)); + } + + $sql_i = "insert into sys_f_kapus( sysFKapusT_OrderHeaderID, sysFKapusAmount, sysFKapusRunAmount, + sysFKapusAmountAfterRounding, + sysFKapusM_UserID, sysFKapusDate, sysFKapusPct, sysFKapusSysFKapusSumID ) + values(?,?,?, ?, ?,?,?,?)"; + $curPct = 0; + $sum_total = 0; + $sum_total_after_rounding = 0; + foreach($rows as $r) { + $x_id = $r["T_OrderHeaderID"]; + $x_total = $r["T_OrderHeaderTotal"]; + $x_total_after_rounding = $r["T_OrderHeaderTotalAfterRounding"]; + $sum_total += $x_total; + $sum_total_after_rounding += $x_total_after_rounding; + $curPct = $sum_total / $totalAmount * 100 ; + $qry = $this->db->query($sql_i, array($x_id, $x_total, $sum_total, + $x_total_after_rounding, + $userID,$date, $curPct,$sysFKapusSumID ) ); + if (! $qry ) { + $this->db->trans_rollback(); + return array("status" => "ERR" , "message" => "Error insert sys_f_kapus " . print_r($this->db->error(),true)); + } + if ($curPct >= $targetPct ) { + break; + } + } + $sql = "update sys_f_kapus_sum set sysFKapusSumAmount = ? , sysFKapusSumActualPct = ? , + sysFKapusSumTargetPct = ?, sysFKapusSumAmountAfterRounding = ? + where sysFKapusSumID = ?"; + $qry = $this->db->query($sql, array($sum_total, $curPct, $targetPct, $sum_total_after_rounding, $sysFKapusSumID)); + if (! $qry ) { + $this->db->trans_rollback(); + return array("status" => "ERR" , "message" => "Error update sysFKapusSum " . print_r($this->db->error(),true)); + } + $this->db->trans_commit(); + return array("status" => "OK" , "message" => ""); + } + +} diff --git a/application/libraries/KelainanLab.php b/application/libraries/KelainanLab.php new file mode 100644 index 00000000..acaa6400 --- /dev/null +++ b/application/libraries/KelainanLab.php @@ -0,0 +1,282 @@ +db_onedev = $CI->load->database("default", true); + $this->db_smartone = $CI->load->database("default", true); + } + + function clean_mysqli_connection($dbc) + { + while (mysqli_more_results($dbc)) { + if (mysqli_next_result($dbc)) { + $result = mysqli_use_result($dbc); + + if (get_class($result) == 'mysqli_stmt') { + mysqli_stmt_free_result($result); + } else { + unset($result); + } + } + } + } + + function dynamic_comparison($varleft, $op, $varright) + { + + switch ($op) { + case "=": + return $varleft == $varright; + case "!=": + return $varleft != $varright; + case ">=": + return $varleft >= $varright; + case "<=": + return $varleft <= $varright; + case ">": + return $varleft > $varright; + case "<": + return $varleft < $varright; + default: + return true; + } + } + + function generate_kelainan_lab($orderid=0, $orderdetailID=0) + { + $errors = []; + if ($orderid != 0) { + $filterOrderID = " AND T_OrderHeaderID = {$orderid}"; + } else { + $filterOrderID = ""; + } + if ($orderdetailID != 0) { + $filterDetailID = " AND T_OrderDetailID = {$orderdetailID}"; + } else { + $filterDetailID = ""; + } + $sql = "SELECT + T_OrderHeaderID,T_OrderHeaderLabNumber, + T_TestName, T_OrderDetailID, T_OrderDetailResult, T_OrderDetailNat_MethodeID, + T_OrderDetailNat_MethodeID, T_OrderDetailNat_MethodeName, + T_OrderDetailMinValue, T_OrderDetailMaxValue, T_OrderDetailMinValueInclusive, + T_OrderDetailMaxValueInclusive, + Mcu_SummaryLabID, + Mcu_SummaryLabValue, + Mcu_SummaryLabNat_MethodeID, + Mcu_SummaryLabWithMethode, + Mcu_SummaryLabType, + Mcu_SummaryLabIsNormalValue, + Mcu_SummaryLabIsRange, + Mcu_SummaryLabMinInclusive, + Mcu_SummaryLabMinValue, + Mcu_SummaryLabMaxInclusive, + Mcu_SummaryLabMaxValue, + Mcu_KelainanID, Mcu_KelainanName, Mcu_KelainanClasification, + Nat_TestID, + Nat_TestCode, + mcu_kelainangroup.* + from t_orderdetail + join t_orderheader on T_OrderHeaderID = T_OrderDetailT_OrderHeaderID {$filterOrderID} {$filterDetailID} + and T_OrderHeaderID = T_OrderDetailT_OrderHeaderID + and T_OrderDetailIsActive = 'Y' + JOIN m_patient + ON T_OrderHeaderM_PatientID = M_PatientID + JOIN m_sex ON M_PatientM_SexID = M_SexID + join t_test + on T_OrderDetailT_TestID = T_TestID + join nat_test ON T_TestNat_TestID = Nat_TestID + join mcu_summarylab on T_TestNat_TestID = Mcu_SummaryLabNat_TestID AND Mcu_SummaryLabIsActive = 'Y' + AND (Mcu_SummaryLabGender = 'A' OR (Mcu_SummaryLabGender <> 'A' AND Mcu_SummaryLabGender = CASE + WHEN LOWER(M_SexNameLang) = 'male' THEN 'M' + WHEN LOWER(M_SexNameLang) = 'female' THEN 'F' + else '' + END)) + join mcu_kelainan on Mcu_SummaryLabMcu_KelainanID = Mcu_KelainanID + join mcu_kelainangroup on Mcu_KelainanMcu_KelainanGroupID = Mcu_KelainanGroupID"; + //echo $sql; + $qry = $this->db_onedev->query($sql); + if (!$qry) { + + $prm_log = ['SELECT_T_ORDERDETAIL_KELAINAN_LAB_1', 'kelainanlab/generate_kelainan_lab']; + $xsql = $this->db_onedev->last_query(); + $log_error = $this->insert_log_error($xsql, $prm_log,json_encode($errors)); + $errors[] = "SELECT_T_ORDERDETAIL_KELAINAN_LAB_1"; + } + + $rows = $qry->result_array(); + $results = []; + + + + foreach ($rows as $r) { + $result_value = $r['T_OrderDetailResult']; + + $value_comparison = 0; + //echo $r['Mcu_SummaryLabIsNormalValue']; + $kelainan = []; + $notavailable = []; + if (trim($result_value) == 'NA') { + $notavailable = $r; + } elseif ($r['Mcu_SummaryLabIsNormalValue'] == 'Y') { + if ($r['Mcu_SummaryLabType'] == '<' || $r['Mcu_SummaryLabType'] == '<=') { + $value_comparison = $r['T_OrderDetailMinValue']; + } + if ($r['Mcu_SummaryLabType'] == '>' || $r['Mcu_SummaryLabType'] == '>=') { + $value_comparison = $r['T_OrderDetailMaxValue']; + } + //echo "Y"; + if ($r['Mcu_SummaryLabWithMethode'] == 'N' && $this->dynamic_comparison($result_value, $r['Mcu_SummaryLabType'], $value_comparison)) { + //echo $r['T_TestName']." : ".$r['Mcu_KelainanName'].", "; + $kelainan = $r; + $results[] = array('test' => $r['T_TestName'], 'nat_test' => $r['Nat_TestCode'], 'kelainan' => $r['Mcu_KelainanName'], 'orderdetailID' => $r['T_OrderDetailID'], 'orderheaderID' => $r['T_OrderHeaderID'], 'nat_testID' => $r['Nat_TestID'], 'mcu_summarylabID' => $r['Mcu_SummaryLabID']); + } + } else if ($r['Mcu_SummaryLabIsRange'] == 'Y') { + // Mcu_SummaryLabIsNormalValue, + // Mcu_SummaryLabIsRange, + // Mcu_SummaryLabMinInclusive, + // Mcu_SummaryLabMinValue, + // Mcu_SummaryLabMaxInclusive, + // Mcu_SummaryLabMaxValue, + $isWithinMin = $r['Mcu_SummaryLabMinInclusive'] === 'Y' ? floatval($result_value) >= floatval($r['Mcu_SummaryLabMinValue']) : floatval($result_value) > floatval($r['Mcu_SummaryLabMinValue']); + $isWithinMax = $r['Mcu_SummaryLabMaxInclusive'] === 'Y' ? floatval($result_value) <= floatval($r['Mcu_SummaryLabMaxValue']) : floatval($result_value) < floatval($r['Mcu_SummaryLabMaxValue']); + + if ($isWithinMax && $isWithinMin) { + $kelainan = $r; + $results[] = array('test' => $r['T_TestName'], 'nat_test' => $r['Nat_TestCode'], 'kelainan' => $r['Mcu_KelainanName'], 'orderdetailID' => $r['T_OrderDetailID'], 'orderheaderID' => $r['T_OrderHeaderID'], 'nat_testID' => $r['Nat_TestID'], 'mcu_summarylabID' => $r['Mcu_SummaryLabID']); + } + } else { + $value_comparison = $r['Mcu_SummaryLabValue']; + if ($r['Mcu_SummaryLabType'] == '!=' || $r['Mcu_SummaryLabType'] == '==') { + if ($this->dynamic_comparison($result_value, $r['Mcu_SummaryLabType'], $value_comparison)) { + //echo $r['T_TestName']." : ".$r['Mcu_KelainanName'].", "; + $kelainan = $r; + $results[] = array('test' => $r['T_TestName'], 'nat_test' => $r['Nat_TestCode'], 'kelainan' => $r['Mcu_KelainanName'], 'orderdetailID' => $r['T_OrderDetailID'], 'orderheaderID' => $r['T_OrderHeaderID'], 'nat_testID' => $r['Nat_TestID'], 'mcu_summarylabID' => $r['Mcu_SummaryLabID']); + } + } else { + if (is_numeric($result_value) && $this->dynamic_comparison($result_value, $r['Mcu_SummaryLabType'], $value_comparison)) { + //echo $r['T_TestName']." : ".$r['Mcu_KelainanName'].", "; + $kelainan = $r; + $results[] = array('test' => $r['T_TestName'], 'nat_test' => $r['Nat_TestCode'], 'kelainan' => $r['Mcu_KelainanName'], 'orderdetailID' => $r['T_OrderDetailID'], 'orderheaderID' => $r['T_OrderHeaderID'], 'nat_testID' => $r['Nat_TestID'], 'mcu_summarylabID' => $r['Mcu_SummaryLabID']); + } + } + } + + if (count($results) > 0) { + $sql_update_kel = ""; + if ($orderdetailID != 0) { + $sql_update_kel = "UPDATE t_kelainan_lab + SET T_KelainanLabIsActive = 'N' + WHERE + T_KelainanLabT_OrderDetailID = {$orderdetailID}"; + } else { + $sql_update_kel = "UPDATE t_kelainan_lab + SET T_KelainanLabIsActive = 'N' + WHERE + T_KelainanLabT_OrderHeaderID = {$orderid}"; + + } + $qry_update_kel = $this->db_onedev->query($sql_update_kel); + if (!$qry_update_kel) { + $prm_log = ['UPDATE_T_KELAINAN_LAB_N', 'kelainanlab/generate_kelainan_lab']; + $xsql = $this->db_onedev->last_query(); + $log_error = $this->insert_log_error($xsql, $prm_log,json_encode(['orderid' => $orderid, 'orderdetailID' => $orderdetailID])); + $errors[] = "UPDATE_T_KELAINAN_LAB_N"; + } + + foreach ($results as $v_result) { + $sql_kel_lab = "SELECT * + FROM t_kelainan_lab + WHERE T_KelainanLabT_OrderDetailID = ? + GROUP BY T_KelainanLabT_OrderDetailID"; + $qry_kel_lab = $this->db_onedev->query($sql_kel_lab, array($v_result['orderdetailID'])); + if ($qry_kel_lab) { + $rows_kel = $qry_kel_lab->result_array(); + } else { + $prm_log = ['SELECT_T_KELAINAN_LAB', 'kelainanlab/generate_kelainan_lab']; + $xsql = $this->db_onedev->last_query(); + $log_error = $this->insert_log_error($xsql, $prm_log,json_encode($v_result)); + $errors[] = "SELECT_T_KELAINAN_LAB"; + } + + if (count($rows_kel) > 0) { + + // print_r($v_result['orderdetailID']); + // exit; + + $sql_update_kel = "UPDATE t_kelainan_lab + SET T_KelainanLabT_OrderDetailID = {$v_result['orderdetailID']}, + T_KelainanLabT_OrderHeaderID = {$v_result['orderheaderID']}, + T_KelainanLabNat_TestID = {$v_result['nat_testID']}, + T_KelainanLabMcu_SummaryLabID = {$v_result['mcu_summarylabID']}, + T_KelainanLabCreatedUserID = 1, + T_KelainanLabIsActive = 'Y', + T_KelainanLabCreated = NOW() + WHERE T_KelainanLabID = {$rows_kel[0]['T_KelainanLabID']}"; + $qry_update_kel = $this->db_onedev->query($sql_update_kel); + if (!$qry_update_kel) { + $prm_log = ['UPDATE_T_KELAINAN_LAB', 'kelainanlab/generate_kelainan_lab']; + $xsql = $this->db_onedev->last_query(); + $log_error = $this->insert_log_error($xsql, $prm_log,json_encode($v_result)); + $errors[] = "UPDATE_T_KELAINAN_LAB"; + } + } else { + // print_r('insert'); + // exit; + $sql_insert_lab = "INSERT INTO t_kelainan_lab( + T_KelainanLabT_OrderDetailID, + T_KelainanLabT_OrderHeaderID, + T_KelainanLabNat_TestID, + T_KelainanLabMcu_SummaryLabID, + T_KelainanLabCreatedUserID, + T_KelainanLabCreated) + VALUES( + '{$v_result['orderdetailID']}', + '{$v_result['orderheaderID']}', + '{$v_result['nat_testID']}', + '{$v_result['mcu_summarylabID']}', + 1, + NOW())"; + $qry_insert_lab = $this->db_onedev->query($sql_insert_lab); + + if (!$qry_insert_lab) { + $prm_log = ['INSERT_T_KELAINAN_LAB', 'kelainanlab/generate_kelainan_lab']; + $xsql = $this->db_onedev->last_query(); + $log_error = $this->insert_log_error($xsql, $prm_log,json_encode($v_result)); + $errors[] = "INSERT_T_KELAINAN_LAB"; + } + } + } + } + } + + return $errors; + } + + function insert_log_error($log_sql, $params,$data='') + { + // Membersihkan SQL dari \r\n dan whitespace berlebih + //$clean_log_sql = trim(str_replace(["\r\n", "\r", "\n"], ' ', $log_sql)); + + $sql = "INSERT INTO error_log( + ErrorLogCode, + ErrorLogName, + ErrorLogDescription, + ErrorLogData, + ErrorLogOrderCreated + ) + VALUES( + ?,?,?,?,NOW() + )"; + + $query = $this->db_log->query($sql, [$params[0],$params[1],$log_sql,json_encode($data)]); + //echo $this->db_log->last_query(); + if (!$query) { + return false; + } + return true; + } +} diff --git a/application/libraries/Kesimpulanfisik.php b/application/libraries/Kesimpulanfisik.php new file mode 100644 index 00000000..77f387d7 --- /dev/null +++ b/application/libraries/Kesimpulanfisik.php @@ -0,0 +1,1945 @@ +db_onedev = $CI->load->database("default", true); + $this->db_smartone = $CI->load->database("default", true); + } + + function clean_mysqli_connection($dbc) + { + while (mysqli_more_results($dbc)) { + if (mysqli_next_result($dbc)) { + $result = mysqli_use_result($dbc); + + if (get_class($result) == 'mysqli_stmt') { + mysqli_stmt_free_result($result); + } else { + unset($result); + } + } + } + } + + function get_kelainans($id_code){ + $rst = []; + $sql = "SELECT Mcu_SummaryFisikID, Mcu_SummaryFisikType, Mcu_KelainanID, Mcu_KelainanName + FROM mcu_summaryfisik + JOIN mcu_kelainan ON Mcu_SummaryFisikMcu_KelainanID = Mcu_KelainanID + WHERE + ? IN (Mcu_SummaryFisikIDCodes) AND Mcu_SummaryFisikIsActive = 'Y'"; + $qry = $this->db_smartone->query($sql, array($id_code)); + if($id_code == 'tanda_vital_5') + //echo $this->db_smartone->last_query(); + if(!$qry){ + echo "error get kelainan ".$id_code; + } + + $rst = $qry->result_array(); + + return $rst; + } + + function status_gizi($id) { + $sql = "SELECT * + FROM so_resultentry + LEFT JOIN t_samplingso_additional_fisik_bbtb ON So_ResultEntryT_OrderHeaderID = T_SamplingAdditionalFisikBBTBT_OrderHeaderID + WHERE + So_ResultEntryID = ? LIMIT 1"; + $qry = $this->db_smartone->query($sql,array($id)); + if (! $qry) { + return json_encode(array()); + } +//echo $this->db_smartone->last_query(); + $row_result = $qry->row_array(); + //print_r($row_result); + + $status_gizi = array(); + $bb = $row_result["T_SamplingAdditionalFisikBBTBValueBB"]; + $tb = $row_result["T_SamplingAdditionalFisikBBTBValueTB"]; + $standart_bmi = $row_result["T_SamplingAdditionalFisikBBTBStandart"]; + $get_bmi = $this->hitung_bmi($bb,$tb,$standart_bmi); + $bmi = $get_bmi['bmi']; + $classification = $get_bmi['class']; + + $standart_text = ucwords(str_replace("_"," ",$standart_bmi)); + + return array('bmi' => $bmi, 'xclassification' => $classification, 'standart' => $standart_text); + } + + function persepsi_warna($id) { + $sql = "SELECT IFNULL(T_SamplingAdditionalFisikBWPWValue,'') as result, IFNULL(T_SamplingAdditionalFisikBWPWVAngka,'') as angka + FROM so_resultentry + LEFT JOIN t_samplingso_additional_fisik_bw ON T_SamplingAdditionalFisikBWT_OrderHeaderID = So_ResultEntryT_OrderHeaderID + WHERE + So_ResultEntryID = ? LIMIT 1 "; + $qry = $this->db_smartone->query($sql,array($id)); + + if (! $qry) { + return json_encode(array()); + } + $row_result = $qry->row_array(); + //keluhan saat ini + return $row_result['result']; + } + + function visus($id) { + $sql = " SELECT * , IFNULL(T_SamplingAdditionalFisikVisusID,0) as visus_id + FROM so_resultentry + LEFT JOIN t_samplingso_additional_fisik_visus ON T_SamplingAdditionalFisikVisusT_OrderHeaderID = So_ResultEntryT_OrderHeaderID + WHERE + So_ResultEntryID = ? LIMIT 1"; + $qry = $this->db_smartone->query($sql,array($id)); + if (! $qry) { + return json_encode(array()); + } + + $row_result = $qry->row_array(); + + $visus = array(); + $visus_kiri = ""; + $visus_kanan = ""; + $visus_kesimpulan = ""; + $normal = array("20/20", "20/25"); + $rst['kelainan'] = "Normal"; + + + if(($row_result['T_SamplingAdditionalFisikVisusTKODV'] != "" && $row_result['T_SamplingAdditionalFisikVisusTKODV'] != "-") && ($row_result['T_SamplingAdditionalFisikVisusTKOSV'] != "" && $row_result['T_SamplingAdditionalFisikVisusTKOSV'] != "-")){ + $visus[] = array( + "xx1" => "Tanpa Kacamata", + "xx2" => "OD : ", + "xx3" => $row_result['T_SamplingAdditionalFisikVisusTKODV'] + ); + + $visus[] = array( + "xx1" => "Tanpa Kacamata", + "xx2" => "OS", + "xx3" => $row_result['T_SamplingAdditionalFisikVisusTKOSV'] + ); + + $rst['kelainan'] = "Kelainan refraksi (tanpa kacamata)"; + + if (!in_array($row_result['T_SamplingAdditionalFisikVisusTKODV'], $normal)){ + $value_koreksi_od = ""; + $od_sph = $row_result['T_SamplingAdditionalFisikVisusODSPH']; + if($od_sph != "" && $od_sph != "-" && $od_sph != "--" && $od_sph != "/-" && $od_sph != "/" && $od_sph != "-/" && strtolower(trim($od_sph)) != 'plano'){ + if ($visus_kesimpulan != "") $visus_kesimpulan .= ", "; + $visus_kesimpulan .= "Miopia OD"; + } + + $od_cyl = $row_result['T_SamplingAdditionalFisikVisusODCYL']; + if($od_cyl != "" && $od_cyl != "-" && $od_cyl != "--" && $od_cyl != "/-" && $od_cyl != "/" && $od_cyl != "-/"){ + if ($visus_kesimpulan != "") $visus_kesimpulan .= ", "; + $visus_kesimpulan .= "Astigmatismus OD"; + } + + + $od_x = $row_result['T_SamplingAdditionalFisikVisusODX']; + if($od_x != "" && $od_x != "-" && $od_x != "--" && $od_x != "/-" && $od_x != "/" && $od_x != "-/") + $value_koreksi_od .= "X (".$od_x.") "; + + $od_add = $row_result['T_SamplingAdditionalFisikVisusADD']; + if($od_add != "" && $od_add != "-" && $od_add != "--" && $od_add != "/-" && $od_add != "/" && $od_add != "-/"){ + if ($visus_kesimpulan != "") $visus_kesimpulan .= ", "; + $visus_kesimpulan .= "Presbiopia OD"; + } + + } + + if (!in_array($row_result['T_SamplingAdditionalFisikVisusTKOSV'], $normal)){ + $value_koreksi_os = ""; + $os_sph = $row_result['T_SamplingAdditionalFisikVisusOSSPH']; + if(strtolower(trim($os_sph)) != "tidak terkoreksi" && strtolower(trim($os_sph)) != "tidak dapat dinilai" && $os_sph != "" && $os_sph != "-" && $os_sph != "--" && $os_sph != "/-" && $os_sph != "/" && $os_sph != "-/" && strtolower(trim($os_sph)) != 'plano'){ + if ($visus_kesimpulan != "") $visus_kesimpulan .= ", "; + $visus_kesimpulan .= "Miopia OS"; + } + + + $os_cyl = $row_result['T_SamplingAdditionalFisikVisusOSCYL']; + if(strtolower(trim($os_cyl)) != "tidak terkoreksi" && strtolower(trim($os_cyl)) != "tidak dapat dinilai" && $os_cyl != "" && $os_cyl != "-" && $os_cyl != "--" && $os_cyl != "/-" && $os_cyl != "/" && $os_cyl != "-/"){ + if ($visus_kesimpulan != "") $visus_kesimpulan .= ", "; + $visus_kesimpulan .= "Astigmatismus OS"; + } + + + $os_x = $row_result['T_SamplingAdditionalFisikVisusOSX']; + if(strtolower(trim($os_x)) != "tidak terkoreksi" && strtolower(trim($os_x)) != "tidak dapat dinilai" && $os_x != "" && $os_x != "-" && $os_x != "--" && $os_x != "/-" && $os_x != "/" && $os_x != "-/") + $value_koreksi_os .= "X (".$os_x.") "; + + $od_add = $row_result['T_SamplingAdditionalFisikVisusADD']; + if($od_add != "" && $od_add != "-" && $od_add != "--" && $od_add != "/-" && $od_add != "/" && $od_add != "-/"){ + if ($visus_kesimpulan != "") $visus_kesimpulan .= ", "; + $visus_kesimpulan .= "Presbiopia OS"; + } + + + } + } + + if(($row_result['T_SamplingAdditionalFisikVisusDKODV'] != "" && $row_result['T_SamplingAdditionalFisikVisusDKODV'] != "-") && ($row_result['T_SamplingAdditionalFisikVisusDKOSV'] != "" && $row_result['T_SamplingAdditionalFisikVisusDKOSV'] != "-")){ + $visus[] = array( + "xx1" => "Dengan Kacamata", + "xx2" => "OD : ", + "xx3" => $row_result['T_SamplingAdditionalFisikVisusDKODV'] + ); + + $visus[] = array( + "xx1" => "Dengan Kacamata", + "xx2" => "OS", + "xx3" => $row_result['T_SamplingAdditionalFisikVisusDKOSV'] + ); + + $rst['kelainan'] = "Kelainan refraksi (dengan kacamata)"; + + + $value_koreksi_od = ""; + $od_sph = $row_result['T_SamplingAdditionalFisikVisusODSPH']; + if(strtolower(trim($od_sph)) != "tidak terkoreksi" && strtolower(trim($od_sph)) != "tidak dapat dinilai" && $od_sph != "" && $od_sph != "-" && $od_sph != "--" && $od_sph != "/-" && $od_sph != "/" && $od_sph != "-/" && strtolower(trim($od_sph)) != 'plano'){ + if ($visus_kesimpulan != "") $visus_kesimpulan .= ", "; + $visus_kesimpulan .= "Miopia OD"; + } + + + $od_cyl = $row_result['T_SamplingAdditionalFisikVisusODCYL']; + if(strtolower(trim($od_cyl)) != "tidak terkoreksi" && strtolower(trim($od_cyl)) != "tidak dapat dinilai" && $od_cyl != "" && $od_cyl != "-" && $od_cyl != "--" && $od_cyl != "/-" && $od_cyl != "/" && $od_cyl != "-/"){ + if ($visus_kesimpulan != "") $visus_kesimpulan .= ", "; + $visus_kesimpulan .= "Astigmatismus OD"; + } + + + $od_x = $row_result['T_SamplingAdditionalFisikVisusODX']; + if(strtolower(trim($od_x)) != "tidak terkoreksi" && strtolower(trim($od_x)) != "tidak dapat dinilai" && $od_x != "" && $od_x != "-" && $od_x != "--" && $od_x != "/-" && $od_x != "/" && $od_x != "-/") + $value_koreksi_od .= "X (".$od_x.") "; + + $od_add = $row_result['T_SamplingAdditionalFisikVisusADD']; + if($od_add != "" && $od_add != "-" && $od_add != "--" && $od_add != "/-" && $od_add != "/" && $od_add != "-/"){ + if ($visus_kesimpulan != "") $visus_kesimpulan .= ", "; + $visus_kesimpulan .= "Presbiopia OD"; + } + + + + + $value_koreksi_os = ""; + $os_sph = $row_result['T_SamplingAdditionalFisikVisusOSSPH']; + if(strtolower(trim($os_sph)) != "tidak terkoreksi" && strtolower(trim($os_sph)) != "tidak dapat dinilai" && $os_sph != "" && $os_sph != "-" && $os_sph != "--" && $os_sph != "/-" && $os_sph != "/" && $os_sph != "-/" && strtolower(trim($os_sph)) != 'plano'){ + if ($visus_kesimpulan != "") $visus_kesimpulan .= ", "; + $visus_kesimpulan .= "Miopia OS"; + } + + $os_cyl = $row_result['T_SamplingAdditionalFisikVisusOSCYL']; + if(strtolower(trim($os_cyl)) != "tidak terkoreksi" && strtolower(trim($os_cyl)) != "tidak dapat dinilai" && $os_cyl != "" && $os_cyl != "-" && $os_cyl != "--" && $os_cyl != "/-" && $os_cyl != "/" && $os_cyl != "-/"){ + if ($visus_kesimpulan != "") $visus_kesimpulan .= ", "; + $visus_kesimpulan .= "Astigmatismus OS"; + } + + $os_x = $row_result['T_SamplingAdditionalFisikVisusOSX']; + if(strtolower(trim($os_x)) != "tidak terkoreksi" && strtolower(trim($os_x)) != "tidak dapat dinilai" && $os_x != "" && $os_x != "-" && $os_x != "--" && $os_x != "/-" && $os_x != "/" && $os_x != "-/") + $value_koreksi_os .= "X (".$os_x.") "; + + $od_add = $row_result['T_SamplingAdditionalFisikVisusADD']; + if($od_add != "" && $od_add != "-" && $od_add != "--" && $od_add != "/-" && $od_add != "/" && $od_add != "-/"){ + if ($visus_kesimpulan != "") $visus_kesimpulan .= ", "; + $visus_kesimpulan .= "Presbiopia OS"; + } + + + } + + $rst['kesimpulan'] = $visus_kesimpulan; + $rst['kelainan'] = $rst['kelainan']; + return $rst; + } + + function kesimpulan($id) + { + $kesimpulan = ""; + $sql = "SELECT * + FROM fisik_template + JOIN so_resultentry_fisik_umum ON So_ResultEntryFisikUmumFisikTemplateID = FisikTemplateID AND So_ResultEntryFisikUmumSo_ResultEntryID = ? + WHERE + FisikTemplateIsActive = 'Y' AND + FisikTemplateType = 'Riwayat' + ORDER BY FisikTemplateCode ASC + "; + $qry = $this->db_smartone->query($sql, array($id)); + // echo $this->db_smartone->last_query(); + $xriwayats = $qry->result_array(); + $riwayat_data = []; + foreach ($xriwayats as $key => $value) { + $riwayat_data[] = json_decode($value['So_ResultEntryFisikUmumDetails'], true); + } + //print_r($riwayat_data); + foreach ($riwayat_data as $riwayat_da) { + //print_r($riwayat_da); + //echo $riwayat_da["title"]; + if ($riwayat_da["title"] == "KELUHAN SAAT INI") { + //print_r($riwayat_da["details"]); + foreach ($riwayat_da["details"] as $riwayat_db) { + if (($riwayat_db["chx"] == "1" || $riwayat_db["chx"] != false) && $riwayat_db["label"] == 'Gastritis (maag)') { + if ($kesimpulan != "") $kesimpulan .= ", "; + $kesimpulan .= $riwayat_db["label"] . " " . $riwayat_db["value"]; + } + } + } + } + + $kode_gigi = array( + "X" => "Berlubang", + "C" => "Tambalan", + "O" => "Tanggal", + "R" => "Sisa akar", + "A" => "Gigi Palsu", + "K" => "Karang Gigi" + ); + + $rst_statusgizi = $this->status_gizi($id); + //print_r($rst_statusgizi); + if($rst_statusgizi['xclassification'] != 'Normal'){ + if ($kesimpulan != "") $kesimpulan .= ", "; + $kesimpulan .= $rst_statusgizi['xclassification'] . " ( BMI : ".$rst_statusgizi['bmi']." )"; + } + + $rst_persepsi_warna = $this->persepsi_warna($id); + if($rst_persepsi_warna == 'BW'){ + if ($kesimpulan != "") $kesimpulan .= ", "; + $kesimpulan .= "Red Green Deficiency"; + } + + $rst_visus = $this->visus($id); + if($rst_visus['kesimpulan'] != ''){ + if ($kesimpulan != "") $kesimpulan .= ", "; + $kesimpulan .= $rst_visus['kesimpulan']; + } + + $sql = "SELECT * + FROM fisik_template + JOIN so_resultentry_fisik_umum ON So_ResultEntryFisikUmumFisikTemplateID = FisikTemplateID AND So_ResultEntryFisikUmumSo_ResultEntryID = ? + JOIN so_resultentry ON So_ResultEntryFisikUmumSo_ResultEntryID = So_ResultEntryID + JOIN t_orderheader ON So_ResultEntryT_OrderHeaderID = T_OrderHeaderID + JOIN m_patient ON T_OrderHeaderM_PatientID = M_PatientID + WHERE + FisikTemplateIsActive = 'Y' AND + FisikTemplateType = 'Fisik' + ORDER BY FisikTemplateCode ASC + "; + $qry = $this->db_smartone->query($sql, array($id)); + // echo $this->db_smartone->last_query(); + $xfisiks = $qry->result_array(); + $fisik_data = []; + foreach ($xfisiks as $kex => $valux) { + $fisik_data[] = json_decode($valux['So_ResultEntryFisikUmumDetails'], true); + } + + $sexcode = $xfisiks[0]["M_PatientGender"] == 'male' ? 'L' : 'P'; + + foreach ($fisik_data as $da) { + //echo $da["title"]; + if ($da["title"] == "TANDA VITAL") { + foreach ($da["details"] as $db) { + //print_r($db); + if ($db["chx_x"] == "1" && $db["id_code"] != 'tanda_vital_5' ) { + if ($kesimpulan != "") $kesimpulan .= ", "; + $kesimpulan .= $db["label"] . " " . $db["label_x"]; + } + if ($db["id_code"] == "tanda_vital_1") { + //echo $db["value"]; + if (intval($db["value"]) > 100) { + if ($kesimpulan != "") $kesimpulan .= ", "; + $kesimpulan .= "Takhikardi " . " ( " . $db["value"] . " x/menit )"; + } + if (intval($db["value"]) < 60) { + if ($kesimpulan != "") $kesimpulan .= ", "; + $kesimpulan .= "Bradikardi " . " ( " . $db["value"] . " x/menit )"; + } + } + if ($db["id_code"] == "tanda_vital_3") { + if (intval($db["value"]) > 20 || intval($db["value"]) < 16) { + if ($kesimpulan != "") $kesimpulan .= ", "; + $kesimpulan .= $db["label"] . " ( " . $db["value"] . " x/menit )"; + } + } + if ($db["id_code"] == 'tanda_vital_5' && $db["value"] != 'NORMAL' && $db["value"] != 'OPTIMAL' && $db['value'] != 'HIGH NORMAL') { + if ($kesimpulan != "") $kesimpulan .= ", "; + $kesimpulan .= $db["label"] . " " . $db["value_x"] . "/" . $db["value_y"]." " . $db["unit"] . " ( " . ucwords(strtolower($db["value"])) . " )"; + } + + + + } + } + elseif ($da["title"] == "LAPANG PANDANG") { + foreach($da["details"] as $gp) { + if ($gp["chx_x"] == "1"){ + $keterangan = ""; + if($gp['value'] != "") + $keterangan = " ( ".$gp['value']." )"; + + if ($kesimpulan != "") $kesimpulan .= ", "; + $kesimpulan .= ucwords(strtolower($da["title"]))." : ".$gp["label_x"] .$keterangan; + + } + } + + //echo $kesimpulan; + } + elseif ($da["title"] == "KEADAAN UMUM") { + foreach ($da["details"] as $db) { + if ($db["chx_x"] == "1") { + if ($kesimpulan != "") $kesimpulan .= ", "; + $kesimpulan .= $db["label"] . " : ( " . $db["label_x"] . " ) " . $db["value"]; + } + } + //echo $kesimpulan; + } elseif ($da["title"] == "KEPALA WAJAH") { + //echo json_encode($da["details"]); + $rst_x = ''; + foreach ($da["details"] as $db) { + if ($db["chx"] == "1" && $db["is_normal"] == "N" && $db["label"] != "Lain-lain") { + if ($rst_x != "") $rst_x .= ", "; + $rst_x .= $db["label"] . " " . $db["value"]; + } + if ($db["label"] == "Lain-lain" && $db["chx"] == "1") { + if ($rst_x != "") $rst_x .= ", "; + $rst_x .= $db["value"]; + } + } + //echo $kesimpulan; + + if ($rst_x !== '') { + if ($kesimpulan != "") $kesimpulan .= "
"; + $kesimpulan .= ucwords(strtolower($da["title"])) . " : " . $rst_x; + } + //echo $kesimpulan; + } elseif ($da["title"] == "MATA") { + $rst_x = ''; + foreach ($da["details"] as $db) { + if ($db["chx"] == "1" && $db["is_normal"] == "N" && $db["label"] != "Lain-lain") { + if ($rst_x != "") $rst_x .= ", "; + $rst_x .= $db["label"] . " " . $db["value"]; + } + if ($db["label"] == "Lain-lain" && $db["chx"] == "1") { + if ($rst_x != "") $rst_x .= ", "; + $rst_x .= $db["value"]; + } + } + + if ($rst_x !== '') { + if ($kesimpulan != "") $kesimpulan .= "
"; + $kesimpulan .= ucwords(strtolower($da["title"])) . " : " . $rst_x; + } + //echo $kesimpulan; + } + elseif ($da["title"] == "TELINGA") { + $rst_x = ''; + foreach ($da["details"] as $db) { + if ($db["chx"] == "1" && $db["is_normal"] == "N" && $db["label"] != "Lain-lain") { + if ($rst_x != "") $rst_x .= ", "; + $rst_x .= $db["label"] . " " . $db["value"]; + } + if ($db["label"] == "Lain-lain" && $db["chx"] == "1") { + if ($rst_x != "") $rst_x .= ", "; + $rst_x .= $db["value"]; + } + } + + if ($rst_x !== '') { + if ($kesimpulan != "") $kesimpulan .= "
"; + $kesimpulan .= ucwords(strtolower($da["title"])) . " : " . $rst_x; + } + } elseif ($da["title"] == "HIDUNG") { + $rst_x = ''; + foreach ($da["details"] as $db) { + if ($db["chx"] == "1" && $db["is_normal"] == "N" && $db["label"] != "Lain-lain") { + if ($rst_x != "") $rst_x .= ", "; + $rst_x .= $db["label"] . " " . $db["value"]; + } + if ($db["label"] == "Lain-lain" && $db["chx"] == "1") { + if ($rst_x != "") $rst_x .= ", "; + $rst_x .= $db["value"]; + } + } + + if ($rst_x !== '') { + if ($kesimpulan != "") $kesimpulan .= "
"; + $kesimpulan .= ucwords(strtolower($da["title"])) . " : " . $rst_x; + } + //echo $kesimpulan; + } + elseif ($da["title"] == "GIGI") { + $rst_x = ''; + foreach ($da["details"] as $db) { + if ($db["chx"] == "1" && $db["is_normal"] == "N" && $db["label"] != "Lain-lain") { + if ($rst_x != "") $rst_x .= ", "; + $rst_x .= $db["label"] . " " . $db["value"]; + } + if ($db["label"] == "Lain-lain" && $db["chx"] == "1") { + if ($rst_x != "") $rst_x .= ", "; + $rst_x .= $db["value"]; + } + } + + if ($rst_x !== '') { + if ($kesimpulan != "") $kesimpulan .= "
"; + $kesimpulan .= ucwords(strtolower($da["title"])) . " : " . $rst_x; + } + //echo $kesimpulan; + } elseif ($da["title"] == "MULUT") { + $s_rst = ''; + foreach ($da["details"] as $db) { + $s_res = ""; + foreach ($db["details"] as $dc) { + if ($dc["chx"] == "1" && $dc["is_normal"] == "N" && $dc["label"] != 'Lain-lain') { + if ($s_res != "") $s_res .= ", "; + $s_res .= $dc["label"] . " " . $dc["value"]; + } + if ($dc["label"] == 'Lain-lain' && $dc["chx"] == "1") { + if ($s_res != "") $s_res .= ", "; + $s_res .= $dc["value"]; + } + } + if ($s_res != "") { + if ($s_rst != "") $s_rst .= "
"; + $s_rst .= "" . $db["name"] . " : " . $s_res . ""; + } + } + if ($s_rst != "") { + if ($kesimpulan != "") $kesimpulan .= "
"; + $kesimpulan .= "" . ucwords(strtolower($da["title"])) . "
"; + $kesimpulan .= $s_rst; + } + //echo $kesimpulan; + + } elseif ($da["title"] == "LEHER") { + $rst_x = ''; + foreach ($da["details"] as $db) { + if ($db["chx"] == "1" && $db["is_normal"] == "N" && $db["label"] != "Lain-lain") { + if ($rst_x != "") $rst_x .= ", "; + $rst_x .= $db["label"] . " " . $db["value"]; + } + if ($db["label"] == "Lain-lain" && $db["chx"] == "1") { + if ($rst_x != "") $rst_x .= ", "; + $rst_x .= $db["value"]; + } + } + + if ($rst_x !== '') { + if ($kesimpulan != "") $kesimpulan .= "
"; + $kesimpulan .= ucwords(strtolower($da["title"])) . " : " . $rst_x; + } + } elseif ($da["title"] == "THORAX / DADA") { + $rst_x = ''; + foreach ($da["details"] as $db) { + if ($db["chx"] == "1" && $db["is_normal"] == "N" && $db["label"] != "Lain-lain") { + if ($rst_x != "") $rst_x .= ", "; + $rst_x .= $db["label"] . " " . $db["value"]; + } + if ($db["label"] == "Lain-lain" && $db["chx"] == "1") { + if ($rst_x != "") $rst_x .= ", "; + $rst_x .= $db["value"]; + } + } + + if ($rst_x !== '') { + if ($kesimpulan != "") $kesimpulan .= "
"; + $kesimpulan .= ucwords(strtolower($da["title"])) . " : " . $rst_x; + } + //echo $kesimpulan; + } elseif ($da["title"] == "PARU-PARU") { + $rst_x = ''; + foreach ($da["details"] as $db) { + if ($db["chx"] == "1" && $db["is_normal"] == "N" && $db["label"] != "Lain-lain") { + if ($rst_x != "") $rst_x .= ", "; + $rst_x .= $db["label"] . " " . $db["value"]; + } + if ($db["label"] == "Lain-lain" && $db["chx"] == "1") { + if ($rst_x != "") $rst_x .= ", "; + $rst_x .= $db["value"]; + } + } + + if ($rst_x !== '') { + if ($kesimpulan != "") $kesimpulan .= "
"; + $kesimpulan .= ucwords(strtolower($da["title"])) . " : " . $rst_x; + } + } elseif ($da["title"] == "JANTUNG") { + $s_rst = ''; + foreach ($da["details"] as $db) { + $s_res = ""; + foreach ($db["details"] as $dc) { + if ($dc["chx"] == "1" && $dc["is_normal"] == "N" && $dc["label"] != 'Lain-lain') { + if ($s_res != "") $s_res .= ", "; + $s_res .= " ( " . $dc["label"] . " : ". $dc["value"] . " )"; + } + if ($dc["label"] == 'Lain-lain' && $dc["chx"] == "1") { + if ($s_res != "") $s_res .= ", "; + $s_res .= $dc["value"]; + } + } + if ($s_res != "") { + if ($s_rst != "") $s_rst .= "
"; + $s_rst .= "" . $db["name"] . " : " . $s_res . ""; + } + } + if ($s_rst != "") { + if ($kesimpulan != "") $kesimpulan .= "
"; + $kesimpulan .= ucwords(strtolower($da["title"])) . "
"; + $kesimpulan .= $s_rst; + } + } elseif ($da["title"] == "PERUT / ABDOMEN") { + $s_res = ""; + $rst_x = ''; + foreach($da["details"] as $gp) { + if($gp["name"] != 'Hernia' && $gp["name"] != 'Pengukuran' ){ + foreach($gp["details"] as $xd) { + if ($xd["chx"] == 1 && $xd["is_normal"] == "N" && $xd["label"] != 'Lain-lain' && $xd['label'] != 'Tidak Ada'){ + $arr_result[] = array($gp["name"],$xd["label"],$xd["value"]) ; + if ($rst_x != "") $rst_x .= ", "; + $rst_x .= $gp["name"]." : ".$db["label"] . " " . $db["value"]; + + if ($s_res != "") $s_res .= ", "; + $s_res .= $xd["label"] . " " . $xd["value"]; + } + + if ($xd["label"] == 'Lain-lain' && $xd["chx"] == "1") { + if ($s_res != "") $s_res .= ", "; + $s_res .= $xd["value"]; + } + + + } + }elseif($gp["name"] == 'Hernia') { + //print_r($gp["details"][1]); + if($gp["details"][1]["chx"] == 1){ + $hasil = $gp["details"][1]["value"]; + $hasil_detail = ""; + //print_r($gp["details"][1]); + if($gp["details"][1]["details"][0]["chx_value"] == 1){ + if($hasil_detail != "") $hasil_detail .= ", "; + $hasil_detail .= " ".$gp["details"][1]["details"][0]["label"]; + } + //print_r($gp["details"][1]["details"][1]); + if($gp["details"][1]["details"][1]["chx_a_value"] == 1 || $gp["details"][1]["details"][1]["chx_b_value"] == 1 ){ + $ds_hasil = ""; + if($gp["details"][1]["details"][1]["chx_a_value"] == 1){ + if($ds_hasil != "") $ds_hasil .= ", "; + $ds_hasil .= $gp["details"][1]["details"][1]["chx_a_label"]; + } + + if($gp["details"][1]["details"][1]["chx_b_value"] == 1){ + if($ds_hasil != "") $ds_hasil .= ", "; + $ds_hasil .= $gp["details"][1]["details"][1]["chx_b_label"]; + } + + if($hasil_detail != "") $hasil_detail .= ", "; + $hasil_detail .= " ".$gp["details"][1]["details"][1]["label"]." (".$ds_hasil.")"; + } + + if($gp["details"][1]["details"][2]["chx_a_value"] == 1 || $gp["details"][1]["details"][2]["chx_b_value"] == 1 ){ + $ds_hasil = ""; + if($gp["details"][1]["details"][2]["chx_a_value"] == 1){ + if($ds_hasil != "") $ds_hasil .= ", "; + $ds_hasil .= $gp["details"][1]["details"][1]["chx_a_label"]; + } + + if($gp["details"][1]["details"][2]["chx_b_value"] == 1){ + if($ds_hasil != "") $ds_hasil .= ", "; + $ds_hasil .= $gp["details"][1]["details"][2]["chx_b_label"]; + } + + if($hasil_detail != "") $hasil_detail .= ", "; + $hasil_detail .= " ".$gp["details"][1]["details"][2]["label"]." (".$ds_hasil.")"; + } + + if ($rst_x != "") $rst_x .= ", "; + $rst_x .= $gp["name"]." : ".$gp["details"][1]["label"] . " " . $hasil.$hasil_detail ; + + if ($s_res != "") $s_res .= ", "; + $s_res .= $gp["name"]." : ".$gp["details"][1]["label"] . " " . $hasil.$hasil_detail ; + } + + + + } + elseif($gp["name"] == 'Pengukuran' ){ + $perut[] = array( + "mm1" => $gp["name"], + "mm2" => $gp["details"][0]["label"]." : ".$gp["details"][0]["value"]." ".$gp["details"][0]["unit"], + "mm3" => $gp["details"][1]["label"]." : ".$gp["details"][1]["value"]." ".$gp["details"][1]["unit"] + ); + if ($rst_x != "") $rst_x .= ", ";{ + $rst_x .= $gp["details"][0]["label"]." : ".$gp["details"][0]["value"]." ".$gp["details"][0]["unit"] ; + $rst_x .= $gp["details"][1]["label"]." : ".$gp["details"][1]["value"]." ".$gp["details"][1]["unit"] ; + } + + } + + } + + + if ($s_res != "") { + if ($kesimpulan != "") $kesimpulan .= "
"; + $kesimpulan .= ucwords(strtolower($da["title"])) . "
"; + $kesimpulan .= $s_res; + } + + //echo $kesimpulan; + } + /*elseif ($da["title"] == "PERUT / ABDOMEN") { + foreach ($da["details"] as $db) { + $s_res = ""; + if($db['name'] != 'Hernia' ){ + foreach ($db["details"] as $dc) { + if ($dc["chx"] == "1" && $dc["is_normal"] == "N" && $dc["label"] != 'Lain-lain' && $dc['label'] != 'Tidak Ada') { + if ($s_res != "") $s_res .= ", "; + $s_res .= $dc["label"] . " " . $dc["value"]; + } + if ($dc["label"] == 'Lain-lain' && $dc["chx"] == "1") { + if ($s_res != "") $s_res .= ", "; + $s_res .= $dc["value"]; + } + } + }else{ + foreach ($db["details"] as $dc) { + if ($dc["chx"] == "1" && $dc["is_normal"] == "N" && $dc["label"] != 'Lain-lain' && $dc['label'] != 'Tidak Ada') { + + $regio_value = ""; + + foreach ($dc['details'] as $k_regio => $v_regio) { + if($v_regio['chx_a_value'] == "1" || $v_regio['chx_b_value'] == "1"){ + $check_regio = ""; + if($v_regio['chx_a_value'] == "1"){ + if ($check_regio != "") $check_regio .= ", "; + $check_regio .= $v_regio['chx_a_label']; + } + if($v_regio['chx_b_value'] == "1"){ + if ($check_regio != "") $check_regio .= ", "; + $check_regio .= $v_regio['chx_b_label']; + } + + if ($regio_value != "") $regio_value .= ", "; + $regio_value .= $v_regio['label']. " (".$check_regio.")" ; + } + } + + if ($s_res != "") $s_res .= ", "; + $s_res .= $regio_value; + } + + } + } + + if ($s_res != "") { + if ($kesimpulan != "") $kesimpulan .= "
"; + $kesimpulan .= $db["name"] . " : " . $s_res; + } + } + //echo $kesimpulan; + }*/ elseif ($da["title"] == "GENITOURINARIA") { + $rst_x = ''; + foreach ($da["details"] as $db) { + if ($db["chx"] == "1" && $db["is_normal"] == "N" && $db["label"] != "Tidak diperiksa" && $db["label"] != "Lain-lain") { + if ($rst_x != "") $rst_x .= ", "; + $rst_x .= $db["label"] . " " . $db["value"]; + } + if ($db["label"] == "Lain-lain" && $db["chx"] == "1") { + if ($rst_x != "") $rst_x .= ", "; + $rst_x .= $db["value"]; + } + } + + if ($rst_x !== '') { + if ($kesimpulan != "") $kesimpulan .= "
"; + $kesimpulan .= ucwords(strtolower($da["title"])) . " : " . $rst_x; + } + } elseif ($da["title"] == "ANGGOTA GERAK") { + foreach ($da["details"] as $db) { + $s_res = ""; + foreach ($db["details"] as $dc) { + if ($dc["chx"] == "1" && $dc["is_normal"] == "N" && $dc["label"] != 'Lain-lain') { + if ($s_res != "") $s_res .= ", "; + $s_res .= "( " . $dc["label"] . " ) " . $dc["value"]; /* perubahan 180320 */ + } + if ($dc["label"] == 'Lain-lain' && $dc["chx"] == "1") { + if ($s_res != "") $s_res .= ", "; + $s_res .= $dc["value"]; + } + } + if ($s_res != "") { + if ($kesimpulan != "") $kesimpulan .= "
"; + $kesimpulan .= $db["name"] . " : " . $s_res; + } + } + } elseif ($da["title"] == "SISTEM PERSYARAFAN") { + foreach ($da["details"] as $db) { + $s_res = ""; + foreach ($db["details"] as $dc) { + if ($dc["chx"] == "1" && $dc["is_normal"] == "N" && $dc["label"] != 'Lain-lain') { + if ($s_res != "") $s_res .= ", "; + $s_res .= "( " . $dc["label"] . " ) " . $dc["value"]; /* perubahan 180320 */ + } + if ($dc["label"] == 'Lain-lain' && $dc["chx"] == "1") { + if ($s_res != "") $s_res .= ", "; + $s_res .= $dc["value"]; + } + } + if ($s_res != "") { + if ($kesimpulan != "") $kesimpulan .= "
"; + $kesimpulan .= $db["name"] . " : " . $s_res; + } + } + } elseif ($da["title"] == "SMELL TEST") { + foreach ($da["details"] as $db) { + $s_res = ""; + foreach ($db["details"] as $dc) { + if ($dc["chx"] == "1" && $dc["is_normal"] == "N" && $dc["label"] != 'Lain-lain') { + if ($s_res != "") $s_res .= ", "; + $s_res .= "( " . $dc["label"] . " ) " . $dc["value"]; /* perubahan 180320 */ + } + if ($dc["label"] == 'Lain-lain' && $dc["chx"] == "1") { + if ($s_res != "") $s_res .= ", "; + $s_res .= $dc["value"]; + } + } + if ($s_res != "") { + if ($kesimpulan != "") $kesimpulan .= "
"; + $kesimpulan .= $db["name"] . " : " . $s_res; + } + } + } elseif ($da["title"] == "LOW BACK PAIN SCREENING TEST") { + foreach ($da["details"] as $db) { + $s_res = ""; + foreach ($db["details"] as $dc) { + if ($dc["chx"] == "1" && $dc["is_normal"] == "N" && $dc["label"] != 'Lain-lain') { + if ($s_res != "") $s_res .= ", "; + $s_res .= "( " . $dc["label"] . " ) " . $dc["value"]; /* perubahan 180320 */ + } + if ($dc["label"] == 'Lain-lain' && $dc["chx"] == "1") { + if ($s_res != "") $s_res .= ", "; + $s_res .= $dc["value"]; + } + } + if ($s_res != "") { + if ($kesimpulan != "") $kesimpulan .= "
"; + $kesimpulan .= $db["name"] . " : " . $s_res; + } + } + //echo $kesimpulan; + } elseif ($da["title"] == "SISTEM INTEGUMEN") { + foreach ($da["details"] as $db) { + $s_res = ""; + foreach ($db["details"] as $dc) { + if ($dc["chx"] == "1" && $dc["is_normal"] == "N" && $dc["label"] != 'Lain-lain') { + if ($s_res != "") $s_res .= ", "; + $s_res .= "( " . $dc["label"] . " ) " . $dc["value"]; + } + if ($dc["label"] == 'Lain-lain' && $dc["chx"] == "1") { + if ($s_res != "") $s_res .= ", "; + $s_res .= $dc["value"]; + } + } + if ($s_res != "") { + if ($kesimpulan != "") $kesimpulan .= "
"; + $kesimpulan .= $db["name"] . " : " . $s_res; + } + } + + //echo $kesimpulan; + + + + + } + } + if ($kesimpulan == "") { + $kesimpulan = "Tidak ditemukan kelainan."; + } else { + $kesimpulan = "Pada saat ini didapatkan kelainan berupa :
" . $kesimpulan; + } + return $kesimpulan; + } + + function insert_t_kelainan_fisik($kelainans,$order_header_id,$re_id){ + + /*foreach ($kelainans as $key => $value) { + + $sql = "UPDATE t_kelainan_fisik SET T_KelainanFiskIsActive = 'N' WHERE T_KelainanFiskSo_ResultEntryID = ? AND T_KelainanFiskMcu_SummaryFisikID = ?"; + $qry = $this->db_smartone->query($sql, array($re_id, $value['Mcu_SummaryFisikID'])); + + $sql = "INSERT INTO t_kelainan_fisik ( + T_KelainanFiskSo_ResultEntryID, + T_KelainanFiskT_OrderHeaderID, + T_KelainanFiskMcu_SummaryFisikID, + T_KelainanLabNonCreated + ) + VALUES ( + ?,?,?,NOW() + )"; + + $qry = $this->db_smartone->query($sql, array($re_id, $order_header_id, $value['Mcu_SummaryFisikID'])); + }*/ + return true; + + } + + function hitung_bmi($bb,$tb,$standart_bmi){ + $tb = $tb/100; + $bmi = ''; + $classs = ""; + $bmi_valuex= 0; + if(intval($bb) != 0 && intval($tb) != 0){ + $bmi = $bb / ($tb * $tb); + $bmi_valuex = number_format($bmi,2); + + if($standart_bmi === 'asia_pacific'){ + if($bmi_valuex < 18.5) + $classs = 'Underweight'; + + if($bmi_valuex >= 18.5 && $bmi_valuex < 23) + $classs = 'Normal'; + + if($bmi_valuex >= 23 && $bmi_valuex < 25) + $classs = 'Overweight'; + + if($bmi_valuex >= 25 && $bmi_valuex < 30) + $classs = 'Obese I'; + + if($bmi_valuex >= 30) + $classs = 'Obese II'; + } + + if($standart_bmi === 'who'){ + if($bmi_valuex < 18.5) + $classs = 'Underweight'; + + if($bmi_valuex >= 18.5 && $bmi_valuex < 25){ + $classs = 'Normal'; + } + + if($bmi_valuex >= 25 && $bmi_valuex < 30){ + $classs = 'Overweight'; + } + + if($bmi_valuex >= 30) + $classs = 'Obese'; + } + + if($standart_bmi === 'kemenkes'){ + if($bmi_valuex < 18.5) + $classs = 'Underweight'; + + if($bmi_valuex >= 18.5 && $bmi_valuex < 25.1) + $classs = 'Normal'; + + if($bmi_valuex >= 25.1 && $bmi_valuex < 27) + $classs = 'Overweight'; + + if($bmi_valuex >= 27) + $classs = 'Obese'; + } + } + + + + + + return array( + 'bmi' => $bmi_valuex, + 'class' => $classs + ); + } + + function generate_all_kelainan_fisik($mgm_mcuid,$limit){ + $sql = "SELECT * + FROM so_resultentry + JOIN t_orderheader ON So_ResultEntryT_OrderHeaderID = T_OrderHeaderID AND T_OrderHeaderIsActive = 'Y' AND + T_OrderHeaderMgm_McuID = ? + WHERE + So_ResultEntryNonlab_TemplateID = 27 AND So_ResultEntryIsActive = 'Y' + LIMIT ?"; + $qry = $this->db_smartone->query($sql, array($mgm_mcuid,intval($limit))); + // echo $this->db_smartone->last_query(); + $datas = $qry->result_array(); + if($datas && count($datas) > 0){ + foreach ($datas as $key => $value) { + $this->generate_kelainan_fisik($value['So_ResultEntryID']); + } + } + } + + function generate_kelainan_fisik($id) + { + $kesimpulan = ""; + $all_kelainans = []; + + $sql = "SELECT * + FROM fisik_template + JOIN so_resultentry_fisik_umum ON So_ResultEntryFisikUmumFisikTemplateID = FisikTemplateID AND So_ResultEntryFisikUmumSo_ResultEntryID = ? + JOIN so_resultentry ON So_ResultEntryFisikUmumSo_ResultEntryID = So_ResultEntryID + WHERE + FisikTemplateIsActive = 'Y' AND + FisikTemplateType = 'Riwayat' + ORDER BY FisikTemplateCode ASC + "; + $qry = $this->db_smartone->query($sql, array($id)); + // echo $this->db_smartone->last_query(); + $xriwayats = $qry->result_array(); + $order_header_id = $xriwayats[0]['So_ResultEntryT_OrderHeaderID']; + $re_id = $xriwayats[0]['So_ResultEntryID']; + $riwayat_data = []; + foreach ($xriwayats as $key => $value) { + $riwayat_data[] = json_decode($value['So_ResultEntryFisikUmumDetails'], true); + } + //print_r($riwayat_data); + foreach ($riwayat_data as $riwayat_da) { + //print_r($riwayat_da); + //echo $riwayat_da["title"]; + if ($riwayat_da["title"] == "KELUHAN SAAT INI") { + //print_r($riwayat_da["details"]); + foreach ($riwayat_da["details"] as $riwayat_db) { + if (($riwayat_db["chx"] == "1" || $riwayat_db["chx"] != false) && $riwayat_db["label"] == 'Gastritis (maag)') { + if ($kesimpulan != "") $kesimpulan .= ", "; + $kesimpulan .= $riwayat_db["label"] . " " . $riwayat_db["value"]; + } + } + }elseif ($riwayat_da["title"] == "RIWAYAT KEBIASAAN HIDUP") { + $rst_x = ''; + foreach ($riwayat_da["details"] as $db) { + foreach ($db['details'] as $dc) { + $rows_summary = $this->get_kelainans($dc["id_code"]); + if(count($rows_summary) > 0){ + $kelainans = []; + foreach ($rows_summary as $key => $value) { + if($value['Mcu_SummaryFisikType'] == 'C' && $dc["chx"] == "1"){ + $kelainans[] = $value; + $all_kelainans[] = $value; + } + } + + if(count($kelainans) > 0){ + $this->insert_t_kelainan_fisik($kelainans,$order_header_id,$re_id); + } + } + } + } + } + } + + $kode_gigi = array( + "X" => "Berlubang", + "C" => "Tambalan", + "O" => "Tanggal", + "R" => "Sisa akar", + "A" => "Gigi Palsu", + "K" => "Karang Gigi" + ); + + $sql = "SELECT * + FROM fisik_template + JOIN so_resultentry_fisik_umum ON So_ResultEntryFisikUmumFisikTemplateID = FisikTemplateID AND So_ResultEntryFisikUmumSo_ResultEntryID = ? + JOIN so_resultentry ON So_ResultEntryFisikUmumSo_ResultEntryID = So_ResultEntryID + JOIN t_orderheader ON So_ResultEntryT_OrderHeaderID = T_OrderHeaderID + JOIN m_patient ON T_OrderHeaderM_PatientID = M_PatientID + WHERE + FisikTemplateIsActive = 'Y' AND + FisikTemplateType = 'Fisik' + ORDER BY FisikTemplateCode ASC + "; + $qry = $this->db_smartone->query($sql, array($id)); + // echo $this->db_smartone->last_query(); + $xfisiks = $qry->result_array(); + $order_header_id = $xfisiks[0]['So_ResultEntryT_OrderHeaderID']; + $re_id = $xfisiks[0]['So_ResultEntryID']; + $fisik_data = []; + foreach ($xfisiks as $kex => $valux) { + $fisik_data[] = json_decode($valux['So_ResultEntryFisikUmumDetails'], true); + } + //print_r($fisik_data); + + $sexcode = $xfisiks[0]["M_PatientGender"] == 'male' ? 'L' : 'P'; + + foreach ($fisik_data as $da) { + //echo $da["title"]; + if ($da["title"] == "TANDA VITAL") { + foreach ($da["details"] as $db) { + //print_r($db); + if ($db["chx_x"] == "1" && $db["id_code"] != 'tanda_vital_5') { + if ($kesimpulan != "") $kesimpulan .= ", "; + $kesimpulan .= $db["label"] . " " . $db["label_x"]; + } + if ($db["id_code"] == "tanda_vital_1") { + //echo $db["value"]; + if (intval($db["value"]) > 100) { + if ($kesimpulan != "") $kesimpulan .= ", "; + $kesimpulan .= "Takhikardi " . " ( " . $db["value"] . " x/menit )"; + } + if (intval($db["value"]) < 60) { + if ($kesimpulan != "") $kesimpulan .= ", "; + $kesimpulan .= "Bradikardi " . " ( " . $db["value"] . " x/menit )"; + } + } + if ($db["id_code"] == "tanda_vital_3") { + if (intval($db["value"]) > 20 || intval($db["value"]) < 16) { + if ($kesimpulan != "") $kesimpulan .= ", "; + $kesimpulan .= $db["label"] . " ( " . $db["value"] . " x/menit )"; + } + } + if ($db["id_code"] == 'tanda_vital_5' && $db["value"] != 'NORMAL' && $db["value"] != 'OPTIMAL' && $db['value'] != 'HIGH NORMAL') { + if ($kesimpulan != "") $kesimpulan .= ", "; + $kesimpulan .= $db["label"] . " " . $db["value_x"] . "/" . $db["value_y"]." " . $db["unit"] . " ( " . ucwords(strtolower($db["value"])) . " )"; + } + + //echo $db['value']." - "; + //echo $db["id_code"]; + $rows_summary = $this->get_kelainans($db["id_code"]); + //print_r($rows_summary); + if(count($rows_summary) > 0){ + $kelainans = []; + foreach ($rows_summary as $key => $value) { + $val = strtolower($db['value']); + $val = str_replace("stadium","stage",$val); + if($value['Mcu_SummaryFisikType'] == 'SD'){ + if(strtolower($value['Mcu_KelainanName']) == $val){ + $kelainans[] = $value; + $all_kelainans[] = $value; + + } + } + } + + if(count($kelainans) > 0){ + $this->insert_t_kelainan_fisik($kelainans,$order_header_id,$re_id); + } + + } + + } + } elseif ($da["title"] == "STATUS GIZI") { + $bmi_value = ""; + + //echo json_encode($da['details']); + foreach ($da["details"] as $db) { + + if ($db["id_code"] == "status_gizi_4") $bmi_value = $db["value"]; + if ($db["chx_x"] == "1") { + if ($kesimpulan != "") $kesimpulan .= ", "; + $kesimpulan .= $db["label"] . " " . $db["label_x"]; + } + if (($db["id_code"] == "status_gizi_6" && $db["value"] != "Normal" && $db["value"] != '-')) { + //echo $db["value"] ; + if ($kesimpulan != "") $kesimpulan .= ", "; + $kesimpulan .= $db["value"] . " ( BMI : $bmi_value )"; + + //echo $kesimpulan; + } + //echo $kesimpulan; + if ($db["id_code"] == "status_gizi_3") { + if (intval($db["value"]) >= 90 && $sexcode == 'L') { + if ($kesimpulan != "") $kesimpulan .= ", "; + $kesimpulan .= $db["label"] . " " . " ( " . $db["value"] . " cm )"; + } + if (intval($db["value"]) >= 80 && $sexcode == 'P') { + if ($kesimpulan != "") $kesimpulan .= ", "; + $kesimpulan .= $db["label"] . " " . " ( " . $db["value"] . " cm )"; + } + } + + $rows_summary = $this->get_kelainans($db["id_code"]); + if(count($rows_summary) > 0){ + $kelainans = []; + foreach ($rows_summary as $key => $value) { + if($value['Mcu_SummaryFisikType'] == 'SD'){ + if($value['Mcu_KelainanName'] == $db['value']){ + $kelainans[] = $value; + $all_kelainans[] = $value; + } + } + } + + if(count($kelainans) > 0){ + $this->insert_t_kelainan_fisik($kelainans,$order_header_id,$re_id); + } + + } + } + } elseif ($da["title"] == "KEADAAN UMUM") { + foreach ($da["details"] as $db) { + if ($db["chx_x"] == "1") { + if ($kesimpulan != "") $kesimpulan .= ", "; + $kesimpulan .= $db["label"] . " : ( " . $db["label_x"] . " ) " . $db["value"]; + } + } + //echo $kesimpulan; + } elseif ($da["title"] == "KEPALA WAJAH") { + //echo json_encode($da["details"]); + $rst_x = ''; + foreach ($da["details"] as $db) { + if ($db["chx"] == "1" && $db["is_normal"] == "N" && $db["label"] != "Lain-lain") { + if ($rst_x != "") $rst_x .= ", "; + $rst_x .= $db["label"] . " " . $db["value"]; + } + if ($db["label"] == "Lain-lain" && $db["chx"] == "1") { + if ($rst_x != "") $rst_x .= ", "; + $rst_x .= $db["value"]; + } + } + //echo $kesimpulan; + + if ($rst_x !== '') { + if ($kesimpulan != "") $kesimpulan .= "
"; + $kesimpulan .= ucwords(strtolower($da["title"])) . " : " . $rst_x; + } + //echo $kesimpulan; + } elseif ($da["title"] == "MATA") { + $rst_x = ''; + foreach ($da["details"] as $db) { + if ($db["chx"] == "1" && $db["is_normal"] == "N" && $db["label"] != "Lain-lain") { + if ($rst_x != "") $rst_x .= ", "; + $rst_x .= $db["label"] . " " . $db["value"]; + } + if ($db["label"] == "Lain-lain" && $db["chx"] == "1") { + if ($rst_x != "") $rst_x .= ", "; + $rst_x .= $db["value"]; + } + } + + if ($rst_x !== '') { + if ($kesimpulan != "") $kesimpulan .= "
"; + $kesimpulan .= ucwords(strtolower($da["title"])) . " : " . $rst_x; + } + //echo $kesimpulan; + } elseif ($da["title"] == "PERSEPSI WARNA") { + $rst_x = ''; + foreach ($da["details"] as $db) { + if ($db["chx"] == "1" && $db["is_normal"] == "N" && $db["label"] != "Lain-lain") { + if ($rst_x != "") $rst_x .= ", "; + $rst_x .= $db["label"] . " " . $db["value"]; + } + if ($db["label"] == "Lain-lain" && $db["chx"] == "1") { + if ($rst_x != "") $rst_x .= ", "; + $rst_x .= $db["value"]; + } + + $rows_summary = $this->get_kelainans($db["id_code"]); + if(count($rows_summary) > 0){ + $kelainans = []; + foreach ($rows_summary as $key => $value) { + if($value['Mcu_SummaryFisikType'] == 'C'){ + if($db["chx"] == "1"){ + $kelainans[] = $value; + $all_kelainans[] = $value; + } + } + } + + if(count($kelainans) > 0){ + $this->insert_t_kelainan_fisik($kelainans,$order_header_id,$re_id); + } + } + } + + if ($rst_x !== '') { + if ($kesimpulan != "") $kesimpulan .= "
"; + $kesimpulan .= ucwords(strtolower($da["title"])) . " : " . $rst_x; + } + //echo $kesimpulan; + } elseif ($da["title"] == "VISUS JAUH") { + + $s_rst = ''; + foreach ($da["details"] as $db) { + $str_data = ""; + $r_ods = ''; + $xr_ods = array(); + $kelainan = ''; + foreach ($db['details'] as $dc) { + if ($dc['chx'] == '1' && $dc['segment_name'] == 'Tanpa kacamata' && ($dc['value'] != '' && $dc['value'] != '20/20')) { + $r_ods .= $dc['label'] . " : " . $dc['value'] . " "; + array_push($xr_ods, $dc['value']); + } + if ($dc['chx'] == '1' && $dc['segment_name'] == 'Dengan kacamata' && $dc['value'] != '') { + if ($dc['value'] != '20/20') + $r_ods .= $dc['label'] . " : " . $dc['value'] . " "; + + array_push($r_ods); + array_push($xr_ods, $dc['value']); + } + } + //print_r($xr_ods); + if (!empty($xr_ods)) { + if ($db['name'] == 'Tanpa kacamata') { + $kelainan = "Kelainan refraksi". " " . strtolower($db['name']); + $str_data .= $kelainan . " ( " . $r_ods . ")"; + } + if ($db['name'] == 'Dengan kacamata') { + $all66 = true; + foreach ($xr_ods as $xd => $xv) { + if ($xv != '20/20') { + $all66 = false; + } + } + if ($all66) { + $kelainan = "Kelainan refraksi terkoreksi". " " . strtolower($db['name']) ; + } else { + $kelainan = "Kelainan refraksi". " " . strtolower($db['name']) ; + } + if ($r_ods != '') + $str_data .= $kelainan . " ( " . $r_ods . ")"; + else + $str_data .= $kelainan; + } + $s_rst .= $str_data; + + $rows_summary = $this->get_kelainans($db["id_code"]); + if(count($rows_summary) > 0){ + $kelainans = []; + foreach ($rows_summary as $key => $value) { + if($value['Mcu_SummaryFisikType'] == 'SD'){ + if($value['Mcu_KelainanName'] == $kelainan){ + $kelainans[] = $value; + $all_kelainans[] = $value; + } + } + } + + if(count($kelainans) > 0){ + $this->insert_t_kelainan_fisik($kelainans,$order_header_id,$re_id); + } + + } + } + //echo $str_data; + + + + } + if ($s_rst != "") { + if ($kesimpulan != "") $kesimpulan .= "
"; + $kesimpulan .= $s_rst; + } + //echo $kesimpulan; + } elseif ($da["title"] == "TELINGA") { + $rst_x = ''; + foreach ($da["details"] as $db) { + if ($db["chx"] == "1" && $db["is_normal"] == "N" && $db["label"] != "Lain-lain") { + if ($rst_x != "") $rst_x .= ", "; + $rst_x .= $db["label"] . " " . $db["value"]; + } + if ($db["label"] == "Lain-lain" && $db["chx"] == "1") { + if ($rst_x != "") $rst_x .= ", "; + $rst_x .= $db["value"]; + } + + $rows_summary = $this->get_kelainans($db["id_code"]); + if(count($rows_summary) > 0){ + $kelainans = []; + foreach ($rows_summary as $key => $value) { + if($value['Mcu_SummaryFisikType'] == 'C' && $db["chx"] == "1"){ + $kelainans[] = $value; + $all_kelainans[] = $value; + } + } + + if(count($kelainans) > 0){ + $this->insert_t_kelainan_fisik($kelainans,$order_header_id,$re_id); + } + } + } + + if ($rst_x !== '') { + if ($kesimpulan != "") $kesimpulan .= "
"; + $kesimpulan .= ucwords(strtolower($da["title"])) . " : " . $rst_x; + } + } elseif ($da["title"] == "HIDUNG") { + $rst_x = ''; + foreach ($da["details"] as $db) { + if ($db["chx"] == "1" && $db["is_normal"] == "N" && $db["label"] != "Lain-lain") { + if ($rst_x != "") $rst_x .= ", "; + $rst_x .= $db["label"] . " " . $db["value"]; + } + if ($db["label"] == "Lain-lain" && $db["chx"] == "1") { + if ($rst_x != "") $rst_x .= ", "; + $rst_x .= $db["value"]; + } + + $rows_summary = $this->get_kelainans($db["id_code"]); + if(count($rows_summary) > 0){ + $kelainans = []; + foreach ($rows_summary as $key => $value) { + if($value['Mcu_SummaryFisikType'] == 'C' && $db["chx"] == "1"){ + $kelainans[] = $value; + $all_kelainans[] = $value; + } + } + + if(count($kelainans) > 0){ + $this->insert_t_kelainan_fisik($kelainans,$order_header_id,$re_id); + } + } + + } + + if ($rst_x !== '') { + if ($kesimpulan != "") $kesimpulan .= "
"; + $kesimpulan .= ucwords(strtolower($da["title"])) . " : " . $rst_x; + } + //echo $kesimpulan; + } + elseif ($da["title"] == "GIGI") { + $rst_x = ''; + foreach ($da["details"] as $db) { + if ($db["chx"] == "1" && $db["is_normal"] == "N" && $db["label"] != "Lain-lain") { + if ($rst_x != "") $rst_x .= ", "; + $rst_x .= $db["label"] . " " . $db["value"]; + } + if ($db["label"] == "Lain-lain" && $db["chx"] == "1") { + if ($rst_x != "") $rst_x .= ", "; + $rst_x .= $db["value"]; + } + + $rows_summary = $this->get_kelainans($db["id_code"]); + if(count($rows_summary) > 0){ + $kelainans = []; + foreach ($rows_summary as $key => $value) { + if($value['Mcu_SummaryFisikType'] == 'CSD' && $db["chx"] == "1"){ + if($value['Mcu_KelainanName'] == $db["label"]){ + $kelainans[] = $value; + $all_kelainans[] = $value; + } + } + } + + if(count($kelainans) > 0){ + $this->insert_t_kelainan_fisik($kelainans,$order_header_id,$re_id); + } + } + } + + if ($rst_x !== '') { + if ($kesimpulan != "") $kesimpulan .= "
"; + $kesimpulan .= ucwords(strtolower($da["title"])) . " : " . $rst_x; + } + //echo $kesimpulan; + } elseif ($da["title"] == "MULUT") { + $s_rst = ''; + foreach ($da["details"] as $db) { + $s_res = ""; + foreach ($db["details"] as $dc) { + // print_r($dc); + if ($dc["chx"] == "1" && $dc["is_normal"] == "N" && $dc["label"] != 'Lain-lain') { + if ($s_res != "") $s_res .= ", "; + $s_res .= $dc["label"] . " " . $dc["value"]; + } + if ($dc["label"] == 'Lain-lain' && $dc["chx"] == "1") { + if ($s_res != "") $s_res .= ", "; + $s_res .= $dc["value"]; + } + + $rows_summary = $this->get_kelainans($dc["id_code"]); + if(count($rows_summary) > 0){ + $kelainans = []; + foreach ($rows_summary as $key => $value) { + if($value['Mcu_SummaryFisikType'] == 'C' && $dc["chx"] == "1"){ + $kelainans[] = $value; + $all_kelainans[] = $value; + } + } + + if(count($kelainans) > 0){ + $this->insert_t_kelainan_fisik($kelainans,$order_header_id,$re_id); + } + } + } + if ($s_res != "") { + if ($s_rst != "") $s_rst .= "
"; + $s_rst .= "" . $db["name"] . " : " . $s_res . ""; + } + } + if ($s_rst != "") { + if ($kesimpulan != "") $kesimpulan .= "
"; + $kesimpulan .= "" . ucwords(strtolower($da["title"])) . "
"; + $kesimpulan .= $s_rst; + } + //echo $kesimpulan; + + } elseif ($da["title"] == "LEHER") { + $rst_x = ''; + foreach ($da["details"] as $db) { + if ($db["chx"] == "1" && $db["is_normal"] == "N" && $db["label"] != "Lain-lain") { + if ($rst_x != "") $rst_x .= ", "; + $rst_x .= $db["label"] . " " . $db["value"]; + } + if ($db["label"] == "Lain-lain" && $db["chx"] == "1") { + if ($rst_x != "") $rst_x .= ", "; + $rst_x .= $db["value"]; + } + } + + if ($rst_x !== '') { + if ($kesimpulan != "") $kesimpulan .= "
"; + $kesimpulan .= ucwords(strtolower($da["title"])) . " : " . $rst_x; + } + } elseif ($da["title"] == "THORAX / DADA") { + $rst_x = ''; + foreach ($da["details"] as $db) { + if ($db["chx"] == "1" && $db["is_normal"] == "N" && $db["label"] != "Lain-lain") { + if ($rst_x != "") $rst_x .= ", "; + $rst_x .= $db["label"] . " " . $db["value"]; + } + if ($db["label"] == "Lain-lain" && $db["chx"] == "1") { + if ($rst_x != "") $rst_x .= ", "; + $rst_x .= $db["value"]; + } + } + + if ($rst_x !== '') { + if ($kesimpulan != "") $kesimpulan .= "
"; + $kesimpulan .= ucwords(strtolower($da["title"])) . " : " . $rst_x; + } + //echo $kesimpulan; + } elseif ($da["title"] == "PARU-PARU") { + $rst_x = ''; + foreach ($da["details"] as $db) { + if ($db["chx"] == "1" && $db["is_normal"] == "N" && $db["label"] != "Lain-lain") { + if ($rst_x != "") $rst_x .= ", "; + $rst_x .= $db["label"] . " " . $db["value"]; + } + if ($db["label"] == "Lain-lain" && $db["chx"] == "1") { + if ($rst_x != "") $rst_x .= ", "; + $rst_x .= $db["value"]; + } + } + + if ($rst_x !== '') { + if ($kesimpulan != "") $kesimpulan .= "
"; + $kesimpulan .= ucwords(strtolower($da["title"])) . " : " . $rst_x; + } + } elseif ($da["title"] == "JANTUNG") { + $s_rst = ''; + foreach ($da["details"] as $db) { + $s_res = ""; + foreach ($db["details"] as $dc) { + if ($dc["chx"] == "1" && $dc["is_normal"] == "N" && $dc["label"] != 'Lain-lain') { + if ($s_res != "") $s_res .= ", "; + $s_res .= " ( " . $dc["label"] . " : " . $dc["label_x"] . " " . $dc["value"] . " )"; + } + if ($dc["label"] == 'Lain-lain' && $dc["chx"] == "1") { + if ($s_res != "") $s_res .= ", "; + $s_res .= $dc["value"]; + } + + $rows_summary = $this->get_kelainans($dc["id_code"]); + if(count($rows_summary) > 0){ + $kelainans = []; + foreach ($rows_summary as $key => $value) { + if($value['Mcu_SummaryFisikType'] == 'C' && $dc["chx"] == "1"){ + $kelainans[] = $value; + $all_kelainans[] = $value; + } + } + + if(count($kelainans) > 0){ + $this->insert_t_kelainan_fisik($kelainans,$order_header_id,$re_id); + } + } + } + if ($s_res != "") { + if ($s_rst != "") $s_rst .= "
"; + $s_rst .= "" . $db["name"] . " : " . $s_res . ""; + } + } + if ($s_rst != "") { + if ($kesimpulan != "") $kesimpulan .= "
"; + $kesimpulan .= ucwords(strtolower($da["title"])) . "
"; + $kesimpulan .= $s_rst; + } + } elseif ($da["title"] == "PERUT / ABDOMEN") { + + $rst_x = ''; + foreach($da["details"] as $gp) { + if($gp["name"] != 'Hernia' && $gp["name"] != 'Pengukuran' ){ + foreach($gp["details"] as $xd) { + if ($xd["chx"] == 1 ){ + $arr_result[] = array($gp["name"],$xd["label"],$xd["value"]) ; + if ($rst_x != "") $rst_x .= ", "; + $rst_x .= $gp["name"]." : ".$xd["label"] . " " . $xd["value"]; + + } + + $rows_summary = $this->get_kelainans($xd["id_code"]); + if(count($rows_summary) > 0){ + $kelainans = []; + foreach ($rows_summary as $key => $value) { + if($value['Mcu_SummaryFisikType'] == 'C' && $xd["chx"] == "1"){ + $kelainans[] = $value; + $all_kelainans[] = $value; + } + } + + if(count($kelainans) > 0){ + $this->insert_t_kelainan_fisik($kelainans,$order_header_id,$re_id); + } + } + } + }elseif($gp["name"] == 'Hernia') { + //print_r($gp["details"][1]); + if($gp["details"][1]["chx"] == 1){ + $hasil = $gp["details"][1]["value"]; + $hasil_detail = ""; + //print_r($gp["details"][1]); + if($gp["details"][1]["details"][0]["chx_value"] == 1){ + if($hasil_detail != "") $hasil_detail .= ", "; + $hasil_detail .= " ".$gp["details"][1]["details"][0]["label"]; + } + //print_r($gp["details"][1]["details"][1]); + if($gp["details"][1]["details"][1]["chx_a_value"] == 1 || $gp["details"][1]["details"][1]["chx_b_value"] == 1 ){ + $ds_hasil = ""; + if($gp["details"][1]["details"][1]["chx_a_value"] == 1){ + if($ds_hasil != "") $ds_hasil .= ", "; + $ds_hasil .= $gp["details"][1]["details"][1]["chx_a_label"]; + } + + if($gp["details"][1]["details"][1]["chx_b_value"] == 1){ + if($ds_hasil != "") $ds_hasil .= ", "; + $ds_hasil .= $gp["details"][1]["details"][1]["chx_b_label"]; + } + + if($hasil_detail != "") $hasil_detail .= ", "; + $hasil_detail .= " ".$gp["details"][1]["details"][1]["label"]." (".$ds_hasil.")"; + } + + if($gp["details"][1]["details"][2]["chx_a_value"] == 1 || $gp["details"][1]["details"][2]["chx_b_value"] == 1 ){ + $ds_hasil = ""; + if($gp["details"][1]["details"][2]["chx_a_value"] == 1){ + if($ds_hasil != "") $ds_hasil .= ", "; + $ds_hasil .= $gp["details"][1]["details"][1]["chx_a_label"]; + } + + if($gp["details"][1]["details"][2]["chx_b_value"] == 1){ + if($ds_hasil != "") $ds_hasil .= ", "; + $ds_hasil .= $gp["details"][1]["details"][2]["chx_b_label"]; + } + + if($hasil_detail != "") $hasil_detail .= ", "; + $hasil_detail .= " ".$gp["details"][1]["details"][2]["label"]." (".$ds_hasil.")"; + } + + if ($rst_x != "") $rst_x .= ", "; + $rst_x .= $gp["name"]." : ".$gp["details"][1]["label"] . " " . $hasil.$hasil_detail ; + + $rows_summary = $this->get_kelainans($gp["details"][1]["id_code"]); + if(count($rows_summary) > 0){ + $kelainans = []; + foreach ($rows_summary as $key => $value) { + if($value['Mcu_SummaryFisikType'] == 'C' && $gp["details"][1]["chx"] == "1"){ + $kelainans[] = $value; + $all_kelainans[] = $value; + } + } + + if(count($kelainans) > 0){ + $this->insert_t_kelainan_fisik($kelainans,$order_header_id,$re_id); + } + } + } + + if($gp["details"][0]["chx"] == 1){ + if ($rst_x != "") $rst_x .= ", "; + $rst_x .= $gp["name"]." : ".$gp["details"][0]["label"]; + + $rows_summary = $this->get_kelainans($gp["details"][0]["id_code"]); + if(count($rows_summary) > 0){ + $kelainans = []; + foreach ($rows_summary as $key => $value) { + if($value['Mcu_SummaryFisikType'] == 'C' && $gp["details"][0]["chx"] == "1"){ + $kelainans[] = $value; + $all_kelainans[] = $value; + } + } + + if(count($kelainans) > 0){ + $this->insert_t_kelainan_fisik($kelainans,$order_header_id,$re_id); + } + } + } + + } + elseif($gp["name"] == 'Pengukuran' ){ + $perut[] = array( + "mm1" => $gp["name"], + "mm2" => $gp["details"][0]["label"]." : ".$gp["details"][0]["value"]." ".$gp["details"][0]["unit"], + "mm3" => $gp["details"][1]["label"]." : ".$gp["details"][1]["value"]." ".$gp["details"][1]["unit"] + ); + if ($rst_x != "") $rst_x .= ", ";{ + $rst_x .= $gp["details"][0]["label"]." : ".$gp["details"][0]["value"]." ".$gp["details"][0]["unit"] ; + $rst_x .= $gp["details"][1]["label"]." : ".$gp["details"][1]["value"]." ".$gp["details"][1]["unit"] ; + } + + } + + } + + + + + //echo $kesimpulan; + } elseif ($da["title"] == "GENITOURINARIA") { + $rst_x = ''; + foreach ($da["details"] as $db) { + if ($db["chx"] == "1" && $db["is_normal"] == "N" && $db["label"] != "Tidak diperiksa" && $db["label"] != "Lain-lain") { + if ($rst_x != "") $rst_x .= ", "; + $rst_x .= $db["label"] . " " . $db["value"]; + } + if ($db["label"] == "Lain-lain" && $db["chx"] == "1") { + if ($rst_x != "") $rst_x .= ", "; + $rst_x .= $db["value"]; + } + } + + if ($rst_x !== '') { + if ($kesimpulan != "") $kesimpulan .= "
"; + $kesimpulan .= ucwords(strtolower($da["title"])) . " : " . $rst_x; + } + } elseif ($da["title"] == "ANGGOTA GERAK") { + foreach ($da["details"] as $db) { + $s_res = ""; + foreach ($db["details"] as $dc) { + if ($dc["chx"] == "1" && $dc["is_normal"] == "N" && $dc["label"] != 'Lain-lain') { + if ($s_res != "") $s_res .= ", "; + $s_res .= "( " . $dc["label"] . " ) " . $dc["value"]; /* perubahan 180320 */ + } + if ($dc["label"] == 'Lain-lain' && $dc["chx"] == "1") { + if ($s_res != "") $s_res .= ", "; + $s_res .= $dc["value"]; + } + + $rows_summary = $this->get_kelainans($dc["id_code"]); + if(count($rows_summary) > 0){ + $kelainans = []; + foreach ($rows_summary as $key => $value) { + if($value['Mcu_SummaryFisikType'] == 'C' && $dc["chx"] == "1"){ + $kelainans[] = $value; + $all_kelainans[] = $value; + } + } + + if(count($kelainans) > 0){ + $this->insert_t_kelainan_fisik($kelainans,$order_header_id,$re_id); + } + } + } + if ($s_res != "") { + if ($kesimpulan != "") $kesimpulan .= "
"; + $kesimpulan .= $db["name"] . " : " . $s_res; + } + } + } elseif ($da["title"] == "SISTEM PERSYARAFAN") { + foreach ($da["details"] as $db) { + $s_res = ""; + foreach ($db["details"] as $dc) { + if ($dc["chx"] == "1" && $dc["is_normal"] == "N" && $dc["label"] != 'Lain-lain') { + if ($s_res != "") $s_res .= ", "; + $s_res .= "( " . $dc["label"] . " ) " . $dc["value"]; /* perubahan 180320 */ + } + if ($dc["label"] == 'Lain-lain' && $dc["chx"] == "1") { + if ($s_res != "") $s_res .= ", "; + $s_res .= $dc["value"]; + } + + $rows_summary = $this->get_kelainans($dc["id_code"]); + if(count($rows_summary) > 0){ + $kelainans = []; + foreach ($rows_summary as $key => $value) { + if($value['Mcu_SummaryFisikType'] == 'C' && $dc["chx"] == "1"){ + $kelainans[] = $value; + $all_kelainans[] = $value; + } + } + + if(count($kelainans) > 0){ + $this->insert_t_kelainan_fisik($kelainans,$order_header_id,$re_id); + } + } + } + if ($s_res != "") { + if ($kesimpulan != "") $kesimpulan .= "
"; + $kesimpulan .= $db["name"] . " : " . $s_res; + } + } + } elseif ($da["title"] == "SMELL TEST") { + foreach ($da["details"] as $db) { + $s_res = ""; + foreach ($db["details"] as $dc) { + if ($dc["chx"] == "1" && $dc["is_normal"] == "N" && $dc["label"] != 'Lain-lain') { + if ($s_res != "") $s_res .= ", "; + $s_res .= "( " . $dc["label"] . " ) " . $dc["value"]; /* perubahan 180320 */ + } + if ($dc["label"] == 'Lain-lain' && $dc["chx"] == "1") { + if ($s_res != "") $s_res .= ", "; + $s_res .= $dc["value"]; + } + + $rows_summary = $this->get_kelainans($dc["id_code"]); + if(count($rows_summary) > 0){ + $kelainans = []; + foreach ($rows_summary as $key => $value) { + if($value['Mcu_SummaryFisikType'] == 'C' && $dc["chx"] == "1"){ + $kelainans[] = $value; + $all_kelainans[] = $value; + } + } + + if(count($kelainans) > 0){ + $this->insert_t_kelainan_fisik($kelainans,$order_header_id,$re_id); + } + } + } + if ($s_res != "") { + if ($kesimpulan != "") $kesimpulan .= "
"; + $kesimpulan .= $db["name"] . " : " . $s_res; + } + } + } elseif ($da["title"] == "LOW BACK PAIN SCREENING TEST") { + foreach ($da["details"] as $db) { + $s_res = ""; + foreach ($db["details"] as $dc) { + if ($dc["chx"] == "1" && $dc["is_normal"] == "N" && $dc["label"] != 'Lain-lain') { + if ($s_res != "") $s_res .= ", "; + $s_res .= "( " . $dc["label"] . " ) " . $dc["value"]; /* perubahan 180320 */ + } + if ($dc["label"] == 'Lain-lain' && $dc["chx"] == "1") { + if ($s_res != "") $s_res .= ", "; + $s_res .= $dc["value"]; + } + + $rows_summary = $this->get_kelainans($dc["id_code"]); + if(count($rows_summary) > 0){ + $kelainans = []; + foreach ($rows_summary as $key => $value) { + if($value['Mcu_SummaryFisikType'] == 'C' && $dc["chx"] == "1"){ + $kelainans[] = $value; + $all_kelainans[] = $value; + } + } + + if(count($kelainans) > 0){ + $this->insert_t_kelainan_fisik($kelainans,$order_header_id,$re_id); + } + } + } + if ($s_res != "") { + if ($kesimpulan != "") $kesimpulan .= "
"; + $kesimpulan .= $db["name"] . " : " . $s_res; + } + } + //echo $kesimpulan; + } elseif ($da["title"] == "SISTEM INTEGUMEN") { + foreach ($da["details"] as $db) { + $s_res = ""; + foreach ($db["details"] as $dc) { + if ($dc["chx"] == "1" && $dc["is_normal"] == "N" && $dc["label"] != 'Lain-lain') { + if ($s_res != "") $s_res .= ", "; + $s_res .= "( " . $dc["label"] . " ) " . $dc["value"]; + } + if ($dc["label"] == 'Lain-lain' && $dc["chx"] == "1") { + if ($s_res != "") $s_res .= ", "; + $s_res .= $dc["value"]; + } + + $rows_summary = $this->get_kelainans($dc["id_code"]); + if(count($rows_summary) > 0){ + $kelainans = []; + foreach ($rows_summary as $key => $value) { + if($value['Mcu_SummaryFisikType'] == 'C' && $dc["chx"] == "1"){ + $kelainans[] = $value; + $all_kelainans[] = $value; + } + } + + if(count($kelainans) > 0){ + $this->insert_t_kelainan_fisik($kelainans,$order_header_id,$re_id); + } + } + } + if ($s_res != "") { + if ($kesimpulan != "") $kesimpulan .= "
"; + $kesimpulan .= $db["name"] . " : " . $s_res; + } + } + + //echo $kesimpulan; + + + + + } + } + + $rst_statusgizi = $this->status_gizi($id); + //print_r($rst_statusgizi); + $rows_summary = $this->get_kelainans("status_gizi_6"); + if(count($rows_summary) > 0){ + $kelainans = []; + foreach ($rows_summary as $key => $value) { + if($value['Mcu_SummaryFisikType'] == 'SD'){ + if($value['Mcu_KelainanName'] == $rst_statusgizi['xclassification']){ + $kelainans[] = $value; + $all_kelainans[] = $value; + } + } + } + + if(count($kelainans) > 0){ + $this->insert_t_kelainan_fisik($kelainans,$order_header_id,$re_id); + } + } + + $rst_persepsi_warna = $this->persepsi_warna($id); + $rows_summary = $this->get_kelainans("persepsi_warna_3"); + $persepsi_warna_hasil = "Normal"; + if($rst_persepsi_warna == 'BW'){ + $persepsi_warna_hasil = "Red Green Deficiency"; + } + + if(count($rows_summary) > 0){ + $kelainans = []; + foreach ($rows_summary as $key => $value) { + if($value['Mcu_SummaryFisikType'] == 'SD'){ + if($value['Mcu_KelainanName'] == $persepsi_warna_hasil){ + $kelainans[] = $value; + $all_kelainans[] = $value; + } + } + } + + if(count($kelainans) > 0){ + $this->insert_t_kelainan_fisik($kelainans,$order_header_id,$re_id); + } + } + + $rows_summary = $this->get_kelainans("visus"); + $rst_visus = $this->visus($id); + //print_r($rst_visus); + //echo $rst_visus['kelainan']; + + if(count($rows_summary) > 0){ + $kelainans = []; + foreach ($rows_summary as $key => $value) { + if($value['Mcu_SummaryFisikType'] == 'SD'){ + if($value['Mcu_KelainanName'] == $rst_visus['kelainan']){ + $kelainans[] = $value; + $all_kelainans[] = $value; + } + } + } + + if(count($kelainans) > 0){ + $this->insert_t_kelainan_fisik($kelainans,$order_header_id,$re_id); + } + } + + return $all_kelainans; + } +} diff --git a/application/libraries/Mcu.php b/application/libraries/Mcu.php new file mode 100644 index 00000000..ec9f5934 --- /dev/null +++ b/application/libraries/Mcu.php @@ -0,0 +1,14 @@ + Array( T_SampleTypeID + // + function export($param) { + $CI =& get_instance(); + $this->db = $CI->load->database("onedev",true); + foreach($param as $orderHeaderID => $samples ) { + $s_samples = impode(",",$samples); + } + } +} diff --git a/application/libraries/Mongo_db.php b/application/libraries/Mongo_db.php new file mode 100644 index 00000000..27fb66d2 --- /dev/null +++ b/application/libraries/Mongo_db.php @@ -0,0 +1,2020 @@ +CI =& get_instance(); + $this->CI->load->config('mongo_db'); + $this->config = $this->CI->config->item('mongo_db'); + $this->param = $param; + $this->connect(); + } + + /** + * -------------------------------------------------------------------------------- + * Class Destructor + * -------------------------------------------------------------------------------- + * + * Close all open connections. + */ + function __destruct() + { + if(is_object($this->connect)) + { + //$this->connect->close(); + } + } + + /** + * -------------------------------------------------------------------------------- + * Prepare configuration for mongoDB connection + * -------------------------------------------------------------------------------- + * + * Validate group name or autoload default group name from config file. + * Validate all the properties present in config file of the group. + */ + + private function prepare() + { + if(is_array($this->param) && count($this->param) > 0 && isset($this->param['activate']) == TRUE) + { + $this->activate = $this->param['activate']; + } + else if(isset($this->config['active']) && !empty($this->config['active'])) + { + $this->activate = $this->config['active']; + }else + { + show_error("MongoDB configuration is missing.", 500); + } + + if(isset($this->config[$this->activate]) == TRUE) + { + if(empty($this->config[$this->activate]['hostname'])) + { + show_error("Hostname missing from mongodb config group : {$this->activate}", 500); + } + else + { + $this->hostname = trim($this->config[$this->activate]['hostname']); + } + + if(empty($this->config[$this->activate]['port'])) + { + show_error("Port number missing from mongodb config group : {$this->activate}", 500); + } + else + { + $this->port = trim($this->config[$this->activate]['port']); + } + + if(isset($this->config[$this->activate]['no_auth']) == FALSE + && empty($this->config[$this->activate]['username'])) + { + show_error("Username missing from mongodb config group : {$this->activate}", 500); + } + else + { + $this->username = trim($this->config[$this->activate]['username']); + } + + if(isset($this->config[$this->activate]['no_auth']) == FALSE + && empty($this->config[$this->activate]['password'])) + { + show_error("Password missing from mongodb config group : {$this->activate}", 500); + } + else + { + $this->password = trim($this->config[$this->activate]['password']); + } + + if(empty($this->config[$this->activate]['database'])) + { + show_error("Database name missing from mongodb config group : {$this->activate}", 500); + } + else + { + $this->database = trim($this->config[$this->activate]['database']); + } + + if(empty($this->config[$this->activate]['db_debug'])) + { + $this->debug = FALSE; + } + else + { + $this->debug = $this->config[$this->activate]['db_debug']; + } + + if(empty($this->config[$this->activate]['return_as'])) + { + $this->return_as = 'array'; + } + else + { + $this->return_as = $this->config[$this->activate]['return_as']; + } + + if(empty($this->config[$this->activate]['legacy_support'])) + { + $this->legacy_support = false; + } + else + { + $this->legacy_support = $this->config[$this->activate]['legacy_support']; + } + + if(empty($this->config[$this->activate]['read_preference']) || + !isset($this->config[$this->activate]['read_preference'])) + { + $this->read_preference = MongoDB\Driver\ReadPreference::RP_PRIMARY; + } + else + { + $this->read_preference = $this->config[$this->activate]['read_preference']; + } + + if(empty($this->config[$this->activate]['read_concern']) || + !isset($this->config[$this->activate]['read_concern'])) + { + $this->read_concern = MongoDB\Driver\ReadConcern::MAJORITY; + } + else + { + $this->read_concern = $this->config[$this->activate]['read_concern']; + } + + + } + else + { + show_error("mongodb config group : {$this->activate} does not exist.", 500); + } + } + + /** + * Sets the return as to object or array + * This is useful if library is used in another library to avoid issue if config values are different + * + * @param string $value + */ + public function set_return_as($value) + { + if(!in_array($value, ['array', 'object'])) + { + show_error("Invalid Return As Type"); + } + $this->return_as = $value; + } + + /** + * -------------------------------------------------------------------------------- + * Connect to MongoDB Database + * -------------------------------------------------------------------------------- + * + * Connect to mongoDB database or throw exception with the error message. + */ + + private function connect() + { + $this->prepare(); + try + { + $dns = "mongodb://{$this->hostname}:{$this->port}/{$this->database}"; + if(isset($this->config[$this->activate]['no_auth']) == TRUE && $this->config[$this->activate]['no_auth'] == TRUE) + { + $options = array(); + } + else + { + $options = array('username'=>$this->username, 'password'=>$this->password); + } + + $this->connect = $this->db = new MongoDB\Driver\Manager($dns, $options); + + } + catch (MongoDB\Driver\Exception\Exception $e) + { + if(isset($this->debug) == TRUE && $this->debug == TRUE) + { + show_error("Unable to connect to MongoDB: {$e->getMessage()}", 500); + } + else + { + show_error("Unable to connect to MongoDB", 500); + } + } + } + + /** + * -------------------------------------------------------------------------------- + * //! Insert + * -------------------------------------------------------------------------------- + * + * Insert a new document into the passed collection + * + * @usage : $this->mongo_db->insert('foo', $data = array()); + */ + public function insert($collection = "", $insert = array()) + { + if (empty($collection)) + { + show_error("No Mongo collection selected to insert into", 500); + } + + if (!is_array($insert) || count($insert) == 0) + { + show_error("Nothing to insert into Mongo collection or insert is not an array", 500); + } + + if(isset($insert['_id']) === false) + { + $insert['_id'] = new MongoDB\BSON\ObjectId; + } + + $bulk = new MongoDB\Driver\BulkWrite(); + $bulk->insert($insert); + + $writeConcern = new MongoDB\Driver\WriteConcern(MongoDB\Driver\WriteConcern::MAJORITY, 1000); + + try + { + $write = $this->db->executeBulkWrite($this->database.".".$collection, $bulk, $writeConcern); + return $this->convert_document_id($insert); + } + // Check if the write concern could not be fulfilled + catch (MongoDB\Driver\Exception\BulkWriteException $e) + { + $result = $e->getWriteResult(); + + if ($writeConcernError = $result->getWriteConcernError()) + { + if(isset($this->debug) == TRUE && $this->debug == TRUE) + { + show_error("WriteConcern failure : {$writeConcernError->getMessage()}", 500); + } + else + { + show_error("WriteConcern failure", 500); + } + } + } + // Check if any general error occured. + catch (MongoDB\Driver\Exception\Exception $e) + { + if(isset($this->debug) == TRUE && $this->debug == TRUE) + { + show_error("Insert of data into MongoDB failed: {$e->getMessage()}", 500); + } + else + { + show_error("Insert of data into MongoDB failed", 500); + } + } + } + + /** + * -------------------------------------------------------------------------------- + * Batch Insert + * -------------------------------------------------------------------------------- + * + * Insert a multiple document into the collection + * + * @usage : $this->mongo_db->batch_insert('foo', $data = array()); + * @return : bool or array : if query fail then false else array of _id successfully inserted. + */ + public function batch_insert($collection = "", $insert = array()) + { + if (empty($collection)) + { + show_error("No Mongo collection selected to insert into", 500); + } + + if (!is_array($insert) || count($insert) == 0) + { + show_error("Nothing to insert into Mongo collection or insert is not an array", 500); + } + + $doc = new MongoDB\Driver\BulkWrite(); + + foreach ($insert as $ins) + { + if(isset($ins['_id']) === false) + { + $ins['_id'] = new MongoDB\BSON\ObjectId; + } + $doc->insert($ins); + } + + $writeConcern = new MongoDB\Driver\WriteConcern(MongoDB\Driver\WriteConcern::MAJORITY, 1000); + + try + { + $result = $this->db->executeBulkWrite($this->database.".".$collection, $doc, $writeConcern); + return $result; + } + // Check if the write concern could not be fulfilled + catch (MongoDB\Driver\Exception\BulkWriteException $e) + { + $result = $e->getWriteResult(); + + if ($writeConcernError = $result->getWriteConcernError()) + { + if(isset($this->debug) == TRUE && $this->debug == TRUE) + { + show_error("WriteConcern failure : {$writeConcernError->getMessage()}", 500); + } + else + { + show_error("WriteConcern failure", 500); + } + } + } + // Check if any general error occured. + catch (MongoDB\Driver\Exception\Exception $e) + { + if(isset($this->debug) == TRUE && $this->debug == TRUE) + { + show_error("Insert of data into MongoDB failed: {$e->getMessage()}", 500); + } + else + { + show_error("Insert of data into MongoDB failed", 500); + } + } + } + + /** + * -------------------------------------------------------------------------------- + * //! Select + * -------------------------------------------------------------------------------- + * + * Determine which fields to include OR which to exclude during the query process. + * If you want to only choose fields to exclude, leave $includes an empty array(). + * + * @usage: $this->mongo_db->select(array('foo', 'bar'))->get('foobar'); + */ + public function select($includes = array(), $excludes = array()) + { + if ( ! is_array($includes)) + { + $includes = array(); + } + if ( ! is_array($excludes)) + { + $excludes = array(); + } + if ( ! empty($includes)) + { + foreach ($includes as $key=> $col) + { + if(is_array($col)){ + //support $elemMatch in select + $this->selects[$key] = $col; + }else{ + $this->selects[$col] = 1; + } + } + } + if ( ! empty($excludes)) + { + foreach ($excludes as $col) + { + $this->selects[$col] = 0; + } + } + return ($this); + } + + /** + * -------------------------------------------------------------------------------- + * //! Where + * -------------------------------------------------------------------------------- + * + * Get the documents based on these search parameters. The $wheres array should + * be an associative array with the field as the key and the value as the search + * criteria. + * + * @usage : $this->mongo_db->where(array('foo' => 'bar'))->get('foobar'); + */ + public function where($wheres, $value = null) + { + if (is_array($wheres)) + { + foreach ($wheres as $wh => $val) + { + $this->wheres[$wh] = $val; + } + } + else + { + $this->wheres[$wheres] = $value; + } + return $this; + } + + /** + * -------------------------------------------------------------------------------- + * or where + * -------------------------------------------------------------------------------- + * + * Get the documents where the value of a $field may be something else + * + * @usage : $this->mongo_db->where_or(array('foo'=>'bar', 'bar'=>'foo'))->get('foobar'); + */ + public function where_or($wheres = array()) + { + if (is_array($wheres) && count($wheres) > 0) + { + if ( ! isset($this->wheres['$or']) || ! is_array($this->wheres['$or'])) + { + $this->wheres['$or'] = array(); + } + foreach ($wheres as $wh => $val) + { + $this->wheres['$or'][] = array($wh=>$val); + } + return ($this); + } + else + { + show_error("Where value should be an array.", 500); + } + } + + /** + * -------------------------------------------------------------------------------- + * Where in + * -------------------------------------------------------------------------------- + * + * Get the documents where the value of a $field is in a given $in array(). + * + * @usage : $this->mongo_db->where_in('foo', array('bar', 'zoo', 'blah'))->get('foobar'); + */ + public function where_in($field = "", $in = array()) + { + if (empty($field)) + { + show_error("Mongo field is require to perform where in query.", 500); + } + + if (is_array($in) && count($in) > 0) + { + $this->_w($field); + $this->wheres[$field]['$in'] = $in; + return ($this); + } + else + { + show_error("in value should be an array.", 500); + } + } + + /** + * -------------------------------------------------------------------------------- + * Where in all + * -------------------------------------------------------------------------------- + * + * Get the documents where the value of a $field is in all of a given $in array(). + * + * @usage : $this->mongo_db->where_in_all('foo', array('bar', 'zoo', 'blah'))->get('foobar'); + */ + public function where_in_all($field = "", $in = array()) + { + if (empty($field)) + { + show_error("Mongo field is require to perform where all in query.", 500); + } + + if (is_array($in) && count($in) > 0) + { + $this->_w($field); + $this->wheres[$field]['$all'] = $in; + return ($this); + } + else + { + show_error("in value should be an array.", 500); + } + } + + /** + * -------------------------------------------------------------------------------- + * Where not in + * -------------------------------------------------------------------------------- + * + * Get the documents where the value of a $field is not in a given $in array(). + * + * @usage : $this->mongo_db->where_not_in('foo', array('bar', 'zoo', 'blah'))->get('foobar'); + */ + public function where_not_in($field = "", $in = array()) + { + if (empty($field)) + { + show_error("Mongo field is require to perform where not in query.", 500); + } + + if (is_array($in) && count($in) > 0) + { + $this->_w($field); + $this->wheres[$field]['$nin'] = $in; + return ($this); + } + else + { + show_error("in value should be an array.", 500); + } + } + + /** + * -------------------------------------------------------------------------------- + * Where greater than + * -------------------------------------------------------------------------------- + * + * Get the documents where the value of a $field is greater than $x + * + * @usage : $this->mongo_db->where_gt('foo', 20); + */ + public function where_gt($field = "", $x) + { + if (!isset($field)) + { + show_error("Mongo field is require to perform greater then query.", 500); + } + + if (!isset($x)) + { + show_error("Mongo field's value is require to perform greater then query.", 500); + } + + $this->_w($field); + $this->wheres[$field]['$gt'] = $x; + return ($this); + } + + /** + * -------------------------------------------------------------------------------- + * Where greater than or equal to + * -------------------------------------------------------------------------------- + * + * Get the documents where the value of a $field is greater than or equal to $x + * + * @usage : $this->mongo_db->where_gte('foo', 20); + */ + public function where_gte($field = "", $x) + { + if (!isset($field)) + { + show_error("Mongo field is require to perform greater then or equal query.", 500); + } + + if (!isset($x)) + { + show_error("Mongo field's value is require to perform greater then or equal query.", 500); + } + + $this->_w($field); + $this->wheres[$field]['$gte'] = $x; + return($this); + } + + /** + * -------------------------------------------------------------------------------- + * Where less than + * -------------------------------------------------------------------------------- + * + * Get the documents where the value of a $field is less than $x + * + * @usage : $this->mongo_db->where_lt('foo', 20); + */ + public function where_lt($field = "", $x) + { + if (!isset($field)) + { + show_error("Mongo field is require to perform less then query.", 500); + } + + if (!isset($x)) + { + show_error("Mongo field's value is require to perform less then query.", 500); + } + + $this->_w($field); + $this->wheres[$field]['$lt'] = $x; + return($this); + } + + /** + * -------------------------------------------------------------------------------- + * Where less than or equal to + * -------------------------------------------------------------------------------- + * + * Get the documents where the value of a $field is less than or equal to $x + * + * @usage : $this->mongo_db->where_lte('foo', 20); + */ + public function where_lte($field = "", $x) + { + if (!isset($field)) + { + show_error("Mongo field is require to perform less then or equal to query.", 500); + } + + if (!isset($x)) + { + show_error("Mongo field's value is require to perform less then or equal to query.", 500); + } + + $this->_w($field); + $this->wheres[$field]['$lte'] = $x; + return ($this); + } + + /** + * -------------------------------------------------------------------------------- + * Where between + * -------------------------------------------------------------------------------- + * + * Get the documents where the value of a $field is between $x and $y + * + * @usage : $this->mongo_db->where_between('foo', 20, 30); + */ + public function where_between($field = "", $x, $y) + { + if (!isset($field)) + { + show_error("Mongo field is require to perform greater then or equal to query.", 500); + } + + if (!isset($x)) + { + show_error("Mongo field's start value is require to perform greater then or equal to query.", 500); + } + + if (!isset($y)) + { + show_error("Mongo field's end value is require to perform greater then or equal to query.", 500); + } + + $this->_w($field); + $this->wheres[$field]['$gte'] = $x; + $this->wheres[$field]['$lte'] = $y; + return ($this); + } + + /** + * -------------------------------------------------------------------------------- + * Where between and but not equal to + * -------------------------------------------------------------------------------- + * + * Get the documents where the value of a $field is between but not equal to $x and $y + * + * @usage : $this->mongo_db->where_between_ne('foo', 20, 30); + */ + public function where_between_ne($field = "", $x, $y) + { + if (!isset($field)) + { + show_error("Mongo field is require to perform between and but not equal to query.", 500); + } + + if (!isset($x)) + { + show_error("Mongo field's start value is require to perform between and but not equal to query.", 500); + } + + if (!isset($y)) + { + show_error("Mongo field's end value is require to perform between and but not equal to query.", 500); + } + + $this->_w($field); + $this->wheres[$field]['$gt'] = $x; + $this->wheres[$field]['$lt'] = $y; + return ($this); + } + + /** + * -------------------------------------------------------------------------------- + * Where not equal + * -------------------------------------------------------------------------------- + * + * Get the documents where the value of a $field is not equal to $x + * + * @usage : $this->mongo_db->where_ne('foo', 1)->get('foobar'); + */ + public function where_ne($field = '', $x) + { + if (!isset($field)) + { + show_error("Mongo field is require to perform Where not equal to query.", 500); + } + + if (!isset($x)) + { + show_error("Mongo field's value is require to perform Where not equal to query.", 500); + } + + $this->_w($field); + $this->wheres[$field]['$ne'] = $x; + return ($this); + } + + /** + * -------------------------------------------------------------------------------- + * Like + * -------------------------------------------------------------------------------- + * + * Get the documents where the (string) value of a $field is like a value. The defaults + * allow for a case-insensitive search. + * + * @param $flags + * Allows for the typical regular expression flags: + * i = case insensitive + * m = multiline + * x = can contain comments + * l = locale + * s = dotall, "." matches everything, including newlines + * u = match unicode + * + * @param $enable_start_wildcard + * If set to anything other than TRUE, a starting line character "^" will be prepended + * to the search value, representing only searching for a value at the start of + * a new line. + * + * @param $enable_end_wildcard + * If set to anything other than TRUE, an ending line character "$" will be appended + * to the search value, representing only searching for a value at the end of + * a line. + * + * @usage : $this->mongo_db->like('foo', 'bar', 'im', FALSE, TRUE); + */ + public function like($field = "", $value = "", $flags = "i", $enable_start_wildcard = TRUE, $enable_end_wildcard = TRUE) + { + if (empty($field)) + { + show_error("Mongo field is require to perform like query.", 500); + } + + if (empty($value)) + { + show_error("Mongo field's value is require to like query.", 500); + } + + $field = (string) trim($field); + $this->_w($field); + $value = (string) trim($value); + $value = quotemeta($value); + if ($enable_start_wildcard !== TRUE) + { + $value = "^" . $value; + } + if ($enable_end_wildcard !== TRUE) + { + $value .= "$"; + } + $regex = "/$value/$flags"; + $this->wheres[$field] = new MongoRegex($regex); + return ($this); + } + + /** + * -------------------------------------------------------------------------------- + * // Get + * -------------------------------------------------------------------------------- + * + * Get the documents based upon the passed parameters + * + * @usage : $this->mongo_db->get('foo'); + */ + public function get($collection = "") + { + if (empty($collection)) + { + show_error("In order to retrieve documents from MongoDB, a collection name must be passed", 500); + } + + try{ + + $read_concern = new MongoDB\Driver\ReadConcern($this->read_concern); + $read_preference = new MongoDB\Driver\ReadPreference($this->read_preference); + + $options = array(); + $options['projection'] = $this->selects; + $options['sort'] = $this->sorts; + $options['skip'] = (int) $this->offset; + $options['limit'] = (int) $this->limit; + $options['readConcern'] = $read_concern; + + $query = new MongoDB\Driver\Query($this->wheres, $options); + $cursor = $this->db->executeQuery($this->database.".".$collection, $query, $read_preference); + + // Clear + $this->_clear(); + $returns = array(); + + if ($cursor instanceof MongoDB\Driver\Cursor) + { + $it = new \IteratorIterator($cursor); + $it->rewind(); + + while ($doc = (array)$it->current()) + { + if ($this->return_as == 'object') + { + $returns[] = (object) $this->convert_document_id($doc); + } + else + { + $returns[] = (array) $this->convert_document_id($doc); + } + $it->next(); + } + } + + if ($this->return_as == 'object') + { + return (object)$returns; + } + else + { + return $returns; + } + } + catch (MongoDB\Driver\Exception $e) + { + if(isset($this->debug) == TRUE && $this->debug == TRUE) + { + show_error("MongoDB query failed: {$e->getMessage()}", 500); + } + else + { + show_error("MongoDB query failed.", 500); + } + } + } + + /** + * -------------------------------------------------------------------------------- + * // Get where + * -------------------------------------------------------------------------------- + * + * Get the documents based upon the passed parameters + * + * @usage : $this->mongo_db->get_where('foo', array('bar' => 'something')); + */ + public function get_where($collection = "", $where = array()) + { + if (is_array($where) && count($where) > 0) + { + return $this->where($where) + ->get($collection); + } + else + { + show_error("Nothing passed to perform search or value is empty.", 500); + } + } + + /** + * -------------------------------------------------------------------------------- + * // Find One + * -------------------------------------------------------------------------------- + * + * Get the single document based upon the passed parameters + * + * @usage : $this->mongo_db->find_one('foo'); + */ + public function find_one($collection = "") + { + + if (empty($collection)) + { + show_error("In order to retrieve documents from MongoDB, a collection name must be passed", 500); + } + + try{ + + $read_concern = new MongoDB\Driver\ReadConcern($this->read_concern); + $read_preference = new MongoDB\Driver\ReadPreference($this->read_preference); + + $options = array(); + $options['projection'] = $this->selects; + $options['sort'] = $this->sorts; + $options['skip'] = (int) $this->offset; + $options['limit'] = (int) 1; + $options['readConcern'] = $read_concern; + + $query = new MongoDB\Driver\Query($this->wheres, $options); + $cursor = $this->db->executeQuery($this->database.".".$collection, $query, $read_preference); + + // Clear + $this->_clear(); + $returns = array(); + + if ($cursor instanceof MongoDB\Driver\Cursor) + { + $it = new \IteratorIterator($cursor); + $it->rewind(); + + while ($doc = (array)$it->current()) + { + if ($this->return_as == 'object') + { + $returns[] = (object) $this->convert_document_id($doc); + } + else + { + $returns[] = (array) $this->convert_document_id($doc); + } + $it->next(); + } + } + + if ($this->return_as == 'object') + { + return (object)$returns; + } + else + { + return $returns; + } + } + catch (MongoDB\Driver\Exception $e) + { + if(isset($this->debug) == TRUE && $this->debug == TRUE) + { + show_error("MongoDB query failed: {$e->getMessage()}", 500); + } + else + { + show_error("MongoDB query failed.", 500); + } + } + } + + /** + * -------------------------------------------------------------------------------- + * Count + * -------------------------------------------------------------------------------- + * + * Count the documents based upon the passed parameters + * + * @usage : $this->mongo_db->count('foo'); + */ + public function count($collection = "") + { + if (empty($collection)) + { + show_error("In order to retrieve documents from MongoDB, a collection name must be passed", 500); + } + + try{ + + $read_concern = new MongoDB\Driver\ReadConcern($this->read_concern); + $read_preference = new MongoDB\Driver\ReadPreference($this->read_preference); + + $options = array(); + $options['projection'] = array('_id'=>1); + $options['sort'] = $this->sorts; + $options['skip'] = (int) $this->offset; + $options['limit'] = (int) $this->limit; + $options['readConcern'] = $read_concern; + + $query = new MongoDB\Driver\Query($this->wheres, $options); + $cursor = $this->db->executeQuery($this->database.".".$collection, $query, $read_preference); + $array = $cursor->toArray(); + // Clear + $this->_clear(); + return count($array); + } + catch (MongoDB\Driver\Exception $e) + { + if(isset($this->debug) == TRUE && $this->debug == TRUE) + { + show_error("MongoDB query failed: {$e->getMessage()}", 500); + } + else + { + show_error("MongoDB query failed.", 500); + } + } + } + + /** + * -------------------------------------------------------------------------------- + * Count All Results + * -------------------------------------------------------------------------------- + * + * Alias to count method for compatibility with CI Query Builder + * + * @usage : $this->mongo_db->count('foo'); + */ + public function count_all_results($collection = "") + { + return $this->count($collection); + } + + /** + * -------------------------------------------------------------------------------- + * Set + * -------------------------------------------------------------------------------- + * + * Sets a field to a value + * + * @usage: $this->mongo_db->where(array('blog_id'=>123))->set('posted', 1)->update('blog_posts'); + * @usage: $this->mongo_db->where(array('blog_id'=>123))->set(array('posted' => 1, 'time' => time()))->update('blog_posts'); + */ + public function set($fields, $value = NULL) + { + $this->_u('$set'); + if (is_string($fields)) + { + $this->updates['$set'][$fields] = $value; + } + elseif (is_array($fields)) + { + foreach ($fields as $field => $value) + { + $this->updates['$set'][$field] = $value; + } + } + return $this; + } + + /** + * -------------------------------------------------------------------------------- + * Unset + * -------------------------------------------------------------------------------- + * + * Unsets a field (or fields) + * + * @usage: $this->mongo_db->where(array('blog_id'=>123))->unset('posted')->update('blog_posts'); + * @usage: $this->mongo_db->where(array('blog_id'=>123))->set(array('posted','time'))->update('blog_posts'); + */ + public function unset_field($fields) + { + $this->_u('$unset'); + if (is_string($fields)) + { + $this->updates['$unset'][$fields] = 1; + } + elseif (is_array($fields)) + { + foreach ($fields as $field) + { + $this->updates['$unset'][$field] = 1; + } + } + return $this; + } + + /** + * -------------------------------------------------------------------------------- + * Add to set + * -------------------------------------------------------------------------------- + * + * Adds value to the array only if its not in the array already + * + * @usage: $this->mongo_db->where(array('blog_id'=>123))->addtoset('tags', 'php')->update('blog_posts'); + * @usage: $this->mongo_db->where(array('blog_id'=>123))->addtoset('tags', array('php', 'codeigniter', 'mongodb'))->update('blog_posts'); + */ + public function addtoset($field, $values) + { + $this->_u('$addToSet'); + if (is_string($values)) + { + $this->updates['$addToSet'][$field] = $values; + } + elseif (is_array($values)) + { + $this->updates['$addToSet'][$field] = array('$each' => $values); + } + return $this; + } + + /** + * -------------------------------------------------------------------------------- + * Push + * -------------------------------------------------------------------------------- + * + * Pushes values into a field (field must be an array) + * + * @usage: $this->mongo_db->where(array('blog_id'=>123))->push('comments', array('text'=>'Hello world'))->update('blog_posts'); + * @usage: $this->mongo_db->where(array('blog_id'=>123))->push(array('comments' => array('text'=>'Hello world')), 'viewed_by' => array('Alex')->update('blog_posts'); + */ + public function push($fields, $value = array()) + { + $this->_u('$push'); + if (is_string($fields)) + { + $this->updates['$push'][$fields] = $value; + } + elseif (is_array($fields)) + { + foreach ($fields as $field => $value) + { + $this->updates['$push'][$field] = $value; + } + } + return $this; + } + + /** + * -------------------------------------------------------------------------------- + * Pop + * -------------------------------------------------------------------------------- + * + * Pops the last value from a field (field must be an array) + * + * @usage: $this->mongo_db->where(array('blog_id'=>123))->pop('comments')->update('blog_posts'); + * @usage: $this->mongo_db->where(array('blog_id'=>123))->pop(array('comments', 'viewed_by'))->update('blog_posts'); + */ + public function pop($field) + { + $this->_u('$pop'); + if (is_string($field)) + { + $this->updates['$pop'][$field] = -1; + } + elseif (is_array($field)) + { + foreach ($field as $pop_field) + { + $this->updates['$pop'][$pop_field] = -1; + } + } + return $this; + } + + /** + * -------------------------------------------------------------------------------- + * Pull + * -------------------------------------------------------------------------------- + * + * Removes by an array by the value of a field + * + * @usage: $this->mongo_db->pull('comments', array('comment_id'=>123))->update('blog_posts'); + */ + public function pull($field = "", $value = array()) + { + $this->_u('$pull'); + $this->updates['$pull'] = array($field => $value); + return $this; + } + + /** + * -------------------------------------------------------------------------------- + * Rename field + * -------------------------------------------------------------------------------- + * + * Renames a field + * + * @usage: $this->mongo_db->where(array('blog_id'=>123))->rename_field('posted_by', 'author')->update('blog_posts'); + */ + public function rename_field($old, $new) + { + $this->_u('$rename'); + $this->updates['$rename'] = array($old => $new); + return $this; + } + + /** + * -------------------------------------------------------------------------------- + * Inc + * -------------------------------------------------------------------------------- + * + * Increments the value of a field + * + * @usage: $this->mongo_db->where(array('blog_id'=>123))->inc(array('num_comments' => 1))->update('blog_posts'); + */ + public function inc($fields = array(), $value = 0) + { + $this->_u('$inc'); + if (is_string($fields)) + { + $this->updates['$inc'][$fields] = $value; + } + elseif (is_array($fields)) + { + foreach ($fields as $field => $value) + { + $this->updates['$inc'][$field] = $value; + } + } + return $this; + } + + /** + * -------------------------------------------------------------------------------- + * Multiple + * -------------------------------------------------------------------------------- + * + * Multiple the value of a field + * + * @usage: $this->mongo_db->where(array('blog_id'=>123))->mul(array('num_comments' => 3))->update('blog_posts'); + */ + public function mul($fields = array(), $value = 0) + { + $this->_u('$mul'); + if (is_string($fields)) + { + $this->updates['$mul'][$fields] = $value; + } + elseif (is_array($fields)) + { + foreach ($fields as $field => $value) + { + $this->updates['$mul'][$field] = $value; + } + } + return $this; + } + + /** + * -------------------------------------------------------------------------------- + * Maximum + * -------------------------------------------------------------------------------- + * + * The $max operator updates the value of the field to a specified value if the specified value is greater than the current value of the field. + * + * @usage: $this->mongo_db->where(array('blog_id'=>123))->max(array('num_comments' => 3))->update('blog_posts'); + */ + public function max($fields = array(), $value = 0) + { + $this->_u('$max'); + if (is_string($fields)) + { + $this->updates['$max'][$fields] = $value; + } + elseif (is_array($fields)) + { + foreach ($fields as $field => $value) + { + $this->updates['$max'][$field] = $value; + } + } + return $this; + } + + /** + * -------------------------------------------------------------------------------- + * Minimum + * -------------------------------------------------------------------------------- + * + * The $min updates the value of the field to a specified value if the specified value is less than the current value of the field. + * + * @usage: $this->mongo_db->where(array('blog_id'=>123))->min(array('num_comments' => 3))->update('blog_posts'); + */ + public function min($fields = array(), $value = 0) + { + $this->_u('$min'); + if (is_string($fields)) + { + $this->updates['$min'][$fields] = $value; + } + elseif (is_array($fields)) + { + foreach ($fields as $field => $value) + { + $this->updates['$min'][$field] = $value; + } + } + return $this; + } + + /** + * -------------------------------------------------------------------------------- + * //! distinct + * -------------------------------------------------------------------------------- + * + * Finds the distinct values for a specified field across a single collection + * + * @usage: $this->mongo_db->distinct('collection', 'field'); + */ + public function distinct($collection = "", $field="") + { + if (empty($collection)) + { + show_error("No Mongo collection selected for update", 500); + } + + if (empty($field)) + { + show_error("Need Collection field information for performing distinct query", 500); + } + + try + { + $documents = $this->db->{$collection}->distinct($field, $this->wheres); + $this->_clear(); + if ($this->return_as == 'object') + { + return (object)$documents; + } + else + { + return $documents; + } + } + catch (MongoCursorException $e) + { + if(isset($this->debug) == TRUE && $this->debug == TRUE) + { + show_error("MongoDB Distinct Query Failed: {$e->getMessage()}", 500); + } + else + { + show_error("MongoDB failed", 500); + } + } + } + + /** + * -------------------------------------------------------------------------------- + * //! Update + * -------------------------------------------------------------------------------- + * + * Updates a single document in Mongo + * + * @usage: $this->mongo_db->update('foo', $data = array()); + */ + public function update($collection = "", $options = array()) + { + if (empty($collection)) + { + show_error("No Mongo collection selected for update", 500); + } + + $bulk = new MongoDB\Driver\BulkWrite(); + $bulk->update($this->wheres, $this->updates, $options); + + $writeConcern = new MongoDB\Driver\WriteConcern(MongoDB\Driver\WriteConcern::MAJORITY, 1000); + + try + { + $write = $this->db->executeBulkWrite($this->database.".".$collection, $bulk, $writeConcern); + $this->_clear(); + return $write; + } + // Check if the write concern could not be fulfilled + catch (MongoDB\Driver\Exception\BulkWriteException $e) + { + $result = $e->getWriteResult(); + + if ($writeConcernError = $result->getWriteConcernError()) + { + if(isset($this->debug) == TRUE && $this->debug == TRUE) + { + show_error("WriteConcern failure : {$writeConcernError->getMessage()}", 500); + } + else + { + show_error("WriteConcern failure", 500); + } + } + } + // Check if any general error occured. + catch (MongoDB\Driver\Exception\Exception $e) + { + if(isset($this->debug) == TRUE && $this->debug == TRUE) + { + show_error("Update of data into MongoDB failed: {$e->getMessage()}", 500); + } + else + { + show_error("Update of data into MongoDB failed", 500); + } + } + } + + /** + * -------------------------------------------------------------------------------- + * Update all + * -------------------------------------------------------------------------------- + * + * Updates a collection of documents + * + * @usage: $this->mongo_db->update_all('foo', $data = array()); + */ + public function update_all($collection = "", $data = array(), $options = array()) + { + if (empty($collection)) + { + show_error("No Mongo collection selected to update", 500); + } + if (is_array($data) && count($data) > 0) + { + $this->updates = array_merge($data, $this->updates); + } + if (count($this->updates) == 0) + { + show_error("Nothing to update in Mongo collection or update is not an array", 500); + } + + $options = array_merge(array('multi' => TRUE), $options); + + $bulk = new MongoDB\Driver\BulkWrite(); + $bulk->update($this->wheres, $this->updates, $options); + + $writeConcern = new MongoDB\Driver\WriteConcern(MongoDB\Driver\WriteConcern::MAJORITY, 1000); + + try + { + $write = $this->db->executeBulkWrite($this->database.".".$collection, $bulk, $writeConcern); + $this->_clear(); + return $write; + } + // Check if the write concern could not be fulfilled + catch (MongoDB\Driver\Exception\BulkWriteException $e) + { + $result = $e->getWriteResult(); + + if ($writeConcernError = $result->getWriteConcernError()) + { + if(isset($this->debug) == TRUE && $this->debug == TRUE) + { + show_error("WriteConcern failure : {$writeConcernError->getMessage()}", 500); + } + else + { + show_error("WriteConcern failure", 500); + } + } + } + // Check if any general error occured. + catch (MongoDB\Driver\Exception\Exception $e) + { + if(isset($this->debug) == TRUE && $this->debug == TRUE) + { + show_error("Update of data into MongoDB failed: {$e->getMessage()}", 500); + } + else + { + show_error("Update of data into MongoDB failed", 500); + } + } + } + + /** + * -------------------------------------------------------------------------------- + * //! Delete + * -------------------------------------------------------------------------------- + * + * delete document from the passed collection based upon certain criteria + * + * @usage : $this->mongo_db->delete('foo'); + */ + public function delete($collection = "") + { + if (empty($collection)) + { + show_error("No Mongo collection selected for update", 500); + } + + $options = array('limit'=>true); + $bulk = new MongoDB\Driver\BulkWrite(); + $bulk->delete($this->wheres, $options); + + $writeConcern = new MongoDB\Driver\WriteConcern(MongoDB\Driver\WriteConcern::MAJORITY, 1000); + + try + { + $write = $this->db->executeBulkWrite($this->database.".".$collection, $bulk, $writeConcern); + $this->_clear(); + return $write; + } + // Check if the write concern could not be fulfilled + catch (MongoDB\Driver\Exception\BulkWriteException $e) + { + $result = $e->getWriteResult(); + + if ($writeConcernError = $result->getWriteConcernError()) + { + if(isset($this->debug) == TRUE && $this->debug == TRUE) + { + show_error("WriteConcern failure : {$writeConcernError->getMessage()}", 500); + } + else + { + show_error("WriteConcern failure", 500); + } + } + } + // Check if any general error occured. + catch (MongoDB\Driver\Exception\Exception $e) + { + if(isset($this->debug) == TRUE && $this->debug == TRUE) + { + show_error("Update of data into MongoDB failed: {$e->getMessage()}", 500); + } + else + { + show_error("Update of data into MongoDB failed", 500); + } + } + } + + /** + * -------------------------------------------------------------------------------- + * Delete all + * -------------------------------------------------------------------------------- + * + * Delete all documents from the passed collection based upon certain criteria + * + * @usage : $this->mongo_db->delete_all('foo', $data = array()); + */ + public function delete_all($collection = "") + { + if (empty($collection)) + { + show_error("No Mongo collection selected for delete", 500); + } + + $options = array('limit'=>false); + $bulk = new MongoDB\Driver\BulkWrite(); + $bulk->delete($this->wheres, $options); + + $writeConcern = new MongoDB\Driver\WriteConcern(MongoDB\Driver\WriteConcern::MAJORITY, 1000); + + try + { + $write = $this->db->executeBulkWrite($this->database.".".$collection, $bulk, $writeConcern); + $this->_clear(); + return $write; + } + // Check if the write concern could not be fulfilled + catch (MongoDB\Driver\Exception\BulkWriteException $e) + { + $result = $e->getWriteResult(); + + if ($writeConcernError = $result->getWriteConcernError()) + { + if(isset($this->debug) == TRUE && $this->debug == TRUE) + { + show_error("WriteConcern failure : {$writeConcernError->getMessage()}", 500); + } + else + { + show_error("WriteConcern failure", 500); + } + } + } + // Check if any general error occured. + catch (MongoDB\Driver\Exception\Exception $e) + { + if(isset($this->debug) == TRUE && $this->debug == TRUE) + { + show_error("Delete of data into MongoDB failed: {$e->getMessage()}", 500); + } + else + { + show_error("Delete of data into MongoDB failed", 500); + } + } + } + + /** + * -------------------------------------------------------------------------------- + * Aggregation Operation + * -------------------------------------------------------------------------------- + * + * Perform aggregation on mongodb collection + * + * @usage : $this->mongo_db->aggregate('foo', $ops = array()); + */ + public function aggregate($collection, $operation) + { + if (empty($collection)) + { + show_error("In order to retreive documents from MongoDB, a collection name must be passed", 500); + } + + if (empty($operation) && !is_array($operation)) + { + show_error("Operation must be an array to perform aggregate.", 500); + } + + $command = array('aggregate'=>$collection, 'pipeline'=>$operation); + return $this->command($command); + } + + /** + * -------------------------------------------------------------------------------- + * // Order by + * -------------------------------------------------------------------------------- + * + * Sort the documents based on the parameters passed. To set values to descending order, + * you must pass values of either -1, FALSE, 'desc', or 'DESC', else they will be + * set to 1 (ASC). + * + * @usage : $this->mongo_db->order_by(array('foo' => 'ASC'))->get('foobar'); + */ + public function order_by($fields = array()) + { + foreach ($fields as $col => $val) + { + if ($val == -1 || $val === FALSE || strtolower($val) == 'desc') + { + $this->sorts[$col] = -1; + } + else + { + $this->sorts[$col] = 1; + } + } + return ($this); + } + + /** + * -------------------------------------------------------------------------------- + * Mongo Date + * -------------------------------------------------------------------------------- + * + * Create new MongoDate object from current time or pass timestamp to create + * mongodate. + * + * @usage : $this->mongo_db->date($timestamp); + */ + public function date($stamp = FALSE) + { + if ( $stamp == FALSE ) + { + return new MongoDB\BSON\UTCDateTime(); + } + else + { + return new MongoDB\BSON\UTCDateTime($stamp); + } + + } + + /** + * -------------------------------------------------------------------------------- + * // Limit results + * -------------------------------------------------------------------------------- + * + * Limit the result set to $x number of documents + * + * @usage : $this->mongo_db->limit($x); + */ + public function limit($x = 99999) + { + if ($x !== NULL && is_numeric($x) && $x >= 1) + { + $this->limit = (int) $x; + } + return ($this); + } + + /** + * -------------------------------------------------------------------------------- + * // Offset + * -------------------------------------------------------------------------------- + * + * Offset the result set to skip $x number of documents + * + * @usage : $this->mongo_db->offset($x); + */ + public function offset($x = 0) + { + if ($x !== NULL && is_numeric($x) && $x >= 1) + { + $this->offset = (int) $x; + } + return ($this); + } + + /** + * Converts document ID and returns document back. + * + * @param stdClass $document [Document] + * @return stdClass + */ + private function convert_document_id($document) + { + if ($this->legacy_support === TRUE && isset($document['_id']) && $document['_id'] instanceof MongoDB\BSON\ObjectId) + { + $new_id = $document['_id']->__toString(); + unset($document['_id']); + $document['_id'] = new \stdClass(); + $document['_id']->{'$id'} = $new_id; + } + return $document; + } + + /** + * -------------------------------------------------------------------------------- + * // Command + * -------------------------------------------------------------------------------- + * + * Runs a MongoDB command + * + * @param string : Collection name, array $query The command query + * @usage : $this->mongo_db->command($collection, array('geoNear'=>'buildings', 'near'=>array(53.228482, -0.547847), 'num' => 10, 'nearSphere'=>true)); + * @access public + * @return object or array + */ + + public function command($command = array()) + { + try{ + $cursor = $this->db->executeCommand($this->database, new MongoDB\Driver\Command($command)); + // Clear + $this->_clear(); + $returns = array(); + + if ($cursor instanceof MongoDB\Driver\Cursor) + { + $it = new \IteratorIterator($cursor); + $it->rewind(); + + while ($doc = (array)$it->current()) + { + if ($this->return_as == 'object') + { + $returns[] = (object) $this->convert_document_id($doc); + } + else + { + $returns[] = (array) $this->convert_document_id($doc); + } + $it->next(); + } + } + + if ($this->return_as == 'object') + { + return (object)$returns; + } + else + { + return $returns; + } + } + catch (MongoDB\Driver\Exception $e) + { + if(isset($this->debug) == TRUE && $this->debug == TRUE) + { + show_error("MongoDB query failed: {$e->getMessage()}", 500); + } + else + { + show_error("MongoDB query failed.", 500); + } + } + } + + + /** + * -------------------------------------------------------------------------------- + * //! Add indexes + * -------------------------------------------------------------------------------- + * + * Ensure an index of the keys in a collection with optional parameters. To set values to descending order, + * you must pass values of either -1, FALSE, 'desc', or 'DESC', else they will be + * set to 1 (ASC). + * + * @usage : $this->mongo_db->add_index($collection, array('first_name' => 'ASC', 'last_name' => -1), array('unique' => TRUE)); + */ + public function add_index($collection = "", $keys = array(), $options = array()) + { + if (empty($collection)) + { + show_error("No Mongo collection specified to add index to", 500); + } + + if (empty($keys) || ! is_array($keys)) + { + show_error("Index could not be created to MongoDB Collection because no keys were specified", 500); + } + + foreach ($keys as $col => $val) + { + if($val == -1 || $val === FALSE || strtolower($val) == 'desc') + { + $keys[$col] = -1; + } + else + { + $keys[$col] = 1; + } + } + $command = array(); + $command['createIndexes'] = $collection; + $command['indexes'] = array($keys); + + return $this->command($command); + } + + /** + * -------------------------------------------------------------------------------- + * Remove index + * -------------------------------------------------------------------------------- + * + * Remove an index of the keys in a collection. To set values to descending order, + * you must pass values of either -1, FALSE, 'desc', or 'DESC', else they will be + * set to 1 (ASC). + * + * @usage : $this->mongo_db->remove_index($collection, 'index_1'); + */ + public function remove_index($collection = "", $name = "") + { + if (empty($collection)) + { + show_error("No Mongo collection specified to remove index from", 500); + } + + if (empty($keys)) + { + show_error("Index could not be removed from MongoDB Collection because no index name were specified", 500); + } + + $command = array(); + $command['dropIndexes'] = $collection; + $command['index'] = $name; + + return $this->command($command); + } + + /** + * -------------------------------------------------------------------------------- + * List indexes + * -------------------------------------------------------------------------------- + * + * Lists all indexes in a collection. + * + * @usage : $this->mongo_db->list_indexes($collection); + */ + public function list_indexes($collection = "") + { + if (empty($collection)) + { + show_error("No Mongo collection specified to list all indexes from", 500); + } + $command = array(); + $command['listIndexes'] = $collection; + + return $this->command($command); + } + + /** + * -------------------------------------------------------------------------------- + * //! Switch database + * -------------------------------------------------------------------------------- + * + * Switch from default database to a different db + * + * $this->mongo_db->switch_db('foobar'); + */ + public function switch_db($database = '') + { + //@todo + } + + /** + * -------------------------------------------------------------------------------- + * //! Drop database + * -------------------------------------------------------------------------------- + * + * Drop a Mongo database + * @usage: $this->mongo_db->drop_db("foobar"); + */ + public function drop_db($database = '') + { + if (empty($database)) + { + show_error('Failed to drop MongoDB database because name is empty', 500); + } + + $command = array(); + $command['dropDatabase'] = 1; + + return $this->command($command); + } + + /** + * -------------------------------------------------------------------------------- + * //! Drop collection + * -------------------------------------------------------------------------------- + * + * Drop a Mongo collection + * @usage: $this->mongo_db->drop_collection('bar'); + */ + public function drop_collection($col = '') + { + if (empty($col)) + { + show_error('Failed to drop MongoDB collection because collection name is empty', 500); + } + + $command = array(); + $command['drop'] = $col; + + return $this->command($command); + } + + /** + * -------------------------------------------------------------------------------- + * _clear + * -------------------------------------------------------------------------------- + * + * Resets the class variables to default settings + */ + private function _clear() + { + $this->selects = array(); + $this->updates = array(); + $this->wheres = array(); + $this->limit = 999999; + $this->offset = 0; + $this->sorts = array(); + } + + /** + * -------------------------------------------------------------------------------- + * Where initializer + * -------------------------------------------------------------------------------- + * + * Prepares parameters for insertion in $wheres array(). + */ + private function _w($param) + { + if ( ! isset($this->wheres[$param])) + { + $this->wheres[ $param ] = array(); + } + } + + /** + * -------------------------------------------------------------------------------- + * Update initializer + * -------------------------------------------------------------------------------- + * + * Prepares parameters for insertion in $updates array(). + */ + private function _u($method) + { + if ( ! isset($this->updates[$method])) + { + $this->updates[ $method ] = array(); + } + } + +} diff --git a/application/libraries/NatPatientLib.php b/application/libraries/NatPatientLib.php new file mode 100644 index 00000000..0478e3e6 --- /dev/null +++ b/application/libraries/NatPatientLib.php @@ -0,0 +1,184 @@ +db = $CI->load->database("default", true); + } + + //remote => status : Y|N Y confirm N, not confirm. + /* + create table m_patient_nat_validation( + M_PatientNatValidationID int not null auto_increment primary key, + M_PatientNatValidationM_PatientID int, + M_PatientNatValidationM_UserID int, + M_PatientNatValidationM_UserUsername varchar(100), + M_PatientNatValidationIsActive char(1) default 'Y', + M_PatientNatValidationCreated datetime default current_timestamp(), + M_PatientNatValidationLastUpdated datetime default current_timestamp() on update current_timestamp(), + key(M_PatientNatValidationM_PatientID), + key(M_PatientNatValidationIsActive), + ); + create table m_patient_nat_log ( + M_PatientNatLogID int not null auto_increment primary key, + M_PatientNatLogDate datetime default current_timestamp(), + M_PatientNatLogStatus enum('New','Retry','Sent'), + M_PatientNatLogLastUpdated datetime default current_timestamp() on update current_timestamp(), + M_PatientNatLogJson text, + key(M_PatientNatLogDate), + key(M_PatientNatLogStatus) + ); + */ + function save_nasional($userName,$patient) { + $resp = $this->get_branch(); + if ($resp["status"] != "OK") { + return $resp; + } + $param = ["M_BranchID" => $resp["branchID"], + "M_BranchCode" => $resp["branchCode"], + "Username" => $userName, + "patient" => $patient ]; + $z_param = gzcompress(json_encode($param)); + $url = $this->NAT_PATIENT_API . "/update_from_local"; + $zresp = $this->post($url, $z_param); + $jresp = gzuncompress($zresp); + $resp = json_decode($jresp, true); + if (!isset($resp["status"])) { + $resp["status"] = "ERR"; + $resp["message"] = $zresp; + } + return $resp; + } + + function confirm($localM_PatientID, $arr_remote, $userID, $userName) + { + $payload = [ + "userID" => $userID, + "userName" => $userName, + "lokalM_PatientID" => $localM_PatientID, + "remote" => $arr_remote, + ]; + $jsonPayload = json_encode($payload); + $sql = "insert into m_patient_nat_log(M_PatientNatLogStatus,M_PatientNatLogJson) + values('New',?)"; + $qry = $this->db->query($sql, [$jsonPayload]); + if (!$qry) { + return [ + "status" => "ERR", + "message" => $this->db->error()["message"], + ]; + } + return ["status" => "OK"]; + } + function check_connection() + { + $start = date("Y-m-d H:i:s"); + $url = $this->NAT_PATIENT_API . "/check_connection"; + $zresp = $this->post($url, json_encode(["dummy" => "load"])); + $jresp = gzuncompress($zresp); + $resp = json_decode($jresp, true); + if (!isset($resp["status"])) { + $resp["status"] = "ERR"; + $resp["message"] = $zresp; + } + $stop = date("Y-m-d H:i:s"); + $resp["start"] = $start; + $resp["stop"] = $stop; + return $resp; + } + function get_branch() + { + $sql = + "select M_BranchID, M_BranchCode from m_branch where M_BranchIsActive = 'Y' and M_BranchIsDefault='Y'"; + $qry = $this->db->query($sql); + if (!$qry) { + return [ + "status" => "ERR", + "message" => + $this->db->error()["message"] . + "|\n" . + $this->db->last_query(), + ]; + } + $rows = $qry->result_array(); + if (count($rows) == 0) { + return ["status" => "ERR", "message" => "No Default Branch"]; + } + return [ + "status" => "OK", + "branchID" => $rows[0]["M_BranchID"], + "branchCode" => $rows[0]["M_BranchCode"], + ]; + } + function search($query) + { + $start = date("Y-m-d H:i:s"); + $url = $this->NAT_PATIENT_API . "/search_bizone"; + $jparam = json_encode(["search" => $query]); + $zresp = $this->post($url, $jparam); + $jresp = gzuncompress($zresp); + $resp = json_decode($jresp, true); + if (!isset($resp["status"])) { + $resp["status"] = "ERR"; + $resp["message"] = $zresp; + } + $stop = date("Y-m-d H:i:s"); + $resp["start"] = $start; + $resp["stop"] = $stop; + return $resp; + } + // param array -> + function search_by_nik($param) + { + $start = date("Y-m-d H:i:s"); + $url = $this->NAT_PATIENT_API . "/search_by_nik"; + $resp = $this->get_branch(); + + if ($resp["status"] != "OK") { + return $resp; + } + $jparam = json_encode($param); + $zresp = $this->post($url, $jparam); + $jresp = gzuncompress($zresp); + $resp = json_decode($jresp, true); + if (!isset($resp["status"])) { + $resp["status"] = "ERR"; + $resp["message"] = $zresp; + } + $stop = date("Y-m-d H:i:s"); + $resp["start"] = $start; + $resp["stop"] = $stop; + return $resp; + } + public function post($url, $data) + { + $ch = curl_init($url); + curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST"); + curl_setopt($ch, CURLOPT_POSTFIELDS, $data); + curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); + curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10); + curl_setopt($ch, CURLOPT_TIMEOUT, 10); + curl_setopt($ch, CURLOPT_HTTPHEADER, [ + "Content-Type: application/text", + "Content-Length: " . strlen($data), + ]); + $result = curl_exec($ch); + if (curl_error($ch) != "") { + echo json_encode([ + "status" => "ERR", + "message" => "Http Error : " . curl_error($ch), + ]); + curl_close($ch); + exit(); + } + curl_close($ch); + return $result; + } +} diff --git a/application/libraries/Nonlabtemplate.php b/application/libraries/Nonlabtemplate.php new file mode 100644 index 00000000..295a8dc4 --- /dev/null +++ b/application/libraries/Nonlabtemplate.php @@ -0,0 +1,947 @@ +db = $CI->load->database("onedev", true); + $this->db_log = $CI->load->database("one_lab_log", true); + + $this->db->trans_begin(); + + $sql = "SELECT NonlabTemplateID as template_id, + NonlabTemplateName as template_name, + T_SamplingSoT_OrderHeaderID as order_header_id, + T_OrderDetailID as order_detail_id + FROM t_samplingso + JOIN t_orderdetail ON T_SamplingSoT_OrderHeaderID = T_OrderDetailT_OrderHeaderID AND T_SamplingSoT_TestID = T_OrderDetailT_TestID AND T_OrderDetailIsActive = 'Y' + JOIN t_test ON T_SamplingSoT_TestID = T_TestID + JOIN nat_test ON Nat_TestID = T_TestNat_TestID + JOIN nonlab_template_mapping ON NonlabTemplateMappingNat_TestID = Nat_TestID AND + NonlabTemplateMappingIsActive = 'Y' + JOIN nonlab_template ON NonlabTemplateMappingNonlabTemplateID = NonlabTemplateID AND NonlabTemplateIsActive = 'Y' + LEFT JOIN so_resultentry ON So_ResultEntryT_OrderDetailID = T_OrderDetailID AND + So_ResultEntryT_OrderHeaderID = T_OrderDetailT_OrderHeaderID AND + So_ResultEntryIsActive = 'Y' + WHERE + T_SamplingSoID = ? AND + T_SamplingSoIsActive = 'Y' AND + So_ResultEntryID IS NULL + GROUP BY NonlabTemplateID + LIMIT 1"; + $qry = $this->db->query($sql, array($T_SamplingSOID)); + //echo $this->db->last_query(); + if (!$qry) { + $dt_log = ['data' => ['id' => $T_SamplingSOID],'error' => $this->db->error()]; + $prm_log = ['SELECT_NONLAB_TEMPLATE', 'nonlabtemplate/generate']; + $xsql = $this->db->last_query(); + $log_error = $this->insert_log_error($xsql, $prm_log,$dt_log); + $this->db->trans_rollback(); + return array(false, print_r($this->db->error(), true)); + } + + $row_arr = $qry->row_array(); + if ($row_arr) { + //print_r($row_arr); + $template_name = $row_arr['template_name']; + if($row_arr['template_name'] == 'Fisik Umum'){ + $sql = "SELECT FisikTemplateType as xtype + FROM fisik_template + JOIN t_orderheader ON T_OrderHeaderID = {$row_arr['order_header_id']} + JOIN mgm_mcutemplate ON Mgm_McuTemplateMgm_McuID = T_OrderHeaderMgm_McuID + JOIN fisik_template_mapping ON Mgm_McuTemplateFisikTemplateMappingID = FisikTemplateMappingID + JOIN fisik_template_mapping_detail ON FisikTemplateMappingDetailFisikTemplateMappingID = FisikTemplateMappingID AND + FisikTemplateMappingDetailFisikTemplateID = FisikTemplateID AND + FisikTemplateMappingDetailIsActive = 'Y' + WHERE + FisikTemplateIsActive = 'Y' + GROUP BY FisikTemplateType"; + $qry = $this->db->query($sql); + //echo $this->db->last_query(); + if (!$qry) { + $dt_log = ['data' => ['id' => $T_SamplingSOID],'error' => $this->db->error()]; + $prm_log = ['SELECT_FISIK_TEMPLATE', 'nonlabtemplate/generate']; + $xsql = $this->db->last_query(); + $log_error = $this->insert_log_error($xsql, $prm_log,$dt_log); + $this->db->trans_rollback(); + return array(false, print_r($this->db->error(), true)); + } + $arr_types = $qry->result_array(); + $xtypes = []; + foreach ($arr_types as $key => $value) { + $xtypes[] = $value['xtype']; + } + + $template_name = "Fisik Umum"; + if(in_array("K3", $xtypes)){ + $template_name = "Fisik Umum K3"; + } +//echo $template_name; + } + + + $sql = "SELECT COUNT(*) as xcount + FROM so_resultentry + WHERE + So_ResultEntryT_OrderHeaderID = ? AND + So_ResultEntryT_OrderDetailID = ? AND + So_ResultEntryIsActive = 'Y'"; + + $query = $this->db->query($sql, array( + $row_arr['order_header_id'], + $row_arr['order_detail_id'] + )); + if (!$qry) { + $dt_log = ['data' => ['id' => $T_SamplingSOID, 'arr' => $row_arr],'error' => $this->db->error()]; + $prm_log = ['CHECK_EXIST_SO_RE', 'nonlabtemplate/generate']; + $xsql = $this->db->last_query(); + $log_error = $this->insert_log_error($xsql, $prm_log,$dt_log); + $this->db->trans_rollback(); + return array(false, print_r($this->db->error(), true)); + } + + $check_exist = $query->row()->xcount; + + if($check_exist == 0){ + $sql = "INSERT INTO so_resultentry( + So_ResultEntryT_OrderHeaderID, + So_ResultEntryT_OrderDetailID, + So_ResultEntryNonlab_TemplateID, + So_ResultEntryNonlab_TemplateName, + So_ResultEntryCreated + ) + VALUES(?,?,?,?,NOW())"; + $qry = $this->db->query($sql, array( + $row_arr['order_header_id'], + $row_arr['order_detail_id'], + $row_arr['template_id'], + $template_name + )); + //echo $this->db->last_query(); + if (!$qry) { + $dt_log = ['data' => ['id' => $T_SamplingSOID],'error' => $this->db->error()]; + $prm_log = ['INSERT_SO_RESULTENTRY', 'nonlabtemplate/generate']; + $xsql = $this->db->last_query(); + $log_error = $this->insert_log_error($xsql, $prm_log,$dt_log); + $this->db->trans_rollback(); + return array(false, print_r($this->db->error(), true)); + } + $soresultentryid = $this->db->insert_id(); + + if($template_name == 'TBBB'){ + $sql = "SELECT COUNT(*) as exist_tbbb + FROM t_samplingso_additional_fisik_bbtb + WHERE T_SamplingAdditionalFisikBBTBIsActive = 'Y' AND + T_SamplingAdditionalFisikBBTBT_OrderHeaderID = ? + "; + $qry = $this->db->query($sql, array( + $row_arr['order_header_id'] + )); + if (!$qry) { + $dt_log = ['data' => ['id' => $row_arr['order_header_id']],'error' => $this->db->error()]; + $prm_log = ['SELECT_ORDER_HEADER_LANG', 'nonlabtemplate/generate']; + $xsql = $this->db->last_query(); + $log_error = $this->insert_log_error($xsql, $prm_log,$dt_log); + $this->db->trans_rollback(); + return array(false, print_r($this->db->error(), true)); + } + + $check_exist_tbbbb = $qry->row()->exist_tbbb; + if($check_exist_tbbbb == 0){ + $sql = "INSERT INTO t_samplingso_additional_fisik_bbtb ( + T_SamplingAdditionalFisikBBTBT_OrderHeaderID, + T_SamplingAdditionalFisikBBTBValueBB, + T_SamplingAdditionalFisikBBTBValueTB, + T_SamplingAdditionalFisikBBTBValueClassification, + T_SamplingAdditionalFisikBBTBBodyFat, + T_SamplingAdditionalFisikBBTBCreated + ) VALUES(?,0,0,'',0, NOW())"; + $qry = $this->db->query($sql, array( + $row_arr['order_header_id'] + )); + if (!$qry) { + $dt_log = ['data' => ['id' => $row_arr['order_header_id']],'error' => $this->db->error()]; + $prm_log = ['INSERT_ADD_TBBB', 'nonlabtemplate/generate']; + $xsql = $this->db->last_query(); + $log_error = $this->insert_log_error($xsql, $prm_log,$dt_log); + $this->db->trans_rollback(); + return array(false, print_r($this->db->error(), true)); + } + } + } + + if($template_name == 'VISUS'){ + $sql = "SELECT COUNT(*) as exist_visus + FROM t_samplingso_additional_fisik_visus + WHERE + T_SamplingAdditionalFisikVisusT_OrderHeaderID = ? + "; + $qry = $this->db->query($sql, array( + $row_arr['order_header_id'] + )); + // echo $this->db->last_query(); + if (!$qry) { + $dt_log = ['data' => ['id' => $row_arr['order_header_id']],'error' => $this->db->error()]; + $prm_log = ['SELECT_ORDER_HEADER_LANG', 'nonlabtemplate/generate']; + $xsql = $this->db->last_query(); + $log_error = $this->insert_log_error($xsql, $prm_log,$dt_log); + $this->db->trans_rollback(); + return array(false, print_r($this->db->error(), true)); + } + + $check_exist_visus = $qry->row()->exist_visus; + //echo $check_exist_visus ; + if($check_exist_visus == 0){ + $sql = "INSERT INTO t_samplingso_additional_fisik_visus ( + T_SamplingAdditionalFisikVisusT_OrderHeaderID, + T_SamplingAdditionalFisikVisusCreated + ) VALUES(?,NOW())"; + $qry = $this->db->query($sql, array( + $row_arr['order_header_id'] + )); + if (!$qry) { + $dt_log = ['data' => ['id' => $row_arr['order_header_id']],'error' => $this->db->error()]; + $prm_log = ['INSERT_ADD_VISUS', 'nonlabtemplate/generate']; + $xsql = $this->db->last_query(); + $log_error = $this->insert_log_error($xsql, $prm_log,$dt_log); + $this->db->trans_rollback(); + return array(false, print_r($this->db->error(), true)); + } + } + } + + if($template_name == 'BW'){ + $sql = "SELECT COUNT(*) as exist_bw + FROM t_samplingso_additional_fisik_bw + WHERE + T_SamplingAdditionalFisikBWT_OrderHeaderID = ? + "; + $qry = $this->db->query($sql, array( + $row_arr['order_header_id'] + )); + if (!$qry) { + $dt_log = ['data' => ['id' => $row_arr['order_header_id']],'error' => $this->db->error()]; + $prm_log = ['SELECT_ORDER_HEADER_LANG', 'nonlabtemplate/generate']; + $xsql = $this->db->last_query(); + $log_error = $this->insert_log_error($xsql, $prm_log,$dt_log); + $this->db->trans_rollback(); + return array(false, print_r($this->db->error(), true)); + } + + $check_exist_visus = $qry->row()->exist_bw; + if($check_exist_visus == 0){ + $sql = "INSERT INTO t_samplingso_additional_fisik_bw ( + T_SamplingAdditionalFisikBWT_OrderHeaderID, + T_SamplingAdditionalFisikBWCreated + ) VALUES(?,NOW())"; + $qry = $this->db->query($sql, array( + $row_arr['order_header_id'] + )); + if (!$qry) { + $dt_log = ['data' => ['id' => $row_arr['order_header_id']],'error' => $this->db->error()]; + $prm_log = ['INSERT_ADD_BW', 'nonlabtemplate/generate']; + $xsql = $this->db->last_query(); + $log_error = $this->insert_log_error($xsql, $prm_log,$dt_log); + $this->db->trans_rollback(); + return array(false, print_r($this->db->error(), true)); + } + } + } + + $sql = "SELECT * FROM t_orderheaderlang + WHERE + T_OrderHeaderLangT_OrderHeaderID = ? AND T_OrderHeaderLangIsActive = 'Y'"; + $qry = $this->db->query($sql, array( + $row_arr['order_header_id'] + )); + if (!$qry) { + $dt_log = ['data' => ['id' => $T_SamplingSOID],'error' => $this->db->error()]; + $prm_log = ['SELECT_ORDER_HEADER_LANG', 'nonlabtemplate/generate']; + $xsql = $this->db->last_query(); + $log_error = $this->insert_log_error($xsql, $prm_log,$dt_log); + $this->db->trans_rollback(); + return array(false, print_r($this->db->error(), true)); + } + + $order_langs = $qry->result_array(); + //print_r($order_langs); + + foreach ($order_langs as $k_lang => $val_lang) { + $sql = "SELECT * + FROM nonlab_template_detail + JOIN t_orderheader ON T_OrderHeaderID = ? + JOIN m_patient ON T_OrderHeaderM_PatientID = M_PatientID + JOIN m_sex ON M_SexID = M_PatientM_SexID AND M_SexIsActive = 'Y' AND + ( NonlabTemplateDetailGender = 'all' OR NonlabTemplateDetailGender = M_SexNameLang) + WHERE + NonlabTemplateDetailNonlabTemplateID = ? AND NonlabTemplateDetailIsActive = 'Y' AND NonlabTemplateDetaiM_LangID = ? "; + $qry = $this->db->query($sql, array( + $row_arr['order_header_id'], + $row_arr['template_id'], + $val_lang['T_OrderHeaderLangM_LangID'] + )); + //echo $this->db->last_query(); + if (!$qry) { + $dt_log = ['data' => ['id' => $soresultentryid ,'arr' => $row_arr ],'error' => $this->db->error()]; + $prm_log = ['SELECT_NONLAB_TEMPLATE_DETAIL', 'nonlabtemplate/generate']; + $xsql = $this->db->last_query(); + $log_error = $this->insert_log_error($xsql, $prm_log,$dt_log); + $this->db->trans_rollback(); + return array(false, print_r($this->db->error(), true)); + } + + $rows_result = $qry->result_array(); + if($rows_result && count($rows_result) > 0){ + foreach ($rows_result as $key => $value) { + if(intval($val_lang['T_OrderHeaderLangM_LangID']) == 1){ + $sql = "SELECT COUNT(*) as xcount + FROM so_resultentrydetail + WHERE + So_ResultEntryDetailSo_ResultEntryID = ? AND + So_ResultEntryDetailNonlab_TemplateDetailID = ? AND + So_ResultEntryDetailIsActive = 'Y'"; + $query = $this->db->query($sql, array( + $soresultentryid, + $value['NonlabTemplateDetailID'] + )); + if (!$qry) { + $dt_log = ['data' => ['id' => $T_SamplingSOID, 'arr' => $value],'error' => $this->db->error()]; + $prm_log = ['CHECK_EXIST_SO_RE', 'nonlabtemplate/generate']; + $xsql = $this->db->last_query(); + $log_error = $this->insert_log_error($xsql, $prm_log,$dt_log); + $this->db->trans_rollback(); + return array(false, print_r($this->db->error(), true)); + } + + $check_exist_detail = $query->row()->xcount; + + if($check_exist_detail == 0){ + $sql = "INSERT INTO so_resultentrydetail ( + So_ResultEntryDetailSo_ResultEntryID, + So_ResultEntryDetailNonlab_TemplateDetailID, + So_ResultEntryDetailNonlab_TemplateDetailName, + So_ResultEntryDetailCreated + ) + VALUES(?,?,?,NOW())"; + $qry = $this->db->query($sql, array( + $soresultentryid, + $value['NonlabTemplateDetailID'], + $value['NonlabTemplateDetailName'] + )); + if (!$qry) { + $dt_log = ['data' => ['id' => $T_SamplingSOID],'error' => $this->db->error()]; + $prm_log = ['INSERT_SO_RESULTENTRY_DETAIL', 'nonlabtemplate/generate']; + $xsql = $this->db->last_query(); + $log_error = $this->insert_log_error($xsql, $prm_log,$dt_log); + $this->db->trans_rollback(); + return array(false, print_r($this->db->error(), true)); + } + } + //echo $this->db->last_query(); + } + } + } + } + } + + + $this->db->trans_commit(); + + + + $sql = "SELECT * + FROM so_resultentry + WHERE + So_ResultEntryID = ? "; + $qry = $this->db->query($sql, array( + $soresultentryid + )); + + if (!$qry) { + return array(false, print_r($this->db->error(), true)); + } + + $rows_return = $qry->row_array(); + + return $rows_return; + } else { + return false; + } + } + + + function insert_log_error($log_sql, $params,$data='') + { + // Membersihkan SQL dari \r\n dan whitespace berlebih + //$clean_log_sql = trim(str_replace(["\r\n", "\r", "\n"], ' ', $log_sql)); + + $sql = "INSERT INTO error_log_order( + ErrorLogOrderCode, + ErrorLogOrderFnName, + ErrorLogOrderDescription, + ErrorLogOrderData, + ErrorLogOrderCreated + ) + VALUES( + ?,?,?,?,NOW() + )"; + + $query = $this->db_log->query($sql, [$params[0],$params[1],$log_sql,json_encode($data)]); + //echo $this->db_log->last_query(); + if (!$query) { + return false; + } + return true; + } + + function create($tPriceHeaderID) + { + $CI = &get_instance(); + $this->db = $CI->load->database("onedev", true); + + $this->db->trans_begin(); + $sql = "select * from t_priceheader where T_PriceHeaderID = ?"; + $qry = $this->db->query($sql, array($tPriceHeaderID)); + if (!$qry) { + return array(false, print_r($this->db->error(), true)); + } + $rows = $qry->result_array(); + if (count($rows) == 0) { + return array(false, "T PriceHeader ID : $tPriceHeaderID not found"); + } + $sql = "select distinct T_PriceT_PriceHeaderID, T_TestID, T_TestName, 'N' IsFromPanel, Nat_TestID, + T_PriceT_TestID, T_PriceIsCito, + T_PricePriority, T_PriceAmount, T_PriceDisc, T_PriceDiscRp, T_PriceSubTotal, + T_PriceOther, T_PriceTotal, T_TestForceSell, 'N' is_packet, 0 packet_id, + 'PX' px_type, '[]' nat_test, '[]' child_test, 'N' IsFavourite, + Nat_TestNat_TestTypeID, T_TestSasCode, $tPriceHeaderID Ss_PriceMouT_PriceHeaderID + from t_price + join t_test on T_PriceT_TestID = T_TestID + and T_PriceIsActive = 'Y' and T_TestIsActive = 'Y' + and T_TestIsPrice = 'Y' + join nat_test on T_TestNat_TestID = Nat_TestID + and Nat_TestIsActive = 'Y' and Nat_TestNat_TestTypeID <> 5 + where T_PriceT_PriceHeaderID= ? + and length(T_TestSasCode) = 8 "; + $qry = $this->db->query($sql, array($tPriceHeaderID)); + + if (!$qry) { + $this->db->trans_rollback(); + return array(false, "Regional select t_price " . print_r($this->db->error(), true)); + } + $rows = $qry->result_array(); + foreach ($rows as $idx => $r) { + $nat_testType = $r["Nat_TestNat_TestTypeID"]; + switch ($nat_testType) { + case 1: //Single + $rows[$idx]['nat_test'] = '[' . $r['Nat_TestID'] . ']'; + break; + case 3: //Multi + case 4: //Panel + $sasCode = $r["T_TestSasCode"] . '%'; + $sql = "select T_TestNat_TestID + from t_test + where T_TestIsResult = 'Y' + and T_TestSasCode like ? + and T_TestIsActive = 'Y'"; + $qry = $this->db->query($sql, array($sasCode)); + if (!$qry) { + // HANYA DEBUG + // echo $this->db->last_query(); + // print_r($this->db->error()); + $this->db->trans_rollback(); + return array(false, "Regional " . print_r($this->db->error(), true)); + } + $nt_rows = $qry->result_array(); + $t_rows = array($r["Nat_TestID"]); + foreach ($nt_rows as $nr) { + $t_rows[] = $nr["T_TestNat_TestID"]; + } + $rows[$idx]['nat_test'] = "[" . join(",", $t_rows) . "]"; + break; + default: + $rows[$idx]['nat_test'] = '[' . $r['Nat_TestID'] . ']'; + break; + } + unset($rows[$idx]["Nat_TestNat_TestTypeID"]); + unset($rows[$idx]["T_TestSasCode"]); + } + + //Test Profile + // wip profile + $sql = "select distinct $tPriceHeaderID T_PriceT_PriceHeaderID, T_TestID, + T_TestName, 'N' IsFromPanel, Nat_TestID, + T_TestID T_PriceT_TestID, 'N' T_PriceIsCito, + 0 T_PricePriority, 0 T_PriceAmount, 0 T_PriceDisc, 0 T_PriceDiscRp, + 0 T_PriceSubTotal, 0 T_PriceOther, 0 T_PriceTotal, T_TestForceSell, + 'N' is_packet, 0 packet_id, + 'PXR' px_type, '[]' nat_test, '[]' child_test, 'N' IsFavourite, + Nat_TestNat_TestTypeID, T_TestSasCode, + $tPriceHeaderID Ss_PriceMouT_PriceHeaderID + from t_test + join nat_test on T_TestNat_TestID = Nat_TestID + and Nat_TestIsActive = 'Y' and Nat_TestNat_TestTypeID = 5 + where length(T_TestSasCode) = 8 "; + $qry = $this->db->query($sql); + if (!$qry) { + return array(false, "Regional " . print_r($this->db->error(), true)); + } + $p_rows = $qry->result_array(); + + $sql = "select distinct substr(T_TestSasCode,1,8) parentCode, T_PriceT_PriceHeaderID, T_TestID, T_TestName, 'N' IsFromPanel, Nat_TestID, + T_PriceT_TestID, T_PriceIsCito, + T_PricePriority, T_PriceAmount, T_PriceDisc, T_PriceDiscRp, T_PriceSubTotal, + T_PriceOther, T_PriceTotal, T_TestForceSell, 'N' is_packet, 0 packet_id, + 'PX' px_type, concat('[', T_TestNat_TestID , ']') nat_test, '[]' child_test, 'N' IsFavourite, + Nat_TestNat_TestTypeID, T_TestSasCode,T_TestIsResult, T_TestCode + from t_price + join t_test on T_PriceT_TestID = T_TestID + and T_PriceIsActive = 'Y' and T_TestIsActive = 'Y' + and T_TestIsPrice = 'Y' + and T_PriceIsCito = 'N' + and length(T_TestSasCode) = 10 + join nat_test on T_TestNat_TestID = Nat_TestID + and Nat_TestIsActive = 'Y' + where T_PriceT_PriceHeaderID= ? "; + $qry = $this->db->query($sql, array($tPriceHeaderID)); + if (!$qry) { + return array(false, "Regional child test " . print_r($this->db->error(), true)); + } + $xrows = $qry->result_array(); + + $arr_child = array(); + $p_codes = "'0'"; + foreach ($xrows as $r) { + $pCode = $r["parentCode"]; + if (!isset($arr_child[$pCode])) { + $arr_child[$pCode] = array(); + } + $cCode = $r["T_TestSasCode"]; + $p_codes .= ", '$cCode'"; + unset($r["parentCode"]); + $arr_child[$pCode][] = $r; + } + $sql = "select substr(T_TestSasCode,1,8) parentCode, + group_concat(distinct T_TestNat_TestID) nat + from t_test + where ( T_TestIsResult = 'Y' or T_TestIsPrice = 'Y' ) + and T_TestSasCode in ( $p_codes ) + and T_TestIsActive = 'Y' + group by parentCode"; + $qry = $this->db->query($sql); + if (!$qry) { + //DEBUG + // echo $this->db->last_query(); + // print_r($this->db->error()); + return array(false, "Regional " . print_r($this->db->error(), true)); + } + $xrows = $qry->result_array(); + $arr_nat = array(); + foreach ($xrows as $r) { + $pCode = $r["parentCode"]; + //if ( ! isset($arr_nat[$pCode])) { + // $arr_nat[$pCode] = array(); + //} + $arr_nat[$pCode] = $r["nat"]; + } + $flag_error = false; + foreach ($p_rows as $idx => $r) { + $T_TestName = $r["T_TestName"]; + $sasCode = $r["T_TestSasCode"]; + if (isset($arr_child[$sasCode])) { + $the_childs = $arr_child[$sasCode]; + $p_rows[$idx]['child_test'] = json_encode($the_childs, true); + if (isset($arr_nat[$sasCode])) { + $p_rows[$idx]['nat_test'] = "[" . $arr_nat[$sasCode] . "]"; + } + unset($p_rows[$idx]["Nat_TestNat_TestTypeID"]); + unset($p_rows[$idx]["T_TestSasCode"]); + } else { + unset($p_rows[$idx]); + } + } + //Paket Panel / Profile + $sql = "select distinct $tPriceHeaderID T_PriceT_PriceHeaderID, T_PacketID T_TestID, T_PacketName T_TestName, 'N' IsFromPanel, 0 Nat_TestID, + T_PacketID T_PriceT_TestID, 'N' T_PriceIsCito, + 0 T_PricePriority, T_PacketOriginalBruto T_PriceAmount, 0 T_PriceDisc, + (T_PacketOriginalBruto - T_PacketPrice) T_PriceDiscRp, 0 T_PriceSubTotal, + 0 T_PriceOther, T_PacketPrice T_PriceTotal, 'Y' T_TestForceSell, 'Y' is_packet, T_PacketID packet_id, + T_PacketType px_type, '[]' nat_test, '[]' child_test, 'N' IsFavourite, + $tPriceHeaderID Ss_PriceMouT_PriceHeaderID + from + t_packet + where + T_PacketIsActive = 'Y' + and T_PacketT_PriceHeaderID= ?"; + + $qry = $this->db->query($sql, array($tPriceHeaderID)); + if (!$qry) { + // echo $this->db->last_query(); + // print_r($this->db->error()); + return array(false, "Regional " . print_r($this->db->error(), true)); + } + $pn_rows = $qry->result_array(); + foreach ($pn_rows as $idx => $pnr) { + $packetID = $pnr["packet_id"]; + //child test + $sql = "select distinct $tPriceHeaderID T_PriceT_PriceHeaderID, T_TestID, T_TestName, 'N' IsFromPanel, Nat_TestID, + T_TestID T_PriceT_TestID, 'N' T_PriceIsCito, 0 T_PricePriority, + T_PacketDetailPrice T_PriceAmount, + 0 T_PriceDisc, + 0 T_PriceDiscRp, T_PacketDetailPrice T_PriceSubTotal, + 0 T_PriceOther, T_PacketDetailPrice T_PriceTotal, + 'Y' T_TestForceSell, 'N' is_packet, 0 packet_id, + 'PX' px_type, concat('[', T_TestNat_TestID , ']') nat_test, '[]' child_test, 'N' IsFavourite, T_TestSasCode + from t_packetdetail + JOIN t_packet ON T_PacketDetailT_PacketID = T_PacketID + JOIN t_price ON T_PacketDetailT_TestID = T_PriceT_TestID AND T_PriceIsActive = 'Y' AND T_PriceT_PriceHeaderID = T_PacketT_PriceHeaderID + join t_test on T_PacketDetailT_TestID = T_TestID + and T_PacketDetailIsActive = 'Y' and T_TestIsActive = 'Y' + and T_PacketDetailT_PacketID = ? + join nat_test on T_TestNat_TestID = Nat_TestID + and Nat_TestIsActive = 'Y'"; + $qry = $this->db->query($sql, array($packetID)); + if (!$qry) { + return array(false, print_r($this->db->error(), true)); + } + $ct_rows = $qry->result_array(); + $p_nat_test = array(); + foreach ($ct_rows as $ct_idx => $cr) { + $sasCode = $cr["T_TestSasCode"] . '%'; + $sql = "select distinct T_TestNat_TestID + from t_test + where T_TestSasCode like ? + and T_TestIsActive = 'Y'"; + $qry = $this->db->query($sql, array($sasCode)); + if (!$qry) { + return array(false, print_r($this->db->error(), true)); + } + $nt_rows = $qry->result_array(); + $t_rows = array(); + foreach ($nt_rows as $nr) { + $t_rows[] = intval($nr["T_TestNat_TestID"]); + $p_nat_test[] = intval($nr["T_TestNat_TestID"]); + } + $ct_rows[$ct_idx]['nat_test'] = json_encode($t_rows, JSON_NUMERIC_CHECK); + } + if (count($ct_rows) > 0) { + $x_arr = array(); + foreach ($ct_rows as $x_cr) { + $x_arr[] = $x_cr; + } + $pn_rows[$idx]['child_test'] = json_encode($x_arr, true); + $pn_rows[$idx]['nat_test'] = json_encode($p_nat_test, true); + } + unset($pn_rows[$idx]["Nat_TestNat_TestTypeID"]); + unset($pn_rows[$idx]["T_TestSasCode"]); + } + + $rows = array_merge($rows, $p_rows, $pn_rows); + $qry = $this->db->query( + "delete from ss_price_mou where Ss_PriceMouT_PriceHeaderID=?", + array($tPriceHeaderID) + ); + if (!$qry) { + $this->db->trans_rollback(); + return array(false, "" . print_r($this->db->error(), true) . $this->db->last_query()); + } + $this->db->insert_batch("ss_price_mou", $rows); + $err = $this->db->error(); + if ($err["code"] != 0) { + echo "ERR Code : " . $err["code"] . " | " . $err["message"] . " \n"; + $this->db->trans_rollback(); + return array(false, "" . print_r($this->db->error(), true) . $this->db->last_query()); + } + + // $sql_i = "insert into ss_price_mou( + // T_TestID, T_TestName, + // IsFromPanel, Nat_TestID,T_PriceT_TestID, T_PriceIsCito, + // T_PricePriority, T_PriceAmount, T_PriceDisc, + // T_PriceDiscRp, T_PriceSubTotal, T_PriceOther, T_PriceTotal, + // T_TestForceSell, is_packet, packet_id, px_type, + // nat_test, child_test, IsFavourite, Ss_PriceMouT_PriceHeaderID) + // values ( + // ?,?, + // ?,?,?,?, + // ?,?,?, + // ?,?,?,?, + // ?,?,?,?, + // ?,?,?,? + // )"; + // foreach ($rows as $r) { + // $arr = [ + // $r["T_TestID"], + // $r["T_TestName"], + // $r["IsFromPanel"], + // $r["Nat_TestID"], + // $r["T_PriceT_TestID"], + // $r["T_PriceIsCito"], + // $r["T_PricePriority"], + // $r["T_PriceAmount"], + // $r["T_PriceDisc"], + // $r["T_PriceDiscRp"], + // $r["T_PriceSubTotal"], + // $r["T_PriceOther"], + // $r["T_PriceTotal"], + // $r["T_TestForceSell"], + // $r["is_packet"], + // $r["packet_id"], + // $r["px_type"], + // $r["nat_test"], + // $r["child_test"], + // $r["IsFavourite"], + // $r["Ss_PriceMouT_PriceHeaderID"], + // ]; + // $qry = $this->db->query($sql_i, $arr); + // if (!$qry) { + // + // header("Content-Type: text/plain"); + // print_r($r); + // echo $this->db->last_query(); + // return array(false, "Regional " . print_r($this->db->error(), true)); + // } + // } + $this->db->trans_commit(); + return array(true, "OK"); + } + // retrun array status, message + public function bisone_create($mouID) + { + $CI = &get_instance(); + $this->db = $CI->load->database("one", true); + + $sql = "select * from m_mou where M_MouID = ?"; + $qry = $this->db->query($sql, array($mouID)); + if (!$qry) { + return array(false, print_r($this->db->error(), true)); + } + $rows = $qry->result_array(); + if (count($rows) == 0) { + return array(false, "MOU ID : $mouID not found"); + } + $companyID = $rows[0]["M_MouM_CompanyID"]; + + $sql = "select distinct T_PriceM_MouID, T_TestID, T_TestName, 'N' IsFromPanel, Nat_TestID, + T_PriceT_TestID, T_PriceIsCito, T_PriceM_CompanyID, T_PriceM_MouID, + T_PricePriority, T_PriceAmount, T_PriceDisc, T_PriceDiscRp, T_PriceSubTotal, + T_PriceOther, T_PriceTotal, T_TestForceSell, 'N' is_packet, 0 packet_id, + 'PX' px_type, '[]' nat_test, '[]' child_test, 'N' IsFavourite, + Nat_TestNat_TestTypeID, T_TestSasCode, $mouID Ss_PriceMouM_MouID + from t_price + join t_test on T_PriceT_TestID = T_TestID + and T_PriceIsActive = 'Y' and T_TestIsActive = 'Y' + and T_TestIsPrice = 'Y' + join nat_test on T_TestNat_TestID = Nat_TestID + and Nat_TestIsActive = 'Y' and Nat_TestNat_TestTypeID <> 5 + where T_PriceM_MouID = ? + and length(T_TestSasCode) = 8 "; + $qry = $this->db->query($sql, array($mouID)); + + if (!$qry) { + return array(false, "Regional select t_price " . print_r($this->db->error(), true)); + } + $rows = $qry->result_array(); + $flag_error = false; + foreach ($rows as $idx => $r) { + $nat_testType = $r["Nat_TestNat_TestTypeID"]; + switch ($nat_testType) { + case 1: //Single + $rows[$idx]['nat_test'] = '[' . $r['Nat_TestID'] . ']'; + break; + case 3: //Multi + case 4: //Panel + $sasCode = $r["T_TestSasCode"] . '%'; + $sql = "select T_TestNat_TestID + from t_test + where T_TestIsResult = 'Y' + and T_TestSasCode like ? + and T_TestIsActive = 'Y'"; + $qry = $this->db->query($sql, array($sasCode)); + if (!$qry) { + return array(false, "Regional " . print_r($this->db->error(), true)); + } + $nt_rows = $qry->result_array(); + $t_rows = array($r["Nat_TestID"]); + foreach ($nt_rows as $nr) { + $t_rows[] = $nr["T_TestNat_TestID"]; + } + $rows[$idx]['nat_test'] = "[" . join(",", $t_rows) . "]"; + break; + default: + $rows[$idx]['nat_test'] = '[' . $r['Nat_TestID'] . ']'; + break; + } + unset($rows[$idx]["Nat_TestNat_TestTypeID"]); + unset($rows[$idx]["T_TestSasCode"]); + } + //Test Profile + // wip profile + $sql = "select distinct $mouID T_PriceM_MouID, T_TestID, T_TestName, 'N' IsFromPanel, Nat_TestID, + T_TestID T_PriceT_TestID, 'N' T_PriceIsCito, $companyID T_PriceM_CompanyID, $mouID T_PriceM_MouID, + 0 T_PricePriority, 0 T_PriceAmount, 0 T_PriceDisc, 0 T_PriceDiscRp, 0 T_PriceSubTotal, + 0 T_PriceOther, 0 T_PriceTotal, T_TestForceSell, 'N' is_packet, 0 packet_id, + 'PXR' px_type, '[]' nat_test, '[]' child_test, 'N' IsFavourite, + Nat_TestNat_TestTypeID, T_TestSasCode, $mouID Ss_PriceMouM_MouID + from t_test + join nat_test on T_TestNat_TestID = Nat_TestID + and Nat_TestIsActive = 'Y' and Nat_TestNat_TestTypeID = 5 + where length(T_TestSasCode) = 8 "; + $qry = $this->db->query($sql, array($mouID)); + if (!$qry) { + return array(false, "Regional " . print_r($this->db->error(), true)); + } + $p_rows = $qry->result_array(); + + $sql = "select distinct substr(T_TestSasCode,1,8) parentCode, T_PriceM_MouID, T_TestID, T_TestName, 'N' IsFromPanel, Nat_TestID, + T_PriceT_TestID, T_PriceIsCito, T_PriceM_CompanyID, T_PriceM_MouID, + T_PricePriority, T_PriceAmount, T_PriceDisc, T_PriceDiscRp, T_PriceSubTotal, + T_PriceOther, T_PriceTotal, T_TestForceSell, 'N' is_packet, 0 packet_id, + 'PX' px_type, concat('[', T_TestNat_TestID , ']') nat_test, '[]' child_test, 'N' IsFavourite, + Nat_TestNat_TestTypeID, T_TestSasCode,T_TestIsResult, T_TestCode + from t_price + join t_test on T_PriceT_TestID = T_TestID + and T_PriceIsActive = 'Y' and T_TestIsActive = 'Y' + and T_TestIsPrice = 'Y' + and T_PriceIsCito = 'N' + and length(T_TestSasCode) = 10 + join nat_test on T_TestNat_TestID = Nat_TestID + and Nat_TestIsActive = 'Y' + where T_PriceM_MouID = ? "; + $qry = $this->db->query($sql, array($mouID)); + if (!$qry) { + return array(false, "Regional child test " . print_r($this->db->error(), true)); + } + $xrows = $qry->result_array(); + $arr_child = array(); + $p_codes = "'0'"; + foreach ($xrows as $r) { + $pCode = $r["parentCode"]; + if (!isset($arr_child[$pCode])) { + $arr_child[$pCode] = array(); + } + $cCode = $r["T_TestSasCode"]; + $p_codes .= ", '$cCode'"; + unset($r["parentCode"]); + $arr_child[$pCode][] = $r; + } + $sql = "select substr(T_TestSasCode,1,8) parentCode, + group_concat(distinct T_TestNat_TestID) nat + from t_test + where ( T_TestIsResult = 'Y' or T_TestIsPrice = 'Y' ) + and T_TestSasCode in ( $p_codes ) + and T_TestIsActive = 'Y' + group by parentCode"; + $qry = $this->db->query($sql, array($mouID)); + if (!$qry) { + return array(false, "Regional " . print_r($this->db->error(), true)); + } + $xrows = $qry->result_array(); + $arr_nat = array(); + foreach ($xrows as $r) { + $pCode = $r["parentCode"]; + //if ( ! isset($arr_nat[$pCode])) { + // $arr_nat[$pCode] = array(); + //} + $arr_nat[$pCode] = $r["nat"]; + } + $flag_error = false; + foreach ($p_rows as $idx => $r) { + $T_TestName = $r["T_TestName"]; + $sasCode = $r["T_TestSasCode"]; + if (isset($arr_child[$sasCode])) { + $the_childs = $arr_child[$sasCode]; + $p_rows[$idx]['child_test'] = json_encode($the_childs, true); + if (isset($arr_nat[$sasCode])) { + $p_rows[$idx]['nat_test'] = "[" . $arr_nat[$sasCode] . "]"; + } + unset($p_rows[$idx]["Nat_TestNat_TestTypeID"]); + unset($p_rows[$idx]["T_TestSasCode"]); + } else { + unset($p_rows[$idx]); + } + } + //Paket Panel / Profile + $sql = "select distinct $mouID T_PriceM_MouID, T_PacketID T_TestID, T_PacketName T_TestName, 'N' IsFromPanel, 0 Nat_TestID, + T_PacketID T_PriceT_TestID, 'N' T_PriceIsCito, $companyID T_PriceM_CompanyID, $mouID T_PriceM_MouID, + 0 T_PricePriority, T_PacketOriginalBruto T_PriceAmount, 0 T_PriceDisc, + (T_PacketOriginalBruto - T_PacketPrice) T_PriceDiscRp, 0 T_PriceSubTotal, + 0 T_PriceOther, T_PacketPrice T_PriceTotal, 'Y' T_TestForceSell, 'Y' is_packet, T_PacketID packet_id, + T_PacketType px_type, '[]' nat_test, '[]' child_test, 'N' IsFavourite, + $mouID Ss_PriceMouM_MouID + from + t_packet + where + T_PacketIsActive = 'Y' + and T_PacketM_MouID = ?"; + + $qry = $this->db->query($sql, array($mouID)); + if (!$qry) { + return array(false, "Regional " . print_r($this->db->error(), true)); + } + $pn_rows = $qry->result_array(); + foreach ($pn_rows as $idx => $pnr) { + $packetID = $pnr["packet_id"]; + //child test + $sql = "select distinct $mouID T_PriceM_MouID, T_TestID, T_TestName, 'N' IsFromPanel, Nat_TestID, + T_TestID T_PriceT_TestID, 'N' T_PriceIsCito, $companyID T_PriceM_CompanyID, + $mouID T_PriceM_MouID, 0 T_PricePriority, T_PacketDetailPriceAmount T_PriceAmount, + T_PacketDetailPriceDisc T_PriceDisc, T_PacketDetailPriceDiscRp T_PriceDiscRp, T_PacketDetailPriceSubTotal T_PriceSubTotal, + 0 T_PriceOther, T_PacketDetailPrice T_PriceTotal, + 'Y' T_TestForceSell, 'N' is_packet, 0 packet_id, + 'PX' px_type, concat('[', T_TestNat_TestID , ']') nat_test, '[]' child_test, 'N' IsFavourite, T_TestSasCode + from t_packetdetail + join t_test on T_PacketDetailT_TestID = T_TestID + and T_PacketDetailIsActive = 'Y' and T_TestIsActive = 'Y' + and T_PacketDetailT_PacketID = ? + join nat_test on T_TestNat_TestID = Nat_TestID + and Nat_TestIsActive = 'Y'"; + $qry = $this->db->query($sql, array($packetID)); + if (!$qry) { + return array(false, print_r($this->db->error(), true)); + } + $ct_rows = $qry->result_array(); + $p_nat_test = array(); + foreach ($ct_rows as $ct_idx => $cr) { + $sasCode = $cr["T_TestSasCode"] . '%'; + $sql = "select distinct T_TestNat_TestID + from t_test + where T_TestSasCode like ? + and T_TestIsActive = 'Y'"; + $qry = $this->db->query($sql, array($sasCode)); + if (!$qry) { + return array(false, print_r($this->db->error(), true)); + } + $nt_rows = $qry->result_array(); + $t_rows = array(); + foreach ($nt_rows as $nr) { + $t_rows[] = intval($nr["T_TestNat_TestID"]); + $p_nat_test[] = intval($nr["T_TestNat_TestID"]); + } + $ct_rows[$ct_idx]['nat_test'] = json_encode($t_rows, JSON_NUMERIC_CHECK); + } + if (count($ct_rows) > 0) { + $x_arr = array(); + foreach ($ct_rows as $x_cr) { + $x_arr[] = $x_cr; + } + $pn_rows[$idx]['child_test'] = json_encode($x_arr, true); + $pn_rows[$idx]['nat_test'] = json_encode($p_nat_test, true); + } + unset($pn_rows[$idx]["Nat_TestNat_TestTypeID"]); + unset($pn_rows[$idx]["T_TestSasCode"]); + } + + $rows = array_merge($rows, $p_rows, $pn_rows); + $qry = $this->db->query("delete from ss_price_mou where Ss_PriceMouM_MouID=?", array($mouID)); + if (!$qry) { + return array(false, "Regional " . print_r($this->db->error(), true)); + } + $qry = $this->db->insert_batch("ss_price_mou", $rows); + if (!$qry) { + return array(false, "Regional " . print_r($this->db->error(), true)); + } + return array(true, "OK"); + } +} diff --git a/application/libraries/Ocr_alibaba.php b/application/libraries/Ocr_alibaba.php new file mode 100644 index 00000000..106d9de0 --- /dev/null +++ b/application/libraries/Ocr_alibaba.php @@ -0,0 +1,118 @@ + "ERR", "message" => "Error: File not found."]; + } + + // Load image and convert to black and white + $image = imagecreatefromstring(file_get_contents($imagePath)); + // imagefilter($image, IMG_FILTER_GRAYSCALE); + + // Get original dimensions and resize + // $originalWidth = imagesx($image); + // $originalHeight = imagesy($image); + // $newWidth = intval(640); + // $newHeight = intval($originalHeight * ($newWidth / $originalWidth)); + // $resizedImage = imagecreatetruecolor($newWidth, $newHeight); + // imagecopyresampled($resizedImage, $image, 0, 0, 0, 0, $newWidth, $newHeight, $originalWidth, $originalHeight); + + // Convert image to base64 + ob_start(); + imagejpeg($image); + $imageData = ob_get_clean(); + $imgStr = base64_encode($imageData); + $imgStrNew = "data:image/jpeg;base64," . $imgStr; + + // Prepare request payload + $payload = json_encode([ + "model" => $this->modelName, + "messages" => [[ + "role" => "user", + "content" => [ + [ + "type" => "text", + "text" => "Extract all text from the given image. Return result only, in the pattern label:value as it is, without translation." + ], + [ + "type" => "image_url", + "image_url" => [ + "url" => $imgStrNew + ], + ] + ], + ]], + "options" => ["temperature" => $this->temperature], + "stream" => false + ]); + + // Initialize cURL + $ch = curl_init(self::API_URL); + curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); + curl_setopt($ch, CURLOPT_POST, true); + curl_setopt($ch, CURLOPT_HTTPHEADER, [ + "Content-Type: application/json", + "Authorization: Bearer " . self::API_KEY + ]); + curl_setopt($ch, CURLOPT_POSTFIELDS, $payload); + + // Execute request + $response = curl_exec($ch); + if (curl_errno($ch)) { + $error = curl_error($ch); + curl_close($ch); + return ["status" => "ERR", "message" => curl_error($ch)]; + } + curl_close($ch); + + $response = strip_tags($response); + $responseData = json_decode($response, true); + $content = $responseData['choices'][0]['message']['content']; + + if (is_null($responseData) || !isset($content)) { + return ["status" => "ERR", "message" => "raw : $response"]; + } + + $parsedData = []; + $lines = explode("\n", $content); + foreach ($lines as $line) { + $parts = explode(":", $line, 2); + if (count($parts) == 2) { + $key = trim(str_replace("*", "", $parts[0])); + $key = strtolower($key); + $key = str_replace(" ", "_", $key); + $value = trim(str_replace("*", "", $parts[1])); + + if (strpos($key, "/")) { + $a_key = explode("/", $key); + $a_val = explode(",", $value); + if (strpos($value, "/")) { + $a_val = explode("/", $value); + } + foreach ($a_key as $a_idx => $sub_key) { + $sub_val = $a_val[$a_idx]; + $parsedData[trim($sub_key)] = trim($sub_val); + } + } else { + $parsedData[$key] = $value; + } + } + } + $info["prompt_tokens"] = $responseData["usage"]["prompt_tokens"]; + $info["completion_tokens"] = $responseData["usage"]["completion_tokens"]; + $info["total_tokens"] = $responseData["usage"]["total_tokens"]; + $info["estimated_cost"] = $responseData["usage"]["estimated_cost"]; + $info["model"] = $this->modelName; + $info["temperature"] = $this->temperature; + return ["status" => "OK", "data" => $parsedData, "info" => $info]; + } +} diff --git a/application/libraries/Ocr_deepinfra.php b/application/libraries/Ocr_deepinfra.php new file mode 100644 index 00000000..c287956a --- /dev/null +++ b/application/libraries/Ocr_deepinfra.php @@ -0,0 +1,124 @@ + "ERR", "message" => "Error: File not found."]; + } + + // Load image and convert to black and white + $image = imagecreatefromstring(file_get_contents($imagePath)); + // imagefilter($image, IMG_FILTER_GRAYSCALE); + + // Get original dimensions and resize + // $originalWidth = imagesx($image); + // $originalHeight = imagesy($image); + // $newWidth = intval(640); + // $newHeight = intval($originalHeight * ($newWidth / $originalWidth)); + // $resizedImage = imagecreatetruecolor($newWidth, $newHeight); + // imagecopyresampled($resizedImage, $image, 0, 0, 0, 0, $newWidth, $newHeight, $originalWidth, $originalHeight); + + // Convert image to base64 + ob_start(); + // imagejpeg($resizedImage); + imagejpeg($image); + $imageData = ob_get_clean(); + $imgStr = base64_encode($imageData); + $imgStrNew = "data:image/jpeg;base64," . $imgStr; + + // Prepare request payload + $payload = json_encode([ + "model" => $this->modelName, + "messages" => [[ + "role" => "user", + "content" => [ + [ + "type" => "text", + "text" => "Extract all text from the given image. Return result only, in the pattern label:value as it is, without translation." + ], + [ + "type" => "image_url", + "image_url" => [ + "url" => $imgStrNew + ], + ] + ], + ]], + "options" => ["temperature" => $this->temperature], + "stream" => false + ]); + + // Initialize cURL + $ch = curl_init(self::API_URL); + curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); + curl_setopt($ch, CURLOPT_POST, true); + curl_setopt($ch, CURLOPT_HTTPHEADER, [ + "Content-Type: application/json", + "Authorization: Bearer " . self::API_KEY + ]); + curl_setopt($ch, CURLOPT_POSTFIELDS, $payload); + + // Execute request + $response = curl_exec($ch); + if (curl_errno($ch)) { + $error = curl_error($ch); + curl_close($ch); + return ["status" => "ERR", "message" => curl_error($ch)]; + } + curl_close($ch); + + $response = strip_tags($response); + $responseData = json_decode($response, true); + + $content = $responseData['choices'][0]['message']['content']; + + if (is_null($responseData) || !isset($content)) { + return ["status" => "ERR", "message" => "raw : $response"]; + } + + // echo "content:\n"; + // echo $content . "\n"; + // echo "\n"; + + $parsedData = []; + $lines = explode("\n", $content); + foreach ($lines as $line) { + $parts = explode(":", $line, 2); + if (count($parts) == 2) { + $key = trim(str_replace("*", "", $parts[0])); + $key = strtolower($key); + $key = str_replace(" ", "_", $key); + $value = trim(str_replace("*", "", $parts[1])); + + if (strpos($key, "/")) { + $a_key = explode("/", $key); + $a_val = explode(",", $value); + if (strpos($value, "/")) { + $a_val = explode("/", $value); + } + foreach ($a_key as $a_idx => $sub_key) { + $sub_val = $a_val[$a_idx]; + $parsedData[trim($sub_key)] = trim($sub_val); + } + } else { + $parsedData[$key] = $value; + } + } + } + $info["prompt_tokens"] = $responseData["usage"]["prompt_tokens"]; + $info["completion_tokens"] = $responseData["usage"]["completion_tokens"]; + $info["total_tokens"] = $responseData["usage"]["total_tokens"]; + $info["estimated_cost"] = $responseData["usage"]["estimated_cost"]; + $info["model"] = $this->modelName; + $info["temperature"] = $this->temperature; + return ["status" => "OK", "data" => $parsedData, "info" => $info]; + } +} diff --git a/application/libraries/Ocr_llama.php b/application/libraries/Ocr_llama.php new file mode 100644 index 00000000..3ee935e5 --- /dev/null +++ b/application/libraries/Ocr_llama.php @@ -0,0 +1,104 @@ +"ERR", "message"=> "Error: File not found."]; + } + + // Load image and convert to black and white + $image = imagecreatefromstring(file_get_contents($imagePath)); + imagefilter($image, IMG_FILTER_GRAYSCALE); + + // Get original dimensions and resize + // $newWidth = intval(imagesx($image) / 2); + // $newHeight = intval(imagesy($image) / ); + // $resizedImage = imagecreatetruecolor($newWidth, $newHeight); + // imagecopyresampled($resizedImage, $image, 0, 0, 0, 0, $newWidth, $newHeight, imagesx($image), imagesy($image)); + + // Convert image to base64 + ob_start(); + imagejpeg($image); + $imageData = ob_get_clean(); + $imgStr = base64_encode($imageData); + + // Prepare request payload + $payload = json_encode([ + "model" => $this->modelName, + "messages" => [[ + "role" => "user", + "content" => "Extract all text from the given image. Return result only, in the pattern label:value as it is, without translation.", + "images" => [$imgStr] + ]], + "options" => ["temperature" => $this->temperature], + "stream" => false + ]); + + // Initialize cURL + $ch = curl_init($this->ollamaUrl); + curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); + curl_setopt($ch, CURLOPT_POST, true); + curl_setopt($ch, CURLOPT_HTTPHEADER, ["Content-Type: application/json"]); + curl_setopt($ch, CURLOPT_POSTFIELDS, $payload); + + // Execute request + $response = curl_exec($ch); + if (curl_errno($ch)) { + $error = curl_error($ch); + curl_close($ch); + return ["status" => "ERR", "message" => curl_error($ch)]; + } + curl_close($ch); + // Decode response + // Remove
 tags if present
+    $response = strip_tags($response);
+
+    $responseData = json_decode($response, true);
+    if (!$responseData || !isset($responseData['message']['content'])) {
+      return ["status"=>"ERR", "message"=> "raw : $response"];
+    }
+
+    // Parse content into JSON object
+    $content = $responseData["message"]["content"];
+    // echo "content:\n";
+    // echo $content . "\n";
+    // echo "\n";
+    $parsedData = [];
+    $lines = explode("\n", $content);
+    foreach ($lines as $line) {
+      $parts = explode(":", $line, 2);
+      if (count($parts) == 2) {
+        $key = trim(str_replace("*","",$parts[0]));
+        $key = strtolower($key);
+        $key = str_replace(" ","_",$key);
+        $value = trim(str_replace("*","",$parts[1]));
+        
+        if (strpos($key, "/")) {
+          $a_key = explode("/", $key);
+          $a_val = explode(",", $value);
+          if (strpos($value, "/")) {
+            $a_val = explode("/", $value);
+          }
+          foreach($a_key as $a_idx => $sub_key) {
+            $sub_val = $a_val[$a_idx];
+            $parsedData[trim($sub_key)] = trim($sub_val);
+          }
+        } else {
+          $parsedData[$key] = $value;
+        }
+      }
+    }
+    $info["total_duration"] = $responseData["total_duration"];
+    $info["prompt_eval_duration"] = $responseData["prompt_eval_duration"];
+    $info["eval_duration"] = $responseData["eval_duration"];
+    $info["model"] = $responseData["model"];
+    return ["status"=>"OK", "data" => $parsedData, "info"=> $info];
+  }
+}
diff --git a/application/libraries/Ocr_oroute.php b/application/libraries/Ocr_oroute.php
new file mode 100644
index 00000000..89cef430
--- /dev/null
+++ b/application/libraries/Ocr_oroute.php
@@ -0,0 +1,119 @@
+ "ERR", "message" => "Error: File not found."];
+    }
+
+    // Load image and convert to black and white
+    $image = imagecreatefromstring(file_get_contents($imagePath));
+    // imagefilter($image, IMG_FILTER_GRAYSCALE);
+
+    // Get original dimensions and resize
+    // $originalWidth = imagesx($image);
+    // $originalHeight = imagesy($image);
+    // $newWidth = intval(640);
+    // $newHeight = intval($originalHeight * ($newWidth / $originalWidth));
+    // $resizedImage = imagecreatetruecolor($newWidth, $newHeight);
+    // imagecopyresampled($resizedImage, $image, 0, 0, 0, 0, $newWidth, $newHeight, $originalWidth, $originalHeight);
+
+    // Convert image to base64
+    ob_start();
+    // imagejpeg($resizedImage);
+    imagejpeg($image);
+    $imageData = ob_get_clean();
+    $imgStr = base64_encode($imageData);
+    $imgStrNew = "data:image/jpeg;base64," . $imgStr;
+
+    // Prepare request payload
+    $payload = json_encode([
+      "model" => $this->modelName,
+      "messages" => [[
+        "role" => "user",
+        "content" => [
+          [
+            "type" => "text",
+            "text" => "Extract all text from the given image. Return result only, in the pattern label:value as it is, without translation."
+          ],
+          [
+            "type" => "image_url",
+            "image_url" => [
+              "url" => $imgStrNew
+            ],
+          ]
+        ],
+      ]],
+      "options" => ["temperature" => $this->temperature],
+      "stream" => false
+    ]);
+
+    // Initialize cURL
+    $ch = curl_init(self::API_URL);
+    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
+    curl_setopt($ch, CURLOPT_POST, true);
+    curl_setopt($ch, CURLOPT_HTTPHEADER, [
+      "Content-Type: application/json",
+      "Authorization: Bearer " . self::API_KEY
+    ]);
+    curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
+
+    // Execute request
+    $response = curl_exec($ch);
+    if (curl_errno($ch)) {
+      $error = curl_error($ch);
+      curl_close($ch);
+      return ["status" => "ERR", "message" => "Error CURL ke API " . curl_error($ch)];
+    }
+    curl_close($ch);
+
+    $response = strip_tags($response);
+    $responseData = json_decode($response, true);
+    $content = $responseData['choices'][0]['message']['content'];
+
+    if (is_null($responseData) || !isset($content)) {
+      return ["status" => "ERR", "message" => "raw : $response"];
+    }
+
+    $parsedData = [];
+    $lines = explode("\n", $content);
+    foreach ($lines as $line) {
+      $parts = explode(":", $line, 2);
+      if (count($parts) == 2) {
+        $key = trim(str_replace("*", "", $parts[0]));
+        $key = strtolower($key);
+        $key = str_replace(" ", "_", $key);
+        $value = trim(str_replace("*", "", $parts[1]));
+
+        if (strpos($key, "/")) {
+          $a_key = explode("/", $key);
+          $a_val = explode(",", $value);
+          if (strpos($value, "/")) {
+            $a_val = explode("/", $value);
+          }
+          foreach ($a_key as $a_idx => $sub_key) {
+            $sub_val = $a_val[$a_idx];
+            $parsedData[trim($sub_key)] = trim($sub_val);
+          }
+        } else {
+          $parsedData[$key] = $value;
+        }
+      }
+    }
+    $info["prompt_tokens"] = $responseData["usage"]["prompt_tokens"];
+    $info["completion_tokens"] = $responseData["usage"]["completion_tokens"];
+    $info["total_tokens"] = $responseData["usage"]["total_tokens"];
+    $info["estimated_cost"] = $responseData["usage"]["estimated_cost"];
+    $info["model"] = $this->modelName;
+    $info["temperature"] = $this->temperature;
+    return ["status" => "OK", "data" => $parsedData, "info" => $info];
+  }
+}
diff --git a/application/libraries/Report.php b/application/libraries/Report.php
new file mode 100644
index 00000000..77e490ca
--- /dev/null
+++ b/application/libraries/Report.php
@@ -0,0 +1,319 @@
+db = $CI->load->database("onedev", true);
+    $this->db_log = $CI->load->database("one_lab_log", true);
+
+    $this->db->trans_begin();
+
+    $sql = "SELECT NonlabTemplateID as template_id,
+            NonlabTemplateName as template_name,
+            T_SamplingSoT_OrderHeaderID as order_header_id,
+            T_OrderDetailID as order_detail_id
+            FROM t_samplingso 
+            JOIN t_orderdetail ON T_SamplingSoT_OrderHeaderID = T_OrderDetailT_OrderHeaderID AND T_SamplingSoT_TestID = T_OrderDetailT_TestID AND T_OrderDetailIsActive = 'Y'
+            JOIN t_test ON T_SamplingSoT_TestID = T_TestID 
+            JOIN nat_test ON Nat_TestID = T_TestNat_TestID
+            JOIN nonlab_template_mapping ON NonlabTemplateMappingNat_TestID = Nat_TestID AND 
+              NonlabTemplateMappingIsActive = 'Y'
+            JOIN nonlab_template ON NonlabTemplateMappingNonlabTemplateID = NonlabTemplateID AND NonlabTemplateIsActive = 'Y'
+            LEFT JOIN so_resultentry ON So_ResultEntryT_OrderDetailID = T_OrderDetailID AND 
+            So_ResultEntryT_OrderHeaderID = T_OrderDetailT_OrderHeaderID AND 
+            So_ResultEntryIsActive = 'Y'
+            WHERE 
+            T_SamplingSoID = ?  AND
+            T_SamplingSoIsActive = 'Y' AND 
+            So_ResultEntryID IS NULL
+            GROUP BY NonlabTemplateID
+            LIMIT 1";
+    $qry = $this->db->query($sql, array($T_SamplingSOID));
+    //echo $this->db->last_query();
+    if (!$qry) {
+        $dt_log = ['data' => ['id' => $T_SamplingSOID],'error' => $this->db->error()];
+        $prm_log = ['SELECT_NONLAB_TEMPLATE', 'nonlabtemplate/generate'];
+        $xsql = $this->db->last_query();
+        $log_error = $this->insert_log_error($xsql, $prm_log,$dt_log);
+        $this->db->trans_rollback();
+        return array(false, print_r($this->db->error(), true));
+    }
+    
+    $row_arr = $qry->row_array();
+    if ($row_arr) {
+      //print_r($row_arr);
+      $template_name = $row_arr['template_name'];
+      if($row_arr['template_name'] == 'Fisik Umum'){
+        $sql = "SELECT FisikTemplateType as xtype
+                FROM fisik_template 
+                JOIN t_orderheader ON T_OrderHeaderID = {$row_arr['order_header_id']}
+                JOIN mgm_mcutemplate ON Mgm_McuTemplateMgm_McuID = T_OrderHeaderMgm_McuID
+                JOIN fisik_template_mapping ON Mgm_McuTemplateFisikTemplateMappingID = FisikTemplateMappingID 
+                JOIN fisik_template_mapping_detail ON FisikTemplateMappingDetailFisikTemplateMappingID = FisikTemplateMappingID AND 
+                  FisikTemplateMappingDetailFisikTemplateID = FisikTemplateID AND 
+                  FisikTemplateMappingDetailIsActive = 'Y'
+                WHERE
+                FisikTemplateIsActive = 'Y'
+                GROUP BY FisikTemplateType";
+          $qry = $this->db->query($sql);
+          //echo $this->db->last_query();
+          if (!$qry) {
+            $dt_log = ['data' => ['id' => $T_SamplingSOID],'error' => $this->db->error()];
+            $prm_log = ['SELECT_FISIK_TEMPLATE', 'nonlabtemplate/generate'];
+            $xsql = $this->db->last_query();
+            $log_error = $this->insert_log_error($xsql, $prm_log,$dt_log);
+            $this->db->trans_rollback();
+            return array(false, print_r($this->db->error(), true));
+          }
+          $arr_types = $qry->result_array();
+          $xtypes = [];
+          foreach ($arr_types as $key => $value) {
+            $xtypes[] = $value['xtype'];
+          }
+
+          $template_name = "Fisik Umum";
+          if(in_array("K3", $xtypes)){
+            $template_name = "Fisik Umum K3";
+          }
+//echo $template_name;
+      }
+
+      $sql = "INSERT INTO so_resultentry(
+                So_ResultEntryT_OrderHeaderID,
+                So_ResultEntryT_OrderDetailID,
+                So_ResultEntryNonlab_TemplateID,
+                So_ResultEntryNonlab_TemplateName,
+                So_ResultEntryCreated
+              )
+              VALUES(?,?,?,?,NOW())";
+      $qry = $this->db->query($sql, array(
+        $row_arr['order_header_id'],
+        $row_arr['order_detail_id'],
+        $row_arr['template_id'],
+        $template_name
+      ));
+      if (!$qry) {
+        $dt_log = ['data' => ['id' => $T_SamplingSOID],'error' => $this->db->error()];
+        $prm_log = ['INSERT_SO_RESULTENTRY', 'nonlabtemplate/generate'];
+        $xsql = $this->db->last_query();
+        $log_error = $this->insert_log_error($xsql, $prm_log,$dt_log);
+        $this->db->trans_rollback();
+        return array(false, print_r($this->db->error(), true));
+      }
+      $soresultentryid = $this->db->insert_id();
+
+      $sql = "SELECT * FROM t_orderheaderlang 
+              WHERE
+              T_OrderHeaderLangT_OrderHeaderID = ? AND T_OrderHeaderLangIsActive = 'Y'";
+      $qry = $this->db->query($sql, array(
+        $row_arr['order_header_id']
+      ));
+      if (!$qry) {
+        $dt_log = ['data' => ['id' => $T_SamplingSOID],'error' => $this->db->error()];
+        $prm_log = ['SELECT_ORDER_HEADER_LANG', 'nonlabtemplate/generate'];
+        $xsql = $this->db->last_query();
+        $log_error = $this->insert_log_error($xsql, $prm_log,$dt_log);
+        $this->db->trans_rollback();
+        return array(false, print_r($this->db->error(), true));
+      }
+
+      $order_langs = $qry->result_array();
+      //print_r($order_langs);
+
+      foreach ($order_langs as $k_lang => $val_lang) {
+        $sql = "SELECT *
+                FROM nonlab_template_detail
+                JOIN t_orderheader ON T_OrderHeaderID = ?
+                JOIN m_patient ON T_OrderHeaderM_PatientID = M_PatientID 
+                JOIN m_sex ON M_SexID = M_PatientM_SexID AND M_SexIsActive = 'Y' AND 
+                ( NonlabTemplateDetailGender = 'all' OR NonlabTemplateDetailGender = M_SexNameLang)
+                WHERE
+                NonlabTemplateDetailNonlabTemplateID = ? AND NonlabTemplateDetailIsActive = 'Y' AND NonlabTemplateDetaiM_LangID = ? ";
+        $qry = $this->db->query($sql, array(
+          $row_arr['order_header_id'],
+          $row_arr['template_id'],
+          $val_lang['T_OrderHeaderLangM_LangID']
+        ));
+        //echo $this->db->last_query();
+        if (!$qry) {
+          $dt_log = ['data' => ['id' => $T_SamplingSOID],'error' => $this->db->error()];
+          $prm_log = ['SELECT_NONLAB_TEMPLATE_DETAIL', 'nonlabtemplate/generate'];
+          $xsql = $this->db->last_query();
+          $log_error = $this->insert_log_error($xsql, $prm_log,$dt_log);
+          $this->db->trans_rollback();
+          return array(false, print_r($this->db->error(), true));
+        }
+
+        $rows_result = $qry->result_array();
+        if($rows_result && count($rows_result) > 0){
+          foreach ($rows_result as $key => $value) {
+            if(intval($val_lang['T_OrderHeaderLangM_LangID']) == 1){
+              $sql = "INSERT INTO so_resultentrydetail (
+                      So_ResultEntryDetailSo_ResultEntryID,
+                      So_ResultEntryDetailNonlab_TemplateDetailID,
+                      So_ResultEntryDetailNonlab_TemplateDetailName,
+                      So_ResultEntryDetailCreated   
+                    )
+                    VALUES(?,?,?,NOW())";
+              $qry = $this->db->query($sql, array(
+                $soresultentryid,
+                $value['NonlabTemplateDetailID'],
+                $value['NonlabTemplateDetailName']
+              ));
+              if (!$qry) {
+                $dt_log = ['data' => ['id' => $T_SamplingSOID],'error' => $this->db->error()];
+                $prm_log = ['INSERT_SO_RESULTENTRY_DETAIL', 'nonlabtemplate/generate'];
+                $xsql = $this->db->last_query();
+                $log_error = $this->insert_log_error($xsql, $prm_log,$dt_log);
+                $this->db->trans_rollback();
+                return array(false, print_r($this->db->error(), true));
+              }
+              //echo $this->db->last_query();
+            }
+          }
+        }
+        
+
+      }
+
+      
+      $this->db->trans_commit();
+      
+
+
+      $sql = "SELECT *
+              FROM so_resultentry
+              WHERE
+              So_ResultEntryID = ? ";
+      $qry = $this->db->query($sql, array(
+        $soresultentryid
+      ));
+
+      if (!$qry) {
+        return array(false, print_r($this->db->error(), true));
+      }
+
+      $rows_return = $qry->row_array();
+
+      return $rows_return;
+    } else {
+      return false;
+    }
+  }
+
+  function get_report_by_code($report_code, $params){
+    $sql = "SELECT *
+              FROM print_transaction
+              WHERE
+              Print_TransactionCode = ? ";
+      $qry = $this->db->query($sql, array(
+        $report_code
+      ));
+
+      if (!$qry) {
+        return array(false, print_r($this->db->error(), true));
+      }
+
+      $rows_return = $qry->row_array();
+
+      return $rows_return;
+  }
+
+  function get_report_url_by_code($report_code, $params = array()){
+    $CI = &get_instance();
+    $this->db = $CI->load->database("onedev", true);
+
+    // Get report data by code
+    $report_data = $this->get_report_by_code($report_code, $params);
+    
+    if (!$report_data || empty($report_data)) {
+      return array(false, "Report code not found: " . $report_code);
+    }
+
+    // Get URL template
+    $url_template = $report_data['Print_TransactionUrl'];
+    
+    if (empty($url_template)) {
+      return array(false, "URL template is empty for report code: " . $report_code);
+    }
+
+    // Replace placeholders with actual parameter values
+    $final_url = $url_template;
+    
+    foreach ($params as $param_key => $param_value) {
+      // Determine if value should be quoted (string) or not (numeric)
+      $replacement_value = is_numeric($param_value) ? $param_value : "'" . $param_value . "'";
+      
+      // Replace placeholder in URL
+      $final_url = str_replace($param_key, $replacement_value, $final_url);
+    }
+
+    return array(true, $final_url);
+  }
+  /*
+CREATE TABLE `print_transaction` (
+  `Print_TransactionID` int(11) NOT NULL AUTO_INCREMENT,
+  `Print_TransactionType` char(2) NOT NULL DEFAULT 'P' COMMENT 'P (paper), E (Email)',
+  `Print_TransactionCode` varchar(20) NOT NULL DEFAULT '',
+  `Print_TransactionName` varchar(150) NOT NULL DEFAULT '',
+  `Print_TransactionUrl` varchar(500) NOT NULL DEFAULT '',
+  `Print_TransactionParams` varchar(500) NOT NULL DEFAULT '',
+  `Print_TransactionCreated` datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
+  `Print_TransactionCreatedUserID` int(11) NOT NULL DEFAULT 0,
+  `Print_TransactionLastUpdated` datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
+  `Print_TransactionLastUpdatedUserID` int(11) NOT NULL DEFAULT 0,
+  PRIMARY KEY (`Print_TransactionID`)
+) ENGINE=InnoDB DEFAULT CHARSET=latin1;
+
+INSERT INTO `print_transaction` (`Print_TransactionID`, `Print_TransactionType`, `Print_TransactionCode`, `Print_TransactionName`, `Print_TransactionUrl`, `Print_TransactionParams`, `Print_TransactionCreated`, `Print_TransactionCreatedUserID`, `Print_TransactionLastUpdated`, `Print_TransactionLastUpdatedUserID`) VALUES
+(1,	'P',	'LAB-RESULT-P-01',	'Report hasil test lab untuk diprint',	'/birt/frameset?__report=report/onelab/lab/rpt_test.rptdesign&__format=pdf&username=PUsername&PID=PT_OrderHeaderID&tm=TS',	'PUsername,PT_OrderHeaderID,TS',	'2026-02-06 09:26:48',	555,	'0000-00-00 00:00:00',	0),
+(2,	'P',	'LAB-RESULT-P-02',	'Report hasil test lab untuk diprint',	'/birt/frameset?__report=report/onelab/lab/rpt_test_email.rptdesign&__format=pdf&username=PUsername&PID=PT_OrderHeaderID&tm=TS',	'PUsername,PT_OrderHeaderID,TS',	'0000-00-00 00:00:00',	555,	'0000-00-00 00:00:00',	0),
+(3,	'P',	'LAB-RESULT-P-03',	'Report hasil test lab untuk diprint',	'/birt/frameset?__report=report/onelab/lab/rpt_test_prev.rptdesign&__format=pdf&username=PUsername&PID=PT_OrderHeaderID&tm=TS',	'PUsername,PT_OrderHeaderID,TS',	'2026-02-06 10:32:54',	555,	'0000-00-00 00:00:00',	0),
+(4,	'P',	'LAB-RESULT-NP-01',	'Report hasil test lab tidak untuk diprint',	'/birt/frameset?__report=report/onelab/lab/rpt_test_not_print.rptdesign&__format=pdf&username=PUsername&PID=PT_OrderHeaderID&tm=TS',	'PUsername,PT_OrderHeaderID,TS',	'2026-02-06 10:25:02',	555,	'0000-00-00 00:00:00',	0),
+(5,	'E',	'LAB-RESULT-NP-02',	'Report hasil test lab tidak untuk email',	'/birt/frameset?__report=report/onelab/lab/rpt_test_email_not_print.rptdesign&__format=pdf&username=PUsername&PID=PT_OrderHeaderID&tm=TS',	'PUsername,PT_OrderHeaderID,TS',	'2026-02-06 10:25:51',	555,	'0000-00-00 00:00:00',	0),
+(6,	'P',	'LAB-RESULT-NP-03',	'Report hasil test lab tidak untuk diprint',	'/birt/frameset?__report=report/onelab/lab/rpt_test_prev_not_print.rptdesign&__format=pdf&username=PUsername&PID=PT_OrderHeaderID&tm=TS',	'PUsername,PT_OrderHeaderID,TS',	'2026-02-06 10:25:51',	555,	'0000-00-00 00:00:00',	0),
+(7,	'P',	'LABEN-RESULT-P-01',	'Report hasil test lab untuk diprint versi inggris',	'/birt/frameset?__report=report/onelab/lab/rpt_test_eng.rptdesign&__format=pdf&username=PUsername&PID=PT_OrderHeaderID&tm=TS',	'PUsername,PT_OrderHeaderID,TS',	'2026-02-06 10:32:09',	555,	'0000-00-00 00:00:00',	0),
+(8,	'E',	'LABEN-RESULT-P-02',	'Report hasil test lab untuk email versi inggris',	'/birt/frameset?__report=report/onelab/lab/rpt_test_email_eng.rptdesign&__format=pdf&username=PUsername&PID=PT_OrderHeaderID&tm=TS',	'PUsername,PT_OrderHeaderID,TS',	'2026-02-06 10:34:57',	555,	'0000-00-00 00:00:00',	0),
+(9,	'P',	'LABEN-RESULT-P-03',	'Report hasil test lab untuk diprint versi inggris',	'/birt/frameset?__report=report/onelab/lab/rpt_test_eng_prev.rptdesign&__format=pdf&username=PUsername&PID=PT_OrderHeaderID&tm=TS',	'PUsername,PT_OrderHeaderID,TS',	'2026-02-06 10:34:57',	555,	'0000-00-00 00:00:00',	0),
+(10,	'P',	'LABEN-RESULT-NP-01',	'Report hasil test lab tidak untuk diprint versi inggris',	'/birt/frameset?__report=report/onelab/lab/rpt_test_not_print_eng.rptdesign&__format=pdf&username=PUsername&PID=PT_OrderHeaderID&tm=TS',	'PUsername,PT_OrderHeaderID,TS',	'2026-02-06 10:34:57',	555,	'0000-00-00 00:00:00',	0),
+(11,	'P',	'MIKROEN-RESULT-P-01',	'Report hasil test mikro untuk diprint versi inggris',	'/birt/frameset?__report=report/onelab/lab/rpt_test_eng.rptdesign&__format=pdf&username=PUsername&PID=PT_OrderHeaderID&tm=TS',	'PUsername,PT_OrderHeaderID,TS',	'2026-02-06 10:34:57',	555,	'0000-00-00 00:00:00',	0),
+(12,	'E',	'MIKROEN-RESULT-P-02',	'Report hasil test mikro untuk email versi inggris',	'/birt/frameset?__report=report/onelab/lab/rpt_test_email_eng.rptdesign&__format=pdf&username=PUsername&PID=PT_OrderHeaderID&tm=TS',	'PUsername,PT_OrderHeaderID,TS',	'2026-02-06 10:34:57',	555,	'0000-00-00 00:00:00',	0),
+(13,	'P',	'MIKROEN-RESULT-P-03',	'Report hasil test mikro untuk diprint versi inggris',	'/birt/frameset?__report=report/onelab/lab/rpt_test_eng_prev.rptdesign&__format=pdf&username=PUsername&PID=PT_OrderHeaderID&tm=TS',	'PUsername,PT_OrderHeaderID,TS',	'2026-02-06 10:34:57',	555,	'0000-00-00 00:00:00',	0),
+(14,	'P',	'MIKROEN-RESULT-NP-01',	'Report hasil test mikro tidak untuk diprint versi inggris',	'/birt/frameset?__report=report/onelab/lab/rpt_test_not_print_eng.rptdesign&__format=pdf&username=PUsername&PID=PT_OrderHeaderID&tm=TS',	'PUsername,PT_OrderHeaderID,TS',	'2026-02-06 10:34:57',	555,	'0000-00-00 00:00:00',	0),
+(45,	'P',	'PS-RESULT-P-01',	'Report hasil test preparasi sperma untuk diprint',	'/birt/frameset?__report=report/onelab/lab/rpt_hasil_sperma.rptdesign&__format=pdf&username=PUsername&PID=PT_OrderHeaderID&tm=TS',	'PUsername,PT_OrderHeaderID,TS',	'2026-02-06 11:24:51',	555,	'0000-00-00 00:00:00',	0),
+(46,	'E',	'PS-RESULT-P-02',	'Report hasil test preparasi sperma untuk email',	'/birt/frameset?__report=report/onelab/lab/rpt_hasil_sperma_email.rptdesign&__format=pdf&username=PUsername&PID=PT_OrderHeaderID&tm=TS',	'PUsername,PT_OrderHeaderID,TS',	'2026-02-06 11:24:51',	555,	'0000-00-00 00:00:00',	0),
+(47,	'P',	'PS-RESULT-NP-01',	'Report hasil test preparasi sperma tidak untuk diprint',	'/birt/frameset?__report=report/onelab/lab/rpt_hasil_sperma_not_print.rptdesign&__format=pdf&username=PUsername&PID=PT_OrderHeaderID&tm=TS',	'PUsername,PT_OrderHeaderID,TS',	'2026-02-06 11:24:51',	555,	'0000-00-00 00:00:00',	0),
+(48,	'P',	'DFI-RESULT-P-01',	'Report hasil test dfi untuk diprint',	'/birt/frameset?__report=report/onelab/lab/rpt_hasil_dfi.rptdesign&__format=pdf&username=PUsername&PID=PT_OrderHeaderID&tm=TS',	'PUsername,PT_OrderHeaderID,TS',	'2026-02-06 11:24:51',	555,	'0000-00-00 00:00:00',	0),
+(49,	'E',	'DFI-RESULT-P-02',	'Report hasil test dfi untuk email',	'/birt/frameset?__report=report/onelab/lab/rpt_hasil_dfi_email.rptdesign&__format=pdf&username=PUsername&PID=PT_OrderHeaderID&tm=TS',	'PUsername,PT_OrderHeaderID,TS',	'2026-02-06 11:24:51',	555,	'0000-00-00 00:00:00',	0),
+(50,	'P',	'DFI-RESULT-NP-01',	'Report hasil test dfi tidak untuk diprint',	'/birt/frameset?__report=report/onelab/lab/rpt_hasil_dfi_not_print.rptdesign&__format=pdf&username=PUsername&PID=PT_OrderHeaderID&tm=TS',	'PUsername,PT_OrderHeaderID,TS',	'2026-02-06 11:24:51',	555,	'0000-00-00 00:00:00',	0),
+(51,	'P',	'FNA-RESULT-P-01',	'Report hasil test fna untuk diprint',	'/birt/frameset?__report=report/onelab/lab/rpt_hasil_fna.rptdesign&__format=pdf&username=PUsername&PID=PT_OrderHeaderID&tm=TS',	'PUsername,PT_OrderHeaderID,TS',	'2026-02-06 11:24:51',	555,	'0000-00-00 00:00:00',	0),
+(52,	'E',	'FNA-RESULT-P-02',	'Report hasil test fna untuk diprint',	'/birt/frameset?__report=report/onelab/lab/rpt_hasil_fna_email.rptdesign&__format=pdf&username=PUsername&PID=PT_OrderHeaderID&tm=TS',	'PUsername,PT_OrderHeaderID,TS',	'2026-02-06 11:24:51',	555,	'0000-00-00 00:00:00',	0),
+(53,	'P',	'FNA-RESULT-NP-01',	'Report hasil test fna tidak untuk diprint',	'/birt/frameset?__report=report/onelab/lab/rpt_hasil_fna_not_print.rptdesign&__format=pdf&username=PUsername&PID=PT_OrderHeaderID&tm=TS',	'PUsername,PT_OrderHeaderID,TS',	'2026-02-06 11:24:51',	555,	'0000-00-00 00:00:00',	0),
+(54,	'P',	'PA-RESULT-P-01',	'Report hasil test patologi anatomi untuk diprint',	'/birt/frameset?__report=report/onelab/lab/rpt_patologi_anatomy.rptdesign&__format=pdf&username=PUsername&PID=PT_OrderHeaderID&tm=TS',	'PUsername,PT_OrderHeaderID,TS',	'2026-02-06 11:24:51',	555,	'0000-00-00 00:00:00',	0),
+(55,	'E',	'PA-RESULT-P-02',	'Report hasil test patologi anatomi untuk diprint',	'/birt/frameset?__report=report/onelab/lab/rpt_patologi_anatomy_email.rptdesign&__format=pdf&username=PUsername&PID=PT_OrderHeaderID&tm=TS',	'PUsername,PT_OrderHeaderID,TS',	'2026-02-06 11:24:51',	555,	'0000-00-00 00:00:00',	0),
+(56,	'P',	'PA-RESULT-NP-01',	'Report hasil test patologi anatomi tidak untuk diprint',	'/birt/frameset?__report=report/onelab/lab/rpt_patologi_anatomy_not_print.rptdesign&__format=pdf&username=PUsername&PID=PT_OrderHeaderID&tm=TS',	'PUsername,PT_OrderHeaderID,TS',	'2026-02-06 11:24:51',	555,	'0000-00-00 00:00:00',	0),
+(57,	'P',	'PAP-RESULT-P-01',	'Report hasil test pap smear untuk diprint',	'/birt/frameset?__report=report/onelab/lab/rpt_hasil_papsmear.rptdesign&__format=pdf&username=PUsername&PID=PT_OrderHeaderID&tm=TS',	'PUsername,PT_OrderHeaderID,TS',	'2026-02-06 11:24:51',	555,	'0000-00-00 00:00:00',	0),
+(58,	'E',	'PAP-RESULT-P-02',	'Report hasil test pap smear untuk diprint',	'/birt/frameset?__report=report/onelab/lab/rpt_hasil_papsmear_email.rptdesign&__format=pdf&username=PUsername&PID=PT_OrderHeaderID&tm=TS',	'PUsername,PT_OrderHeaderID,TS',	'2026-02-06 11:24:51',	555,	'0000-00-00 00:00:00',	0),
+(59,	'P',	'PAP-RESULT-NP-01',	'Report hasil test pap smear tidak untuk diprint',	'/birt/frameset?__report=report/onelab/lab/rpt_hasil_papsmear_not_print.rptdesign&__format=pdf&username=PUsername&PID=PT_OrderHeaderID&tm=TS',	'PUsername,PT_OrderHeaderID,TS',	'2026-02-06 11:24:51',	555,	'0000-00-00 00:00:00',	0),
+(60,	'P',	'PAPLCP-RESULT-P-01',	'Report hasil test pap smear (liquid c prep) untuk diprint',	'/birt/frameset?__report=report/onelab/lab/rpt_hasil_lcprep.rptdesign&__format=pdf&username=PUsername&PID=PT_OrderHeaderID&tm=TS',	'PUsername,PT_OrderHeaderID,TS',	'2026-02-06 11:24:51',	555,	'0000-00-00 00:00:00',	0),
+(61,	'E',	'PAPLCP-RESULT-P-02',	'Report hasil test pap smear (liquid c prep) untuk diprint',	'/birt/frameset?__report=report/onelab/lab/rpt_hasil_lcprep_email.rptdesign&__format=pdf&username=PUsername&PID=PT_OrderHeaderID&tm=TS',	'PUsername,PT_OrderHeaderID,TS',	'2026-02-06 11:24:51',	555,	'0000-00-00 00:00:00',	0),
+(62,	'P',	'PAPLCP-RESULT-NP-01',	'Report hasil test pap smear (liquid c prep) tidak untuk diprint',	'/birt/frameset?__report=report/onelab/lab/rpt_hasil_lcprep_not_print.rptdesign&__format=pdf&username=PUsername&PID=PT_OrderHeaderID&tm=TS',	'PUsername,PT_OrderHeaderID,TS',	'2026-02-06 11:24:51',	555,	'0000-00-00 00:00:00',	0),
+(63,	'P',	'PAPLEN-RESULT-P-01',	'Report hasil test pap smear (liquid c prep) untuk diprint versi inggris',	'/birt/frameset?__report=report/onelab/lab/rpt_hasil_lcprep_eng.rptdesign&__format=pdf&username=PUsername&PID=PT_OrderHeaderID&tm=TS',	'PUsername,PT_OrderHeaderID,TS',	'2026-02-06 11:24:51',	555,	'0000-00-00 00:00:00',	0),
+(64,	'E',	'PAPLEN-RESULT-P-02',	'Report hasil test pap smear (liquid c prep) untuk diprint versi inggris',	'/birt/frameset?__report=report/onelab/lab/rpt_hasil_lcprep_email_eng.rptdesign&__format=pdf&username=PUsername&PID=PT_OrderHeaderID&tm=TS',	'PUsername,PT_OrderHeaderID,TS',	'2026-02-06 11:24:51',	555,	'0000-00-00 00:00:00',	0),
+(65,	'P',	'PAPLEN-RESULT-NP-01',	'Report hasil test pap smear (liquid c prep) tidak untuk diprint versi inggris',	'/birt/frameset?__report=report/onelab/lab/rpt_hasil_lcprep_not_print_eng.rptdesign&__format=pdf&username=PUsername&PID=PT_OrderHeaderID&tm=TS',	'PUsername,PT_OrderHeaderID,TS',	'2026-02-06 11:24:51',	555,	'0000-00-00 00:00:00',	0),
+(66,	'P',	'MIKRO-RESULT-P-01',	'Report hasil test mikro untuk diprint terlampir',	'/birt/frameset?__report=report/onelab/lab/rpt_test_mikro.rptdesign&__format=pdf&username=PUsername&PID=PT_OrderHeaderID&tm=TS',	'PUsername,PT_OrderHeaderID,TS',	'2026-02-06 11:24:51',	555,	'0000-00-00 00:00:00',	0),
+(67,	'E',	'MIKRO-RESULT-P-02',	'Report hasil test mikro untuk email terlampir',	'/birt/frameset?__report=report/onelab/lab/rpt_test_mikro_email.rptdesign&__format=pdf&username=PUsername&PID=PT_OrderHeaderID&tm=TS',	'PUsername,PT_OrderHeaderID,TS',	'2026-02-06 11:24:51',	555,	'0000-00-00 00:00:00',	0),
+(68,	'P',	'MIKRO-RESULT-NP-01',	'Report hasil test mikro tidak untuk diprint terlampir',	'/birt/frameset?__report=report/onelab/lab/rpt_test_mikro_not_print.rptdesign&__format=pdf&username=PUsername&PID=PT_OrderHeaderID&tm=TS',	'PUsername,PT_OrderHeaderID,TS',	'2026-02-06 11:24:51',	555,	'0000-00-00 00:00:00',	0),
+(69,	'P',	'MIKROO-RESULT-P-01',	'Report hasil test mikro untuk diprint tidak terlampir',	'/birt/frameset?__report=report/onelab/lab/rpt_test.rptdesign&__format=pdf&username=PUsername&PID=PT_OrderHeaderID&tm=TS',	'PUsername,PT_OrderHeaderID,TS',	'2026-02-06 11:24:51',	555,	'0000-00-00 00:00:00',	0),
+(70,	'E',	'MIKROO-RESULT-P-02',	'Report hasil test mikro untuk email tidak terlampir',	'/birt/frameset?__report=report/onelab/lab/rpt_test_email.rptdesign&__format=pdf&username=PUsername&PID=PT_OrderHeaderID&tm=TS',	'PUsername,PT_OrderHeaderID,TS',	'2026-02-06 11:24:51',	555,	'0000-00-00 00:00:00',	0),
+(71,	'P',	'MIKROO-RESULT-NP-01',	'Report hasil test mikro untuk tidak diprint tidak terlampir',	'/birt/frameset?__report=report/onelab/lab/rpt_test_not_print.rptdesign&__format=pdf&username=PUsername&PID=PT_OrderHeaderID&tm=TS',	'PUsername,PT_OrderHeaderID,TS',	'2026-02-06 11:24:51',	555,	'0000-00-00 00:00:00',	0),
+(72,	'P',	'CT-RESULT-P-01',	'Report hasil test citology untuk diprint',	'/birt/frameset?__report=report/onelab/lab/rpt_hasil_cytologi.rptdesign&__format=pdf&username=PUsername&PID=PT_OrderHeaderID&tm=TS',	'PUsername,PT_OrderHeaderID,TS',	'2026-02-06 11:24:51',	555,	'0000-00-00 00:00:00',	0),
+(73,	'E',	'CT-RESULT-P-02',	'Report hasil test citology untuk email',	'/birt/frameset?__report=report/onelab/lab/rpt_hasil_cytologi_email.rptdesign&__format=pdf&username=PUsername&PID=PT_OrderHeaderID&tm=TS',	'PUsername,PT_OrderHeaderID,TS',	'2026-02-06 11:24:51',	555,	'0000-00-00 00:00:00',	0),
+(74,	'P',	'CT-RESULT-NP-01',	'Report hasil test citology untuk tidak diprint',	'/birt/frameset?__report=report/onelab/lab/rpt_hasil_cytologi_not_print.rptdesign&__format=pdf&username=PUsername&PID=PT_OrderHeaderID&tm=TS',	'PUsername,PT_OrderHeaderID,TS',	'2026-02-06 11:24:51',	555,	'0000-00-00 00:00:00',	0);
+
+-- 2026-02-06 06:35:26
+  */
+}
diff --git a/application/libraries/Reporturl.php b/application/libraries/Reporturl.php
new file mode 100644
index 00000000..88459e66
--- /dev/null
+++ b/application/libraries/Reporturl.php
@@ -0,0 +1,138 @@
+db = $CI->load->database("onedev", true);
+  }
+
+  function get_report_by_code($report_code, $params){
+    $sql = "SELECT *
+              FROM print_transaction
+              WHERE
+              Print_TransactionCode = ? ";
+      $qry = $this->db->query($sql, array(
+        $report_code
+      ));
+
+      if (!$qry) {
+        return array(false, print_r($this->db->error(), true));
+      }
+
+      $rows_return = $qry->row_array();
+
+      return $rows_return;
+  }
+
+  function get_report_url_by_code($report_code, $params = array(), $show='N'){
+    $CI = &get_instance();
+    $this->db = $CI->load->database("onedev", true);
+
+    // Get report data by code
+    $report_data = $this->get_report_by_code($report_code, $params);
+    
+    if (!$report_data || empty($report_data)) {
+      return array(false, "Report code not found: " . $report_code);
+    }
+
+    // Get URL template
+    $url_template = $report_data['Print_TransactionUrl'];
+    
+    if (empty($url_template)) {
+      return array(false, "URL template is empty for report code: " . $report_code);
+    }
+
+    // Replace placeholders with actual parameter values
+    $final_url = $url_template;
+    
+    foreach ($params as $param_key => $param_value) {
+      // Determine if value should be quoted (string) or not (numeric)
+      $replacement_value = is_numeric($param_value) ? $param_value : "'" . $param_value . "'";
+      
+      // Replace placeholder in URL
+      $final_url = str_replace($param_key, $replacement_value, $final_url);
+    }
+
+    if($show == 'N'){
+        return array(true, $final_url);
+    }
+    else{
+      $final_url = 'http'.($_SERVER['HTTPS'] == 'on' ? 's' : '').'://'.$_SERVER['HTTP_HOST'].$final_url;
+      
+      $response = file_get_contents($final_url);
+      header("Content-type: application/pdf");
+      header(
+      'Content-Disposition: inline; filename="' .
+          $output_file_name .
+          '"'
+      );
+      echo ($response);
+    }
+    
+  }
+  /*
+CREATE TABLE `print_transaction` (
+  `Print_TransactionID` int(11) NOT NULL AUTO_INCREMENT,
+  `Print_TransactionType` char(2) NOT NULL DEFAULT 'P' COMMENT 'P (paper), E (Email)',
+  `Print_TransactionCode` varchar(20) NOT NULL DEFAULT '',
+  `Print_TransactionName` varchar(150) NOT NULL DEFAULT '',
+  `Print_TransactionUrl` varchar(500) NOT NULL DEFAULT '',
+  `Print_TransactionParams` varchar(500) NOT NULL DEFAULT '',
+  `Print_TransactionCreated` datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
+  `Print_TransactionCreatedUserID` int(11) NOT NULL DEFAULT 0,
+  `Print_TransactionLastUpdated` datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
+  `Print_TransactionLastUpdatedUserID` int(11) NOT NULL DEFAULT 0,
+  PRIMARY KEY (`Print_TransactionID`)
+) ENGINE=InnoDB DEFAULT CHARSET=latin1;
+
+INSERT INTO `print_transaction` (`Print_TransactionID`, `Print_TransactionType`, `Print_TransactionCode`, `Print_TransactionName`, `Print_TransactionUrl`, `Print_TransactionParams`, `Print_TransactionCreated`, `Print_TransactionCreatedUserID`, `Print_TransactionLastUpdated`, `Print_TransactionLastUpdatedUserID`) VALUES
+(1,	'P',	'LAB-RESULT-P-01',	'Report hasil test lab untuk diprint',	'/birt/frameset?__report=report/onelab/lab/rpt_test.rptdesign&__format=pdf&username=PUsername&PID=PT_OrderHeaderID&tm=TS',	'PUsername,PT_OrderHeaderID,TS',	'2026-02-06 09:26:48',	555,	'0000-00-00 00:00:00',	0),
+(2,	'P',	'LAB-RESULT-P-02',	'Report hasil test lab untuk diprint',	'/birt/frameset?__report=report/onelab/lab/rpt_test_email.rptdesign&__format=pdf&username=PUsername&PID=PT_OrderHeaderID&tm=TS',	'PUsername,PT_OrderHeaderID,TS',	'0000-00-00 00:00:00',	555,	'0000-00-00 00:00:00',	0),
+(3,	'P',	'LAB-RESULT-P-03',	'Report hasil test lab untuk diprint',	'/birt/frameset?__report=report/onelab/lab/rpt_test_prev.rptdesign&__format=pdf&username=PUsername&PID=PT_OrderHeaderID&tm=TS',	'PUsername,PT_OrderHeaderID,TS',	'2026-02-06 10:32:54',	555,	'0000-00-00 00:00:00',	0),
+(4,	'P',	'LAB-RESULT-NP-01',	'Report hasil test lab tidak untuk diprint',	'/birt/frameset?__report=report/onelab/lab/rpt_test_not_print.rptdesign&__format=pdf&username=PUsername&PID=PT_OrderHeaderID&tm=TS',	'PUsername,PT_OrderHeaderID,TS',	'2026-02-06 10:25:02',	555,	'0000-00-00 00:00:00',	0),
+(5,	'E',	'LAB-RESULT-NP-02',	'Report hasil test lab tidak untuk email',	'/birt/frameset?__report=report/onelab/lab/rpt_test_email_not_print.rptdesign&__format=pdf&username=PUsername&PID=PT_OrderHeaderID&tm=TS',	'PUsername,PT_OrderHeaderID,TS',	'2026-02-06 10:25:51',	555,	'0000-00-00 00:00:00',	0),
+(6,	'P',	'LAB-RESULT-NP-03',	'Report hasil test lab tidak untuk diprint',	'/birt/frameset?__report=report/onelab/lab/rpt_test_prev_not_print.rptdesign&__format=pdf&username=PUsername&PID=PT_OrderHeaderID&tm=TS',	'PUsername,PT_OrderHeaderID,TS',	'2026-02-06 10:25:51',	555,	'0000-00-00 00:00:00',	0),
+(7,	'P',	'LABEN-RESULT-P-01',	'Report hasil test lab untuk diprint versi inggris',	'/birt/frameset?__report=report/onelab/lab/rpt_test_eng.rptdesign&__format=pdf&username=PUsername&PID=PT_OrderHeaderID&tm=TS',	'PUsername,PT_OrderHeaderID,TS',	'2026-02-06 10:32:09',	555,	'0000-00-00 00:00:00',	0),
+(8,	'E',	'LABEN-RESULT-P-02',	'Report hasil test lab untuk email versi inggris',	'/birt/frameset?__report=report/onelab/lab/rpt_test_email_eng.rptdesign&__format=pdf&username=PUsername&PID=PT_OrderHeaderID&tm=TS',	'PUsername,PT_OrderHeaderID,TS',	'2026-02-06 10:34:57',	555,	'0000-00-00 00:00:00',	0),
+(9,	'P',	'LABEN-RESULT-P-03',	'Report hasil test lab untuk diprint versi inggris',	'/birt/frameset?__report=report/onelab/lab/rpt_test_eng_prev.rptdesign&__format=pdf&username=PUsername&PID=PT_OrderHeaderID&tm=TS',	'PUsername,PT_OrderHeaderID,TS',	'2026-02-06 10:34:57',	555,	'0000-00-00 00:00:00',	0),
+(10,	'P',	'LABEN-RESULT-NP-01',	'Report hasil test lab tidak untuk diprint versi inggris',	'/birt/frameset?__report=report/onelab/lab/rpt_test_not_print_eng.rptdesign&__format=pdf&username=PUsername&PID=PT_OrderHeaderID&tm=TS',	'PUsername,PT_OrderHeaderID,TS',	'2026-02-06 10:34:57',	555,	'0000-00-00 00:00:00',	0),
+(11,	'P',	'MIKROEN-RESULT-P-01',	'Report hasil test mikro untuk diprint versi inggris',	'/birt/frameset?__report=report/onelab/lab/rpt_test_eng.rptdesign&__format=pdf&username=PUsername&PID=PT_OrderHeaderID&tm=TS',	'PUsername,PT_OrderHeaderID,TS',	'2026-02-06 10:34:57',	555,	'0000-00-00 00:00:00',	0),
+(12,	'E',	'MIKROEN-RESULT-P-02',	'Report hasil test mikro untuk email versi inggris',	'/birt/frameset?__report=report/onelab/lab/rpt_test_email_eng.rptdesign&__format=pdf&username=PUsername&PID=PT_OrderHeaderID&tm=TS',	'PUsername,PT_OrderHeaderID,TS',	'2026-02-06 10:34:57',	555,	'0000-00-00 00:00:00',	0),
+(13,	'P',	'MIKROEN-RESULT-P-03',	'Report hasil test mikro untuk diprint versi inggris',	'/birt/frameset?__report=report/onelab/lab/rpt_test_eng_prev.rptdesign&__format=pdf&username=PUsername&PID=PT_OrderHeaderID&tm=TS',	'PUsername,PT_OrderHeaderID,TS',	'2026-02-06 10:34:57',	555,	'0000-00-00 00:00:00',	0),
+(14,	'P',	'MIKROEN-RESULT-NP-01',	'Report hasil test mikro tidak untuk diprint versi inggris',	'/birt/frameset?__report=report/onelab/lab/rpt_test_not_print_eng.rptdesign&__format=pdf&username=PUsername&PID=PT_OrderHeaderID&tm=TS',	'PUsername,PT_OrderHeaderID,TS',	'2026-02-06 10:34:57',	555,	'0000-00-00 00:00:00',	0),
+(45,	'P',	'PS-RESULT-P-01',	'Report hasil test preparasi sperma untuk diprint',	'/birt/frameset?__report=report/onelab/lab/rpt_hasil_sperma.rptdesign&__format=pdf&username=PUsername&PID=PT_OrderHeaderID&tm=TS',	'PUsername,PT_OrderHeaderID,TS',	'2026-02-06 11:24:51',	555,	'0000-00-00 00:00:00',	0),
+(46,	'E',	'PS-RESULT-P-02',	'Report hasil test preparasi sperma untuk email',	'/birt/frameset?__report=report/onelab/lab/rpt_hasil_sperma_email.rptdesign&__format=pdf&username=PUsername&PID=PT_OrderHeaderID&tm=TS',	'PUsername,PT_OrderHeaderID,TS',	'2026-02-06 11:24:51',	555,	'0000-00-00 00:00:00',	0),
+(47,	'P',	'PS-RESULT-NP-01',	'Report hasil test preparasi sperma tidak untuk diprint',	'/birt/frameset?__report=report/onelab/lab/rpt_hasil_sperma_not_print.rptdesign&__format=pdf&username=PUsername&PID=PT_OrderHeaderID&tm=TS',	'PUsername,PT_OrderHeaderID,TS',	'2026-02-06 11:24:51',	555,	'0000-00-00 00:00:00',	0),
+(48,	'P',	'DFI-RESULT-P-01',	'Report hasil test dfi untuk diprint',	'/birt/frameset?__report=report/onelab/lab/rpt_hasil_dfi.rptdesign&__format=pdf&username=PUsername&PID=PT_OrderHeaderID&tm=TS',	'PUsername,PT_OrderHeaderID,TS',	'2026-02-06 11:24:51',	555,	'0000-00-00 00:00:00',	0),
+(49,	'E',	'DFI-RESULT-P-02',	'Report hasil test dfi untuk email',	'/birt/frameset?__report=report/onelab/lab/rpt_hasil_dfi_email.rptdesign&__format=pdf&username=PUsername&PID=PT_OrderHeaderID&tm=TS',	'PUsername,PT_OrderHeaderID,TS',	'2026-02-06 11:24:51',	555,	'0000-00-00 00:00:00',	0),
+(50,	'P',	'DFI-RESULT-NP-01',	'Report hasil test dfi tidak untuk diprint',	'/birt/frameset?__report=report/onelab/lab/rpt_hasil_dfi_not_print.rptdesign&__format=pdf&username=PUsername&PID=PT_OrderHeaderID&tm=TS',	'PUsername,PT_OrderHeaderID,TS',	'2026-02-06 11:24:51',	555,	'0000-00-00 00:00:00',	0),
+(51,	'P',	'FNA-RESULT-P-01',	'Report hasil test fna untuk diprint',	'/birt/frameset?__report=report/onelab/lab/rpt_hasil_fna.rptdesign&__format=pdf&username=PUsername&PID=PT_OrderHeaderID&tm=TS',	'PUsername,PT_OrderHeaderID,TS',	'2026-02-06 11:24:51',	555,	'0000-00-00 00:00:00',	0),
+(52,	'E',	'FNA-RESULT-P-02',	'Report hasil test fna untuk diprint',	'/birt/frameset?__report=report/onelab/lab/rpt_hasil_fna_email.rptdesign&__format=pdf&username=PUsername&PID=PT_OrderHeaderID&tm=TS',	'PUsername,PT_OrderHeaderID,TS',	'2026-02-06 11:24:51',	555,	'0000-00-00 00:00:00',	0),
+(53,	'P',	'FNA-RESULT-NP-01',	'Report hasil test fna tidak untuk diprint',	'/birt/frameset?__report=report/onelab/lab/rpt_hasil_fna_not_print.rptdesign&__format=pdf&username=PUsername&PID=PT_OrderHeaderID&tm=TS',	'PUsername,PT_OrderHeaderID,TS',	'2026-02-06 11:24:51',	555,	'0000-00-00 00:00:00',	0),
+(54,	'P',	'PA-RESULT-P-01',	'Report hasil test patologi anatomi untuk diprint',	'/birt/frameset?__report=report/onelab/lab/rpt_patologi_anatomy.rptdesign&__format=pdf&username=PUsername&PID=PT_OrderHeaderID&tm=TS',	'PUsername,PT_OrderHeaderID,TS',	'2026-02-06 11:24:51',	555,	'0000-00-00 00:00:00',	0),
+(55,	'E',	'PA-RESULT-P-02',	'Report hasil test patologi anatomi untuk diprint',	'/birt/frameset?__report=report/onelab/lab/rpt_patologi_anatomy_email.rptdesign&__format=pdf&username=PUsername&PID=PT_OrderHeaderID&tm=TS',	'PUsername,PT_OrderHeaderID,TS',	'2026-02-06 11:24:51',	555,	'0000-00-00 00:00:00',	0),
+(56,	'P',	'PA-RESULT-NP-01',	'Report hasil test patologi anatomi tidak untuk diprint',	'/birt/frameset?__report=report/onelab/lab/rpt_patologi_anatomy_not_print.rptdesign&__format=pdf&username=PUsername&PID=PT_OrderHeaderID&tm=TS',	'PUsername,PT_OrderHeaderID,TS',	'2026-02-06 11:24:51',	555,	'0000-00-00 00:00:00',	0),
+(57,	'P',	'PAP-RESULT-P-01',	'Report hasil test pap smear untuk diprint',	'/birt/frameset?__report=report/onelab/lab/rpt_hasil_papsmear.rptdesign&__format=pdf&username=PUsername&PID=PT_OrderHeaderID&tm=TS',	'PUsername,PT_OrderHeaderID,TS',	'2026-02-06 11:24:51',	555,	'0000-00-00 00:00:00',	0),
+(58,	'E',	'PAP-RESULT-P-02',	'Report hasil test pap smear untuk diprint',	'/birt/frameset?__report=report/onelab/lab/rpt_hasil_papsmear_email.rptdesign&__format=pdf&username=PUsername&PID=PT_OrderHeaderID&tm=TS',	'PUsername,PT_OrderHeaderID,TS',	'2026-02-06 11:24:51',	555,	'0000-00-00 00:00:00',	0),
+(59,	'P',	'PAP-RESULT-NP-01',	'Report hasil test pap smear tidak untuk diprint',	'/birt/frameset?__report=report/onelab/lab/rpt_hasil_papsmear_not_print.rptdesign&__format=pdf&username=PUsername&PID=PT_OrderHeaderID&tm=TS',	'PUsername,PT_OrderHeaderID,TS',	'2026-02-06 11:24:51',	555,	'0000-00-00 00:00:00',	0),
+(60,	'P',	'PAPLCP-RESULT-P-01',	'Report hasil test pap smear (liquid c prep) untuk diprint',	'/birt/frameset?__report=report/onelab/lab/rpt_hasil_lcprep.rptdesign&__format=pdf&username=PUsername&PID=PT_OrderHeaderID&tm=TS',	'PUsername,PT_OrderHeaderID,TS',	'2026-02-06 11:24:51',	555,	'0000-00-00 00:00:00',	0),
+(61,	'E',	'PAPLCP-RESULT-P-02',	'Report hasil test pap smear (liquid c prep) untuk diprint',	'/birt/frameset?__report=report/onelab/lab/rpt_hasil_lcprep_email.rptdesign&__format=pdf&username=PUsername&PID=PT_OrderHeaderID&tm=TS',	'PUsername,PT_OrderHeaderID,TS',	'2026-02-06 11:24:51',	555,	'0000-00-00 00:00:00',	0),
+(62,	'P',	'PAPLCP-RESULT-NP-01',	'Report hasil test pap smear (liquid c prep) tidak untuk diprint',	'/birt/frameset?__report=report/onelab/lab/rpt_hasil_lcprep_not_print.rptdesign&__format=pdf&username=PUsername&PID=PT_OrderHeaderID&tm=TS',	'PUsername,PT_OrderHeaderID,TS',	'2026-02-06 11:24:51',	555,	'0000-00-00 00:00:00',	0),
+(63,	'P',	'PAPLEN-RESULT-P-01',	'Report hasil test pap smear (liquid c prep) untuk diprint versi inggris',	'/birt/frameset?__report=report/onelab/lab/rpt_hasil_lcprep_eng.rptdesign&__format=pdf&username=PUsername&PID=PT_OrderHeaderID&tm=TS',	'PUsername,PT_OrderHeaderID,TS',	'2026-02-06 11:24:51',	555,	'0000-00-00 00:00:00',	0),
+(64,	'E',	'PAPLEN-RESULT-P-02',	'Report hasil test pap smear (liquid c prep) untuk diprint versi inggris',	'/birt/frameset?__report=report/onelab/lab/rpt_hasil_lcprep_email_eng.rptdesign&__format=pdf&username=PUsername&PID=PT_OrderHeaderID&tm=TS',	'PUsername,PT_OrderHeaderID,TS',	'2026-02-06 11:24:51',	555,	'0000-00-00 00:00:00',	0),
+(65,	'P',	'PAPLEN-RESULT-NP-01',	'Report hasil test pap smear (liquid c prep) tidak untuk diprint versi inggris',	'/birt/frameset?__report=report/onelab/lab/rpt_hasil_lcprep_not_print_eng.rptdesign&__format=pdf&username=PUsername&PID=PT_OrderHeaderID&tm=TS',	'PUsername,PT_OrderHeaderID,TS',	'2026-02-06 11:24:51',	555,	'0000-00-00 00:00:00',	0),
+(66,	'P',	'MIKRO-RESULT-P-01',	'Report hasil test mikro untuk diprint terlampir',	'/birt/frameset?__report=report/onelab/lab/rpt_test_mikro.rptdesign&__format=pdf&username=PUsername&PID=PT_OrderHeaderID&tm=TS',	'PUsername,PT_OrderHeaderID,TS',	'2026-02-06 11:24:51',	555,	'0000-00-00 00:00:00',	0),
+(67,	'E',	'MIKRO-RESULT-P-02',	'Report hasil test mikro untuk email terlampir',	'/birt/frameset?__report=report/onelab/lab/rpt_test_mikro_email.rptdesign&__format=pdf&username=PUsername&PID=PT_OrderHeaderID&tm=TS',	'PUsername,PT_OrderHeaderID,TS',	'2026-02-06 11:24:51',	555,	'0000-00-00 00:00:00',	0),
+(68,	'P',	'MIKRO-RESULT-NP-01',	'Report hasil test mikro tidak untuk diprint terlampir',	'/birt/frameset?__report=report/onelab/lab/rpt_test_mikro_not_print.rptdesign&__format=pdf&username=PUsername&PID=PT_OrderHeaderID&tm=TS',	'PUsername,PT_OrderHeaderID,TS',	'2026-02-06 11:24:51',	555,	'0000-00-00 00:00:00',	0),
+(69,	'P',	'MIKROO-RESULT-P-01',	'Report hasil test mikro untuk diprint tidak terlampir',	'/birt/frameset?__report=report/onelab/lab/rpt_test.rptdesign&__format=pdf&username=PUsername&PID=PT_OrderHeaderID&tm=TS',	'PUsername,PT_OrderHeaderID,TS',	'2026-02-06 11:24:51',	555,	'0000-00-00 00:00:00',	0),
+(70,	'E',	'MIKROO-RESULT-P-02',	'Report hasil test mikro untuk email tidak terlampir',	'/birt/frameset?__report=report/onelab/lab/rpt_test_email.rptdesign&__format=pdf&username=PUsername&PID=PT_OrderHeaderID&tm=TS',	'PUsername,PT_OrderHeaderID,TS',	'2026-02-06 11:24:51',	555,	'0000-00-00 00:00:00',	0),
+(71,	'P',	'MIKROO-RESULT-NP-01',	'Report hasil test mikro untuk tidak diprint tidak terlampir',	'/birt/frameset?__report=report/onelab/lab/rpt_test_not_print.rptdesign&__format=pdf&username=PUsername&PID=PT_OrderHeaderID&tm=TS',	'PUsername,PT_OrderHeaderID,TS',	'2026-02-06 11:24:51',	555,	'0000-00-00 00:00:00',	0),
+(72,	'P',	'CT-RESULT-P-01',	'Report hasil test citology untuk diprint',	'/birt/frameset?__report=report/onelab/lab/rpt_hasil_cytologi.rptdesign&__format=pdf&username=PUsername&PID=PT_OrderHeaderID&tm=TS',	'PUsername,PT_OrderHeaderID,TS',	'2026-02-06 11:24:51',	555,	'0000-00-00 00:00:00',	0),
+(73,	'E',	'CT-RESULT-P-02',	'Report hasil test citology untuk email',	'/birt/frameset?__report=report/onelab/lab/rpt_hasil_cytologi_email.rptdesign&__format=pdf&username=PUsername&PID=PT_OrderHeaderID&tm=TS',	'PUsername,PT_OrderHeaderID,TS',	'2026-02-06 11:24:51',	555,	'0000-00-00 00:00:00',	0),
+(74,	'P',	'CT-RESULT-NP-01',	'Report hasil test citology untuk tidak diprint',	'/birt/frameset?__report=report/onelab/lab/rpt_hasil_cytologi_not_print.rptdesign&__format=pdf&username=PUsername&PID=PT_OrderHeaderID&tm=TS',	'PUsername,PT_OrderHeaderID,TS',	'2026-02-06 11:24:51',	555,	'0000-00-00 00:00:00',	0);
+
+-- 2026-02-06 06:35:26
+  */
+}
diff --git a/application/libraries/Resultcalc-bkp.php b/application/libraries/Resultcalc-bkp.php
new file mode 100644
index 00000000..c7680ee4
--- /dev/null
+++ b/application/libraries/Resultcalc-bkp.php
@@ -0,0 +1,113 @@
+db = $CI->load->database("onedev",true);
+       $sql = "select 
+          T_TestCalculationID,T_TestCalculationFormula,
+          T_OrderDetailID, T_OrderDetailT_TestID, T_TestNat_TestID Nat_TestID,
+          T_TestCalculationID,T_OrderDetailResult, 
+          fn_global_age_count_day(M_PatientDOB, date(T_OrderHeaderDate)) / 365 AgeInYear,
+          T_TestCalculationNat_SexID
+       from t_orderdetail
+       join t_orderheader on T_OrderDetailT_OrderHeaderID = T_OrderHeaderID 
+            and T_OrderHeaderID = ?
+       join m_patient on T_OrderHeaderM_PatientID = M_PatientID 
+       join t_test on T_OrderDetailT_TestID = T_TestID 
+         and T_OrderDetailIsActive = 'Y' and T_TestIsActive = 'Y'
+       join t_testcalculation on T_TestNat_TestID  = T_TestCalculationNat_TestID 
+         and T_TestCalculationIsActive = 'Y'
+         and (
+            T_TestCalculationNat_SexID = M_PatientM_SexID
+            or 
+            T_TestCalculationNat_SexID = 0
+         )
+       ";
+
+       $sql_det = "select T_TestCalculationDetailCode, T_OrderDetailResult
+          from 
+         t_testcalculation_detail td 
+         join t_testcalculation on T_TestCalculationID = T_TestCalculationDetailT_TestCalculationID
+            and T_TestCalculationID = ?
+         join t_test t on td.T_TestCalculationDetailNat_TestID = T_TestNat_TestID 
+         left join t_orderdetail on T_TestID = T_OrderDetailT_TestID and T_OrderDetailIsActive = 'Y'
+            and T_OrderDetailT_OrderHeaderID = ?
+         where T_OrderDetailID is not null";
+      
+
+       $qry = $this->db->query($sql, array($id));
+       $rows = $qry->result_array();
+       
+       if ( count($rows) > 0 ) {
+          foreach($rows as $r) {
+             $tc_id = $r["T_TestCalculationID"];
+             $formula = $r["T_TestCalculationFormula"];
+             $qry_det = $this->db->query($sql_det, array($tc_id, $id));
+             $drows = $qry_det->result_array();
+             $have_all = true;
+             $have_one = false;
+             $formula = str_replace("AGE",$r["AgeInYear"], $formula);
+             $flag_recursive = false;
+             if (strpos($formula,"[REC]") > -1 ) {
+                $flag_recursive = true;
+             }
+             if ( ! $flag_recursive ) {
+                if( trim($r["T_OrderDetailResult"]) != "") continue;
+             }
+
+             $formula = str_replace("[REC]","", $formula);
+             foreach($drows as $dr) {
+                $code = $dr["T_TestCalculationDetailCode"];
+                $value = $dr["T_OrderDetailResult"];
+                if($dr["T_OrderDetailResult"] == "" ) {
+                   $have_all = false;
+                   break;
+                }
+                $have_one = true;
+                $formula = str_replace($code, $value,$formula);
+             }
+             if ($have_all && $have_one) {
+
+                eval("\$f_value = $formula;");
+                //formating 
+               //echo "\n$f_value ..";
+                //file_put_contents("/xtmp/formula",$f_value. "\n",FILE_APPEND);
+                if (is_numeric($f_value)) {
+                   $f_value = $this->format_value($f_value,$r["Nat_TestID"]);
+                }
+                //file_put_contents("/xtmp/formula",$f_value. "\n",FILE_APPEND);
+                $od_id = $r["T_OrderDetailID"]; 
+                $sql = "update t_orderdetail set T_OrderDetailResult = ?
+                where T_OrderDetailID = ?";
+                $this->db->query($sql, array($f_value,$od_id));
+             } 
+         } 
+       }
+   }
+   function format_value($f_value, $nat_test_id){
+       $CI =& get_instance();
+       $this->db = $CI->load->database("onedev",true);
+       $sql = "select * from m_instrumentmethode
+            where M_InstrumentMethodeIsActive = 'Y'
+           and M_InstrumentMethodeNat_TestID = ?
+           limit 0,1";
+       $qry = $this->db->query($sql, array($nat_test_id) ); 
+       if ($qry) {
+         $rows = $qry->result_array();
+         if (count($rows) > 0 ) {
+            if ($f_value > 0 ) {
+               $fmt = $rows[0]["M_InstrumentMethodeResultFormatAboveSF"];
+            } else {
+               $fmt = $rows[0]["M_InstrumentMethodeResultFormatSF"];
+            }
+            $idx = strpos($fmt,".");
+            $dec = strlen($fmt) - $idx;
+            if ($dec > 0 ) $dec = $dec -1;
+            return number_format($f_value,$dec);
+         }
+       }
+       return number_format($f_value,0,".",",");
+   }
+}
diff --git a/application/libraries/Resultcalc-new.php b/application/libraries/Resultcalc-new.php
new file mode 100644
index 00000000..d21256d0
--- /dev/null
+++ b/application/libraries/Resultcalc-new.php
@@ -0,0 +1,107 @@
+db = $CI->load->database("onedev",true);
+       $sql = "select 
+          T_TestCalculationID,T_TestCalculationFormula,
+          T_OrderDetailID, T_OrderDetailT_TestID, T_TestNat_TestID Nat_TestID,
+          T_TestCalculationID,T_OrderDetailResult, 
+          fn_global_age_count_day(M_PatientDOB, date(T_OrderHeaderDate)) / 365 AgeInYear,
+          T_TestCalculationNat_SexID
+       from t_orderdetail
+       join t_orderheader on T_OrderDetailT_OrderHeaderID = T_OrderHeaderID 
+            and T_OrderHeaderID = ?
+       join m_patient on T_OrderHeaderM_PatientID = M_PatientID 
+       join t_test on T_OrderDetailT_TestID = T_TestID 
+         and T_OrderDetailIsActive = 'Y' and T_TestIsActive = 'Y'
+       join t_testcalculation on T_TestNat_TestID  = T_TestCalculationNat_TestID 
+         and T_TestCalculationIsActive = 'Y'
+         and (
+            T_TestCalculationNat_SexID = M_PatientM_SexID
+            or 
+            T_TestCalculationNat_SexID = 0
+         )
+       ";
+
+       $sql_det = "select T_TestCalculationDetailCode, T_OrderDetailResult
+          from 
+         t_testcalculation_detail td 
+         join t_testcalculation on T_TestCalculationID = T_TestCalculationDetailT_TestCalculationID
+            and T_TestCalculationID = ?
+         join t_test t on td.T_TestCalculationDetailNat_TestID = T_TestNat_TestID 
+         left join t_orderdetail on T_TestID = T_OrderDetailT_TestID and T_OrderDetailIsActive = 'Y'
+            and T_OrderDetailT_OrderHeaderID = ?
+         where T_OrderDetailID is not null";
+      
+
+       $qry = $this->db->query($sql, array($id));
+       $rows = $qry->result_array();
+       if ( count($rows) > 0 ) {
+          foreach($rows as $r) {
+             $tc_id = $r["T_TestCalculationID"];
+             $qry_det = $this->db->query($sql_det, array($tc_id, $id));
+             $drows = $qry_det->result_array();
+             $formula = $r["T_TestCalculationFormula"];
+             $have_all = true;
+             $have_one = false;
+             $formula = str_replace("AGE",$r["AgeInYear"], $formula);
+             $flag_recursive = false;
+             if (strpos($formula,"[REC]") > -1 ) {
+                $flag_recursive = true;
+             }
+             if ( ! $flag_recursive ) {
+                if( $r["T_OrderDetailResult"] != "") continue;
+             }
+             $formula = str_replace("[REC]","", $formula);
+             foreach($drows as $dr) {
+                if($dr["T_OrderDetailResult"] == "" ) {
+                   $have_all = false;
+                   break;
+                }
+                $have_one = true;
+                $code = $dr["T_TestCalculationDetailCode"];
+                $value = $dr["T_OrderDetailResult"];
+                $formula = str_replace($code, $value,$formula);
+             }
+             if ($have_all && $have_one) {
+
+                eval("\$f_value = $formula;");
+                file_put_contents("/xtmp/formula",$formula . "\n",FILE_APPEND);
+                //formating 
+                $f_value = $this->format_value($f_value,$r["Nat_TestID"]);
+                $od_id = $r["T_OrderDetailID"]; 
+                $sql = "update t_orderdetail set T_OrderDetailResult = ?
+                where T_OrderDetailID = ?";
+                $this->db->query($sql, array($f_value,$od_id));
+             } 
+         } 
+       }
+   }
+   function format_value($f_value, $nat_test_id){
+       $CI =& get_instance();
+       $this->db = $CI->load->database("onedev",true);
+       $sql = "select * from m_instrumentmethode
+            where M_InstrumentMethodeIsActive = 'Y'
+           and M_InstrumentMethodeNat_TestID = ?
+           limit 0,1";
+       $qry = $this->db->query($sql, array($nat_test_id) ); 
+       if ($qry) {
+         $rows = $qry->result_array();
+         if (count($rows) > 0 ) {
+            if ($f_value > 0 ) {
+               $fmt = $rows[0]["M_InstrumentMethodeResultFormatAboveSF"];
+            } else {
+               $fmt = $rows[0]["M_InstrumentMethodeResultFormatSF"];
+            }
+            $idx = strpos($fmt,".");
+            $dec = strlen($fmt) - $idx;
+            if ($dec > 0 ) $dec = $dec -1;
+            return number_format($f_value,$dec);
+         }
+       }
+       return number_format($f_value,0,".",",");
+   }
+}
diff --git a/application/libraries/Resultcalc-riau.php b/application/libraries/Resultcalc-riau.php
new file mode 100644
index 00000000..fc7f8bb0
--- /dev/null
+++ b/application/libraries/Resultcalc-riau.php
@@ -0,0 +1,110 @@
+db = $CI->load->database("onedev",true);
+       $sql = "select 
+          T_TestCalculationID,T_TestCalculationFormula,
+          T_OrderDetailID, T_OrderDetailT_TestID, T_TestNat_TestID Nat_TestID,
+          T_TestCalculationID,T_OrderDetailResult, 
+          fn_global_age_count_day(M_PatientDOB, date(T_OrderHeaderDate)) / 365 AgeInYear,
+          T_TestCalculationNat_SexID
+       from t_orderdetail
+       join t_orderheader on T_OrderDetailT_OrderHeaderID = T_OrderHeaderID 
+            and T_OrderHeaderID = ?
+       join m_patient on T_OrderHeaderM_PatientID = M_PatientID 
+       join t_test on T_OrderDetailT_TestID = T_TestID 
+         and T_OrderDetailIsActive = 'Y' and T_TestIsActive = 'Y'
+       join t_testcalculation on T_TestNat_TestID  = T_TestCalculationNat_TestID 
+         and T_TestCalculationIsActive = 'Y'
+         and (
+            T_TestCalculationNat_SexID = M_PatientM_SexID
+            or 
+            T_TestCalculationNat_SexID = 0
+         )
+       ";
+
+       $sql_det = "select T_TestCalculationDetailCode, T_OrderDetailResult
+          from 
+         t_testcalculation_detail td 
+         join t_testcalculation on T_TestCalculationID = T_TestCalculationDetailT_TestCalculationID
+            and T_TestCalculationID = ?
+         join t_test t on td.T_TestCalculationDetailNat_TestID = T_TestNat_TestID 
+         left join t_orderdetail on T_TestID = T_OrderDetailT_TestID and T_OrderDetailIsActive = 'Y'
+            and T_OrderDetailT_OrderHeaderID = ?
+         where T_OrderDetailID is not null";
+      
+
+       $qry = $this->db->query($sql, array($id));
+       $rows = $qry->result_array();
+       if ( count($rows) > 0 ) {
+          foreach($rows as $r) {
+             $tc_id = $r["T_TestCalculationID"];
+             $qry_det = $this->db->query($sql_det, array($tc_id, $id));
+             $drows = $qry_det->result_array();
+             $formula = $r["T_TestCalculationFormula"];
+             $have_all = true;
+             $have_one = false;
+             $formula = str_replace("AGE",$r["AgeInYear"], $formula);
+             $flag_recursive = false;
+             if (strpos($formula,"[REC]") > -1 ) {
+                $flag_recursive = true;
+             }
+             //echo "$formula " . $r["T_OrderDetailResult"] . "\n";
+             if ( ! $flag_recursive ) {
+                if( trim($r["T_OrderDetailResult"]) != "") continue;
+             }
+
+             $formula = str_replace("[REC]","", $formula);
+             foreach($drows as $dr) {
+                $code = $dr["T_TestCalculationDetailCode"];
+                $value = $dr["T_OrderDetailResult"];
+                //echo "$code , $value , $formula \n";
+                if($dr["T_OrderDetailResult"] == "" ) {
+                   $have_all = false;
+                   break;
+                }
+                $have_one = true;
+                $formula = str_replace($code, $value,$formula);
+             }
+             if ($have_all && $have_one) {
+
+                eval("\$f_value = $formula;");
+                //formating 
+                //echo "\n$f_value ..";
+                $f_value = $this->format_value($f_value,$r["Nat_TestID"]);
+                $od_id = $r["T_OrderDetailID"]; 
+                $sql = "update t_orderdetail set T_OrderDetailResult = ?
+                where T_OrderDetailID = ?";
+                $this->db->query($sql, array($f_value,$od_id));
+             } 
+         } 
+       }
+   }
+   function format_value($f_value, $nat_test_id){
+       $CI =& get_instance();
+       $this->db = $CI->load->database("onedev",true);
+       $sql = "select * from m_instrumentmethode
+            where M_InstrumentMethodeIsActive = 'Y'
+           and M_InstrumentMethodeNat_TestID = ?
+           limit 0,1";
+       $qry = $this->db->query($sql, array($nat_test_id) ); 
+       if ($qry) {
+         $rows = $qry->result_array();
+         if (count($rows) > 0 ) {
+            if ($f_value > 0 ) {
+               $fmt = $rows[0]["M_InstrumentMethodeResultFormatAboveSF"];
+            } else {
+               $fmt = $rows[0]["M_InstrumentMethodeResultFormatSF"];
+            }
+            $idx = strpos($fmt,".");
+            $dec = strlen($fmt) - $idx;
+            if ($dec > 0 ) $dec = $dec -1;
+            return number_format($f_value,$dec);
+         }
+       }
+       return number_format($f_value,0,".",",");
+   }
+}
diff --git a/application/libraries/Resultcalc.php b/application/libraries/Resultcalc.php
new file mode 100644
index 00000000..7205eefd
--- /dev/null
+++ b/application/libraries/Resultcalc.php
@@ -0,0 +1,175 @@
+db = $CI->load->database("onedev", true);
+    $sql = "select 
+          T_TestCalculationID,T_TestCalculationFormula,
+          T_OrderDetailID, T_OrderDetailT_TestID, T_TestNat_TestID Nat_TestID,
+          T_TestCalculationID,T_OrderDetailResult, 
+          fn_global_age_count_day(M_PatientDOB, date(T_OrderHeaderDate)) / 365 AgeInYear,
+          T_TestCalculationNat_SexID,
+          T_OrderDetailT_TestName
+       from t_orderdetail
+       join t_orderheader on T_OrderDetailT_OrderHeaderID = T_OrderHeaderID 
+            and T_OrderHeaderID = ?
+       join m_patient on T_OrderHeaderM_PatientID = M_PatientID 
+       join t_test on T_OrderDetailT_TestID = T_TestID 
+         and T_OrderDetailIsActive = 'Y' and T_TestIsActive = 'Y'
+       join t_testcalculation on T_TestNat_TestID  = T_TestCalculationNat_TestID 
+         and T_TestCalculationIsActive = 'Y'
+         and (
+            T_TestCalculationNat_SexID = M_PatientM_SexID
+            or 
+            T_TestCalculationNat_SexID = 0
+         )
+       ";
+
+    $sql_det = "select T_OrderDetailT_TestName, T_TestCalculationDetailCode, T_OrderDetailResult
+          from 
+         t_testcalculation_detail td 
+         join t_testcalculation on T_TestCalculationID = T_TestCalculationDetailT_TestCalculationID
+            and T_TestCalculationID = ? and T_TestCalculationDetailIsActive = 'Y'
+         join t_test t on td.T_TestCalculationDetailNat_TestID = T_TestNat_TestID 
+         left join t_orderdetail on T_TestID = T_OrderDetailT_TestID and T_OrderDetailIsActive = 'Y'
+            and T_OrderDetailT_OrderHeaderID = ?
+         Order by T_TestCalculationDetailCode,T_OrderDetailResult desc";
+    //where T_OrderDetailID is not null";
+
+
+    $qry = $this->db->query($sql, array($id));
+    $date = date("Y-m-d H:i:s");
+    //file_put_contents("/xtmp/debug-calc.log", "$date : {$this->db->last_query()} \n");
+    $rows = $qry->result_array();
+    if ($debug != "") {
+      print_r($rows);
+    }
+
+    if (count($rows) > 0) {
+      foreach ($rows as $r) {
+        $tc_id = $r["T_TestCalculationID"];
+        $qry_det = $this->db->query($sql_det, array($tc_id, $id));
+        $drows = $qry_det->result_array();
+        $formula = $r["T_TestCalculationFormula"];
+        $have_all = true;
+        $have_one = false;
+        $formula = str_replace("AGE", $r["AgeInYear"], $formula);
+        $flag_recursive = false;
+        if (strpos($formula, "[REC]") > -1) {
+          $flag_recursive = true;
+        }
+        if (!$flag_recursive) {
+          if (trim($r["T_OrderDetailResult"]) != "") continue;
+        }
+
+        $formula = str_replace("[REC]", "", $formula);
+        $org_formula = $formula;
+        $s_code_value = "";
+        $tc_name = $r["T_OrderDetailT_TestName"];
+
+        $arr_code = array();
+
+        $arr_param = [];
+        foreach ($drows as $dr) {
+          $code = $dr["T_TestCalculationDetailCode"];
+          $value = $dr["T_OrderDetailResult"];
+          $s_code_value .= "^$code=$value";
+          $arr_param[] = $code;
+          if (isset($arr_code[$code])) continue;
+          $arr_code[$code] = "exist";
+          if ($dr["T_OrderDetailResult"] == "" || $dr["T_OrderDetailResult"] == "-") {
+            $have_all = false;
+            break;
+          }
+          $arr_code[$code] = $value;
+          $have_one = true;
+          $formula = str_replace($code, $value, $formula);
+        }
+        $have_all = true;
+        if (count($arr_param) == 0) $have_all = false;
+        foreach($arr_param as $p) {
+          if ($debug != "") {
+            echo "code $p : ";
+          }
+          if (!isset($arr_code[$p])) {
+            if ($debug != "") {
+              echo "not exists \n";
+            }
+            $have_all = false;
+            break;
+          } else {
+            if ($arr_code[$p] == "exist") {
+              $have_all = false;
+            }
+            if ($debug != "") {
+              echo "exists : {$arr_code[$p]} \n";
+            }
+          }
+        }
+        if ($debug != "") {
+          echo "$formula " . $r["T_OrderDetailResult"] . "\n";
+          echo "-- have one : " . $have_one ? "Y" : "N";
+          echo "\n";
+          echo "-- have all : " . $have_all ? "Y" : "N";
+          echo "\n";
+        }
+        if ($have_all && $have_one) {
+
+          $date = date("Y-m-d H:i:s");
+          try {
+            // file_put_contents("/xtmp/debug-calc.log", "$date : $tc_name => \$f_value = $formula; \n");
+            // file_put_contents("/xtmp/debug-calc.log", "$date : Formula : $org_formula\n",FILE_APPEND);
+            // file_put_contents("/xtmp/debug-calc.log", print_r($drows,true),FILE_APPEND);
+
+            eval("\$f_value = $formula;");
+            //formating 
+            $f_value = $this->format_value($f_value, $r["Nat_TestID"]);
+            if (is_numeric($f_value)) {
+              $f_value = $this->format_value($f_value, $r["Nat_TestID"]);
+            }
+            $od_id = $r["T_OrderDetailID"];
+            $sql = "update t_orderdetail set T_OrderDetailResult = ?
+                  where T_OrderDetailID = ?";
+            $this->db->query($sql, array($f_value, $od_id));
+
+            if ($tc_id == 2) {
+              $sql = "insert into t_order_calc(T_OrderCalcT_OrderDetailID,
+                      T_OrderCalcFormula,T_OrderCalcResult) values(?,?,?)";
+              $this->db->query($sql, array($od_id, $formula . " | " . $s_code_value, $f_value));
+            }
+          } catch (Exception $e) {
+            //print_r($e);
+          }
+        }
+      }
+    }
+  }
+  function format_value($f_value, $nat_test_id)
+  {
+    $CI = &get_instance();
+    $this->db = $CI->load->database("onedev", true);
+    $sql = "select * from m_instrumentmethode
+            where M_InstrumentMethodeIsActive = 'Y'
+           and M_InstrumentMethodeNat_TestID = ?
+           limit 0,1";
+    $qry = $this->db->query($sql, array($nat_test_id));
+    if ($qry) {
+      $rows = $qry->result_array();
+      if (count($rows) > 0) {
+        if ($f_value > 0) {
+          $fmt = $rows[0]["M_InstrumentMethodeResultFormatAboveSF"];
+        } else {
+          $fmt = $rows[0]["M_InstrumentMethodeResultFormatSF"];
+        }
+        $idx = strpos($fmt, ".");
+        $dec = strlen($fmt) - $idx;
+        if ($dec > 0) $dec = $dec - 1;
+        return number_format($f_value, $dec);
+      }
+    }
+    return number_format($f_value, 0, ".", ",");
+  }
+}
diff --git a/application/libraries/Resultcalcv2.php b/application/libraries/Resultcalcv2.php
new file mode 100644
index 00000000..e36d34c1
--- /dev/null
+++ b/application/libraries/Resultcalcv2.php
@@ -0,0 +1,116 @@
+db = $CI->load->database("onedev",true);
+       $sql = "select 
+          T_TestCalculationID,T_TestCalculationFormula,
+          T_OrderDetailID, T_OrderDetailT_TestID, T_TestNat_TestID Nat_TestID,
+          T_TestCalculationID,T_OrderDetailResult, 
+          fn_global_age_count_day(M_PatientDOB, date(T_OrderHeaderDate)) / 365 AgeInYear,
+          T_TestCalculationNat_SexID
+       from t_orderdetail
+       join t_orderheader on T_OrderDetailT_OrderHeaderID = T_OrderHeaderID 
+            and T_OrderHeaderID = ?
+       join m_patient on T_OrderHeaderM_PatientID = M_PatientID 
+       join t_test on T_OrderDetailT_TestID = T_TestID 
+         and T_OrderDetailIsActive = 'Y' and T_TestIsActive = 'Y'
+       join t_testcalculation on T_TestNat_TestID  = T_TestCalculationNat_TestID 
+         and T_TestCalculationIsActive = 'Y'
+         and (
+            T_TestCalculationNat_SexID = M_PatientM_SexID
+            or 
+            T_TestCalculationNat_SexID = 0
+         )
+       ";
+
+       $sql_det = "select T_TestCalculationDetailCode, T_OrderDetailResult
+          from 
+         t_testcalculation_detail td 
+         join t_testcalculation on T_TestCalculationID = T_TestCalculationDetailT_TestCalculationID
+            and T_TestCalculationID = ?
+         join t_test t on td.T_TestCalculationDetailNat_TestID = T_TestNat_TestID 
+         left join t_orderdetail on T_TestID = T_OrderDetailT_TestID and T_OrderDetailIsActive = 'Y'
+            and T_OrderDetailT_OrderHeaderID = ?
+         where T_OrderDetailID is not null";
+      
+
+       $qry = $this->db->query($sql, array($id));
+       $rows = $qry->result_array();
+       if ( count($rows) > 0 ) {
+          foreach($rows as $r) {
+             $tc_id = $r["T_TestCalculationID"];
+             $qry_det = $this->db->query($sql_det, array($tc_id, $id));
+             $drows = $qry_det->result_array();
+             $formula = $r["T_TestCalculationFormula"];
+             $have_all = true;
+             $have_one = false;
+             $formula = str_replace("AGE",$r["AgeInYear"], $formula);
+             $flag_recursive = false;
+             if (strpos($formula,"[REC]") > -1 ) {
+                $flag_recursive = true;
+             }
+             echo "$formula " . $r["T_OrderDetailResult"] . "\n";
+             if ( ! $flag_recursive ) {
+                if( trim($r["T_OrderDetailResult"]) != "") continue;
+             }
+
+             $formula = str_replace("[REC]","", $formula);
+             foreach($drows as $dr) {
+                $code = $dr["T_TestCalculationDetailCode"];
+                $value = $dr["T_OrderDetailResult"];
+                echo "$code , $value , $formula \n";
+                if($dr["T_OrderDetailResult"] == "" ) {
+                   $have_all = false;
+                   break;
+                }
+                $have_one = true;
+                $formula = str_replace($code, $value,$formula);
+             }
+             if ($have_all && $have_one) {
+
+                eval("\$f_value = $formula;");
+                //formating 
+                echo "\n$f_value ..";
+                $f_value = $this->format_value($f_value,$r["Nat_TestID"]);
+                if (is_numeric($f_value)) {
+                   $f_value = $this->format_value($f_value,$r["Nat_TestID"]);
+                }
+                $od_id = $r["T_OrderDetailID"]; 
+                $sql = "update t_orderdetail set T_OrderDetailResult = ?
+                where T_OrderDetailID = ?";
+                $this->db->query($sql, array($f_value,$od_id));
+                $sql = "insert into t_order_calc(T_OrderCalcT_OrderDetailID,
+                   T_OrderCalcFormula,T_OrderCalcResult) values(?,?,?)";
+                $this->db->query($sql, array($od_id,$formula,$f_value));
+             } 
+         } 
+       }
+   }
+   function format_value($f_value, $nat_test_id){
+       $CI =& get_instance();
+       $this->db = $CI->load->database("onedev",true);
+       $sql = "select * from m_instrumentmethode
+            where M_InstrumentMethodeIsActive = 'Y'
+           and M_InstrumentMethodeNat_TestID = ?
+           limit 0,1";
+       $qry = $this->db->query($sql, array($nat_test_id) ); 
+       if ($qry) {
+         $rows = $qry->result_array();
+         if (count($rows) > 0 ) {
+            if ($f_value > 0 ) {
+               $fmt = $rows[0]["M_InstrumentMethodeResultFormatAboveSF"];
+            } else {
+               $fmt = $rows[0]["M_InstrumentMethodeResultFormatSF"];
+            }
+            $idx = strpos($fmt,".");
+            $dec = strlen($fmt) - $idx;
+            if ($dec > 0 ) $dec = $dec -1;
+            return number_format($f_value,$dec);
+         }
+       }
+       return number_format($f_value,0,".",",");
+   }
+}
diff --git a/application/libraries/Sas_s3.php b/application/libraries/Sas_s3.php
new file mode 100644
index 00000000..fec64826
--- /dev/null
+++ b/application/libraries/Sas_s3.php
@@ -0,0 +1,49 @@
+bucket = "audio-sample";
+        $this->s3 = new Aws\S3\S3Client([
+            "region"  => "us-east-1",
+            "endpoint" => $this->endpoint,
+            "use_path_style_endpoint" => true,
+            "credentials" => [
+                "key" => "DLBFBBB8R22W4B5IE7PC",
+                "secret" => "byCv726DN1TCQvLVHdSLMJg3K0i3Ajhm4rXPAVCu"
+            ]
+        ]);
+    }
+    function create_bucket($bucket)
+    {
+        $result = $this->s3->createBucket(["Bucket" =>  $bucket]);
+        return $result;
+    }
+    function upload($bucket, $key, $contentType, $body)
+    {
+        $result = $this->s3->putObject(
+            [
+                "Bucket" => $bucket,
+                "Key" => $key,
+                "Body" => $body,
+                "ContentType" => $contentType
+            ]
+        );
+        return $result;
+    }
+    // avail : 10 minutes
+    function show_url($bucket, $key, $avail)
+    {
+        $cmd = $this->s3->getCommand("GetObject", ['Bucket' => $bucket, 'Key' => $key]);
+        $request = $this->s3->createPresignedRequest($cmd, '+20 minutes');
+        $presignedUrl = $request->getUri();
+        return $presignedUrl;
+    }
+}
diff --git a/application/libraries/Satu_sehat.php b/application/libraries/Satu_sehat.php
new file mode 100644
index 00000000..02f762d6
--- /dev/null
+++ b/application/libraries/Satu_sehat.php
@@ -0,0 +1,584 @@
+tz = "+07:00";
+    $this->is_staging = false;
+    $this->base_url = "https://api-satusehat.kemkes.go.id/fhir-r4/v1";
+    $this->base_oauth_url = "https://api-satusehat.kemkes.go.id/oauth2/v1";
+    $this->base_consent_url = "https://api-satusehat.dto.kemkes.go.id/consent/v1";
+    $CI = &get_instance();
+    $this->db = $CI->load->database("default", true);
+
+    $this->dbname = "one_health";
+    if ($this->is_staging) {
+      $this->base_url = "https://api-satusehat-stg.kemkes.go.id/fhir-r4/v1";
+      $this->base_oauth_url = "https://api-satusehat-stg.kemkes.go.id/oauth2/v1";
+      $this->base_consent_url = "https://api-satusehat-stg.dto.kemkes.go.id/consent/v1";
+      $this->dbname = "one_health_dev";
+    }
+    $this->get_organization_id();
+  }
+  function load_clinic()
+  {
+    $this->dbname = "one_health_clinic";
+  }
+  function ss_organization()
+  {
+    $this->get_organization_id();
+    $o_resp = $this->ss_get("/Organization/{$this->organizationID}");
+    $resp = $this->objToArray($o_resp);
+    $id = $resp["id"];
+    $name = $resp["name"];
+    $x_type = $resp["type"][0]["coding"][0];
+    $type = $x_type["display"];
+    $code = $x_type["code"];
+    $system = $x_type["system"];
+    return json_encode([
+      "ID" => $id,
+      "Name" => $name,
+      "Type" => $type,
+      "CodeSystem" => $code . " | " . $system,
+    ]);
+  }
+
+  function search_practicioner_by_nik($nik, $debug = "")
+  {
+    $service =  "/Practitioner?identifier=https://fhir.kemkes.go.id/id/nik|" . $nik;
+    $o_resp = $this->ss_get($service, $debug);
+    $resp = $this->objToArray($o_resp);
+    if (count($resp["entry"]) > 0) {
+      $rs = $resp["entry"][0]["resource"];
+      return json_encode([
+        "status" => "OK",
+        "ihsID" => $rs["id"],
+        "name" =>  $rs["name"][0]["text"]
+      ]);
+    }
+    return json_encode([
+      "status" => "ERR",
+      "message" => "Practitioner not found [$nik]"
+    ]);
+  }
+
+  function search_patient_by_nik($nik, $debug = "")
+  {
+    $service = "/Patient?identifier=https://fhir.kemkes.go.id/id/nik|" . $nik;
+    $resp = $this->ss_get($service);
+    if ($debug != "") {
+      echo "resp : ";
+      print_r($resp);
+    }
+    $a_resp = $this->objToArray($resp);
+    if (isset($a_resp["entry"][0]["resource"]["id"])) {
+      return $a_resp["entry"][0]["resource"]["id"];
+    }
+    return "";
+  }
+
+  function location_by_organization($organizationIhsID, $debug = "")
+  {
+    $service = "/Location?organization=" . $organizationIhsID;
+    $resp = $this->ss_get($service);
+    if ($debug != "") {
+      echo "resp : ";
+      print_r($resp);
+    }
+    $a_resp = $this->objToArray($resp);
+    return $a_resp;
+  }
+
+  function location_create(
+    $code,
+    $name,
+    $description,
+    $address,
+    $city,
+    $kodePos,
+    $administrativeCode,
+    $rt,
+    $rw,
+    $phone,
+    $type,
+    $partOf = "",
+    $email = "",
+    $fax = "",
+    $url = "",
+    $long = "",
+    $lat = ""
+  ) {
+    $this->get_organization_id();
+    $organizationID = $this->organizationID;
+    list($type_code, $type_display) = explode("^", $type);
+    $telecom = [];
+    $telecom[] = ["system" => "phone", "value" => "$phone", "use" => "work"];
+    if ($fax != "")   $telecom[] = ["system" => "fax", "value" => "$fax", "use" => "work"];
+    if ($email != "") $telecom[] = ["system" => "email", "value" => "$email"];
+    if ($url != "")   $telecom[] = ["system" => "url", "value" => "$url"];
+    $provCode = substr($administrativeCode, 0, 2);
+    $cityCode = substr($administrativeCode, 0, 4);
+    $districtCode = substr($administrativeCode, 0, 7);
+    $villageCode = substr($administrativeCode, 0, 10);
+
+    $data = [
+      "resourceType" => "Location",
+      "identifier" => [
+        [
+          "system" => "http://sys-ids.kemkes.go.id/location/{$organizationID}",
+          "value" => "$code",
+        ],
+      ],
+      "status" => "active",
+      "name" => "$name",
+      "description" => "$description",
+      "mode" => "instance",
+      "telecom" => $telecom,
+      "address" => [
+        "use" => "work",
+        "line" => [
+          $address,
+        ],
+        "city" => "$city",
+        "postalCode" => "$kodePos",
+        "country" => "ID",
+        "extension" => [
+          [
+            "url" =>
+            "https://fhir.kemkes.go.id/r4/StructureDefinition/administrativeCode",
+            "extension" => [
+              ["url" => "province", "valueCode" => $provCode],
+              ["url" => "city", "valueCode" => $cityCode],
+              ["url" => "district", "valueCode" => "$districtCode"],
+              ["url" => "village", "valueCode" => "$villageCode"],
+              ["url" => "rt", "valueCode" => "$rt"],
+              ["url" => "rw", "valueCode" => "$rw"],
+            ],
+          ],
+        ],
+      ],
+      "physicalType" => [
+        "coding" => [
+          [
+            "system" =>
+            "http://terminology.hl7.org/CodeSystem/location-physical-type",
+            "code" => "$type_code",
+            "display" => "$type_display",
+          ],
+        ],
+      ],
+      "position" => [
+        "longitude" => intval($long),
+        "latitude" => intval($lat),
+        "altitude" => 0,
+      ],
+      "managingOrganization" => ["reference" => "Organization/{$organizationID}"],
+    ];
+    if ($partOf != "") {
+      $data["partOf"] = [
+        "reference" => "Location/$partOf"
+      ];
+    }
+    $service = "/Location";
+    $resp = $this->ss_post($service, $data);
+    $oresp = $this->objToArray($resp);
+    if (!isset($oresp["id"])) {
+      header("Content-Type: text/plain");
+      print_r($data);
+      print_r($resp);
+    }
+    return $oresp;
+  }
+
+  function location_nonactive(
+    $ihsID
+  ) {
+    $this->get_organization_id();
+    $data = [
+      [
+        "op" => "replace",
+        "path" => "/status",
+        "value" => "inactive"
+      ]
+    ];
+
+    $service = "/Location/$ihsID";
+    $resp = $this->ss_patch($service, $data);
+    return $this->objToArray($resp);
+  }
+  function get_location($locationID)
+  {
+  }
+
+
+
+
+  function encounter_by_id($encounterID)
+  {
+    $this->get_organization_id();
+    $service = "/Encounter/$";
+    $resp = $this->ss_get($service);
+    return $this->objToArray($resp);
+  }
+  function encounter_by_subject($patientIhsID)
+  {
+    $this->get_organization_id();
+    $service = "/Encounter?subject=$patientIhsID";
+    $resp = $this->ss_get($service);
+    return $this->objToArray($resp);
+  }
+  function encounter(
+    $orderDate,
+    $patientIhsID,
+    $patientName,
+    $doctorIhsID,
+    $doctorName,
+    $locationID,
+    $locationName,
+    $labNumber,
+    $tz = "+07:00",
+    $payload_only = false
+  ) {
+    $service = "/Encounter";
+    $xdate = substr($orderDate, 0, 10) . "T" . substr($orderDate, 11) . $tz;
+    $this->get_organization_id();
+    $param = $this->encounter_param(
+      $patientIhsID,
+      $patientName,
+      $doctorIhsID,
+      $doctorName,
+      $locationID,
+      $locationName,
+      $this->organizationID,
+      $labNumber,
+      $xdate
+    );
+    $payload = json_encode($param);
+    if ($payload_only) {
+      return ["", "", $payload, ""];
+    }
+    $jresp = $this->ss_post($service, $param);
+    $resp = $this->objToArray($jresp);
+    $response = json_encode($resp);
+    if (is_array($resp) && isset($resp["id"])) {
+      $encounterResponseID = $resp["id"];
+      return [$encounterResponseID, "", $payload, $response];
+    } else {
+      return ["", $response, $payload, $response];
+    }
+  }
+  function encounter_param(
+    $patientIhs,
+    $patientName,
+    $dpjpIhs,
+    $dpjpName,
+    $locationIhs,
+    $locationName,
+    $organizationID,
+    $orderHeaderNumber,
+    $dateTime // 2022-06-14T07:00:00+07:00
+  ) {
+    if ($this->is_staging) {
+      $dpjpIhs = "N10000001";
+      $dpjpName = "Dokter Bronsig";
+    }
+    $encounterParam = [
+      "resourceType" => "Encounter",
+      "status" => "arrived",
+      "class" => [
+        "system" => "http://terminology.hl7.org/CodeSystem/v3-ActCode",
+        "code" => "AMB",
+        "display" => "ambulatory"
+      ],
+      "subject" => [
+        "reference" => "Patient/{$patientIhs}",
+        "display" => "$patientName"
+      ],
+      "participant" => [
+        [
+          "type" => [
+            [
+              "coding" => [
+                [
+                  "system" => "http://terminology.hl7.org/CodeSystem/v3-ParticipationType",
+                  "code" => "ATND",
+                  "display" => "attender"
+                ]
+              ]
+            ]
+          ],
+          "individual" => [
+            "reference" => "Practitioner/{$dpjpIhs}",
+            "display" => "$dpjpName"
+          ]
+        ]
+      ],
+      "period" => [
+        "start" => "$dateTime",
+      ],
+      "location" => [
+        [
+          "location" => [
+            "reference" => "Location/$locationIhs",
+            "display" => "$locationName"
+          ]
+        ]
+      ],
+      "statusHistory" => [
+        [
+          "status" => "arrived",
+          "period" => [
+            "start" => $dateTime
+          ]
+        ]
+      ],
+      "serviceProvider" => [
+        "reference" => "Organization/{$organizationID}"
+      ],
+      "identifier" => [
+        [
+          "system" => "http://sys-ids.kemkes.go.id/encounter/{$organizationID}",
+          "value" => "$orderHeaderNumber"
+        ]
+      ]
+    ];
+    return $encounterParam;
+  }
+
+
+
+
+  // helper
+  function get_organization_id()
+  {
+
+    $sql = "SELECT organizationID
+      FROM {$this->dbname}.organization
+      JOIN m_branch ON organizationM_BranchID = M_BranchID AND M_BranchIsDefault = 'Y' AND M_BranchIsActive = 'Y'
+      WHERE organizationIsActive = 'Y'";
+    $qry = $this->db->query($sql);
+    if (!$qry) {
+      return;
+    }
+    $rows = $qry->result_array();
+    if (count($rows) > 0) {
+      $this->organizationID = $rows[0]["organizationID"];
+    }
+  }
+
+  function ss_patch($service, $data)
+  {
+    $token = $this->get_token();
+    $authorization = "Authorization: Bearer " . $token;
+    $xbase_url = $this->base_url;
+    $url = $xbase_url . "$service";
+    $ch = curl_init($url);
+    # Setup request to send json via POST.
+    $payload = json_encode($data);
+
+    curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
+    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PATCH");
+    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json-patch+json', $authorization));
+    # Return response instead of printing.
+    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
+    # Send request.
+    $result = curl_exec($ch);
+    curl_close($ch);
+    # Print response.
+    $data_rst = json_decode($result);
+    return $data_rst;
+  }
+
+  function get_client_key($debug = "")
+  {
+    $sql = "select * from {$this->dbname}.client where clientIsActive = 'Y'";
+    $qry = $this->db->query($sql);
+    if (!$qry) {
+      return [false, "", ""];
+    }
+    $rows = $qry->result_array();
+    if (count($rows) == 0) {
+      if ($debug != "") {
+        print_r([false, "", ""]);
+      }
+      return [false, "", ""];
+    }
+    if ($debug != "") {
+      print_r([true, $rows[0]["clientKey"], $rows[0]["clientSecret"]]);
+    }
+
+    return [true, $rows[0]["clientKey"], $rows[0]["clientSecret"]];
+  }
+
+  function reset_token()
+  {
+    $sql = "delete from {$this->dbname}.token ";
+    $qry = $this->db->query($sql);
+    if (!$qry) {
+      echo "ERR : " . $this->db->error()["message"];
+      echo "      " . $this->db->last_query();
+      exit;
+    }
+  }
+
+  function put_token()
+  {
+    $auth_url = $this->base_oauth_url;
+    $url = $auth_url . "/accesstoken?grant_type=client_credentials";
+    list($status, $key, $secret) = $this->get_client_key();
+    $data = [
+      "client_id" => $key,
+      "client_secret" => $secret
+    ];
+    $ch = curl_init($url);
+    $post_data = http_build_query($data);
+    curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
+    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
+    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
+    $result = curl_exec($ch);
+    curl_close($ch);
+    if ($result) {
+      $token_rst = json_decode($result);
+      $sql = "select count(*) as xcount, tokenID
+                from {$this->dbname}.token
+                where
+                tokenIsActive = 'y'
+                ";
+      $qry = $this->db->query($sql);
+      if (!$qry) {
+        echo "get count token error";
+        exit;
+      }
+
+      $rst_count = $qry->row_array();
+      // print_r($token_rst);
+      if ($rst_count['xcount'] > 0) {
+        $sql = "update {$this->dbname}.token set tokenValue = ?, tokenExpired = date_add(now(), interval 50 minute)
+                    where tokenID = ?";
+        $qry = $this->db->query($sql, [$token_rst->access_token, $rst_count['tokenID']]);
+        if (!$qry) {
+          $this->sys_error_db("refresh token error", $this->db->last_query());
+          exit;
+        }
+      } else {
+        $sql = "update {$this->dbname}.token set tokenIsActive = 'N' where tokenIsActive = 'Y'";
+        $qry = $this->db->query($sql);
+        if (!$qry) {
+          echo "nonactive token error";
+          exit;
+        }
+
+        $sql = "insert into {$this->dbname}.token(tokenValue,tokenExpired) values(?,date_add(now(), interval 50 minute))";
+        $qry = $this->db->query($sql, [$token_rst->access_token]);
+        if (!$qry) {
+          echo "insert token error";
+          exit;
+        }
+      }
+
+      $sql = "select tokenValue
+                from {$this->dbname}.token
+                where
+                tokenIsActive = 'Y' limit 1
+                ";
+      $qry = $this->db->query($sql);
+      if (!$qry) {
+        echo "get token error";
+        exit;
+      }
+
+      return $qry->row()->tokenValue;
+    }
+  }
+
+  function get_token()
+  {
+    $sql = "SELECT COUNT(*) as xcount, tokenValue
+            FROM {$this->dbname}.token 
+            WHERE tokenIsActive = 'Y' AND NOW() < tokenExpired AND tokenValue IS NOT NULL ";
+    $qry = $this->db->query($sql);
+    $this->check_error($qry, "select token");
+
+    $data_token = $qry->row_array();
+    //print_r($data_token);
+    if ($data_token['xcount'] > 0) {
+      return $data_token['tokenValue'];
+    } else {
+      return $this->put_token();
+    }
+  }
+
+
+  function ss_post($service, $data)
+  {
+    $token = $this->get_token();
+    $authorization = "Authorization: Bearer " . $token;
+    $xbase_url = $this->base_url;
+    $url = $xbase_url . "$service";
+    $ch = curl_init($url);
+    # Setup request to send json via POST.
+    $payload = json_encode($data);
+
+    curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
+    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
+    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json', $authorization));
+    # Return response instead of printing.
+    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
+    # Send request.
+    $result = curl_exec($ch);
+    curl_close($ch);
+    # Print response.
+    $data_rst = json_decode($result);
+    return $data_rst;
+  }
+  function ss_get($service, $debug = "")
+  {
+    $token = $this->get_token();
+    $authorization = "Authorization: Bearer " . $token;
+    $xbase_url = $this->base_url;
+    $url = $xbase_url . "$service";
+    $ch = curl_init($url);
+
+    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
+    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json', $authorization));
+    # Return response instead of printing.
+    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
+    # Send request.
+    $result = curl_exec($ch);
+    curl_close($ch);
+    # Print response.
+    if ($debug != "") {
+      echo "url : $url \n";
+      print_r($result);
+    }
+    $data_rst = json_decode($result);
+    return $data_rst;
+  }
+  protected function objToArray($obj)
+  {
+    if (!is_object($obj) && !is_array($obj)) {
+      return $obj;
+    }
+    foreach ($obj as $key => $value) {
+      $arr[$key] = $this->objToArray($value);
+    }
+    return $arr;
+  }
+
+  function check_error($qry, $stage)
+  {
+    if (!$qry) {
+      echo json_encode([
+        "status" => "ERR",
+        "message" => $this->db->error(),
+        "sql" => $this->db->last_query()
+      ]);
+      exit;
+    }
+  }
+}
diff --git a/application/libraries/Satusehat.php b/application/libraries/Satusehat.php
new file mode 100644
index 00000000..842bdf3d
--- /dev/null
+++ b/application/libraries/Satusehat.php
@@ -0,0 +1,244 @@
+db_onedev = $CI->load->database("default", true);
+    
+  }
+
+  function clean_mysqli_connection( $dbc )
+{
+    while( mysqli_more_results($dbc) )
+    {
+        if(mysqli_next_result($dbc))
+        {
+            $result = mysqli_use_result($dbc);
+            
+            if( get_class($result) == 'mysqli_stmt' )
+            {
+                mysqli_stmt_free_result($result);
+            }
+            else
+            {
+                unset($result);
+            }
+        }
+    }
+}
+
+/*function get_token(){
+    $sql = "SELECT COUNT(*) as xcount, tokenValue
+            FROM one_health.token 
+            WHERE tokenIsActive = 'Y' AND NOW() < tokenExpired AND tokenValue IS NOT NULL
+            ";
+    $qry = $this->db_onedev->query($sql);
+    if (!$qry) {
+        echo "select token error";
+        exit;
+    }
+
+    $data_token = $qry->row_array();
+    //print_r($data_token);
+    if($data_token['xcount'] > 0){
+        return $data_token['tokenValue'];
+    }else{
+        return $this->putx_token();
+    }
+
+
+}*/
+
+function get_new_token(){
+ 
+
+    $curl = curl_init();
+
+    curl_setopt_array($curl, array(
+    CURLOPT_URL => 'https://api-satusehat-dev.dto.kemkes.go.id/oauth2/v1/accesstoken?grant_type=client_credentials',
+    CURLOPT_RETURNTRANSFER => true,
+    CURLOPT_ENCODING => '',
+    CURLOPT_MAXREDIRS => 10,
+    CURLOPT_TIMEOUT => 0,
+    CURLOPT_FOLLOWLOCATION => true,
+    CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
+    CURLOPT_CUSTOMREQUEST => 'POST',
+    CURLOPT_POSTFIELDS => 'client_id=6PukKqO0RQqu0cKBOC8EKGcXQySfPR4aVkiVmuTgkx5xvva4&client_secret=89ZqsmY3z5W7rVscHTp9gJoAWWiAZG4A2unS3maTw3DxBFxTdaRsSeTUbD8mRN3p',
+    ));
+
+    $response = curl_exec($curl);
+
+    curl_close($curl);
+    echo $response;
+
+}
+
+function put_token(){
+    $auth_url = "https://api-satusehat-dev.dto.kemkes.go.id/oauth2/v1"; 
+    //API URL
+    $url = $auth_url."/accesstoken?grant_type=client_credentials";
+    //echo $url;
+
+    $data = [
+        "client_id" => "6PukKqO0RQqu0cKBOC8EKGcXQySfPR4aVkiVmuTgkx5xvva4",
+        "client_secret" => "89ZqsmY3z5W7rVscHTp9gJoAWWiAZG4A2unS3maTw3DxBFxTdaRsSeTUbD8mRN3p"
+    ];
+                
+            
+    $ch = curl_init($url);
+    # Setup request to send json via POST.
+
+    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
+    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
+    curl_setopt($ch,CURLOPT_HTTPHEADER,
+        array(
+            'Content-Type: application/x-www-form-urlencoded'
+        )
+    );
+    # Return response instead of printing.
+    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
+    # Send request.
+    $result = curl_exec($ch);
+    curl_close($ch);
+    # Print response.
+    print_r($result);
+    //echo $token_rst->access_token;
+    if($result){
+        $token_rst = json_decode($result);
+        
+        $sql = "SELECT COUNT(*) as xcount, tokenID
+                FROM one_health.token
+                WHERE
+                tokenIsActive = 'Y'
+                ";
+        $qry = $this->db_onedev->query($sql);
+        if (!$qry) {
+            echo "get count token error";
+            exit;
+        }
+
+        $rst_count = $qry->row_array();
+
+        if($rst_count['xcount'] > 0){
+            $sql = "UPDATE one_health.token SET tokenValue = ?, tokenExpired = DATE_ADD(NOW(), INTERVAL 50 MINUTE)
+                    WHERE tokenID = ?";
+            $qry = $this->db_onedev->query($sql, [$token_rst->access_token,$rst_count['tokenID']]);
+            if (!$qry) {
+                $this->sys_error_db("refresh token error", $this->db_onedev->last_query());
+                exit;
+            }
+        }else{
+            $sql = "UPDATE one_health.token SET tokenIsActive = 'N' WHERE tokenIsActive = 'Y'";
+            $qry = $this->db_onedev->query($sql);
+            if (!$qry) {
+                echo "nonactive token error";
+                exit;
+            }
+    
+            $sql = "INSERT INTO one_health.token(tokenValue,tokenExpired) VALUES(?,DATE_ADD(NOW(), INTERVAL 50 MINUTE))";
+            $qry = $this->db_onedev->query($sql, [$token_rst->access_token]);
+            if (!$qry) {
+                echo "insert token error";
+                exit;
+            }
+        }
+    
+        $sql = "SELECT tokenValue
+                FROM one_health.token
+                WHERE
+                tokenIsActive = 'Y' LIMIT 1
+                ";
+        $qry = $this->db_onedev->query($sql);
+        if (!$qry) {
+            echo "get token error";
+            exit;
+        }
+    
+        return $qry->row()->tokenValue;
+    }
+   
+    
+}
+
+/*function search_practicioner_by_nik($nik){
+    $sql = "SELECT tokenValue
+            FROM one_health.token
+            WHERE
+            tokenIsActive = 'Y' LIMIT 1
+            ";
+    $qry = $this->db_onedev->query($sql);
+    if (!$qry) {
+        echo "get token error";
+        exit;
+    }
+
+    $token = $qry->row()->tokenValue;
+
+    $authorization = "Authorization: Bearer ".$token;
+    //API URL
+    $url = $this->xbase_url."/Practitioner?identifier=https://fhir.kemkes.go.id/id/nik|".$nik;
+    //echo $url;
+        
+            
+    $ch = curl_init($url);
+    # Setup request to send json via POST.
+    //$payload = json_encode($data);
+
+    //curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
+    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
+    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json' , $authorization ));
+    # Return response instead of printing.
+    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
+    # Send request.
+    $result = curl_exec($ch);
+    curl_close($ch);
+    # Print response.
+    $data_rst = json_decode($result);
+    print_r($result);
+
+    return $data_rst;
+}*/
+
+function gen_uuid() {
+    return sprintf( '%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
+        // 32 bits for "time_low"
+        mt_rand( 0, 0xffff ), mt_rand( 0, 0xffff ),
+
+        // 16 bits for "time_mid"
+        mt_rand( 0, 0xffff ),
+
+        // 16 bits for "time_hi_and_version",
+        // four most significant bits holds version number 4
+        mt_rand( 0, 0x0fff ) | 0x4000,
+
+        // 16 bits, 8 bits for "clk_seq_hi_res",
+        // 8 bits for "clk_seq_low",
+        // two most significant bits holds zero and one for variant DCE1.1
+        mt_rand( 0, 0x3fff ) | 0x8000,
+
+        // 48 bits for "node"
+        mt_rand( 0, 0xffff ), mt_rand( 0, 0xffff ), mt_rand( 0, 0xffff )
+    );
+}
+
+protected function objToArray($obj)
+    {
+        // Not an object or array
+        if (!is_object($obj) && !is_array($obj)) {
+            return $obj;
+        }
+
+        // Parse array
+        foreach ($obj as $key => $value) {
+            $arr[$key] = $this->objToArray($value);
+        }
+
+        // Return parsed array
+        return $arr;
+    }
+}
+
+
diff --git a/application/libraries/Soresultlog.php b/application/libraries/Soresultlog.php
new file mode 100644
index 00000000..e50fdaff
--- /dev/null
+++ b/application/libraries/Soresultlog.php
@@ -0,0 +1,69 @@
+db_onedev = $CI->load->database("default", true);
+      $this->db_smartone = $CI->load->database("default", true);
+   }
+
+   function clean_mysqli_connection($dbc)
+   {
+      while (mysqli_more_results($dbc)) {
+         if (mysqli_next_result($dbc)) {
+            $result = mysqli_use_result($dbc);
+
+            if (get_class($result) == 'mysqli_stmt') {
+               mysqli_stmt_free_result($result);
+            } else {
+               unset($result);
+            }
+         }
+      }
+   }
+   
+  public function step_action($act,$re_id,$userid)
+  {
+    //$CI = &get_instance();
+    //$this->db = $CI->load->database("one", true);
+
+    $sql = "INSERT INTO so_reactionlog(
+					So_REActionLogDate,
+					So_REActionLogSo_ResultEntryID,
+					So_REActionLogAction,
+					So_REActionLogUserID
+				)
+				VALUES(
+					NOW(),?,?,?
+				)";
+    $qry = $this->db_onedev->query($sql, array($re_id,$act,$userid));
+    if (!$qry) {
+      return array(false, print_r($this->db_onedev->error(), true));
+    }else
+    return array(true);
+  }
+
+  public function log_result($data_json,$re_id,$userid)
+  {
+    //$CI = &get_instance();
+    //$this->db = $CI->load->database("one", true);
+    //echo $re_id;
+    $sql = "INSERT INTO cpone_log.log_resultentry_so(
+          Log_ResultEntrySoDate,
+					Log_ResultEntrySoReID,
+					Log_ResultEntrySoJSON,
+					Log_ResultEntrySoUserID
+				)
+				VALUES(
+					NOW(),?,?,?
+				)";
+    $qry = $this->db_onedev->query($sql, array($re_id,$data_json,$userid));
+    if (!$qry) {
+      return array(false, print_r($this->db_onedev->error(), true));
+    }else
+    return array(true);
+  }
+}
diff --git a/application/libraries/SsPriceMou.php b/application/libraries/SsPriceMou.php
new file mode 100644
index 00000000..4d29d4ce
--- /dev/null
+++ b/application/libraries/SsPriceMou.php
@@ -0,0 +1,547 @@
+db = $CI->load->database("onedev",true);
+
+      $sql = "select * from m_mou where M_MouID  = ?";
+      $qry = $this->db->query($sql, array($mouID));
+      if (! $qry ) {
+         return array(false, print_r($this->db->error(),true));
+      }
+      $rows = $qry->result_array();
+      if (count($rows) == 0 ) {
+         return array(false, "MOU ID : $mouID not found");
+      }
+      $companyID = $rows[0]["M_MouM_CompanyID"];
+
+      $sql = "select distinct T_PriceM_MouID, T_TestID, T_TestName, 'N' IsFromPanel, Nat_TestID,
+         T_PriceT_TestID, T_PriceIsCito, T_PriceM_CompanyID, T_PriceM_MouID,
+         T_PricePriority, T_PriceAmount, T_PriceDisc, T_PriceDiscRp, T_PriceSubTotal,
+         T_PriceOther, T_PriceTotal, T_TestForceSell, 'N' is_packet, 0 packet_id,
+         'PX' px_type, '[]' nat_test, '[]' child_test, 'N' IsFavourite,
+         Nat_TestNat_TestTypeID, T_TestSasCode, $mouID Ss_PriceMouM_MouID
+         from t_price 
+         join t_test on T_PriceT_TestID = T_TestID 
+         and T_PriceIsActive = 'Y' and T_TestIsActive = 'Y' 
+         and T_TestIsPrice  = 'Y' 
+         join nat_test on T_TestNat_TestID = Nat_TestID 
+         and Nat_TestIsActive = 'Y' and Nat_TestNat_TestTypeID <> 5
+         where T_PriceM_MouID = ?
+         and length(T_TestSasCode) = 8 ";
+      $qry = $this->db->query($sql, array($mouID));
+
+      if (! $qry ) {
+         return array(false, "Regional select t_price " . print_r($this->db->error(),true));
+      }
+      $rows = $qry->result_array();
+      $flag_error = false;
+      foreach($rows as $idx => $r) {
+         $nat_testType = $r["Nat_TestNat_TestTypeID"];
+         switch($nat_testType) {
+         case 1: //Single 
+            $rows[$idx]['nat_test'] = '[' . $r['Nat_TestID'] . ']';
+            break;
+         case 3: //Multi
+         case 4: //Panel 
+            $sasCode = $r["T_TestSasCode"] . '%';
+            $sql = "select T_TestNat_TestID  
+               from t_test
+               where T_TestIsResult = 'Y'
+               and T_TestSasCode like ? 
+               and T_TestIsActive = 'Y'";
+            $qry = $this->db->query($sql,array($sasCode));
+            if (!$qry )  {
+               return array(false, "Regional " . print_r($this->db->error(),true));
+            }
+            $nt_rows = $qry->result_array();
+            $t_rows = array($r["Nat_TestID"]);
+            foreach($nt_rows as $nr) {
+               $t_rows[] = $nr["T_TestNat_TestID"];
+            }
+            $rows[$idx]['nat_test'] = "[" . join(",",$t_rows) . "]";
+            break;
+         default :
+            $rows[$idx]['nat_test'] = '[' . $r['Nat_TestID'] . ']';
+            break;
+         }
+         unset($rows[$idx]["Nat_TestNat_TestTypeID"]);
+         unset($rows[$idx]["T_TestSasCode"]);
+      }
+      //Test Profile 
+      // wip profile
+      $sql = "select distinct $mouID T_PriceM_MouID, T_TestID, T_TestName, 'N' IsFromPanel, Nat_TestID,
+         T_TestID T_PriceT_TestID, 'N' T_PriceIsCito, $companyID T_PriceM_CompanyID, $mouID T_PriceM_MouID,
+         0 T_PricePriority, 0 T_PriceAmount, 0 T_PriceDisc, 0 T_PriceDiscRp, 0 T_PriceSubTotal,
+         0 T_PriceOther, 0 T_PriceTotal, T_TestForceSell, 'N' is_packet, 0 packet_id,
+         'PXR' px_type, '[]' nat_test, '[]' child_test, 'N' IsFavourite,
+         Nat_TestNat_TestTypeID, T_TestSasCode, $mouID Ss_PriceMouM_MouID
+         from t_test  
+         join nat_test on T_TestNat_TestID = Nat_TestID 
+         and Nat_TestIsActive = 'Y' and Nat_TestNat_TestTypeID = 5
+         where length(T_TestSasCode) = 8 ";
+      $qry = $this->db->query($sql, array($mouID));
+      if (! $qry ) {
+         return array(false, "Regional " . print_r($this->db->error(),true));
+      }
+      $p_rows = $qry->result_array();
+
+      $sql = "select distinct substr(T_TestSasCode,1,8) parentCode, T_PriceM_MouID, T_TestID, T_TestName, 'N' IsFromPanel, Nat_TestID,
+         T_PriceT_TestID, T_PriceIsCito, T_PriceM_CompanyID, T_PriceM_MouID,
+         T_PricePriority, T_PriceAmount, T_PriceDisc, T_PriceDiscRp, T_PriceSubTotal,
+         T_PriceOther, T_PriceTotal, T_TestForceSell, 'N' is_packet, 0 packet_id,
+         'PX' px_type, concat('[', T_TestNat_TestID , ']') nat_test, '[]' child_test, 'N' IsFavourite,
+         Nat_TestNat_TestTypeID, T_TestSasCode,T_TestIsResult, T_TestCode
+         from t_price 
+         join t_test on T_PriceT_TestID = T_TestID 
+         and T_PriceIsActive = 'Y' and T_TestIsActive = 'Y' 
+         and T_TestIsPrice  = 'Y' 
+         and T_PriceIsCito = 'N'
+         and length(T_TestSasCode) = 10
+         join nat_test on T_TestNat_TestID = Nat_TestID 
+         and Nat_TestIsActive = 'Y' 
+         where T_PriceM_MouID = ?  ";
+      $qry = $this->db->query($sql,array($mouID));
+      if (!$qry )  {
+         return array(false, "Regional child test " . print_r($this->db->error(),true));
+      }
+      $xrows = $qry->result_array();
+      $arr_child = array();
+      $p_codes = "'0'";
+      foreach($xrows as $r ) {
+         $pCode = $r["parentCode"];
+         if ( ! isset($arr_child[$pCode])) {
+            $arr_child[$pCode] = array();
+         }
+         $cCode = $r["T_TestSasCode"];
+         $p_codes .= ", '$cCode'";
+         unset($r["parentCode"]);
+         $arr_child[$pCode][] = $r;
+      }
+      $sql = "select substr(T_TestSasCode,1,8) parentCode, 
+         group_concat(distinct T_TestNat_TestID) nat  
+         from t_test
+         where ( T_TestIsResult = 'Y' or T_TestIsPrice = 'Y' )
+         and T_TestSasCode in ( $p_codes )  
+         and T_TestIsActive = 'Y'
+         group by parentCode";
+      $qry = $this->db->query($sql,array($mouID));
+      if (!$qry )  {
+         return array(false, "Regional " . print_r($this->db->error(),true));
+      }
+      $xrows = $qry->result_array();
+      $arr_nat = array();
+      foreach($xrows as $r ) {
+         $pCode = $r["parentCode"];
+         //if ( ! isset($arr_nat[$pCode])) {
+         //   $arr_nat[$pCode] = array();
+         //}
+         $arr_nat[$pCode] = $r["nat"];
+      }
+      $flag_error = false;
+      foreach($p_rows as $idx => $r) {
+         $T_TestName= $r["T_TestName"] ;
+         $sasCode = $r["T_TestSasCode"];
+         if ( isset($arr_child[$sasCode]) ) {
+            $the_childs = $arr_child[$sasCode];
+            $p_rows[$idx]['child_test'] = json_encode($the_childs,true);
+            if ( isset($arr_nat[$sasCode] )) {
+               $p_rows[$idx]['nat_test'] = "[" . $arr_nat[$sasCode] . "]";
+            } 
+            unset($p_rows[$idx]["Nat_TestNat_TestTypeID"]);
+            unset($p_rows[$idx]["T_TestSasCode"]);
+         } else {
+            unset($p_rows[$idx]);
+         }
+      }
+      //Paket Panel / Profile
+      $sql = "select distinct $mouID T_PriceM_MouID, T_PacketID T_TestID, T_PacketName T_TestName, 'N' IsFromPanel, 0 Nat_TestID,
+         T_PacketID T_PriceT_TestID, 'N' T_PriceIsCito, $companyID T_PriceM_CompanyID, $mouID T_PriceM_MouID,
+         0 T_PricePriority, T_PacketOriginalBruto T_PriceAmount, 0 T_PriceDisc, 
+         (T_PacketOriginalBruto - T_PacketPrice) T_PriceDiscRp, 0 T_PriceSubTotal,
+         0 T_PriceOther, T_PacketPrice T_PriceTotal, 'Y' T_TestForceSell, 'Y' is_packet, T_PacketID  packet_id,
+         T_PacketType px_type, '[]' nat_test, '[]' child_test, 'N' IsFavourite,
+         $mouID Ss_PriceMouM_MouID
+         from 
+         t_packet
+         where 
+         T_PacketIsActive = 'Y' 
+         and T_PacketM_MouID = ?";
+
+      $qry = $this->db->query($sql, array($mouID));
+      if (! $qry ) {
+         return array(false, "Regional " . print_r($this->db->error(),true));
+      }
+      $pn_rows = $qry->result_array();
+      foreach($pn_rows as $idx => $pnr) {
+         $packetID = $pnr["packet_id"];
+         //child test
+         $sql = "select distinct $mouID T_PriceM_MouID, T_TestID, T_TestName, 'N' IsFromPanel, Nat_TestID,
+            T_TestID T_PriceT_TestID, 'N' T_PriceIsCito, $companyID T_PriceM_CompanyID, 
+            $mouID T_PriceM_MouID, 0 T_PricePriority, T_PacketDetailPriceAmount T_PriceAmount, 
+            T_PacketDetailPriceDisc T_PriceDisc, T_PacketDetailPriceDiscRp T_PriceDiscRp, T_PacketDetailPriceSubTotal T_PriceSubTotal,
+            0 T_PriceOther, T_PacketDetailPrice T_PriceTotal, 
+            'Y' T_TestForceSell, 'N' is_packet, 0 packet_id,
+            'PX' px_type, concat('[', T_TestNat_TestID , ']') nat_test, '[]' child_test, 'N' IsFavourite, T_TestSasCode
+            from t_packetdetail
+            join t_test on T_PacketDetailT_TestID = T_TestID 
+            and T_PacketDetailIsActive = 'Y' and T_TestIsActive = 'Y' 
+            and T_PacketDetailT_PacketID = ?
+            join nat_test on T_TestNat_TestID = Nat_TestID 
+            and Nat_TestIsActive = 'Y'";
+         $qry = $this->db->query($sql,array($packetID));
+         if (!$qry )  {
+            return array(false, print_r($this->db->error(),true));
+         }
+         $ct_rows = $qry->result_array();
+         $p_nat_test = array();
+         foreach($ct_rows as $ct_idx => $cr) {
+            $sasCode = $cr["T_TestSasCode"] . '%';
+            $sql = "select distinct T_TestNat_TestID 
+               from t_test
+               where T_TestSasCode like ? 
+               and T_TestIsActive = 'Y'";
+            $qry = $this->db->query($sql,array($sasCode));
+            if (!$qry )  {
+               return array(false, print_r($this->db->error(),true));
+            }
+            $nt_rows = $qry->result_array();
+            $t_rows = array();
+            foreach($nt_rows as $nr) {
+               $t_rows[] = intval( $nr["T_TestNat_TestID"]);
+               $p_nat_test[]= intval( $nr["T_TestNat_TestID"]);
+            }
+            $ct_rows[$ct_idx]['nat_test'] = json_encode($t_rows,JSON_NUMERIC_CHECK);
+         }
+         if (count($ct_rows) > 0 ) {
+            $x_arr = array();
+            foreach($ct_rows as $x_cr) {
+               $x_arr[] = $x_cr;
+            }
+            $pn_rows[$idx]['child_test'] = json_encode($x_arr,true);
+            $pn_rows[$idx]['nat_test'] = json_encode($p_nat_test,true);
+         }
+         unset($pn_rows[$idx]["Nat_TestNat_TestTypeID"]);
+         unset($pn_rows[$idx]["T_TestSasCode"]);
+      }
+
+      $rows = array_merge($rows,$p_rows, $pn_rows);
+      $qry = $this->db->query("delete from ss_price_mou where Ss_PriceMouM_MouID=?", array($mouID));
+      if ( ! $qry ) {
+         return array(false, "Regional " . print_r($this->db->error(),true));
+      }
+      $qry = $this->db->insert_batch("ss_price_mou", $rows);
+      if ( ! $qry ) {
+         return array(false, "Regional " . print_r($this->db->error(),true));
+      }
+      return array(true, "OK");
+   }
+   public function edit($mouID,$testID,$cito) {
+      $CI =& get_instance();
+      $this->db = $CI->load->database("onedev",true);
+
+      $sql = "select * from t_test where T_TestID = ? ";
+      $qry = $this->db->query($sql, array($testID));
+      if (! $qry ) {
+         return array(false, print_r($this->db->error(),true));
+      }
+      $rows = $qry->result_array();
+      if (count($rows) == 0 ) {
+         return array(false, "No Test $testID found");
+      }
+      $sasCode = $rows[0]["T_TestSasCode"];
+      if ( strlen($sasCode) == 8 ) {
+         $flagProfile = false;
+      } else {
+         $flagProfile = true;
+      } 
+
+      $sql = "select * from m_mou where M_MouID  = ?";
+      $qry = $this->db->query($sql, array($mouID));
+      if (! $qry ) {
+         return array(false, print_r($this->db->error(),true));
+      }
+      $rows = $qry->result_array();
+      if (count($rows) == 0 ) {
+         return array(false, "No MOU $mouID found");
+      }
+      $mouName = $rows[0]["M_MouName"];
+      $companyID = $rows[0]["M_MouM_CompanyID"];
+
+      $sql = "select distinct T_PriceM_MouID, T_TestID, T_TestName, 'N' IsFromPanel, Nat_TestID,
+         T_PriceT_TestID, T_PriceIsCito, T_PriceM_CompanyID, T_PriceM_MouID,
+         T_PricePriority, T_PriceAmount, T_PriceDisc, T_PriceDiscRp, T_PriceSubTotal,
+         T_PriceOther, T_PriceTotal, T_TestForceSell, 'N' is_packet, 0 packet_id,
+         'PX' px_type, '[]' nat_test, '[]' child_test, 'N' IsFavourite,
+         Nat_TestNat_TestTypeID, T_TestSasCode, $mouID Ss_PriceMouM_MouID
+         from t_price 
+         join t_test on T_PriceT_TestID = T_TestID and T_TestID = ?
+         and T_PriceIsActive = 'Y' and T_TestIsActive = 'Y' 
+         and T_TestIsPrice  = 'Y' and T_PriceIsCito = ?
+         join nat_test on T_TestNat_TestID = Nat_TestID 
+         and Nat_TestIsActive = 'Y' and Nat_TestNat_TestTypeID <> 5
+         where T_PriceM_MouID = ?";
+      $qry = $this->db->query($sql, array($testID, $cito, $mouID));
+      if (! $qry ) {
+         return array(false, print_r($this->db->error(),true));
+      }
+      $rows = $qry->result_array();
+
+      foreach($rows as $idx => $r) {
+         $nat_testType = $r["Nat_TestNat_TestTypeID"];
+         switch($nat_testType) {
+         case 1: //Single 
+            $rows[$idx]['nat_test'] = '[' . $r['Nat_TestID'] . ']';
+            break;
+         case 3: //Multi
+         case 4: //Panel 
+            $sasCode = $r["T_TestSasCode"] . '%';
+            $sql = "select T_TestNat_TestID  
+               from t_test
+               where T_TestIsResult = 'Y'
+               and T_TestSasCode like ? 
+               and T_TestIsActive = 'Y'";
+            $qry = $this->db->query($sql,array($sasCode));
+            if (!$qry )  {
+               return array(false, print_r($this->db->error(),true));
+            }
+            $nt_rows = $qry->result_array();
+            $t_rows = array($r["Nat_TestID"]);
+            foreach($nt_rows as $nr) {
+               $t_rows[] = $nr["T_TestNat_TestID"];
+            }
+            $rows[$idx]['nat_test'] = "[" . join(",",$t_rows) . "]";
+            break;
+         default :
+            $rows[$idx]['nat_test'] = '[' . $r['Nat_TestID'] . ']';
+            break;
+         }
+         unset($rows[$idx]["Nat_TestNat_TestTypeID"]);
+      }
+      if ( count($rows) > 0 ) {
+         $r = $rows[0];
+         unset($r["T_TestSasCode"]);
+         $this->db->where("T_PriceM_MouID", $r["T_PriceM_MouID"]);
+         $this->db->where("T_TestID", $r["T_TestID"]);
+         $this->db->where("T_PriceIsCito", $r["T_PriceIsCito"]);
+         $qry = $this->db->update("ss_price_mou",$r);
+         if (! $qry ) {
+            return array(false, print_r($this->db->error(),true));
+         }
+      }
+      $sasCode = substr($sasCode,0,8);
+      foreach($rows as $idx => $r ) {
+         if ( strlen($r["T_TestSasCode"]) > 8  ) {
+            unset($rows[$idx]);
+         }  else {
+            unset($rows[$idx]["T_TestSasCode"]);
+         }
+      }
+      if ($cito == 'Y' ) {
+         return array(true,"OK",$rows);
+      }
+      // for non cito
+      if($flagProfile ) {
+         //wip profile
+         $sql = "select distinct $mouID T_PriceM_MouID, T_TestID, T_TestName, 'N' IsFromPanel, Nat_TestID,
+            T_TestID T_PriceT_TestID, 'N' T_PriceIsCito, $companyID T_PriceM_CompanyID, $mouID T_PriceM_MouID,
+            0 T_PricePriority, 0 T_PriceAmount, 0 T_PriceDisc, 0 T_PriceDiscRp, 0 T_PriceSubTotal,
+            0 T_PriceOther, 0 T_PriceTotal, T_TestForceSell, 'N' is_packet, 0 packet_id,
+            'PXR' px_type, '[]' nat_test, '[]' child_test, 'N' IsFavourite,
+            Nat_TestNat_TestTypeID, T_TestSasCode, $mouID Ss_PriceMouM_MouID
+            from t_test  
+            join nat_test on T_TestNat_TestID = Nat_TestID and T_TestSasCode = ?
+            and Nat_TestIsActive = 'Y' and Nat_TestNat_TestTypeID = 5
+            where length(T_TestSasCode) = 8 ";
+         $qry = $this->db->query($sql, array($sasCode));
+
+         if (! $qry ) {
+            return array(false, print_r($this->db->error(),true));
+         }
+         $p_rows = $qry->result_array();
+
+         $sasCodeLike = $sasCode . "%";
+         $sql = "select distinct substr(T_TestSasCode,1,8) parentCode, T_PriceM_MouID, T_TestID, T_TestName, 'N' IsFromPanel, Nat_TestID,
+            T_PriceT_TestID, T_PriceIsCito, T_PriceM_CompanyID, T_PriceM_MouID,
+            T_PricePriority, T_PriceAmount, T_PriceDisc, T_PriceDiscRp, T_PriceSubTotal,
+            T_PriceOther, T_PriceTotal, T_TestForceSell, 'N' is_packet, 0 packet_id,
+            'PX' px_type, concat('[', T_TestNat_TestID , ']') nat_test, '[]' child_test, 'N' IsFavourite,
+            Nat_TestNat_TestTypeID, T_TestSasCode,T_TestIsResult, T_TestCode
+            from t_price 
+            join t_test on T_PriceT_TestID = T_TestID 
+            and T_PriceIsActive = 'Y' and T_TestIsActive = 'Y' 
+            and T_TestIsPrice  = 'Y' and T_PriceIsCito = 'N'
+            and T_TestSasCode like ?
+            join nat_test on T_TestNat_TestID = Nat_TestID 
+            and Nat_TestIsActive = 'Y' 
+            where T_PriceM_MouID = ?  ";
+         $qry = $this->db->query($sql,array($sasCodeLike,$mouID));
+         if (!$qry )  {
+            return array(false, "Regional child_test " . print_r($this->db->error(),true));
+         }
+         $xrows = $qry->result_array();
+         $arr_child = array();
+         $p_codes = "'0'";
+         foreach($xrows as $r ) {
+            $pCode = $r["parentCode"];
+            if ( ! isset($arr_child[$pCode])) {
+               $arr_child[$pCode] = array();
+            }
+            $cCode = $r["T_TestSasCode"];
+            $p_codes .= ", '$cCode'";
+            unset($r["parentCode"]);
+            $arr_child[$pCode][] = $r;
+         }
+
+         $sql = "select substr(T_TestSasCode,1,8) parentCode, 
+            group_concat(distinct T_TestNat_TestID) nat  
+            from t_test
+            where ( T_TestIsResult = 'Y' or T_TestIsPrice = 'Y' )
+            and T_TestSasCode in ( $p_codes )  
+            and T_TestIsActive = 'Y'
+            group by parentCode";
+         $qry = $this->db->query($sql,array($mouID));
+         if (!$qry )  {
+            return array(false, "Regional nat_test " . print_r($this->db->error(),true));
+         }
+         $xrows = $qry->result_array();
+         $arr_nat = array();
+         foreach($xrows as $r ) {
+            $pCode = $r["parentCode"];
+            //if ( ! isset($arr_nat[$pCode])) {
+            //   $arr_nat[$pCode] = array();
+            //}
+            $arr_nat[$pCode] = $r["nat"];
+         }
+
+         $flag_error = false;
+         foreach($p_rows as $idx => $r) {
+            $T_TestName= $r["T_TestName"] ;
+            $sasCode = $r["T_TestSasCode"];
+            if ( isset($arr_child[$sasCode]) ) {
+               $the_childs = $arr_child[$sasCode];
+               $p_rows[$idx]['child_test'] = json_encode($the_childs,true);
+               if ( isset($arr_nat[$sasCode] )) {
+                  $p_rows[$idx]['nat_test'] = "[" . $arr_nat[$sasCode] . "]";
+               } 
+               unset($p_rows[$idx]["Nat_TestNat_TestTypeID"]);
+               unset($p_rows[$idx]["T_TestSasCode"]);
+            } else {
+               unset($p_rows[$idx]);
+            }
+         }
+
+         foreach($p_rows as $r) {
+            $this->db->where("T_PriceM_MouID", $r["T_PriceM_MouID"]);
+            $this->db->where("T_TestID", $r["T_TestID"]);
+            $this->db->where("T_PriceIsCito", $r["T_PriceIsCito"]);
+            $qry = $this->db->update("ss_price_mou",$r);
+            if (! $qry ) {
+               return array(false, "Err Update Ss_priceMou " . print_r($this->db->error(),true));
+            }
+         }
+         $rows = array_merge($rows,$p_rows);
+      }
+      //Update Panel yang mengandung Test 
+      $sql = "select 
+         distinct T_PacketDetailT_PacketID
+         from 
+         t_packetdetail
+         where T_PacketDetailIsActive = 'Y'
+         and T_PacketDetailT_TestID = ?";
+      $qry = $this->db->query($sql, array($testID));
+      if (!$qry) {
+         return array(false, print_r($this->db->error(),true));
+      }
+      $xrows = $qry->result_array();
+      $packet_ids = "0";
+      foreach($xrows as $r ) {
+         $packet_ids .= "," . $r["T_PacketDetailT_PacketID"]; 
+      }
+
+      $sql = "select distinct $mouID T_PriceM_MouID, T_PacketID T_TestID, T_PacketName T_TestName, 'N' IsFromPanel, 0 Nat_TestID,
+         T_PacketID T_PriceT_TestID, 'N' T_PriceIsCito, $companyID T_PriceM_CompanyID, $mouID T_PriceM_MouID,
+         0 T_PricePriority, T_PacketOriginalBruto T_PriceAmount, 0 T_PriceDisc, 
+         (T_PacketOriginalBruto - T_PacketPrice) T_PriceDiscRp, 0 T_PriceSubTotal,
+         0 T_PriceOther, T_PacketPrice T_PriceTotal, 'Y' T_TestForceSell, 'Y' is_packet, T_PacketID  packet_id,
+         T_PacketType px_type, '[]' nat_test, '[]' child_test, 'N' IsFavourite,
+         $mouID Ss_PriceMouM_MouID
+         from 
+         t_packet
+         where 
+         T_PacketIsActive = 'Y' and T_PacketID in ( $packet_ids )
+         and T_PacketM_MouID = ?";
+
+      $qry = $this->db->query($sql, array($mouID));
+      if (! $qry ) {
+         return array(false, print_r($this->db->error(),true));
+      }
+      $pn_rows = $qry->result_array();
+      foreach($pn_rows as $idx => $pnr) {
+         $packetID = $pnr["packet_id"];
+         //child test
+         $sql = "select $mouID T_PriceM_MouID, T_TestID, T_TestName, 'N' IsFromPanel, Nat_TestID,
+            T_TestID T_PriceT_TestID, 'N' T_PriceIsCito, $companyID T_PriceM_CompanyID, 
+            $mouID T_PriceM_MouID, 0 T_PricePriority, T_PacketDetailPriceAmount T_PriceAmount, 
+            T_PacketDetailPriceDisc T_PriceDisc, T_PacketDetailPriceDiscRp T_PriceDiscRp, T_PacketDetailPriceSubTotal T_PriceSubTotal,
+            0 T_PriceOther, T_PacketDetailPrice T_PriceTotal, 
+            'Y' T_TestForceSell, 'N' is_packet, 0 packet_id,
+            'PX' px_type, '[]' nat_test, '[]' child_test, 'N' IsFavourite, T_TestSasCode
+            from t_packetdetail
+            join t_test on T_PacketDetailT_TestID = T_TestID 
+            and T_PacketDetailIsActive = 'Y' and T_TestIsActive = 'Y' 
+            and T_PacketDetailT_PacketID = ?
+            join nat_test on T_TestNat_TestID = Nat_TestID 
+            and Nat_TestIsActive = 'Y' 
+";
+         $qry = $this->db->query($sql,array($packetID));
+         if (!$qry )  {
+            return array(false, print_r($this->db->error(),true));
+         }
+         $ct_rows = $qry->result_array();
+         $p_nat_test = array();
+         foreach($ct_rows as $ct_idx => $cr) {
+            $sasCode = $cr["T_TestSasCode"] . '%';
+            $sql = "select distinct T_TestNat_TestID 
+               from t_test
+               where T_TestSasCode like ? 
+               and T_TestIsActive = 'Y'";
+            $qry = $this->db->query($sql,array($sasCode));
+            if (!$qry )  {
+               return array(false, print_r($this->db->error(),true));
+            }
+            $nt_rows = $qry->result_array();
+            $t_rows = array();
+            foreach($nt_rows as $nr) {
+               $t_rows[] = intval( $nr["T_TestNat_TestID"]);
+               $p_nat_test[]= intval( $nr["T_TestNat_TestID"]);
+            }
+            $ct_rows[$ct_idx]['nat_test'] = json_encode($t_rows,JSON_NUMERIC_CHECK);
+         }
+         if (count($ct_rows) > 0 ) {
+            $x_arr = array();
+            foreach($ct_rows as $x_cr) {
+               $x_arr[] = $x_cr;
+            }
+            $pn_rows[$idx]['child_test'] = json_encode($x_arr,true);
+            $pn_rows[$idx]['nat_test'] = json_encode($p_nat_test,true);
+         }
+         unset($pn_rows[$idx]["Nat_TestNat_TestTypeID"]);
+         unset($pn_rows[$idx]["T_TestSasCode"]);
+      }
+      foreach($pn_rows as $r ) {
+         $this->db->where("T_PriceM_MouID", $r["T_PriceM_MouID"]);
+         $this->db->where("T_TestID", $r["T_TestID"]);
+         $this->db->where("T_PriceIsCito", $r["T_PriceIsCito"]);
+         $qry = $this->db->update("ss_price_mou",$r);
+         if (! $qry ) {
+            return array(false, print_r($this->db->error(),true));
+         }
+      }
+      $rows = array_merge($rows,$pn_rows);
+      return array(true,"OK",$rows);
+   }
+}
diff --git a/application/libraries/SsPriceMouPx.php b/application/libraries/SsPriceMouPx.php
new file mode 100644
index 00000000..25407c34
--- /dev/null
+++ b/application/libraries/SsPriceMouPx.php
@@ -0,0 +1,52 @@
+db = $CI->load->database("onedev",true);
+
+      $sql = "select * from ss_price_mou where Ss_PriceMouM_MouID = ? and px_type in ('PR','PXR')";
+      $qry = $this->db->query($sql, array($mouID));
+      if ( ! $qry ) {
+         return array(false, "Ss Price Mou " . print_r($this->db->error(),true));
+      }
+      $rows = $qry->result_array();
+      $sql ="delete from ss_price_mou_px where Ss_PriceMouPxSs_PriceMouID in ( select Ss_PriceMouID from ss_price_mou
+         where Ss_PriceMouM_MouID = ? )";
+      $qry = $this->db->query($sql, array($mouID));
+      if ( ! $qry ) {
+         return array(false, "Clear Ss Price Mou Px" . print_r($this->db->error(),true));
+      }
+      $a_data = array();
+      foreach($rows as $r) {
+         $j_ct = $r["child_test"];
+         $ct = json_decode($j_ct,true);
+         foreach($ct as $c) {
+            $a_data[] = array(
+               "Ss_PriceMouPxM_MouID" => $r["Ss_PriceMouM_MouID"],
+               "Ss_PriceMouPxSs_PriceMouID" => $r["Ss_PriceMouID"],
+                "Ss_PriceMouPxT_TestID" => $c["T_TestID"],
+                "Ss_PriceMouPxT_TestName" => $c["T_TestName"],
+               "Ss_PriceMouPxT_PriceIsCito" => $c["T_PriceIsCito"],
+                "Ss_PriceMouPxT_PriceM_CompanyID" => $c["T_PriceM_CompanyID"],
+                "Ss_PriceMouPxT_PricePriority" => $c["T_PricePriority"],
+               "Ss_PriceMouPxT_PriceAmount" => $c["T_PriceAmount"],
+                "Ss_PriceMouPxT_PriceDisc" => $c["T_PriceDisc"],
+                "Ss_PriceMouPxT_PriceDiscRp" => $c["T_PriceDiscRp"],
+               "Ss_PriceMouPxT_PriceSubTotal" => $c["T_PriceSubTotal"],
+                "Ss_PriceMouPxT_PriceOther" => $c["T_PriceOther"],
+                "Ss_PriceMouPxT_PriceTotal" => $c["T_PriceTotal"],
+               "Ss_PriceMouPxT_TestForceSell" => $c["T_TestForSell"],
+                "nat_test" => $c["nat_test"]
+            );
+         }
+      }
+      $qry = $this->db->insert_batch("ss_price_mou_px",$a_data);
+      if ( ! $qry ) {
+         return array(false, "Batch Ss Price Mou Px" . print_r($this->db->error(),true));
+      }
+
+      return array(true, "");
+   }
+}
diff --git a/application/libraries/Txbranchstatus-cabang.php b/application/libraries/Txbranchstatus-cabang.php
new file mode 100644
index 00000000..e6e9f469
--- /dev/null
+++ b/application/libraries/Txbranchstatus-cabang.php
@@ -0,0 +1,249 @@
+db = $CI->load->database("onedev",true);
+      $s_ids = join(",",$ids);
+      $sql = "select T_OrderDetailT_TestID, T_OrderDetailT_OrderHeaderID 
+         from 
+         t_orderdetail 
+         where T_OrderDetailID in ($s_ids)  ";
+      $qry = $this->db->query($sql);
+      $incomingRefID = 0;
+      $s_detail_ids = "0";
+      $s_child_ids = "0";
+      if ($qry) {
+         $rows = $qry->result_array();
+         if(count($rows) > 0 ) {
+            $headerID = $rows[0]["T_OrderDetailT_OrderHeaderID"];
+            $s_test = "0";
+            foreach($rows as $r) {
+               $s_test .= "," . $r["T_OrderDetailT_TestID"];
+            }
+            $sql = "select incomingRefDetailID , incomingRefDetailIncomingRefID
+               from incoming_ref_detail
+               where incomingRefDetailNewT_OrderHeaderID = ?
+               and incomingRefDetailT_TestID in ($s_test) ";
+            $qryd = $this->db->query($sql, array($headerID));
+            $flag_found = false;
+            if($qryd) {
+               $rowsd = $qryd->result_array();
+               if ( count($rowsd) > 0 ) {
+                  $incomingRefID = $rowsd[0]["incomingRefDetailIncomingRefID"];
+                  foreach($rowsd as $r) {
+                     $s_detail_ids .= "," . $r["incomingRefDetailID"];
+                  }
+               }
+            } 
+            //check child
+            if(! $flag_found ) {
+               $sql = "select incomingRefChildID , incomingRefChildIncomingRefID
+                  from incoming_ref_child
+                  where incomingRefChildNewT_OrderHeaderID = ?
+                  and incomingRefChildT_TestID in ($s_test) ";
+               $qryd = $this->db->query($sql, array($headerID));
+               if($qryd) {
+                  $rowsd = $qryd->result_array();
+                  if ( count($rowsd) > 0 ) {
+                     $incomingRefID = $rowsd[0]["incomingRefChildIncomingRefID"];
+                     foreach($rowsd as $r) {
+                        $s_child_ids .=  "," . $r["incomingRefChildID"];
+                     }
+                  }
+               }
+           } 
+         }
+      }
+      if ($s_detail_ids == "0" && $s_child_ids == "0" ) {
+         return false;
+      } 
+      $sql = "select M_BranchID, M_BranchIPAddress
+         from m_branch
+         join incoming_ref
+         on M_BranchID = incomingRefM_BranchID
+         where incomingRefID = ?";
+      $qry = $this->db->query($sql, array($incomingRefID));
+      $branchID = 0;
+      if ($qry) {
+         $rows = $qry->result_array();
+         if(count($rows)>0) {
+            $branchID = $rows[0]["M_BranchID"];
+            $branchIPAddress = $rows[0]["M_BranchIPAddress"];
+         }
+      }   
+      if ($branchID == 0 ) {
+         return false;
+      }  
+
+      $note = "$stage by $username";
+      if ($s_detail_ids!= "0" ) {
+         $sql = "select 
+            incomingRefT_RefDeliveryOrderID, 
+            incomingRefDetailT_OrderDetailID,
+            incomingRefDetailStatus,
+            T_OrderDetailResult,
+            T_OrderDetailNat_NormalValueID,
+            T_OrderDetailVerification,
+            T_OrderDetailValidation,
+            ? note
+            from incoming_ref_detail
+            join incoming_ref on incomingRefID = incomingRefDetailIncomingRefID
+            and incomingRefDetailID in ($s_detail_ids)
+            left join t_orderdetail on incomingRefDetailNewT_OrderHeaderID = T_OrderDetailT_OrderHeaderID
+            and T_OrderDetailIsActive = 'Y' and incomingRefDetailT_TestID = T_OrderDetailT_TestID";
+         $qry = $this->db->query($sql, array($note));
+         if ($qry) {
+            $rows = $qry->result_array();
+            $param = json_encode($rows);
+            //insert to 
+            $sql = "insert into tx_branch_status(TxBranchStatusStage, TxBranchStatusM_BranchID,
+               TxBranchStatusM_BranchIP, TxBranchStatusJson,TxBranchStatusNote )
+               values (?,?,?,?,?)";
+            $qry = $this->db->query($sql, array($stage,$branchID, $branchIPAddress, $param, $note));
+         }
+      }   
+      if ($s_child_ids!= "0" ) {
+         $sql = "select 
+            incomingRefT_RefDeliveryOrderID, 
+            incomingRefChildT_OrderDetailID incomingRefDetailT_OrderDetailID,
+            '' incomingRefDetailStatus,
+            T_OrderDetailResult,
+            T_OrderDetailNat_NormalValueID,
+            T_OrderDetailVerification,
+            T_OrderDetailValidation,
+            ? note
+            from incoming_ref_child
+            join incoming_ref on incomingRefID = incomingRefChildIncomingRefID
+            and incomingRefChildID in ($s_child_ids)
+            left join t_orderdetail on incomingRefChildNewT_OrderHeaderID = T_OrderDetailT_OrderHeaderID
+            and T_OrderDetailIsActive = 'Y' and incomingRefChildT_TestID = T_OrderDetailT_TestID";
+         $qry = $this->db->query($sql, array($note));
+         if ($qry) {
+            $rows = $qry->result_array();
+            $param = json_encode($rows);
+            //insert to 
+            $sql = "insert into tx_branch_status(TxBranchStatusStage, TxBranchStatusM_BranchID,
+               TxBranchStatusM_BranchIP, TxBranchStatusJson,TxBranchStatusNote )
+               values (?,?,?,?,?)";
+            $qry = $this->db->query($sql, array($stage,$branchID, $branchIPAddress, $param, $note));
+         }   
+      }
+   }
+
+   public function update($stage,$orderDetailID,$username)
+   {
+      $CI =& get_instance();
+      $this->db = $CI->load->database("onedev",true);
+      $sql = "select T_OrderDetailT_TestID, T_OrderDetailT_OrderHeaderID 
+         from 
+         t_orderdetail 
+         where T_OrderDetailID = ? ";
+      $qry = $this->db->query($sql, array($orderDetailID));
+      $incomingRefID = 0;
+      $incomingRefDetailID = 0;
+      $flag_child = false;
+      if ($qry) {
+         $rows = $qry->result_array();
+         $flag_found = false;
+         if(count($rows) > 0 ) {
+            $headerID = $rows[0]["T_OrderDetailT_OrderHeaderID"];
+            $testID = $rows[0]["T_OrderDetailT_TestID"];
+            $sql = "select incomingRefDetailID , incomingRefDetailIncomingRefID
+               from incoming_ref_detail
+               where incomingRefDetailNewT_OrderHeaderID = ?
+               and incomingRefDetailT_TestID = ?";
+            $qryd = $this->db->query($sql, array($headerID,$testID));
+            if($qryd) {
+               $rowsd = $qryd->result_array();
+               if ( count($rowsd) > 0 ) {
+                  $incomingRefID = $rowsd[0]["incomingRefDetailIncomingRefID"];
+                  $incomingRefDetailID = $rowsd[0]["incomingRefDetailID"];
+                  $flag_found = true;
+               }
+            }
+            //check child
+            if(! $flag_found ) {
+               $sql = "select incomingRefChildID , incomingRefChildIncomingRefID
+                  from incoming_ref_child
+                  where incomingRefChildNewT_OrderHeaderID = ?
+                  and incomingRefChildT_TestID = ?";
+               $qryd = $this->db->query($sql, array($headerID,$testID));
+               if($qryd) {
+                  $rowsd = $qryd->result_array();
+                  if ( count($rowsd) > 0 ) {
+                     $incomingRefID = $rowsd[0]["incomingRefChildIncomingRefID"];
+                     $incomingRefDetailID = $rowsd[0]["incomingRefChildID"];
+                     $flag_found = true;
+                     $flag_child = true;
+                  }
+               }
+           } 
+         }
+      }
+      if ($incomingRefDetailID == 0 || $incomingRefDetailID == "") {
+         return false;
+      } 
+      $sql = "select M_BranchID, M_BranchIPAddress
+         from m_branch
+         join incoming_ref
+         on M_BranchID = incomingRefM_BranchID
+         where incomingRefID = ?";
+      $qry = $this->db->query($sql, array($incomingRefID));
+      $branchID = 0;
+      if ($qry) {
+         $rows = $qry->result_array();
+         if(count($rows)>0) {
+            $branchID = $rows[0]["M_BranchID"];
+            $branchIPAddress = $rows[0]["M_BranchIPAddress"];
+         }
+      }   
+      if ($branchID == 0 ) {
+         return false;
+      }  
+
+      $note = "$stage by $username";
+      $sql = "select 
+         incomingRefT_RefDeliveryOrderID, 
+         incomingRefDetailT_OrderDetailID,
+         incomingRefDetailStatus,
+         T_OrderDetailResult,
+         T_OrderDetailNat_NormalValueID,
+         T_OrderDetailVerification,
+         T_OrderDetailValidation,
+         ? note
+         from incoming_ref_detail
+         join incoming_ref on incomingRefID = incomingRefDetailIncomingRefID
+         and incomingRefDetailID = ?
+         left join t_orderdetail on incomingRefDetailNewT_OrderHeaderID = T_OrderDetailT_OrderHeaderID
+         and T_OrderDetailIsActive = 'Y' and incomingRefDetailT_TestID = T_OrderDetailT_TestID";
+      if ($flag_child ) {
+         $sql = "select 
+            incomingRefT_RefDeliveryOrderID, 
+            incomingRefChildT_OrderDetailID incomingRefDetailT_OrderDetailID,
+            '' incomingRefDetailStatus,
+            T_OrderDetailResult,
+            T_OrderDetailNat_NormalValueID,
+            T_OrderDetailVerification,
+            T_OrderDetailValidation,
+            ? note
+            from incoming_ref_child
+            join incoming_ref on incomingRefID = incomingRefChildIncomingRefID
+            and incomingRefChildID = ?
+            left join t_orderdetail on incomingRefChildNewT_OrderHeaderID = T_OrderDetailT_OrderHeaderID
+            and T_OrderDetailIsActive = 'Y' and incomingRefChildT_TestID = T_OrderDetailT_TestID";
+      }
+      $qry = $this->db->query($sql, array($note, $incomingRefDetailID));
+      if ($qry) {
+         $rows = $qry->result_array();
+         $param = json_encode($rows);
+         //insert to 
+         $sql = "insert into tx_branch_status(TxBranchStatusStage, TxBranchStatusM_BranchID,
+            TxBranchStatusM_BranchIP, TxBranchStatusJson,TxBranchStatusNote )
+            values (?,?,?,?,?)";
+         $qry = $this->db->query($sql, array($stage,$branchID, $branchIPAddress, $param, $note));
+      }   
+   }
+}
diff --git a/application/libraries/Txbranchstatus.php b/application/libraries/Txbranchstatus.php
new file mode 100644
index 00000000..75fb2d56
--- /dev/null
+++ b/application/libraries/Txbranchstatus.php
@@ -0,0 +1,300 @@
+db = $CI->load->database("onedev",true);
+      $s_ids = join(",",$ids);
+      $sql = "select T_OrderDetailT_TestID, T_OrderDetailT_OrderHeaderID 
+         from 
+         t_orderdetail 
+         where T_OrderDetailID in ($s_ids)  ";
+      $qry = $this->db->query($sql);
+      $incomingRefID = 0;
+      $s_detail_ids = "0";
+      $s_child_ids = "0";
+      $headerID = 0;
+
+      if ($qry) {
+         $rows = $qry->result_array();
+         if(count($rows) > 0 ) {
+            $headerID = $rows[0]["T_OrderDetailT_OrderHeaderID"];
+            $s_test = "0";
+            foreach($rows as $r) {
+               $s_test .= "," . $r["T_OrderDetailT_TestID"];
+            }
+            $sql = "select incomingRefDetailID , incomingRefDetailIncomingRefID
+               from incoming_ref_detail
+               where incomingRefDetailNewT_OrderHeaderID = ?
+               and incomingRefDetailT_TestID in ($s_test) ";
+            $qryd = $this->db->query($sql, array($headerID));
+            $flag_found = false;
+            if($qryd) {
+               $rowsd = $qryd->result_array();
+               if ( count($rowsd) > 0 ) {
+                  $incomingRefID = $rowsd[0]["incomingRefDetailIncomingRefID"];
+                  foreach($rowsd as $r) {
+                     $s_detail_ids .= "," . $r["incomingRefDetailID"];
+                  }
+               }
+            } 
+            //check child
+            if(! $flag_found ) {
+               $sql = "select incomingRefChildID , incomingRefChildIncomingRefID
+                  from incoming_ref_child
+                  where incomingRefChildNewT_OrderHeaderID = ?
+                  and incomingRefChildT_TestID in ($s_test) ";
+               $qryd = $this->db->query($sql, array($headerID));
+               if($qryd) {
+                  $rowsd = $qryd->result_array();
+                  if ( count($rowsd) > 0 ) {
+                     $incomingRefID = $rowsd[0]["incomingRefChildIncomingRefID"];
+                     foreach($rowsd as $r) {
+                        $s_child_ids .=  "," . $r["incomingRefChildID"];
+                     }
+                  }
+               }
+            } 
+         }
+      }
+      if ($s_detail_ids == "0" && $s_child_ids == "0" ) {
+         return false;
+      } 
+      $sql = "select M_BranchID, M_BranchIPAddress
+         from m_branch
+         join incoming_ref
+         on M_BranchID = incomingRefM_BranchID
+         where incomingRefID = ?";
+      $qry = $this->db->query($sql, array($incomingRefID));
+      $branchID = 0;
+      if ($qry) {
+         $rows = $qry->result_array();
+         if(count($rows)>0) {
+            $branchID = $rows[0]["M_BranchID"];
+            $branchIPAddress = $rows[0]["M_BranchIPAddress"];
+         }
+      }   
+      if ($branchID == 0 ) {
+         return false;
+      }  
+      $val_note = "";
+      $val_note_int = "";
+      if ($headerID > 0 ) {
+         $sql = "select T_OrderHeaderAddOnValidationNote, T_OrderHeaderAddOnValidationInternal
+            from t_orderheaderaddon
+            where T_orderHeaderAddOnT_OrderHeaderID = ?";
+         $qry = $this->db->query($sql,array($headerID));
+         if ($qry) {
+            $rows = $qry->result_array();
+            if (count($rows) > 0 ) {
+               $val_note = $rows[0]["T_OrderHeaderAddOnValidationNote"];
+               $val_note_int  = $rows[0]["T_OrderHeaderAddOnValidationInternal"];
+               if ( $val_note == null ) $val_note = "";
+               if ( $val_note_int == null ) $val_note_int = "";
+            }
+         } 
+      }
+      $note = "$stage by $username";
+      if ($s_detail_ids!= "0" ) {
+         $sql = "select 
+            incomingRefT_RefDeliveryOrderID, 
+            incomingRefDetailID,
+            incomingRefDetailT_OrderDetailID,
+            incomingRefDetailStatus,
+            T_OrderDetailResult,
+            T_OrderDetailNat_NormalValueID,
+            T_OrderDetailVerification,
+            T_OrderDetailValidation,
+            T_OrderDetailNote, 
+            ? note,
+            ? validation_note,
+            ? validation_note_internal
+            from incoming_ref_detail
+            join incoming_ref on incomingRefID = incomingRefDetailIncomingRefID
+            and incomingRefDetailID in ($s_detail_ids)
+            left join t_orderdetail on incomingRefDetailNewT_OrderHeaderID = T_OrderDetailT_OrderHeaderID
+            and T_OrderDetailIsActive = 'Y' and incomingRefDetailT_TestID = T_OrderDetailT_TestID";
+         $qry = $this->db->query($sql, array($note,$val_note,$val_note_int));
+         if ($qry) {
+            $rows = $qry->result_array();
+            $param = json_encode($rows);
+            //insert to 
+            $sql = "insert into tx_branch_status(TxBranchStatusStage, TxBranchStatusM_BranchID,
+               TxBranchStatusM_BranchIP, TxBranchStatusJson,TxBranchStatusNote )
+               values (?,?,?,?,?)";
+            $qry = $this->db->query($sql, array($stage,$branchID, $branchIPAddress, $param, $note));
+         }
+      }   
+      if ($s_child_ids!= "0" ) {
+         $sql = "select 
+            incomingRefT_RefDeliveryOrderID, 
+            incomingRefChildID,
+            incomingRefChildT_OrderDetailID incomingRefDetailT_OrderDetailID,
+            '' incomingRefDetailStatus,
+            T_OrderDetailResult,
+            T_OrderDetailNat_NormalValueID,
+            T_OrderDetailVerification,
+            T_OrderDetailValidation,
+            T_OrderDetailNote, 
+            ? note,
+            ? validation_note,
+            ? validation_note_internal
+            from incoming_ref_child
+            join incoming_ref on incomingRefID = incomingRefChildIncomingRefID
+            and incomingRefChildID in ($s_child_ids)
+            left join t_orderdetail on incomingRefChildNewT_OrderHeaderID = T_OrderDetailT_OrderHeaderID
+            and T_OrderDetailIsActive = 'Y' and incomingRefChildT_TestID = T_OrderDetailT_TestID";
+         $qry = $this->db->query($sql, array($note,$val_note,$val_note_int));
+         if ($qry) {
+            $rows = $qry->result_array();
+            $param = json_encode($rows);
+            //insert to 
+            $sql = "insert into tx_branch_status(TxBranchStatusStage, TxBranchStatusM_BranchID,
+               TxBranchStatusM_BranchIP, TxBranchStatusJson,TxBranchStatusNote )
+               values (?,?,?,?,?)";
+            $qry = $this->db->query($sql, array($stage,$branchID, $branchIPAddress, $param, $note));
+         }   
+      }
+   }
+
+   public function update($stage,$orderDetailID,$username)
+   {
+      $CI =& get_instance();
+      $this->db = $CI->load->database("onedev",true);
+      $sql = "select T_OrderDetailT_TestID, T_OrderDetailT_OrderHeaderID 
+         from 
+         t_orderdetail 
+         where T_OrderDetailID = ? ";
+      $qry = $this->db->query($sql, array($orderDetailID));
+      $incomingRefID = 0;
+      $incomingRefDetailID = 0;
+      $flag_child = false;
+      if ($qry) {
+         $rows = $qry->result_array();
+         $flag_found = false;
+         if(count($rows) > 0 ) {
+            $headerID = $rows[0]["T_OrderDetailT_OrderHeaderID"];
+            $testID = $rows[0]["T_OrderDetailT_TestID"];
+            $sql = "select incomingRefDetailID , incomingRefDetailIncomingRefID
+               from incoming_ref_detail
+               where incomingRefDetailNewT_OrderHeaderID = ?
+               and incomingRefDetailT_TestID = ?";
+            $qryd = $this->db->query($sql, array($headerID,$testID));
+            if($qryd) {
+               $rowsd = $qryd->result_array();
+               if ( count($rowsd) > 0 ) {
+                  $incomingRefID = $rowsd[0]["incomingRefDetailIncomingRefID"];
+                  $incomingRefDetailID = $rowsd[0]["incomingRefDetailID"];
+                  $flag_found = true;
+               }
+            }
+            //check child
+            if(! $flag_found ) {
+               $sql = "select incomingRefChildID , incomingRefChildIncomingRefID
+                  from incoming_ref_child
+                  where incomingRefChildNewT_OrderHeaderID = ?
+                  and incomingRefChildT_TestID = ?";
+               $qryd = $this->db->query($sql, array($headerID,$testID));
+               if($qryd) {
+                  $rowsd = $qryd->result_array();
+                  if ( count($rowsd) > 0 ) {
+                     $incomingRefID = $rowsd[0]["incomingRefChildIncomingRefID"];
+                     $incomingRefDetailID = $rowsd[0]["incomingRefChildID"];
+                     $flag_found = true;
+                     $flag_child = true;
+                  }
+               }
+            } 
+         }
+      }
+      if ($incomingRefDetailID == 0 || $incomingRefDetailID == "") {
+         return false;
+      } 
+      $sql = "select M_BranchID, M_BranchIPAddress
+         from m_branch
+         join incoming_ref
+         on M_BranchID = incomingRefM_BranchID
+         where incomingRefID = ?";
+      $qry = $this->db->query($sql, array($incomingRefID));
+      $branchID = 0;
+      if ($qry) {
+         $rows = $qry->result_array();
+         if(count($rows)>0) {
+            $branchID = $rows[0]["M_BranchID"];
+            $branchIPAddress = $rows[0]["M_BranchIPAddress"];
+         }
+      }   
+      if ($branchID == 0 ) {
+         return false;
+      }  
+
+      $val_note = "";
+      $val_note_int = "";
+      if ($headerID > 0 ) {
+         $sql = "select T_OrderHeaderAddOnValidationNote, T_OrderHeaderAddOnValidationInternal
+            from t_orderheaderaddon
+            where T_orderHeaderAddOnT_OrderHeaderID = ?";
+         $qry = $this->db->query($sql,array($headerID));
+         if ($qry) {
+            $rows = $qry->result_array();
+            if (count($rows) > 0 ) {
+               $val_note = $rows[0]["T_OrderHeaderAddOnValidationNote"];
+               $val_note_int = $rows[0]["T_OrderHeaderAddOnValidationInternal"];
+               if ( $val_note == null ) $val_note = "";
+               if ( $val_note_int == null ) $val_note_int = "";
+            }
+         } 
+      }
+      $note = "$stage by $username";
+      $sql = "select 
+         incomingRefT_RefDeliveryOrderID, 
+         incomingRefDetailID,
+         incomingRefDetailT_OrderDetailID,
+         incomingRefDetailStatus,
+         T_OrderDetailResult,
+         T_OrderDetailNat_NormalValueID,
+         T_OrderDetailVerification,
+         T_OrderDetailValidation,
+         T_OrderDetailNote, 
+         ? note,
+         ? validation_note,
+         ? validation_note_internal
+         from incoming_ref_detail
+         join incoming_ref on incomingRefID = incomingRefDetailIncomingRefID
+         and incomingRefDetailID = ?
+         left join t_orderdetail on incomingRefDetailNewT_OrderHeaderID = T_OrderDetailT_OrderHeaderID
+         and T_OrderDetailIsActive = 'Y' and incomingRefDetailT_TestID = T_OrderDetailT_TestID";
+      if ($flag_child ) {
+         $sql = "select 
+            incomingRefT_RefDeliveryOrderID, 
+            incomingRefChildID,
+            incomingRefChildT_OrderDetailID incomingRefDetailT_OrderDetailID,
+            '' incomingRefDetailStatus,
+            T_OrderDetailResult,
+            T_OrderDetailNat_NormalValueID,
+            T_OrderDetailVerification,
+            T_OrderDetailValidation,
+            T_OrderDetailNote, 
+            ? note,
+            ? validation_note,
+            ? validation_note_internal
+            from incoming_ref_child
+            join incoming_ref on incomingRefID = incomingRefChildIncomingRefID
+            and incomingRefChildID = ?
+            left join t_orderdetail on incomingRefChildNewT_OrderHeaderID = T_OrderDetailT_OrderHeaderID
+            and T_OrderDetailIsActive = 'Y' and incomingRefChildT_TestID = T_OrderDetailT_TestID";
+      }
+      $qry = $this->db->query($sql, array($note, $val_note, $val_note_int, $incomingRefDetailID));
+      if ($qry) {
+         $rows = $qry->result_array();
+         $param = json_encode($rows);
+         //insert to 
+         $sql = "insert into tx_branch_status(TxBranchStatusStage, TxBranchStatusM_BranchID,
+            TxBranchStatusM_BranchIP, TxBranchStatusJson,TxBranchStatusNote )
+            values (?,?,?,?,?)";
+         $qry = $this->db->query($sql, array($stage,$branchID, $branchIPAddress, $param, $note));
+      }   
+   }
+}
diff --git a/application/libraries/Txbranchstatus_updated.php b/application/libraries/Txbranchstatus_updated.php
new file mode 100644
index 00000000..79eba71b
--- /dev/null
+++ b/application/libraries/Txbranchstatus_updated.php
@@ -0,0 +1,296 @@
+db = $CI->load->database("onedev",true);
+      $s_ids = join(",",$ids);
+      $sql = "select T_OrderDetailT_TestID, T_OrderDetailT_OrderHeaderID 
+         from 
+         t_orderdetail 
+         where T_OrderDetailID in ($s_ids)  ";
+      $qry = $this->db->query($sql);
+      $incomingRefID = 0;
+      $s_detail_ids = "0";
+      $s_child_ids = "0";
+      $headerID = 0;
+
+      if ($qry) {
+         $rows = $qry->result_array();
+         if(count($rows) > 0 ) {
+            $headerID = $rows[0]["T_OrderDetailT_OrderHeaderID"];
+            $s_test = "0";
+            foreach($rows as $r) {
+               $s_test .= "," . $r["T_OrderDetailT_TestID"];
+            }
+            $sql = "select incomingRefDetailID , incomingRefDetailIncomingRefID
+               from incoming_ref_detail
+               where incomingRefDetailNewT_OrderHeaderID = ?
+               and incomingRefDetailT_TestID in ($s_test) ";
+            $qryd = $this->db->query($sql, array($headerID));
+            $flag_found = false;
+            if($qryd) {
+               $rowsd = $qryd->result_array();
+               if ( count($rowsd) > 0 ) {
+                  $incomingRefID = $rowsd[0]["incomingRefDetailIncomingRefID"];
+                  foreach($rowsd as $r) {
+                     $s_detail_ids .= "," . $r["incomingRefDetailID"];
+                  }
+               }
+            } 
+            //check child
+            if(! $flag_found ) {
+               $sql = "select incomingRefChildID , incomingRefChildIncomingRefID
+                  from incoming_ref_child
+                  where incomingRefChildNewT_OrderHeaderID = ?
+                  and incomingRefChildT_TestID in ($s_test) ";
+               $qryd = $this->db->query($sql, array($headerID));
+               if($qryd) {
+                  $rowsd = $qryd->result_array();
+                  if ( count($rowsd) > 0 ) {
+                     $incomingRefID = $rowsd[0]["incomingRefChildIncomingRefID"];
+                     foreach($rowsd as $r) {
+                        $s_child_ids .=  "," . $r["incomingRefChildID"];
+                     }
+                  }
+               }
+            } 
+         }
+      }
+      if ($s_detail_ids == "0" && $s_child_ids == "0" ) {
+         return false;
+      } 
+      $sql = "select M_BranchID, M_BranchIPAddress
+         from m_branch
+         join incoming_ref
+         on M_BranchID = incomingRefM_BranchID
+         where incomingRefID = ?";
+      $qry = $this->db->query($sql, array($incomingRefID));
+      $branchID = 0;
+      if ($qry) {
+         $rows = $qry->result_array();
+         if(count($rows)>0) {
+            $branchID = $rows[0]["M_BranchID"];
+            $branchIPAddress = $rows[0]["M_BranchIPAddress"];
+         }
+      }   
+      if ($branchID == 0 ) {
+         return false;
+      }  
+      $val_note = "";
+      $val_note_int = "";
+      if ($headerID > 0 ) {
+         $sql = "select T_OrderHeaderAddOnValidationNote, T_OrderHeaderAddOnValidationInternal
+            from t_orderheaderaddon
+            where T_orderHeaderAddOnT_OrderHeaderID = ?";
+         $qry = $this->db->query($sql,array($headerID));
+         if ($qry) {
+            $rows = $qry->result_array();
+            if (count($rows) > 0 ) {
+               $val_note = $rows[0]["T_OrderHeaderAddOnValidationNote"];
+               $val_note_int  = $rows[0]["T_OrderHeaderAddOnValidationInternal"];
+               if ( $val_note == null ) $val_note = "";
+               if ( $val_note_int == null ) $val_note_int = "";
+            }
+         } 
+      }
+      $note = "$stage by $username";
+      if ($s_detail_ids!= "0" ) {
+         $sql = "select 
+            incomingRefT_RefDeliveryOrderID, 
+            incomingRefDetailT_OrderDetailID,
+            incomingRefDetailStatus,
+            T_OrderDetailResult,
+            T_OrderDetailNat_NormalValueID,
+            T_OrderDetailVerification,
+            T_OrderDetailValidation,
+            T_OrderDetailNote, 
+            ? note,
+            ? validation_note,
+            ? validation_note_internal
+            from incoming_ref_detail
+            join incoming_ref on incomingRefID = incomingRefDetailIncomingRefID
+            and incomingRefDetailID in ($s_detail_ids)
+            left join t_orderdetail on incomingRefDetailNewT_OrderHeaderID = T_OrderDetailT_OrderHeaderID
+            and T_OrderDetailIsActive = 'Y' and incomingRefDetailT_TestID = T_OrderDetailT_TestID";
+         $qry = $this->db->query($sql, array($note,$val_note,$val_note_int));
+         if ($qry) {
+            $rows = $qry->result_array();
+            $param = json_encode($rows);
+            //insert to 
+            $sql = "insert into tx_branch_status(TxBranchStatusStage, TxBranchStatusM_BranchID,
+               TxBranchStatusM_BranchIP, TxBranchStatusJson,TxBranchStatusNote )
+               values (?,?,?,?,?)";
+            $qry = $this->db->query($sql, array($stage,$branchID, $branchIPAddress, $param, $note));
+         }
+      }   
+      if ($s_child_ids!= "0" ) {
+         $sql = "select 
+            incomingRefT_RefDeliveryOrderID, 
+            incomingRefChildT_OrderDetailID incomingRefDetailT_OrderDetailID,
+            '' incomingRefDetailStatus,
+            T_OrderDetailResult,
+            T_OrderDetailNat_NormalValueID,
+            T_OrderDetailVerification,
+            T_OrderDetailValidation,
+            T_OrderDetailNote, 
+            ? note,
+            ? validation_note,
+            ? validation_note_internal
+            from incoming_ref_child
+            join incoming_ref on incomingRefID = incomingRefChildIncomingRefID
+            and incomingRefChildID in ($s_child_ids)
+            left join t_orderdetail on incomingRefChildNewT_OrderHeaderID = T_OrderDetailT_OrderHeaderID
+            and T_OrderDetailIsActive = 'Y' and incomingRefChildT_TestID = T_OrderDetailT_TestID";
+         $qry = $this->db->query($sql, array($note,$val_note,$val_note_int));
+         if ($qry) {
+            $rows = $qry->result_array();
+            $param = json_encode($rows);
+            //insert to 
+            $sql = "insert into tx_branch_status(TxBranchStatusStage, TxBranchStatusM_BranchID,
+               TxBranchStatusM_BranchIP, TxBranchStatusJson,TxBranchStatusNote )
+               values (?,?,?,?,?)";
+            $qry = $this->db->query($sql, array($stage,$branchID, $branchIPAddress, $param, $note));
+         }   
+      }
+   }
+
+   public function update($stage,$orderDetailID,$username)
+   {
+      $CI =& get_instance();
+      $this->db = $CI->load->database("onedev",true);
+      $sql = "select T_OrderDetailT_TestID, T_OrderDetailT_OrderHeaderID 
+         from 
+         t_orderdetail 
+         where T_OrderDetailID = ? ";
+      $qry = $this->db->query($sql, array($orderDetailID));
+      $incomingRefID = 0;
+      $incomingRefDetailID = 0;
+      $flag_child = false;
+      if ($qry) {
+         $rows = $qry->result_array();
+         $flag_found = false;
+         if(count($rows) > 0 ) {
+            $headerID = $rows[0]["T_OrderDetailT_OrderHeaderID"];
+            $testID = $rows[0]["T_OrderDetailT_TestID"];
+            $sql = "select incomingRefDetailID , incomingRefDetailIncomingRefID
+               from incoming_ref_detail
+               where incomingRefDetailNewT_OrderHeaderID = ?
+               and incomingRefDetailT_TestID = ?";
+            $qryd = $this->db->query($sql, array($headerID,$testID));
+            if($qryd) {
+               $rowsd = $qryd->result_array();
+               if ( count($rowsd) > 0 ) {
+                  $incomingRefID = $rowsd[0]["incomingRefDetailIncomingRefID"];
+                  $incomingRefDetailID = $rowsd[0]["incomingRefDetailID"];
+                  $flag_found = true;
+               }
+            }
+            //check child
+            if(! $flag_found ) {
+               $sql = "select incomingRefChildID , incomingRefChildIncomingRefID
+                  from incoming_ref_child
+                  where incomingRefChildNewT_OrderHeaderID = ?
+                  and incomingRefChildT_TestID = ?";
+               $qryd = $this->db->query($sql, array($headerID,$testID));
+               if($qryd) {
+                  $rowsd = $qryd->result_array();
+                  if ( count($rowsd) > 0 ) {
+                     $incomingRefID = $rowsd[0]["incomingRefChildIncomingRefID"];
+                     $incomingRefDetailID = $rowsd[0]["incomingRefChildID"];
+                     $flag_found = true;
+                     $flag_child = true;
+                  }
+               }
+            } 
+         }
+      }
+      if ($incomingRefDetailID == 0 || $incomingRefDetailID == "") {
+         return false;
+      } 
+      $sql = "select M_BranchID, M_BranchIPAddress
+         from m_branch
+         join incoming_ref
+         on M_BranchID = incomingRefM_BranchID
+         where incomingRefID = ?";
+      $qry = $this->db->query($sql, array($incomingRefID));
+      $branchID = 0;
+      if ($qry) {
+         $rows = $qry->result_array();
+         if(count($rows)>0) {
+            $branchID = $rows[0]["M_BranchID"];
+            $branchIPAddress = $rows[0]["M_BranchIPAddress"];
+         }
+      }   
+      if ($branchID == 0 ) {
+         return false;
+      }  
+
+      $val_note = "";
+      $val_note_int = "";
+      if ($headerID > 0 ) {
+         $sql = "select T_OrderHeaderAddOnValidationNote, T_OrderHeaderAddOnValidationInternal
+            from t_orderheaderaddon
+            where T_orderHeaderAddOnT_OrderHeaderID = ?";
+         $qry = $this->db->query($sql,array($headerID));
+         if ($qry) {
+            $rows = $qry->result_array();
+            if (count($rows) > 0 ) {
+               $val_note = $rows[0]["T_OrderHeaderAddOnValidationNote"];
+               $val_note_int = $rows[0]["T_OrderHeaderAddOnValidationInternal"];
+               if ( $val_note == null ) $val_note = "";
+               if ( $val_note_int == null ) $val_note_int = "";
+            }
+         } 
+      }
+      $note = "$stage by $username";
+      $sql = "select 
+         incomingRefT_RefDeliveryOrderID, 
+         incomingRefDetailT_OrderDetailID,
+         incomingRefDetailStatus,
+         T_OrderDetailResult,
+         T_OrderDetailNat_NormalValueID,
+         T_OrderDetailVerification,
+         T_OrderDetailValidation,
+         T_OrderDetailNote, 
+         ? note,
+         ? validation_note,
+         ? validation_note_internal
+         from incoming_ref_detail
+         join incoming_ref on incomingRefID = incomingRefDetailIncomingRefID
+         and incomingRefDetailID = ?
+         left join t_orderdetail on incomingRefDetailNewT_OrderHeaderID = T_OrderDetailT_OrderHeaderID
+         and T_OrderDetailIsActive = 'Y' and incomingRefDetailT_TestID = T_OrderDetailT_TestID";
+      if ($flag_child ) {
+         $sql = "select 
+            incomingRefT_RefDeliveryOrderID, 
+            incomingRefChildT_OrderDetailID incomingRefDetailT_OrderDetailID,
+            '' incomingRefDetailStatus,
+            T_OrderDetailResult,
+            T_OrderDetailNat_NormalValueID,
+            T_OrderDetailVerification,
+            T_OrderDetailValidation,
+            T_OrderDetailNote, 
+            ? note,
+            ? validation_note,
+            ? validation_note_internal
+            from incoming_ref_child
+            join incoming_ref on incomingRefID = incomingRefChildIncomingRefID
+            and incomingRefChildID = ?
+            left join t_orderdetail on incomingRefChildNewT_OrderHeaderID = T_OrderDetailT_OrderHeaderID
+            and T_OrderDetailIsActive = 'Y' and incomingRefChildT_TestID = T_OrderDetailT_TestID";
+      }
+      $qry = $this->db->query($sql, array($note, $val_note, $val_note_int, $incomingRefDetailID));
+      if ($qry) {
+         $rows = $qry->result_array();
+         $param = json_encode($rows);
+         //insert to 
+         $sql = "insert into tx_branch_status(TxBranchStatusStage, TxBranchStatusM_BranchID,
+            TxBranchStatusM_BranchIP, TxBranchStatusJson,TxBranchStatusNote )
+            values (?,?,?,?,?)";
+         $qry = $this->db->query($sql, array($stage,$branchID, $branchIPAddress, $param, $note));
+      }   
+   }
+}
diff --git a/application/libraries/Wa_krmv3.php b/application/libraries/Wa_krmv3.php
new file mode 100644
index 00000000..7aeffea7
--- /dev/null
+++ b/application/libraries/Wa_krmv3.php
@@ -0,0 +1,63 @@
+client = new ClientV3([
+      "deviceId" => $this->device_id,
+      "refreshToken" => $this->refresh_token,
+      "idToken" => $this->id_token
+    ]);
+  }
+  function upload($url)
+  {
+    //create tmp file 
+    $fname = tempnam("/tmp", "rpt") . "-rpt.pdf";
+    file_put_contents($fname, file_get_contents($url));
+    $resp = $this->client->upload($fname);
+    unlink($fname);
+    return $resp;
+  }
+  function send_qrcode($phone, $url, $name, $date)
+  {
+    $urlImg = $this->upload($url);
+    $message = [$name, $date];
+    $resp = $this->client->sendMessageTemplateImage($phone, $this->template, "id", $message, $urlImg);
+    return json_decode($resp, true);
+  }
+  function send_otp($phone, $otp)
+  {
+    $resp = $this->client->sendMessageTemplateAuthentication($phone, "pramitamobileotp", "id", $otp);
+    return json_decode($resp, true);
+  }
+  function send_rujukan_external_process($phone, $phone_cabang)
+  {
+
+    $message = [$phone_cabang];
+    $resp = $this->client->sendMessageTemplateText($phone, "rujukan01", "id", $message);
+    return json_decode($resp, true);
+  }
+  function send_eform($phone, $kode_cabang, $nolab, $type = "")
+  {
+
+    $message = [$kode_cabang, $nolab];
+    $resp = $this->client->sendMessageTemplateText($phone, "eform_fisik", "id", $message);
+    return json_decode($resp, true);
+  }
+  function send_msg_button($phone, $url)
+  {
+    $body = ["hello", "world", "there"];
+    $resp = $this->client->sendMessageTemplateButton($phone, "sample-message-button", "id", $body, $url);
+    return json_decode($resp, true);
+  }
+}
diff --git a/application/libraries/Wa_sas.php b/application/libraries/Wa_sas.php
new file mode 100644
index 00000000..56724214
--- /dev/null
+++ b/application/libraries/Wa_sas.php
@@ -0,0 +1,159 @@
+host = "http://sasdev.jala.my.id:3000/send/";
+    //$this->host = "http://139.59.235.205:3000/send/";
+    $this->host = "http://devkedungdoro.aplikasi.web.id:7001/send/";
+    $this->username = "sasdev";
+    $this->password = "sasdev!#102938";
+  }
+  function fix_phone($phone)
+  {
+    //remove - and space
+    $phone = str_replace("-", "", $phone);
+    $phone = str_replace(" ", "", $phone);
+    //remove 1st +
+    if (substr($phone, 0, 1) == "+") {
+      $phone = substr($phone, 1);
+    }
+    if (substr($phone, 0, 1) == "0") {
+      $phone = "62" . substr($phone, 1);
+    }
+    if (substr($phone, 0, 2) != "62") {
+      $phone = "62" . $phone;
+    }
+    return $phone;
+  }
+
+  function send_image_group(
+    $phone,
+    $caption,
+    $url_image,
+    $contentType,
+    $file_name,
+    $extension,
+    $view_once = false,
+    $compress = false
+  ) {
+    $tmpFile = tempnam(sys_get_temp_dir(), 'sasdev') . ".$extension";
+    file_put_contents($tmpFile, file_get_contents($url_image));
+    $data = [
+      "phone" => $phone,
+      "caption" => $caption,
+      "view_once" => $view_once,
+      "compress" => $compress,
+      "image" => curl_file_create($tmpFile, $contentType, $file_name)
+    ];
+    $ch = curl_init($this->host . "image");
+    //curl_setopt($ch, CURLOPT_HEADER, 1);
+    curl_setopt($ch, CURLOPT_USERPWD, $this->username . ":" . $this->password);
+    curl_setopt($ch, CURLOPT_TIMEOUT, 30);
+    curl_setopt($ch, CURLOPT_POST, 1);
+    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
+    curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
+    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: multipart/form-data'));
+    $return = curl_exec($ch);
+    curl_close($ch);
+    unlink($tmpFile);
+    $j_return = json_decode($return, true);
+    if (json_last_error() != 0) {
+      return ["code" => "ERROR", "message" => "Error Json Decode : $return"];
+    }
+    return $j_return;
+  }
+  function send_message($phone, $message, $is_group = false)
+  {
+    $data = [
+      "phone" => $is_group ? $phone : $this->fix_phone($phone),
+      "message" => $message
+    ];
+    $ch = curl_init($this->host . "message");
+    curl_setopt($ch, CURLOPT_USERPWD, $this->username . ":" . $this->password);
+    curl_setopt($ch, CURLOPT_TIMEOUT, 30);
+    curl_setopt($ch, CURLOPT_POST, 1);
+    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
+    curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
+    $return = curl_exec($ch);
+    curl_close($ch);
+    $j_return = json_decode($return, true);
+
+    if (json_last_error() != 0) {
+      return ["code" => "ERROR", "message" => "Error Json Decode : $return"];
+    }
+    return $j_return;
+  }
+  function send_image(
+    $phone,
+    $caption,
+    $url_image,
+    $contentType,
+    $file_name,
+    $extension,
+    $view_once = false,
+    $compress = false
+  ) {
+    $tmpFile = tempnam(sys_get_temp_dir(), 'sasdev') . ".$extension";
+    file_put_contents($tmpFile, file_get_contents($url_image));
+    $data = [
+      "phone" => $this->fix_phone($phone),
+      "caption" => $caption,
+      "view_once" => $view_once,
+      "compress" => $compress,
+      "image" => curl_file_create($tmpFile, $contentType, $file_name)
+    ];
+    $ch = curl_init($this->host . "image");
+    //curl_setopt($ch, CURLOPT_HEADER, 1);
+    curl_setopt($ch, CURLOPT_USERPWD, $this->username . ":" . $this->password);
+    curl_setopt($ch, CURLOPT_TIMEOUT, 30);
+    curl_setopt($ch, CURLOPT_POST, 1);
+    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
+    curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
+    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: multipart/form-data'));
+    $return = curl_exec($ch);
+    curl_close($ch);
+    unlink($tmpFile);
+    $j_return = json_decode($return, true);
+    if (json_last_error() != 0) {
+      return ["code" => "ERROR", "message" => "Error Json Decode : $return"];
+    }
+    return $j_return;
+  }
+  function send_file(
+    $phone,
+    $caption,
+    $url_file,
+    $contentType,
+    $file_name,
+    $extension,
+    $compress = false
+  ) {
+    $tmpFile = tempnam(sys_get_temp_dir(), 'sasdev') . ".$extension";
+    file_put_contents($tmpFile, file_get_contents($url_file));
+    $data = [
+      "phone" => $this->fix_phone($phone),
+      "caption" => $caption,
+      "compress" => $compress,
+      "file" => curl_file_create($tmpFile, $contentType, $file_name)
+    ];
+    $ch = curl_init($this->host . "file");
+    //curl_setopt($ch, CURLOPT_HEADER, 1);
+    curl_setopt($ch, CURLOPT_USERPWD, $this->username . ":" . $this->password);
+    curl_setopt($ch, CURLOPT_TIMEOUT, 30);
+    curl_setopt($ch, CURLOPT_POST, 1);
+    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
+    curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
+    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: multipart/form-data'));
+    $return = curl_exec($ch);
+    curl_close($ch);
+    unlink($tmpFile);
+    $j_return = json_decode($return, true);
+    if (json_last_error() != 0) {
+      return ["code" => "ERROR", "message" => "Error Json Decode : $return"];
+    }
+    return $j_return;
+  }
+}
diff --git a/application/libraries/his/Simrs.php b/application/libraries/his/Simrs.php
new file mode 100644
index 00000000..aa54e190
--- /dev/null
+++ b/application/libraries/his/Simrs.php
@@ -0,0 +1,127 @@
+HisEndPoint = "http://34.101.132.130:8080/query";
+    $this->Timeout = 10;
+    $this->token = "";
+    $this->userName = "adiet";
+    $this->password = "qwerty";
+  }
+
+  function get_token() {
+    if (! file_exists("/tmp/his-token.json")) {
+      $this->login($this->userName,$this->password);
+    } else {
+      $jtoken = file_get_contents("/tmp/his-token.json");
+      $token = json_decode($jtoken,true);
+      $expired = $token["expired"];
+      if ($expired - time() > 180 ) {
+        return "{$token["token"]}";
+      } else {
+        $new_token = $this->login("x");
+        return $new_token;
+      }
+    }
+  }
+
+  function login($debug = "") {
+    list($is_ok,$enc_password)= $this->gql(
+      "mutation",
+      "passwordEncrypt",
+      ["password" => "String!"],
+      ["password" => $this->password],
+      "",
+      "",
+      $debug 
+    );
+    if(! $is_ok) {
+      if ($debug != "") echo "Error : {$this->password} => $enc_password\n";
+      return false;
+    }
+    list($is_ok,$tokenResponse)= $this->gql(
+      "mutation",
+      "userLogin",
+      ["userName" => "String!", "password" => "String!"],
+      ["userName" => $this->userName, "password" => $enc_password],
+      "userID token expired",
+      "",
+      $debug 
+    );
+    if(!$is_ok) return false;
+
+    file_put_contents("/tmp/his-token.json",json_encode($tokenResponse));
+    return $tokenResponse["token"];
+  }
+
+  function gql($type, $name, $param, $variable, $return = "",
+  $token = "",
+  $debug = "")
+  {
+    $prm_gql= "";
+    $prm_body = "";
+    foreach($param as $k => $v) {
+      if ($prm_gql!= "") $prm_gql .= ",";
+      $prm_gql.= '$' . $k . ":" . $v;
+      if ($prm_body != "") $prm_body .= ",";
+      $prm_body .= $k . ":$" . $k;
+    }
+    $body = [];
+    if ($return == "") {
+      $body["query"] = "{$type}($prm_gql){{$name}($prm_body)}";
+    } else {
+      $body["query"] = "{$type}($prm_gql){ {$name}($prm_body){ $return } }";
+    }
+    $body["variables"] = $variable;
+    $gql_body = json_encode($body);
+    if($debug != "") {
+      echo "Debug GQL: $gql_body \n";
+    }
+    $resp =$this->post($gql_body,$token);
+    if($debug != "") {
+      echo "Response GQL: $resp \n";
+    }
+    $j_resp = json_decode($resp,true);
+    if ($j_resp !== false)  {
+      if ($j_resp["data"] != null) {
+        $result = $j_resp["data"][$name];
+        if ($debug != "") {
+          print_r($result);
+        }
+        return [true,$result];
+      } else {
+        return [false,json_encode($j_resp["error"])];
+      }
+    }
+    return [false,$resp];
+  }
+  
+  function post($data,$token = "")
+  {
+    $ch = curl_init($this->HisEndPoint);
+    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
+    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
+    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
+    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $this->Timeout / 2);
+    curl_setopt($ch, CURLOPT_TIMEOUT, $this->Timeout);
+    if ($token == "") {
+      curl_setopt($ch, CURLOPT_HTTPHEADER, [
+        "Content-Type: application/json",
+        "Content-Length: " . strlen($data),
+      ]);
+    } else {
+      curl_setopt($ch, CURLOPT_HTTPHEADER, [
+        "Authorization: Bearer $token",
+        "Content-Type: application/json",
+        "Content-Length: " . strlen($data),
+      ]);
+    }
+    $result = curl_exec($ch);
+    if (curl_error($ch) != "") {
+      return "ERROR SIMRS HIS API {$this->HisEndPoint} : " . curl_error($ch) . "\n";
+    }
+    curl_close($ch);
+    return $result;
+  }}
+
diff --git a/application/libraries/index.html b/application/libraries/index.html
new file mode 100755
index 00000000..b702fbc3
--- /dev/null
+++ b/application/libraries/index.html
@@ -0,0 +1,11 @@
+
+
+
+	403 Forbidden
+
+
+
+

Directory access is forbidden.

+ + + diff --git a/application/libraries/qrcode/phpqrcode.php b/application/libraries/qrcode/phpqrcode.php new file mode 100644 index 00000000..ea8c08f9 --- /dev/null +++ b/application/libraries/qrcode/phpqrcode.php @@ -0,0 +1,3312 @@ + + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ + + + +/* + * Version: 1.1.4 + * Build: 2010100721 + */ + + + +//---- qrconst.php ----------------------------- + + + + + +/* + * PHP QR Code encoder + * + * Common constants + * + * Based on libqrencode C library distributed under LGPL 2.1 + * Copyright (C) 2006, 2007, 2008, 2009 Kentaro Fukuchi + * + * PHP QR Code is distributed under LGPL 3 + * Copyright (C) 2010 Dominik Dzienia + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ + + // Encoding modes + + define('QR_MODE_NUL', -1); + define('QR_MODE_NUM', 0); + define('QR_MODE_AN', 1); + define('QR_MODE_8', 2); + define('QR_MODE_KANJI', 3); + define('QR_MODE_STRUCTURE', 4); + + // Levels of error correction. + + define('QR_ECLEVEL_L', 0); + define('QR_ECLEVEL_M', 1); + define('QR_ECLEVEL_Q', 2); + define('QR_ECLEVEL_H', 3); + + // Supported output formats + + define('QR_FORMAT_TEXT', 0); + define('QR_FORMAT_PNG', 1); + + class qrstr { + public static function set(&$srctab, $x, $y, $repl, $replLen = false) { + $srctab[$y] = substr_replace($srctab[$y], ($replLen !== false)?substr($repl,0,$replLen):$repl, $x, ($replLen !== false)?$replLen:strlen($repl)); + } + } + + + +//---- merged_config.php ----------------------------- + + + + +/* + * PHP QR Code encoder + * + * Config file, tuned-up for merged verion + */ + + define('QR_CACHEABLE', false); // use cache - more disk reads but less CPU power, masks and format templates are stored there + define('QR_CACHE_DIR', false); // used when QR_CACHEABLE === true + define('QR_LOG_DIR', false); // default error logs dir + + define('QR_FIND_BEST_MASK', true); // if true, estimates best mask (spec. default, but extremally slow; set to false to significant performance boost but (propably) worst quality code + define('QR_FIND_FROM_RANDOM', 2); // if false, checks all masks available, otherwise value tells count of masks need to be checked, mask id are got randomly + define('QR_DEFAULT_MASK', 2); // when QR_FIND_BEST_MASK === false + + define('QR_PNG_MAXIMUM_SIZE', 1024); // maximum allowed png image width (in pixels), tune to make sure GD and PHP can handle such big images + + + + +//---- qrtools.php ----------------------------- + + + + +/* + * PHP QR Code encoder + * + * Toolset, handy and debug utilites. + * + * PHP QR Code is distributed under LGPL 3 + * Copyright (C) 2010 Dominik Dzienia + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ + + class QRtools { + + //---------------------------------------------------------------------- + public static function binarize($frame) + { + $len = count($frame); + foreach ($frame as &$frameLine) { + + for($i=0; $i<$len; $i++) { + $frameLine[$i] = (ord($frameLine[$i])&1)?'1':'0'; + } + } + + return $frame; + } + + //---------------------------------------------------------------------- + public static function tcpdfBarcodeArray($code, $mode = 'QR,L', $tcPdfVersion = '4.5.037') + { + $barcode_array = array(); + + if (!is_array($mode)) + $mode = explode(',', $mode); + + $eccLevel = 'L'; + + if (count($mode) > 1) { + $eccLevel = $mode[1]; + } + + $qrTab = QRcode::text($code, false, $eccLevel); + $size = count($qrTab); + + $barcode_array['num_rows'] = $size; + $barcode_array['num_cols'] = $size; + $barcode_array['bcode'] = array(); + + foreach ($qrTab as $line) { + $arrAdd = array(); + foreach(str_split($line) as $char) + $arrAdd[] = ($char=='1')?1:0; + $barcode_array['bcode'][] = $arrAdd; + } + + return $barcode_array; + } + + //---------------------------------------------------------------------- + public static function clearCache() + { + self::$frames = array(); + } + + //---------------------------------------------------------------------- + public static function buildCache() + { + QRtools::markTime('before_build_cache'); + + $mask = new QRmask(); + for ($a=1; $a <= QRSPEC_VERSION_MAX; $a++) { + $frame = QRspec::newFrame($a); + if (QR_IMAGE) { + $fileName = QR_CACHE_DIR.'frame_'.$a.'.png'; + QRimage::png(self::binarize($frame), $fileName, 1, 0); + } + + $width = count($frame); + $bitMask = array_fill(0, $width, array_fill(0, $width, 0)); + for ($maskNo=0; $maskNo<8; $maskNo++) + $mask->makeMaskNo($maskNo, $width, $frame, $bitMask, true); + } + + QRtools::markTime('after_build_cache'); + } + + //---------------------------------------------------------------------- + public static function log($outfile, $err) + { + if (QR_LOG_DIR !== false) { + if ($err != '') { + if ($outfile !== false) { + file_put_contents(QR_LOG_DIR.basename($outfile).'-errors.txt', date('Y-m-d H:i:s').': '.$err, FILE_APPEND); + } else { + file_put_contents(QR_LOG_DIR.'errors.txt', date('Y-m-d H:i:s').': '.$err, FILE_APPEND); + } + } + } + } + + //---------------------------------------------------------------------- + public static function dumpMask($frame) + { + $width = count($frame); + for($y=0;$y<$width;$y++) { + for($x=0;$x<$width;$x++) { + echo ord($frame[$y][$x]).','; + } + } + } + + //---------------------------------------------------------------------- + public static function markTime($markerId) + { + list($usec, $sec) = explode(" ", microtime()); + $time = ((float)$usec + (float)$sec); + + if (!isset($GLOBALS['qr_time_bench'])) + $GLOBALS['qr_time_bench'] = array(); + + $GLOBALS['qr_time_bench'][$markerId] = $time; + } + + //---------------------------------------------------------------------- + public static function timeBenchmark() + { + self::markTime('finish'); + + $lastTime = 0; + $startTime = 0; + $p = 0; + + echo ' + + '; + + foreach($GLOBALS['qr_time_bench'] as $markerId=>$thisTime) { + if ($p > 0) { + echo ''; + } else { + $startTime = $thisTime; + } + + $p++; + $lastTime = $thisTime; + } + + echo ' + + +
BENCHMARK
till '.$markerId.': '.number_format($thisTime-$lastTime, 6).'s
TOTAL: '.number_format($lastTime-$startTime, 6).'s
'; + } + + } + + //########################################################################## + + QRtools::markTime('start'); + + + + +//---- qrspec.php ----------------------------- + + + + +/* + * PHP QR Code encoder + * + * QR Code specifications + * + * Based on libqrencode C library distributed under LGPL 2.1 + * Copyright (C) 2006, 2007, 2008, 2009 Kentaro Fukuchi + * + * PHP QR Code is distributed under LGPL 3 + * Copyright (C) 2010 Dominik Dzienia + * + * The following data / specifications are taken from + * "Two dimensional symbol -- QR-code -- Basic Specification" (JIS X0510:2004) + * or + * "Automatic identification and data capture techniques -- + * QR Code 2005 bar code symbology specification" (ISO/IEC 18004:2006) + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ + + define('QRSPEC_VERSION_MAX', 40); + define('QRSPEC_WIDTH_MAX', 177); + + define('QRCAP_WIDTH', 0); + define('QRCAP_WORDS', 1); + define('QRCAP_REMINDER', 2); + define('QRCAP_EC', 3); + + class QRspec { + + public static $capacity = array( + array( 0, 0, 0, array( 0, 0, 0, 0)), + array( 21, 26, 0, array( 7, 10, 13, 17)), // 1 + array( 25, 44, 7, array( 10, 16, 22, 28)), + array( 29, 70, 7, array( 15, 26, 36, 44)), + array( 33, 100, 7, array( 20, 36, 52, 64)), + array( 37, 134, 7, array( 26, 48, 72, 88)), // 5 + array( 41, 172, 7, array( 36, 64, 96, 112)), + array( 45, 196, 0, array( 40, 72, 108, 130)), + array( 49, 242, 0, array( 48, 88, 132, 156)), + array( 53, 292, 0, array( 60, 110, 160, 192)), + array( 57, 346, 0, array( 72, 130, 192, 224)), //10 + array( 61, 404, 0, array( 80, 150, 224, 264)), + array( 65, 466, 0, array( 96, 176, 260, 308)), + array( 69, 532, 0, array( 104, 198, 288, 352)), + array( 73, 581, 3, array( 120, 216, 320, 384)), + array( 77, 655, 3, array( 132, 240, 360, 432)), //15 + array( 81, 733, 3, array( 144, 280, 408, 480)), + array( 85, 815, 3, array( 168, 308, 448, 532)), + array( 89, 901, 3, array( 180, 338, 504, 588)), + array( 93, 991, 3, array( 196, 364, 546, 650)), + array( 97, 1085, 3, array( 224, 416, 600, 700)), //20 + array(101, 1156, 4, array( 224, 442, 644, 750)), + array(105, 1258, 4, array( 252, 476, 690, 816)), + array(109, 1364, 4, array( 270, 504, 750, 900)), + array(113, 1474, 4, array( 300, 560, 810, 960)), + array(117, 1588, 4, array( 312, 588, 870, 1050)), //25 + array(121, 1706, 4, array( 336, 644, 952, 1110)), + array(125, 1828, 4, array( 360, 700, 1020, 1200)), + array(129, 1921, 3, array( 390, 728, 1050, 1260)), + array(133, 2051, 3, array( 420, 784, 1140, 1350)), + array(137, 2185, 3, array( 450, 812, 1200, 1440)), //30 + array(141, 2323, 3, array( 480, 868, 1290, 1530)), + array(145, 2465, 3, array( 510, 924, 1350, 1620)), + array(149, 2611, 3, array( 540, 980, 1440, 1710)), + array(153, 2761, 3, array( 570, 1036, 1530, 1800)), + array(157, 2876, 0, array( 570, 1064, 1590, 1890)), //35 + array(161, 3034, 0, array( 600, 1120, 1680, 1980)), + array(165, 3196, 0, array( 630, 1204, 1770, 2100)), + array(169, 3362, 0, array( 660, 1260, 1860, 2220)), + array(173, 3532, 0, array( 720, 1316, 1950, 2310)), + array(177, 3706, 0, array( 750, 1372, 2040, 2430)) //40 + ); + + //---------------------------------------------------------------------- + public static function getDataLength($version, $level) + { + return self::$capacity[$version][QRCAP_WORDS] - self::$capacity[$version][QRCAP_EC][$level]; + } + + //---------------------------------------------------------------------- + public static function getECCLength($version, $level) + { + return self::$capacity[$version][QRCAP_EC][$level]; + } + + //---------------------------------------------------------------------- + public static function getWidth($version) + { + return self::$capacity[$version][QRCAP_WIDTH]; + } + + //---------------------------------------------------------------------- + public static function getRemainder($version) + { + return self::$capacity[$version][QRCAP_REMINDER]; + } + + //---------------------------------------------------------------------- + public static function getMinimumVersion($size, $level) + { + + for($i=1; $i<= QRSPEC_VERSION_MAX; $i++) { + $words = self::$capacity[$i][QRCAP_WORDS] - self::$capacity[$i][QRCAP_EC][$level]; + if($words >= $size) + return $i; + } + + return -1; + } + + //###################################################################### + + public static $lengthTableBits = array( + array(10, 12, 14), + array( 9, 11, 13), + array( 8, 16, 16), + array( 8, 10, 12) + ); + + //---------------------------------------------------------------------- + public static function lengthIndicator($mode, $version) + { + if ($mode == QR_MODE_STRUCTURE) + return 0; + + if ($version <= 9) { + $l = 0; + } else if ($version <= 26) { + $l = 1; + } else { + $l = 2; + } + + return self::$lengthTableBits[$mode][$l]; + } + + //---------------------------------------------------------------------- + public static function maximumWords($mode, $version) + { + if($mode == QR_MODE_STRUCTURE) + return 3; + + if($version <= 9) { + $l = 0; + } else if($version <= 26) { + $l = 1; + } else { + $l = 2; + } + + $bits = self::$lengthTableBits[$mode][$l]; + $words = (1 << $bits) - 1; + + if($mode == QR_MODE_KANJI) { + $words *= 2; // the number of bytes is required + } + + return $words; + } + + // Error correction code ----------------------------------------------- + // Table of the error correction code (Reed-Solomon block) + // See Table 12-16 (pp.30-36), JIS X0510:2004. + + public static $eccTable = array( + array(array( 0, 0), array( 0, 0), array( 0, 0), array( 0, 0)), + array(array( 1, 0), array( 1, 0), array( 1, 0), array( 1, 0)), // 1 + array(array( 1, 0), array( 1, 0), array( 1, 0), array( 1, 0)), + array(array( 1, 0), array( 1, 0), array( 2, 0), array( 2, 0)), + array(array( 1, 0), array( 2, 0), array( 2, 0), array( 4, 0)), + array(array( 1, 0), array( 2, 0), array( 2, 2), array( 2, 2)), // 5 + array(array( 2, 0), array( 4, 0), array( 4, 0), array( 4, 0)), + array(array( 2, 0), array( 4, 0), array( 2, 4), array( 4, 1)), + array(array( 2, 0), array( 2, 2), array( 4, 2), array( 4, 2)), + array(array( 2, 0), array( 3, 2), array( 4, 4), array( 4, 4)), + array(array( 2, 2), array( 4, 1), array( 6, 2), array( 6, 2)), //10 + array(array( 4, 0), array( 1, 4), array( 4, 4), array( 3, 8)), + array(array( 2, 2), array( 6, 2), array( 4, 6), array( 7, 4)), + array(array( 4, 0), array( 8, 1), array( 8, 4), array(12, 4)), + array(array( 3, 1), array( 4, 5), array(11, 5), array(11, 5)), + array(array( 5, 1), array( 5, 5), array( 5, 7), array(11, 7)), //15 + array(array( 5, 1), array( 7, 3), array(15, 2), array( 3, 13)), + array(array( 1, 5), array(10, 1), array( 1, 15), array( 2, 17)), + array(array( 5, 1), array( 9, 4), array(17, 1), array( 2, 19)), + array(array( 3, 4), array( 3, 11), array(17, 4), array( 9, 16)), + array(array( 3, 5), array( 3, 13), array(15, 5), array(15, 10)), //20 + array(array( 4, 4), array(17, 0), array(17, 6), array(19, 6)), + array(array( 2, 7), array(17, 0), array( 7, 16), array(34, 0)), + array(array( 4, 5), array( 4, 14), array(11, 14), array(16, 14)), + array(array( 6, 4), array( 6, 14), array(11, 16), array(30, 2)), + array(array( 8, 4), array( 8, 13), array( 7, 22), array(22, 13)), //25 + array(array(10, 2), array(19, 4), array(28, 6), array(33, 4)), + array(array( 8, 4), array(22, 3), array( 8, 26), array(12, 28)), + array(array( 3, 10), array( 3, 23), array( 4, 31), array(11, 31)), + array(array( 7, 7), array(21, 7), array( 1, 37), array(19, 26)), + array(array( 5, 10), array(19, 10), array(15, 25), array(23, 25)), //30 + array(array(13, 3), array( 2, 29), array(42, 1), array(23, 28)), + array(array(17, 0), array(10, 23), array(10, 35), array(19, 35)), + array(array(17, 1), array(14, 21), array(29, 19), array(11, 46)), + array(array(13, 6), array(14, 23), array(44, 7), array(59, 1)), + array(array(12, 7), array(12, 26), array(39, 14), array(22, 41)), //35 + array(array( 6, 14), array( 6, 34), array(46, 10), array( 2, 64)), + array(array(17, 4), array(29, 14), array(49, 10), array(24, 46)), + array(array( 4, 18), array(13, 32), array(48, 14), array(42, 32)), + array(array(20, 4), array(40, 7), array(43, 22), array(10, 67)), + array(array(19, 6), array(18, 31), array(34, 34), array(20, 61)),//40 + ); + + //---------------------------------------------------------------------- + // CACHEABLE!!! + + public static function getEccSpec($version, $level, array &$spec) + { + if (count($spec) < 5) { + $spec = array(0,0,0,0,0); + } + + $b1 = self::$eccTable[$version][$level][0]; + $b2 = self::$eccTable[$version][$level][1]; + $data = self::getDataLength($version, $level); + $ecc = self::getECCLength($version, $level); + + if($b2 == 0) { + $spec[0] = $b1; + $spec[1] = (int)($data / $b1); + $spec[2] = (int)($ecc / $b1); + $spec[3] = 0; + $spec[4] = 0; + } else { + $spec[0] = $b1; + $spec[1] = (int)($data / ($b1 + $b2)); + $spec[2] = (int)($ecc / ($b1 + $b2)); + $spec[3] = $b2; + $spec[4] = $spec[1] + 1; + } + } + + // Alignment pattern --------------------------------------------------- + + // Positions of alignment patterns. + // This array includes only the second and the third position of the + // alignment patterns. Rest of them can be calculated from the distance + // between them. + + // See Table 1 in Appendix E (pp.71) of JIS X0510:2004. + + public static $alignmentPattern = array( + array( 0, 0), + array( 0, 0), array(18, 0), array(22, 0), array(26, 0), array(30, 0), // 1- 5 + array(34, 0), array(22, 38), array(24, 42), array(26, 46), array(28, 50), // 6-10 + array(30, 54), array(32, 58), array(34, 62), array(26, 46), array(26, 48), //11-15 + array(26, 50), array(30, 54), array(30, 56), array(30, 58), array(34, 62), //16-20 + array(28, 50), array(26, 50), array(30, 54), array(28, 54), array(32, 58), //21-25 + array(30, 58), array(34, 62), array(26, 50), array(30, 54), array(26, 52), //26-30 + array(30, 56), array(34, 60), array(30, 58), array(34, 62), array(30, 54), //31-35 + array(24, 50), array(28, 54), array(32, 58), array(26, 54), array(30, 58), //35-40 + ); + + + /** -------------------------------------------------------------------- + * Put an alignment marker. + * @param frame + * @param width + * @param ox,oy center coordinate of the pattern + */ + public static function putAlignmentMarker(array &$frame, $ox, $oy) + { + $finder = array( + "\xa1\xa1\xa1\xa1\xa1", + "\xa1\xa0\xa0\xa0\xa1", + "\xa1\xa0\xa1\xa0\xa1", + "\xa1\xa0\xa0\xa0\xa1", + "\xa1\xa1\xa1\xa1\xa1" + ); + + $yStart = $oy-2; + $xStart = $ox-2; + + for($y=0; $y<5; $y++) { + QRstr::set($frame, $xStart, $yStart+$y, $finder[$y]); + } + } + + //---------------------------------------------------------------------- + public static function putAlignmentPattern($version, &$frame, $width) + { + if($version < 2) + return; + + $d = self::$alignmentPattern[$version][1] - self::$alignmentPattern[$version][0]; + if($d < 0) { + $w = 2; + } else { + $w = (int)(($width - self::$alignmentPattern[$version][0]) / $d + 2); + } + + if($w * $w - 3 == 1) { + $x = self::$alignmentPattern[$version][0]; + $y = self::$alignmentPattern[$version][0]; + self::putAlignmentMarker($frame, $x, $y); + return; + } + + $cx = self::$alignmentPattern[$version][0]; + for($x=1; $x<$w - 1; $x++) { + self::putAlignmentMarker($frame, 6, $cx); + self::putAlignmentMarker($frame, $cx, 6); + $cx += $d; + } + + $cy = self::$alignmentPattern[$version][0]; + for($y=0; $y<$w-1; $y++) { + $cx = self::$alignmentPattern[$version][0]; + for($x=0; $x<$w-1; $x++) { + self::putAlignmentMarker($frame, $cx, $cy); + $cx += $d; + } + $cy += $d; + } + } + + // Version information pattern ----------------------------------------- + + // Version information pattern (BCH coded). + // See Table 1 in Appendix D (pp.68) of JIS X0510:2004. + + // size: [QRSPEC_VERSION_MAX - 6] + + public static $versionPattern = array( + 0x07c94, 0x085bc, 0x09a99, 0x0a4d3, 0x0bbf6, 0x0c762, 0x0d847, 0x0e60d, + 0x0f928, 0x10b78, 0x1145d, 0x12a17, 0x13532, 0x149a6, 0x15683, 0x168c9, + 0x177ec, 0x18ec4, 0x191e1, 0x1afab, 0x1b08e, 0x1cc1a, 0x1d33f, 0x1ed75, + 0x1f250, 0x209d5, 0x216f0, 0x228ba, 0x2379f, 0x24b0b, 0x2542e, 0x26a64, + 0x27541, 0x28c69 + ); + + //---------------------------------------------------------------------- + public static function getVersionPattern($version) + { + if($version < 7 || $version > QRSPEC_VERSION_MAX) + return 0; + + return self::$versionPattern[$version -7]; + } + + // Format information -------------------------------------------------- + // See calcFormatInfo in tests/test_qrspec.c (orginal qrencode c lib) + + public static $formatInfo = array( + array(0x77c4, 0x72f3, 0x7daa, 0x789d, 0x662f, 0x6318, 0x6c41, 0x6976), + array(0x5412, 0x5125, 0x5e7c, 0x5b4b, 0x45f9, 0x40ce, 0x4f97, 0x4aa0), + array(0x355f, 0x3068, 0x3f31, 0x3a06, 0x24b4, 0x2183, 0x2eda, 0x2bed), + array(0x1689, 0x13be, 0x1ce7, 0x19d0, 0x0762, 0x0255, 0x0d0c, 0x083b) + ); + + public static function getFormatInfo($mask, $level) + { + if($mask < 0 || $mask > 7) + return 0; + + if($level < 0 || $level > 3) + return 0; + + return self::$formatInfo[$level][$mask]; + } + + // Frame --------------------------------------------------------------- + // Cache of initial frames. + + public static $frames = array(); + + /** -------------------------------------------------------------------- + * Put a finder pattern. + * @param frame + * @param width + * @param ox,oy upper-left coordinate of the pattern + */ + public static function putFinderPattern(&$frame, $ox, $oy) + { + $finder = array( + "\xc1\xc1\xc1\xc1\xc1\xc1\xc1", + "\xc1\xc0\xc0\xc0\xc0\xc0\xc1", + "\xc1\xc0\xc1\xc1\xc1\xc0\xc1", + "\xc1\xc0\xc1\xc1\xc1\xc0\xc1", + "\xc1\xc0\xc1\xc1\xc1\xc0\xc1", + "\xc1\xc0\xc0\xc0\xc0\xc0\xc1", + "\xc1\xc1\xc1\xc1\xc1\xc1\xc1" + ); + + for($y=0; $y<7; $y++) { + QRstr::set($frame, $ox, $oy+$y, $finder[$y]); + } + } + + //---------------------------------------------------------------------- + public static function createFrame($version) + { + $width = self::$capacity[$version][QRCAP_WIDTH]; + $frameLine = str_repeat ("\0", $width); + $frame = array_fill(0, $width, $frameLine); + + // Finder pattern + self::putFinderPattern($frame, 0, 0); + self::putFinderPattern($frame, $width - 7, 0); + self::putFinderPattern($frame, 0, $width - 7); + + // Separator + $yOffset = $width - 7; + + for($y=0; $y<7; $y++) { + $frame[$y][7] = "\xc0"; + $frame[$y][$width - 8] = "\xc0"; + $frame[$yOffset][7] = "\xc0"; + $yOffset++; + } + + $setPattern = str_repeat("\xc0", 8); + + QRstr::set($frame, 0, 7, $setPattern); + QRstr::set($frame, $width-8, 7, $setPattern); + QRstr::set($frame, 0, $width - 8, $setPattern); + + // Format info + $setPattern = str_repeat("\x84", 9); + QRstr::set($frame, 0, 8, $setPattern); + QRstr::set($frame, $width - 8, 8, $setPattern, 8); + + $yOffset = $width - 8; + + for($y=0; $y<8; $y++,$yOffset++) { + $frame[$y][8] = "\x84"; + $frame[$yOffset][8] = "\x84"; + } + + // Timing pattern + + for($i=1; $i<$width-15; $i++) { + $frame[6][7+$i] = chr(0x90 | ($i & 1)); + $frame[7+$i][6] = chr(0x90 | ($i & 1)); + } + + // Alignment pattern + self::putAlignmentPattern($version, $frame, $width); + + // Version information + if($version >= 7) { + $vinf = self::getVersionPattern($version); + + $v = $vinf; + + for($x=0; $x<6; $x++) { + for($y=0; $y<3; $y++) { + $frame[($width - 11)+$y][$x] = chr(0x88 | ($v & 1)); + $v = $v >> 1; + } + } + + $v = $vinf; + for($y=0; $y<6; $y++) { + for($x=0; $x<3; $x++) { + $frame[$y][$x+($width - 11)] = chr(0x88 | ($v & 1)); + $v = $v >> 1; + } + } + } + + // and a little bit... + $frame[$width - 8][8] = "\x81"; + + return $frame; + } + + //---------------------------------------------------------------------- + public static function debug($frame, $binary_mode = false) + { + if ($binary_mode) { + + foreach ($frame as &$frameLine) { + $frameLine = join('  ', explode('0', $frameLine)); + $frameLine = join('██', explode('1', $frameLine)); + } + + ?> + +


        '; + echo join("
        ", $frame); + echo '






'; + + } else { + + foreach ($frame as &$frameLine) { + $frameLine = join(' ', explode("\xc0", $frameLine)); + $frameLine = join('', explode("\xc1", $frameLine)); + $frameLine = join(' ', explode("\xa0", $frameLine)); + $frameLine = join('', explode("\xa1", $frameLine)); + $frameLine = join('', explode("\x84", $frameLine)); //format 0 + $frameLine = join('', explode("\x85", $frameLine)); //format 1 + $frameLine = join('', explode("\x81", $frameLine)); //special bit + $frameLine = join(' ', explode("\x90", $frameLine)); //clock 0 + $frameLine = join('', explode("\x91", $frameLine)); //clock 1 + $frameLine = join(' ', explode("\x88", $frameLine)); //version + $frameLine = join('', explode("\x89", $frameLine)); //version + $frameLine = join('♦', explode("\x01", $frameLine)); + $frameLine = join('⋅', explode("\0", $frameLine)); + } + + ?> + + "; + echo join("
", $frame); + echo "
"; + + } + } + + //---------------------------------------------------------------------- + public static function serial($frame) + { + return gzcompress(join("\n", $frame), 9); + } + + //---------------------------------------------------------------------- + public static function unserial($code) + { + return explode("\n", gzuncompress($code)); + } + + //---------------------------------------------------------------------- + public static function newFrame($version) + { + if($version < 1 || $version > QRSPEC_VERSION_MAX) + return null; + + if(!isset(self::$frames[$version])) { + + $fileName = QR_CACHE_DIR.'frame_'.$version.'.dat'; + + if (QR_CACHEABLE) { + if (file_exists($fileName)) { + self::$frames[$version] = self::unserial(file_get_contents($fileName)); + } else { + self::$frames[$version] = self::createFrame($version); + file_put_contents($fileName, self::serial(self::$frames[$version])); + } + } else { + self::$frames[$version] = self::createFrame($version); + } + } + + if(is_null(self::$frames[$version])) + return null; + + return self::$frames[$version]; + } + + //---------------------------------------------------------------------- + public static function rsBlockNum($spec) { return $spec[0] + $spec[3]; } + public static function rsBlockNum1($spec) { return $spec[0]; } + public static function rsDataCodes1($spec) { return $spec[1]; } + public static function rsEccCodes1($spec) { return $spec[2]; } + public static function rsBlockNum2($spec) { return $spec[3]; } + public static function rsDataCodes2($spec) { return $spec[4]; } + public static function rsEccCodes2($spec) { return $spec[2]; } + public static function rsDataLength($spec) { return ($spec[0] * $spec[1]) + ($spec[3] * $spec[4]); } + public static function rsEccLength($spec) { return ($spec[0] + $spec[3]) * $spec[2]; } + + } + + + +//---- qrimage.php ----------------------------- + + + + +/* + * PHP QR Code encoder + * + * Image output of code using GD2 + * + * PHP QR Code is distributed under LGPL 3 + * Copyright (C) 2010 Dominik Dzienia + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ + + define('QR_IMAGE', true); + + class QRimage { + + //---------------------------------------------------------------------- + public static function png($frame, $filename = false, $pixelPerPoint = 4, $outerFrame = 4,$saveandprint=FALSE) + { + $image = self::image($frame, $pixelPerPoint, $outerFrame); + + if ($filename === false) { + Header("Content-type: image/png"); + ImagePng($image); + } else { + if($saveandprint===TRUE){ + ImagePng($image, $filename); + header("Content-type: image/png"); + ImagePng($image); + }else{ + ImagePng($image, $filename); + } + } + + ImageDestroy($image); + } + + //---------------------------------------------------------------------- + public static function jpg($frame, $filename = false, $pixelPerPoint = 8, $outerFrame = 4, $q = 85) + { + $image = self::image($frame, $pixelPerPoint, $outerFrame); + + if ($filename === false) { + Header("Content-type: image/jpeg"); + ImageJpeg($image, null, $q); + } else { + ImageJpeg($image, $filename, $q); + } + + ImageDestroy($image); + } + + //---------------------------------------------------------------------- + private static function image($frame, $pixelPerPoint = 4, $outerFrame = 4) + { + $h = count($frame); + $w = strlen($frame[0]); + + $imgW = $w + 2*$outerFrame; + $imgH = $h + 2*$outerFrame; + + $base_image =ImageCreate($imgW, $imgH); + + $col[0] = ImageColorAllocate($base_image,255,255,255); + $col[1] = ImageColorAllocate($base_image,0,0,0); + + imagefill($base_image, 0, 0, $col[0]); + + for($y=0; $y<$h; $y++) { + for($x=0; $x<$w; $x++) { + if ($frame[$y][$x] == '1') { + ImageSetPixel($base_image,$x+$outerFrame,$y+$outerFrame,$col[1]); + } + } + } + + $target_image =ImageCreate($imgW * $pixelPerPoint, $imgH * $pixelPerPoint); + ImageCopyResized($target_image, $base_image, 0, 0, 0, 0, $imgW * $pixelPerPoint, $imgH * $pixelPerPoint, $imgW, $imgH); + ImageDestroy($base_image); + + return $target_image; + } + } + + + +//---- qrinput.php ----------------------------- + + + + +/* + * PHP QR Code encoder + * + * Input encoding class + * + * Based on libqrencode C library distributed under LGPL 2.1 + * Copyright (C) 2006, 2007, 2008, 2009 Kentaro Fukuchi + * + * PHP QR Code is distributed under LGPL 3 + * Copyright (C) 2010 Dominik Dzienia + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ + + define('STRUCTURE_HEADER_BITS', 20); + define('MAX_STRUCTURED_SYMBOLS', 16); + + class QRinputItem { + + public $mode; + public $size; + public $data; + public $bstream; + + public function __construct($mode, $size, $data, $bstream = null) + { + $setData = array_slice($data, 0, $size); + + if (count($setData) < $size) { + $setData = array_merge($setData, array_fill(0,$size-count($setData),0)); + } + + if(!QRinput::check($mode, $size, $setData)) { + throw new Exception('Error m:'.$mode.',s:'.$size.',d:'.join(',',$setData)); + return null; + } + + $this->mode = $mode; + $this->size = $size; + $this->data = $setData; + $this->bstream = $bstream; + } + + //---------------------------------------------------------------------- + public function encodeModeNum($version) + { + try { + + $words = (int)($this->size / 3); + $bs = new QRbitstream(); + + $val = 0x1; + $bs->appendNum(4, $val); + $bs->appendNum(QRspec::lengthIndicator(QR_MODE_NUM, $version), $this->size); + + for($i=0; $i<$words; $i++) { + $val = (ord($this->data[$i*3 ]) - ord('0')) * 100; + $val += (ord($this->data[$i*3+1]) - ord('0')) * 10; + $val += (ord($this->data[$i*3+2]) - ord('0')); + $bs->appendNum(10, $val); + } + + if($this->size - $words * 3 == 1) { + $val = ord($this->data[$words*3]) - ord('0'); + $bs->appendNum(4, $val); + } else if($this->size - $words * 3 == 2) { + $val = (ord($this->data[$words*3 ]) - ord('0')) * 10; + $val += (ord($this->data[$words*3+1]) - ord('0')); + $bs->appendNum(7, $val); + } + + $this->bstream = $bs; + return 0; + + } catch (Exception $e) { + return -1; + } + } + + //---------------------------------------------------------------------- + public function encodeModeAn($version) + { + try { + $words = (int)($this->size / 2); + $bs = new QRbitstream(); + + $bs->appendNum(4, 0x02); + $bs->appendNum(QRspec::lengthIndicator(QR_MODE_AN, $version), $this->size); + + for($i=0; $i<$words; $i++) { + $val = (int)QRinput::lookAnTable(ord($this->data[$i*2 ])) * 45; + $val += (int)QRinput::lookAnTable(ord($this->data[$i*2+1])); + + $bs->appendNum(11, $val); + } + + if($this->size & 1) { + $val = QRinput::lookAnTable(ord($this->data[$words * 2])); + $bs->appendNum(6, $val); + } + + $this->bstream = $bs; + return 0; + + } catch (Exception $e) { + return -1; + } + } + + //---------------------------------------------------------------------- + public function encodeMode8($version) + { + try { + $bs = new QRbitstream(); + + $bs->appendNum(4, 0x4); + $bs->appendNum(QRspec::lengthIndicator(QR_MODE_8, $version), $this->size); + + for($i=0; $i<$this->size; $i++) { + $bs->appendNum(8, ord($this->data[$i])); + } + + $this->bstream = $bs; + return 0; + + } catch (Exception $e) { + return -1; + } + } + + //---------------------------------------------------------------------- + public function encodeModeKanji($version) + { + try { + + $bs = new QRbitrtream(); + + $bs->appendNum(4, 0x8); + $bs->appendNum(QRspec::lengthIndicator(QR_MODE_KANJI, $version), (int)($this->size / 2)); + + for($i=0; $i<$this->size; $i+=2) { + $val = (ord($this->data[$i]) << 8) | ord($this->data[$i+1]); + if($val <= 0x9ffc) { + $val -= 0x8140; + } else { + $val -= 0xc140; + } + + $h = ($val >> 8) * 0xc0; + $val = ($val & 0xff) + $h; + + $bs->appendNum(13, $val); + } + + $this->bstream = $bs; + return 0; + + } catch (Exception $e) { + return -1; + } + } + + //---------------------------------------------------------------------- + public function encodeModeStructure() + { + try { + $bs = new QRbitstream(); + + $bs->appendNum(4, 0x03); + $bs->appendNum(4, ord($this->data[1]) - 1); + $bs->appendNum(4, ord($this->data[0]) - 1); + $bs->appendNum(8, ord($this->data[2])); + + $this->bstream = $bs; + return 0; + + } catch (Exception $e) { + return -1; + } + } + + //---------------------------------------------------------------------- + public function estimateBitStreamSizeOfEntry($version) + { + $bits = 0; + + if($version == 0) + $version = 1; + + switch($this->mode) { + case QR_MODE_NUM: $bits = QRinput::estimateBitsModeNum($this->size); break; + case QR_MODE_AN: $bits = QRinput::estimateBitsModeAn($this->size); break; + case QR_MODE_8: $bits = QRinput::estimateBitsMode8($this->size); break; + case QR_MODE_KANJI: $bits = QRinput::estimateBitsModeKanji($this->size);break; + case QR_MODE_STRUCTURE: return STRUCTURE_HEADER_BITS; + default: + return 0; + } + + $l = QRspec::lengthIndicator($this->mode, $version); + $m = 1 << $l; + $num = (int)(($this->size + $m - 1) / $m); + + $bits += $num * (4 + $l); + + return $bits; + } + + //---------------------------------------------------------------------- + public function encodeBitStream($version) + { + try { + + unset($this->bstream); + $words = QRspec::maximumWords($this->mode, $version); + + if($this->size > $words) { + + $st1 = new QRinputItem($this->mode, $words, $this->data); + $st2 = new QRinputItem($this->mode, $this->size - $words, array_slice($this->data, $words)); + + $st1->encodeBitStream($version); + $st2->encodeBitStream($version); + + $this->bstream = new QRbitstream(); + $this->bstream->append($st1->bstream); + $this->bstream->append($st2->bstream); + + unset($st1); + unset($st2); + + } else { + + $ret = 0; + + switch($this->mode) { + case QR_MODE_NUM: $ret = $this->encodeModeNum($version); break; + case QR_MODE_AN: $ret = $this->encodeModeAn($version); break; + case QR_MODE_8: $ret = $this->encodeMode8($version); break; + case QR_MODE_KANJI: $ret = $this->encodeModeKanji($version);break; + case QR_MODE_STRUCTURE: $ret = $this->encodeModeStructure(); break; + + default: + break; + } + + if($ret < 0) + return -1; + } + + return $this->bstream->size(); + + } catch (Exception $e) { + return -1; + } + } + }; + + //########################################################################## + + class QRinput { + + public $items; + + private $version; + private $level; + + //---------------------------------------------------------------------- + public function __construct($version = 0, $level = QR_ECLEVEL_L) + { + if ($version < 0 || $version > QRSPEC_VERSION_MAX || $level > QR_ECLEVEL_H) { + throw new Exception('Invalid version no'); + return NULL; + } + + $this->version = $version; + $this->level = $level; + } + + //---------------------------------------------------------------------- + public function getVersion() + { + return $this->version; + } + + //---------------------------------------------------------------------- + public function setVersion($version) + { + if($version < 0 || $version > QRSPEC_VERSION_MAX) { + throw new Exception('Invalid version no'); + return -1; + } + + $this->version = $version; + + return 0; + } + + //---------------------------------------------------------------------- + public function getErrorCorrectionLevel() + { + return $this->level; + } + + //---------------------------------------------------------------------- + public function setErrorCorrectionLevel($level) + { + if($level > QR_ECLEVEL_H) { + throw new Exception('Invalid ECLEVEL'); + return -1; + } + + $this->level = $level; + + return 0; + } + + //---------------------------------------------------------------------- + public function appendEntry(QRinputItem $entry) + { + $this->items[] = $entry; + } + + //---------------------------------------------------------------------- + public function append($mode, $size, $data) + { + try { + $entry = new QRinputItem($mode, $size, $data); + $this->items[] = $entry; + return 0; + } catch (Exception $e) { + return -1; + } + } + + //---------------------------------------------------------------------- + + public function insertStructuredAppendHeader($size, $index, $parity) + { + if( $size > MAX_STRUCTURED_SYMBOLS ) { + throw new Exception('insertStructuredAppendHeader wrong size'); + } + + if( $index <= 0 || $index > MAX_STRUCTURED_SYMBOLS ) { + throw new Exception('insertStructuredAppendHeader wrong index'); + } + + $buf = array($size, $index, $parity); + + try { + $entry = new QRinputItem(QR_MODE_STRUCTURE, 3, buf); + array_unshift($this->items, $entry); + return 0; + } catch (Exception $e) { + return -1; + } + } + + //---------------------------------------------------------------------- + public function calcParity() + { + $parity = 0; + + foreach($this->items as $item) { + if($item->mode != QR_MODE_STRUCTURE) { + for($i=$item->size-1; $i>=0; $i--) { + $parity ^= $item->data[$i]; + } + } + } + + return $parity; + } + + //---------------------------------------------------------------------- + public static function checkModeNum($size, $data) + { + for($i=0; $i<$size; $i++) { + if((ord($data[$i]) < ord('0')) || (ord($data[$i]) > ord('9'))){ + return false; + } + } + + return true; + } + + //---------------------------------------------------------------------- + public static function estimateBitsModeNum($size) + { + $w = (int)$size / 3; + $bits = $w * 10; + + switch($size - $w * 3) { + case 1: + $bits += 4; + break; + case 2: + $bits += 7; + break; + default: + break; + } + + return $bits; + } + + //---------------------------------------------------------------------- + public static $anTable = array( + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + 36, -1, -1, -1, 37, 38, -1, -1, -1, -1, 39, 40, -1, 41, 42, 43, + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 44, -1, -1, -1, -1, -1, + -1, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, + 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 + ); + + //---------------------------------------------------------------------- + public static function lookAnTable($c) + { + return (($c > 127)?-1:self::$anTable[$c]); + } + + //---------------------------------------------------------------------- + public static function checkModeAn($size, $data) + { + for($i=0; $i<$size; $i++) { + if (self::lookAnTable(ord($data[$i])) == -1) { + return false; + } + } + + return true; + } + + //---------------------------------------------------------------------- + public static function estimateBitsModeAn($size) + { + $w = (int)($size / 2); + $bits = $w * 11; + + if($size & 1) { + $bits += 6; + } + + return $bits; + } + + //---------------------------------------------------------------------- + public static function estimateBitsMode8($size) + { + return $size * 8; + } + + //---------------------------------------------------------------------- + public function estimateBitsModeKanji($size) + { + return (int)(($size / 2) * 13); + } + + //---------------------------------------------------------------------- + public static function checkModeKanji($size, $data) + { + if($size & 1) + return false; + + for($i=0; $i<$size; $i+=2) { + $val = (ord($data[$i]) << 8) | ord($data[$i+1]); + if( $val < 0x8140 + || ($val > 0x9ffc && $val < 0xe040) + || $val > 0xebbf) { + return false; + } + } + + return true; + } + + /*********************************************************************** + * Validation + **********************************************************************/ + + public static function check($mode, $size, $data) + { + if($size <= 0) + return false; + + switch($mode) { + case QR_MODE_NUM: return self::checkModeNum($size, $data); break; + case QR_MODE_AN: return self::checkModeAn($size, $data); break; + case QR_MODE_KANJI: return self::checkModeKanji($size, $data); break; + case QR_MODE_8: return true; break; + case QR_MODE_STRUCTURE: return true; break; + + default: + break; + } + + return false; + } + + + //---------------------------------------------------------------------- + public function estimateBitStreamSize($version) + { + $bits = 0; + + foreach($this->items as $item) { + $bits += $item->estimateBitStreamSizeOfEntry($version); + } + + return $bits; + } + + //---------------------------------------------------------------------- + public function estimateVersion() + { + $version = 0; + $prev = 0; + do { + $prev = $version; + $bits = $this->estimateBitStreamSize($prev); + $version = QRspec::getMinimumVersion((int)(($bits + 7) / 8), $this->level); + if ($version < 0) { + return -1; + } + } while ($version > $prev); + + return $version; + } + + //---------------------------------------------------------------------- + public static function lengthOfCode($mode, $version, $bits) + { + $payload = $bits - 4 - QRspec::lengthIndicator($mode, $version); + switch($mode) { + case QR_MODE_NUM: + $chunks = (int)($payload / 10); + $remain = $payload - $chunks * 10; + $size = $chunks * 3; + if($remain >= 7) { + $size += 2; + } else if($remain >= 4) { + $size += 1; + } + break; + case QR_MODE_AN: + $chunks = (int)($payload / 11); + $remain = $payload - $chunks * 11; + $size = $chunks * 2; + if($remain >= 6) + $size++; + break; + case QR_MODE_8: + $size = (int)($payload / 8); + break; + case QR_MODE_KANJI: + $size = (int)(($payload / 13) * 2); + break; + case QR_MODE_STRUCTURE: + $size = (int)($payload / 8); + break; + default: + $size = 0; + break; + } + + $maxsize = QRspec::maximumWords($mode, $version); + if($size < 0) $size = 0; + if($size > $maxsize) $size = $maxsize; + + return $size; + } + + //---------------------------------------------------------------------- + public function createBitStream() + { + $total = 0; + + foreach($this->items as $item) { + $bits = $item->encodeBitStream($this->version); + + if($bits < 0) + return -1; + + $total += $bits; + } + + return $total; + } + + //---------------------------------------------------------------------- + public function convertData() + { + $ver = $this->estimateVersion(); + if($ver > $this->getVersion()) { + $this->setVersion($ver); + } + + for(;;) { + $bits = $this->createBitStream(); + + if($bits < 0) + return -1; + + $ver = QRspec::getMinimumVersion((int)(($bits + 7) / 8), $this->level); + if($ver < 0) { + throw new Exception('WRONG VERSION'); + return -1; + } else if($ver > $this->getVersion()) { + $this->setVersion($ver); + } else { + break; + } + } + + return 0; + } + + //---------------------------------------------------------------------- + public function appendPaddingBit(&$bstream) + { + $bits = $bstream->size(); + $maxwords = QRspec::getDataLength($this->version, $this->level); + $maxbits = $maxwords * 8; + + if ($maxbits == $bits) { + return 0; + } + + if ($maxbits - $bits < 5) { + return $bstream->appendNum($maxbits - $bits, 0); + } + + $bits += 4; + $words = (int)(($bits + 7) / 8); + + $padding = new QRbitstream(); + $ret = $padding->appendNum($words * 8 - $bits + 4, 0); + + if($ret < 0) + return $ret; + + $padlen = $maxwords - $words; + + if($padlen > 0) { + + $padbuf = array(); + for($i=0; $i<$padlen; $i++) { + $padbuf[$i] = ($i&1)?0x11:0xec; + } + + $ret = $padding->appendBytes($padlen, $padbuf); + + if($ret < 0) + return $ret; + + } + + $ret = $bstream->append($padding); + + return $ret; + } + + //---------------------------------------------------------------------- + public function mergeBitStream() + { + if($this->convertData() < 0) { + return null; + } + + $bstream = new QRbitstream(); + + foreach($this->items as $item) { + $ret = $bstream->append($item->bstream); + if($ret < 0) { + return null; + } + } + + return $bstream; + } + + //---------------------------------------------------------------------- + public function getBitStream() + { + + $bstream = $this->mergeBitStream(); + + if($bstream == null) { + return null; + } + + $ret = $this->appendPaddingBit($bstream); + if($ret < 0) { + return null; + } + + return $bstream; + } + + //---------------------------------------------------------------------- + public function getByteStream() + { + $bstream = $this->getBitStream(); + if($bstream == null) { + return null; + } + + return $bstream->toByte(); + } + } + + + + + + +//---- qrbitstream.php ----------------------------- + + + + +/* + * PHP QR Code encoder + * + * Bitstream class + * + * Based on libqrencode C library distributed under LGPL 2.1 + * Copyright (C) 2006, 2007, 2008, 2009 Kentaro Fukuchi + * + * PHP QR Code is distributed under LGPL 3 + * Copyright (C) 2010 Dominik Dzienia + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ + + class QRbitstream { + + public $data = array(); + + //---------------------------------------------------------------------- + public function size() + { + return count($this->data); + } + + //---------------------------------------------------------------------- + public function allocate($setLength) + { + $this->data = array_fill(0, $setLength, 0); + return 0; + } + + //---------------------------------------------------------------------- + public static function newFromNum($bits, $num) + { + $bstream = new QRbitstream(); + $bstream->allocate($bits); + + $mask = 1 << ($bits - 1); + for($i=0; $i<$bits; $i++) { + if($num & $mask) { + $bstream->data[$i] = 1; + } else { + $bstream->data[$i] = 0; + } + $mask = $mask >> 1; + } + + return $bstream; + } + + //---------------------------------------------------------------------- + public static function newFromBytes($size, $data) + { + $bstream = new QRbitstream(); + $bstream->allocate($size * 8); + $p=0; + + for($i=0; $i<$size; $i++) { + $mask = 0x80; + for($j=0; $j<8; $j++) { + if($data[$i] & $mask) { + $bstream->data[$p] = 1; + } else { + $bstream->data[$p] = 0; + } + $p++; + $mask = $mask >> 1; + } + } + + return $bstream; + } + + //---------------------------------------------------------------------- + public function append(QRbitstream $arg) + { + if (is_null($arg)) { + return -1; + } + + if($arg->size() == 0) { + return 0; + } + + if($this->size() == 0) { + $this->data = $arg->data; + return 0; + } + + $this->data = array_values(array_merge($this->data, $arg->data)); + + return 0; + } + + //---------------------------------------------------------------------- + public function appendNum($bits, $num) + { + if ($bits == 0) + return 0; + + $b = QRbitstream::newFromNum($bits, $num); + + if(is_null($b)) + return -1; + + $ret = $this->append($b); + unset($b); + + return $ret; + } + + //---------------------------------------------------------------------- + public function appendBytes($size, $data) + { + if ($size == 0) + return 0; + + $b = QRbitstream::newFromBytes($size, $data); + + if(is_null($b)) + return -1; + + $ret = $this->append($b); + unset($b); + + return $ret; + } + + //---------------------------------------------------------------------- + public function toByte() + { + + $size = $this->size(); + + if($size == 0) { + return array(); + } + + $data = array_fill(0, (int)(($size + 7) / 8), 0); + $bytes = (int)($size / 8); + + $p = 0; + + for($i=0; $i<$bytes; $i++) { + $v = 0; + for($j=0; $j<8; $j++) { + $v = $v << 1; + $v |= $this->data[$p]; + $p++; + } + $data[$i] = $v; + } + + if($size & 7) { + $v = 0; + for($j=0; $j<($size & 7); $j++) { + $v = $v << 1; + $v |= $this->data[$p]; + $p++; + } + $data[$bytes] = $v; + } + + return $data; + } + + } + + + + +//---- qrsplit.php ----------------------------- + + + + +/* + * PHP QR Code encoder + * + * Input splitting classes + * + * Based on libqrencode C library distributed under LGPL 2.1 + * Copyright (C) 2006, 2007, 2008, 2009 Kentaro Fukuchi + * + * PHP QR Code is distributed under LGPL 3 + * Copyright (C) 2010 Dominik Dzienia + * + * The following data / specifications are taken from + * "Two dimensional symbol -- QR-code -- Basic Specification" (JIS X0510:2004) + * or + * "Automatic identification and data capture techniques -- + * QR Code 2005 bar code symbology specification" (ISO/IEC 18004:2006) + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ + class QRsplit { + + public $dataStr = ''; + public $input; + public $modeHint; + + //---------------------------------------------------------------------- + public function __construct($dataStr, $input, $modeHint) + { + $this->dataStr = $dataStr; + $this->input = $input; + $this->modeHint = $modeHint; + } + + //---------------------------------------------------------------------- + public static function isdigitat($str, $pos) + { + if ($pos >= strlen($str)) + return false; + + return ((ord($str[$pos]) >= ord('0'))&&(ord($str[$pos]) <= ord('9'))); + } + + //---------------------------------------------------------------------- + public static function isalnumat($str, $pos) + { + if ($pos >= strlen($str)) + return false; + + return (QRinput::lookAnTable(ord($str[$pos])) >= 0); + } + + //---------------------------------------------------------------------- + public function identifyMode($pos) + { + if ($pos >= strlen($this->dataStr)) + return QR_MODE_NUL; + + $c = $this->dataStr[$pos]; + + if(self::isdigitat($this->dataStr, $pos)) { + return QR_MODE_NUM; + } else if(self::isalnumat($this->dataStr, $pos)) { + return QR_MODE_AN; + } else if($this->modeHint == QR_MODE_KANJI) { + + if ($pos+1 < strlen($this->dataStr)) + { + $d = $this->dataStr[$pos+1]; + $word = (ord($c) << 8) | ord($d); + if(($word >= 0x8140 && $word <= 0x9ffc) || ($word >= 0xe040 && $word <= 0xebbf)) { + return QR_MODE_KANJI; + } + } + } + + return QR_MODE_8; + } + + //---------------------------------------------------------------------- + public function eatNum() + { + $ln = QRspec::lengthIndicator(QR_MODE_NUM, $this->input->getVersion()); + + $p = 0; + while(self::isdigitat($this->dataStr, $p)) { + $p++; + } + + $run = $p; + $mode = $this->identifyMode($p); + + if($mode == QR_MODE_8) { + $dif = QRinput::estimateBitsModeNum($run) + 4 + $ln + + QRinput::estimateBitsMode8(1) // + 4 + l8 + - QRinput::estimateBitsMode8($run + 1); // - 4 - l8 + if($dif > 0) { + return $this->eat8(); + } + } + if($mode == QR_MODE_AN) { + $dif = QRinput::estimateBitsModeNum($run) + 4 + $ln + + QRinput::estimateBitsModeAn(1) // + 4 + la + - QRinput::estimateBitsModeAn($run + 1);// - 4 - la + if($dif > 0) { + return $this->eatAn(); + } + } + + $ret = $this->input->append(QR_MODE_NUM, $run, str_split($this->dataStr)); + if($ret < 0) + return -1; + + return $run; + } + + //---------------------------------------------------------------------- + public function eatAn() + { + $la = QRspec::lengthIndicator(QR_MODE_AN, $this->input->getVersion()); + $ln = QRspec::lengthIndicator(QR_MODE_NUM, $this->input->getVersion()); + + $p = 0; + + while(self::isalnumat($this->dataStr, $p)) { + if(self::isdigitat($this->dataStr, $p)) { + $q = $p; + while(self::isdigitat($this->dataStr, $q)) { + $q++; + } + + $dif = QRinput::estimateBitsModeAn($p) // + 4 + la + + QRinput::estimateBitsModeNum($q - $p) + 4 + $ln + - QRinput::estimateBitsModeAn($q); // - 4 - la + + if($dif < 0) { + break; + } else { + $p = $q; + } + } else { + $p++; + } + } + + $run = $p; + + if(!self::isalnumat($this->dataStr, $p)) { + $dif = QRinput::estimateBitsModeAn($run) + 4 + $la + + QRinput::estimateBitsMode8(1) // + 4 + l8 + - QRinput::estimateBitsMode8($run + 1); // - 4 - l8 + if($dif > 0) { + return $this->eat8(); + } + } + + $ret = $this->input->append(QR_MODE_AN, $run, str_split($this->dataStr)); + if($ret < 0) + return -1; + + return $run; + } + + //---------------------------------------------------------------------- + public function eatKanji() + { + $p = 0; + + while($this->identifyMode($p) == QR_MODE_KANJI) { + $p += 2; + } + + $ret = $this->input->append(QR_MODE_KANJI, $p, str_split($this->dataStr)); + if($ret < 0) + return -1; + + return $run; + } + + //---------------------------------------------------------------------- + public function eat8() + { + $la = QRspec::lengthIndicator(QR_MODE_AN, $this->input->getVersion()); + $ln = QRspec::lengthIndicator(QR_MODE_NUM, $this->input->getVersion()); + + $p = 1; + $dataStrLen = strlen($this->dataStr); + + while($p < $dataStrLen) { + + $mode = $this->identifyMode($p); + if($mode == QR_MODE_KANJI) { + break; + } + if($mode == QR_MODE_NUM) { + $q = $p; + while(self::isdigitat($this->dataStr, $q)) { + $q++; + } + $dif = QRinput::estimateBitsMode8($p) // + 4 + l8 + + QRinput::estimateBitsModeNum($q - $p) + 4 + $ln + - QRinput::estimateBitsMode8($q); // - 4 - l8 + if($dif < 0) { + break; + } else { + $p = $q; + } + } else if($mode == QR_MODE_AN) { + $q = $p; + while(self::isalnumat($this->dataStr, $q)) { + $q++; + } + $dif = QRinput::estimateBitsMode8($p) // + 4 + l8 + + QRinput::estimateBitsModeAn($q - $p) + 4 + $la + - QRinput::estimateBitsMode8($q); // - 4 - l8 + if($dif < 0) { + break; + } else { + $p = $q; + } + } else { + $p++; + } + } + + $run = $p; + $ret = $this->input->append(QR_MODE_8, $run, str_split($this->dataStr)); + + if($ret < 0) + return -1; + + return $run; + } + + //---------------------------------------------------------------------- + public function splitString() + { + while (strlen($this->dataStr) > 0) + { + if($this->dataStr == '') + return 0; + + $mode = $this->identifyMode(0); + + switch ($mode) { + case QR_MODE_NUM: $length = $this->eatNum(); break; + case QR_MODE_AN: $length = $this->eatAn(); break; + case QR_MODE_KANJI: + if ($hint == QR_MODE_KANJI) + $length = $this->eatKanji(); + else $length = $this->eat8(); + break; + default: $length = $this->eat8(); break; + + } + + if($length == 0) return 0; + if($length < 0) return -1; + + $this->dataStr = substr($this->dataStr, $length); + } + } + + //---------------------------------------------------------------------- + public function toUpper() + { + $stringLen = strlen($this->dataStr); + $p = 0; + + while ($p<$stringLen) { + $mode = self::identifyMode(substr($this->dataStr, $p), $this->modeHint); + if($mode == QR_MODE_KANJI) { + $p += 2; + } else { + if (ord($this->dataStr[$p]) >= ord('a') && ord($this->dataStr[$p]) <= ord('z')) { + $this->dataStr[$p] = chr(ord($this->dataStr[$p]) - 32); + } + $p++; + } + } + + return $this->dataStr; + } + + //---------------------------------------------------------------------- + public static function splitStringToQRinput($string, QRinput $input, $modeHint, $casesensitive = true) + { + if(is_null($string) || $string == '\0' || $string == '') { + throw new Exception('empty string!!!'); + } + + $split = new QRsplit($string, $input, $modeHint); + + if(!$casesensitive) + $split->toUpper(); + + return $split->splitString(); + } + } + + + +//---- qrrscode.php ----------------------------- + + + + +/* + * PHP QR Code encoder + * + * Reed-Solomon error correction support + * + * Copyright (C) 2002, 2003, 2004, 2006 Phil Karn, KA9Q + * (libfec is released under the GNU Lesser General Public License.) + * + * Based on libqrencode C library distributed under LGPL 2.1 + * Copyright (C) 2006, 2007, 2008, 2009 Kentaro Fukuchi + * + * PHP QR Code is distributed under LGPL 3 + * Copyright (C) 2010 Dominik Dzienia + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ + + class QRrsItem { + + public $mm; // Bits per symbol + public $nn; // Symbols per block (= (1<= $this->nn) { + $x -= $this->nn; + $x = ($x >> $this->mm) + ($x & $this->nn); + } + + return $x; + } + + //---------------------------------------------------------------------- + public static function init_rs_char($symsize, $gfpoly, $fcr, $prim, $nroots, $pad) + { + // Common code for intializing a Reed-Solomon control block (char or int symbols) + // Copyright 2004 Phil Karn, KA9Q + // May be used under the terms of the GNU Lesser General Public License (LGPL) + + $rs = null; + + // Check parameter ranges + if($symsize < 0 || $symsize > 8) return $rs; + if($fcr < 0 || $fcr >= (1<<$symsize)) return $rs; + if($prim <= 0 || $prim >= (1<<$symsize)) return $rs; + if($nroots < 0 || $nroots >= (1<<$symsize)) return $rs; // Can't have more roots than symbol values! + if($pad < 0 || $pad >= ((1<<$symsize) -1 - $nroots)) return $rs; // Too much padding + + $rs = new QRrsItem(); + $rs->mm = $symsize; + $rs->nn = (1<<$symsize)-1; + $rs->pad = $pad; + + $rs->alpha_to = array_fill(0, $rs->nn+1, 0); + $rs->index_of = array_fill(0, $rs->nn+1, 0); + + // PHP style macro replacement ;) + $NN =& $rs->nn; + $A0 =& $NN; + + // Generate Galois field lookup tables + $rs->index_of[0] = $A0; // log(zero) = -inf + $rs->alpha_to[$A0] = 0; // alpha**-inf = 0 + $sr = 1; + + for($i=0; $i<$rs->nn; $i++) { + $rs->index_of[$sr] = $i; + $rs->alpha_to[$i] = $sr; + $sr <<= 1; + if($sr & (1<<$symsize)) { + $sr ^= $gfpoly; + } + $sr &= $rs->nn; + } + + if($sr != 1){ + // field generator polynomial is not primitive! + $rs = NULL; + return $rs; + } + + /* Form RS code generator polynomial from its roots */ + $rs->genpoly = array_fill(0, $nroots+1, 0); + + $rs->fcr = $fcr; + $rs->prim = $prim; + $rs->nroots = $nroots; + $rs->gfpoly = $gfpoly; + + /* Find prim-th root of 1, used in decoding */ + for($iprim=1;($iprim % $prim) != 0;$iprim += $rs->nn) + ; // intentional empty-body loop! + + $rs->iprim = (int)($iprim / $prim); + $rs->genpoly[0] = 1; + + for ($i = 0,$root=$fcr*$prim; $i < $nroots; $i++, $root += $prim) { + $rs->genpoly[$i+1] = 1; + + // Multiply rs->genpoly[] by @**(root + x) + for ($j = $i; $j > 0; $j--) { + if ($rs->genpoly[$j] != 0) { + $rs->genpoly[$j] = $rs->genpoly[$j-1] ^ $rs->alpha_to[$rs->modnn($rs->index_of[$rs->genpoly[$j]] + $root)]; + } else { + $rs->genpoly[$j] = $rs->genpoly[$j-1]; + } + } + // rs->genpoly[0] can never be zero + $rs->genpoly[0] = $rs->alpha_to[$rs->modnn($rs->index_of[$rs->genpoly[0]] + $root)]; + } + + // convert rs->genpoly[] to index form for quicker encoding + for ($i = 0; $i <= $nroots; $i++) + $rs->genpoly[$i] = $rs->index_of[$rs->genpoly[$i]]; + + return $rs; + } + + //---------------------------------------------------------------------- + public function encode_rs_char($data, &$parity) + { + $MM =& $this->mm; + $NN =& $this->nn; + $ALPHA_TO =& $this->alpha_to; + $INDEX_OF =& $this->index_of; + $GENPOLY =& $this->genpoly; + $NROOTS =& $this->nroots; + $FCR =& $this->fcr; + $PRIM =& $this->prim; + $IPRIM =& $this->iprim; + $PAD =& $this->pad; + $A0 =& $NN; + + $parity = array_fill(0, $NROOTS, 0); + + for($i=0; $i< ($NN-$NROOTS-$PAD); $i++) { + + $feedback = $INDEX_OF[$data[$i] ^ $parity[0]]; + if($feedback != $A0) { + // feedback term is non-zero + + // This line is unnecessary when GENPOLY[NROOTS] is unity, as it must + // always be for the polynomials constructed by init_rs() + $feedback = $this->modnn($NN - $GENPOLY[$NROOTS] + $feedback); + + for($j=1;$j<$NROOTS;$j++) { + $parity[$j] ^= $ALPHA_TO[$this->modnn($feedback + $GENPOLY[$NROOTS-$j])]; + } + } + + // Shift + array_shift($parity); + if($feedback != $A0) { + array_push($parity, $ALPHA_TO[$this->modnn($feedback + $GENPOLY[0])]); + } else { + array_push($parity, 0); + } + } + } + } + + //########################################################################## + + class QRrs { + + public static $items = array(); + + //---------------------------------------------------------------------- + public static function init_rs($symsize, $gfpoly, $fcr, $prim, $nroots, $pad) + { + foreach(self::$items as $rs) { + if($rs->pad != $pad) continue; + if($rs->nroots != $nroots) continue; + if($rs->mm != $symsize) continue; + if($rs->gfpoly != $gfpoly) continue; + if($rs->fcr != $fcr) continue; + if($rs->prim != $prim) continue; + + return $rs; + } + + $rs = QRrsItem::init_rs_char($symsize, $gfpoly, $fcr, $prim, $nroots, $pad); + array_unshift(self::$items, $rs); + + return $rs; + } + } + + + +//---- qrmask.php ----------------------------- + + + + +/* + * PHP QR Code encoder + * + * Masking + * + * Based on libqrencode C library distributed under LGPL 2.1 + * Copyright (C) 2006, 2007, 2008, 2009 Kentaro Fukuchi + * + * PHP QR Code is distributed under LGPL 3 + * Copyright (C) 2010 Dominik Dzienia + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ + + define('N1', 3); + define('N2', 3); + define('N3', 40); + define('N4', 10); + + class QRmask { + + public $runLength = array(); + + //---------------------------------------------------------------------- + public function __construct() + { + $this->runLength = array_fill(0, QRSPEC_WIDTH_MAX + 1, 0); + } + + //---------------------------------------------------------------------- + public function writeFormatInformation($width, &$frame, $mask, $level) + { + $blacks = 0; + $format = QRspec::getFormatInfo($mask, $level); + + for($i=0; $i<8; $i++) { + if($format & 1) { + $blacks += 2; + $v = 0x85; + } else { + $v = 0x84; + } + + $frame[8][$width - 1 - $i] = chr($v); + if($i < 6) { + $frame[$i][8] = chr($v); + } else { + $frame[$i + 1][8] = chr($v); + } + $format = $format >> 1; + } + + for($i=0; $i<7; $i++) { + if($format & 1) { + $blacks += 2; + $v = 0x85; + } else { + $v = 0x84; + } + + $frame[$width - 7 + $i][8] = chr($v); + if($i == 0) { + $frame[8][7] = chr($v); + } else { + $frame[8][6 - $i] = chr($v); + } + + $format = $format >> 1; + } + + return $blacks; + } + + //---------------------------------------------------------------------- + public function mask0($x, $y) { return ($x+$y)&1; } + public function mask1($x, $y) { return ($y&1); } + public function mask2($x, $y) { return ($x%3); } + public function mask3($x, $y) { return ($x+$y)%3; } + public function mask4($x, $y) { return (((int)($y/2))+((int)($x/3)))&1; } + public function mask5($x, $y) { return (($x*$y)&1)+($x*$y)%3; } + public function mask6($x, $y) { return ((($x*$y)&1)+($x*$y)%3)&1; } + public function mask7($x, $y) { return ((($x*$y)%3)+(($x+$y)&1))&1; } + + //---------------------------------------------------------------------- + private function generateMaskNo($maskNo, $width, $frame) + { + $bitMask = array_fill(0, $width, array_fill(0, $width, 0)); + + for($y=0; $y<$width; $y++) { + for($x=0; $x<$width; $x++) { + if(ord($frame[$y][$x]) & 0x80) { + $bitMask[$y][$x] = 0; + } else { + $maskFunc = call_user_func(array($this, 'mask'.$maskNo), $x, $y); + $bitMask[$y][$x] = ($maskFunc == 0)?1:0; + } + + } + } + + return $bitMask; + } + + //---------------------------------------------------------------------- + public static function serial($bitFrame) + { + $codeArr = array(); + + foreach ($bitFrame as $line) + $codeArr[] = join('', $line); + + return gzcompress(join("\n", $codeArr), 9); + } + + //---------------------------------------------------------------------- + public static function unserial($code) + { + $codeArr = array(); + + $codeLines = explode("\n", gzuncompress($code)); + foreach ($codeLines as $line) + $codeArr[] = str_split($line); + + return $codeArr; + } + + //---------------------------------------------------------------------- + public function makeMaskNo($maskNo, $width, $s, &$d, $maskGenOnly = false) + { + $b = 0; + $bitMask = array(); + + $fileName = QR_CACHE_DIR.'mask_'.$maskNo.DIRECTORY_SEPARATOR.'mask_'.$width.'_'.$maskNo.'.dat'; + + if (QR_CACHEABLE) { + if (file_exists($fileName)) { + $bitMask = self::unserial(file_get_contents($fileName)); + } else { + $bitMask = $this->generateMaskNo($maskNo, $width, $s, $d); + if (!file_exists(QR_CACHE_DIR.'mask_'.$maskNo)) + mkdir(QR_CACHE_DIR.'mask_'.$maskNo); + file_put_contents($fileName, self::serial($bitMask)); + } + } else { + $bitMask = $this->generateMaskNo($maskNo, $width, $s, $d); + } + + if ($maskGenOnly) + return; + + $d = $s; + + for($y=0; $y<$width; $y++) { + for($x=0; $x<$width; $x++) { + if($bitMask[$y][$x] == 1) { + $d[$y][$x] = chr(ord($s[$y][$x]) ^ (int)$bitMask[$y][$x]); + } + $b += (int)(ord($d[$y][$x]) & 1); + } + } + + return $b; + } + + //---------------------------------------------------------------------- + public function makeMask($width, $frame, $maskNo, $level) + { + $masked = array_fill(0, $width, str_repeat("\0", $width)); + $this->makeMaskNo($maskNo, $width, $frame, $masked); + $this->writeFormatInformation($width, $masked, $maskNo, $level); + + return $masked; + } + + //---------------------------------------------------------------------- + public function calcN1N3($length) + { + $demerit = 0; + + for($i=0; $i<$length; $i++) { + + if($this->runLength[$i] >= 5) { + $demerit += (N1 + ($this->runLength[$i] - 5)); + } + if($i & 1) { + if(($i >= 3) && ($i < ($length-2)) && ($this->runLength[$i] % 3 == 0)) { + $fact = (int)($this->runLength[$i] / 3); + if(($this->runLength[$i-2] == $fact) && + ($this->runLength[$i-1] == $fact) && + ($this->runLength[$i+1] == $fact) && + ($this->runLength[$i+2] == $fact)) { + if(($this->runLength[$i-3] < 0) || ($this->runLength[$i-3] >= (4 * $fact))) { + $demerit += N3; + } else if((($i+3) >= $length) || ($this->runLength[$i+3] >= (4 * $fact))) { + $demerit += N3; + } + } + } + } + } + return $demerit; + } + + //---------------------------------------------------------------------- + public function evaluateSymbol($width, $frame) + { + $head = 0; + $demerit = 0; + + for($y=0; $y<$width; $y++) { + $head = 0; + $this->runLength[0] = 1; + + $frameY = $frame[$y]; + + if ($y>0) + $frameYM = $frame[$y-1]; + + for($x=0; $x<$width; $x++) { + if(($x > 0) && ($y > 0)) { + $b22 = ord($frameY[$x]) & ord($frameY[$x-1]) & ord($frameYM[$x]) & ord($frameYM[$x-1]); + $w22 = ord($frameY[$x]) | ord($frameY[$x-1]) | ord($frameYM[$x]) | ord($frameYM[$x-1]); + + if(($b22 | ($w22 ^ 1))&1) { + $demerit += N2; + } + } + if(($x == 0) && (ord($frameY[$x]) & 1)) { + $this->runLength[0] = -1; + $head = 1; + $this->runLength[$head] = 1; + } else if($x > 0) { + if((ord($frameY[$x]) ^ ord($frameY[$x-1])) & 1) { + $head++; + $this->runLength[$head] = 1; + } else { + $this->runLength[$head]++; + } + } + } + + $demerit += $this->calcN1N3($head+1); + } + + for($x=0; $x<$width; $x++) { + $head = 0; + $this->runLength[0] = 1; + + for($y=0; $y<$width; $y++) { + if($y == 0 && (ord($frame[$y][$x]) & 1)) { + $this->runLength[0] = -1; + $head = 1; + $this->runLength[$head] = 1; + } else if($y > 0) { + if((ord($frame[$y][$x]) ^ ord($frame[$y-1][$x])) & 1) { + $head++; + $this->runLength[$head] = 1; + } else { + $this->runLength[$head]++; + } + } + } + + $demerit += $this->calcN1N3($head+1); + } + + return $demerit; + } + + + //---------------------------------------------------------------------- + public function mask($width, $frame, $level) + { + $minDemerit = PHP_INT_MAX; + $bestMaskNum = 0; + $bestMask = array(); + + $checked_masks = array(0,1,2,3,4,5,6,7); + + if (QR_FIND_FROM_RANDOM !== false) { + + $howManuOut = 8-(QR_FIND_FROM_RANDOM % 9); + for ($i = 0; $i < $howManuOut; $i++) { + $remPos = rand (0, count($checked_masks)-1); + unset($checked_masks[$remPos]); + $checked_masks = array_values($checked_masks); + } + + } + + $bestMask = $frame; + + foreach($checked_masks as $i) { + $mask = array_fill(0, $width, str_repeat("\0", $width)); + + $demerit = 0; + $blacks = 0; + $blacks = $this->makeMaskNo($i, $width, $frame, $mask); + $blacks += $this->writeFormatInformation($width, $mask, $i, $level); + $blacks = (int)(100 * $blacks / ($width * $width)); + $demerit = (int)((int)(abs($blacks - 50) / 5) * N4); + $demerit += $this->evaluateSymbol($width, $mask); + + if($demerit < $minDemerit) { + $minDemerit = $demerit; + $bestMask = $mask; + $bestMaskNum = $i; + } + } + + return $bestMask; + } + + //---------------------------------------------------------------------- + } + + + + +//---- qrencode.php ----------------------------- + + + + +/* + * PHP QR Code encoder + * + * Main encoder classes. + * + * Based on libqrencode C library distributed under LGPL 2.1 + * Copyright (C) 2006, 2007, 2008, 2009 Kentaro Fukuchi + * + * PHP QR Code is distributed under LGPL 3 + * Copyright (C) 2010 Dominik Dzienia + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ + + class QRrsblock { + public $dataLength; + public $data = array(); + public $eccLength; + public $ecc = array(); + + public function __construct($dl, $data, $el, &$ecc, QRrsItem $rs) + { + $rs->encode_rs_char($data, $ecc); + + $this->dataLength = $dl; + $this->data = $data; + $this->eccLength = $el; + $this->ecc = $ecc; + } + }; + + //########################################################################## + + class QRrawcode { + public $version; + public $datacode = array(); + public $ecccode = array(); + public $blocks; + public $rsblocks = array(); //of RSblock + public $count; + public $dataLength; + public $eccLength; + public $b1; + + //---------------------------------------------------------------------- + public function __construct(QRinput $input) + { + $spec = array(0,0,0,0,0); + + $this->datacode = $input->getByteStream(); + if(is_null($this->datacode)) { + throw new Exception('null imput string'); + } + + QRspec::getEccSpec($input->getVersion(), $input->getErrorCorrectionLevel(), $spec); + + $this->version = $input->getVersion(); + $this->b1 = QRspec::rsBlockNum1($spec); + $this->dataLength = QRspec::rsDataLength($spec); + $this->eccLength = QRspec::rsEccLength($spec); + $this->ecccode = array_fill(0, $this->eccLength, 0); + $this->blocks = QRspec::rsBlockNum($spec); + + $ret = $this->init($spec); + if($ret < 0) { + throw new Exception('block alloc error'); + return null; + } + + $this->count = 0; + } + + //---------------------------------------------------------------------- + public function init(array $spec) + { + $dl = QRspec::rsDataCodes1($spec); + $el = QRspec::rsEccCodes1($spec); + $rs = QRrs::init_rs(8, 0x11d, 0, 1, $el, 255 - $dl - $el); + + + $blockNo = 0; + $dataPos = 0; + $eccPos = 0; + for($i=0; $iecccode,$eccPos); + $this->rsblocks[$blockNo] = new QRrsblock($dl, array_slice($this->datacode, $dataPos), $el, $ecc, $rs); + $this->ecccode = array_merge(array_slice($this->ecccode,0, $eccPos), $ecc); + + $dataPos += $dl; + $eccPos += $el; + $blockNo++; + } + + if(QRspec::rsBlockNum2($spec) == 0) + return 0; + + $dl = QRspec::rsDataCodes2($spec); + $el = QRspec::rsEccCodes2($spec); + $rs = QRrs::init_rs(8, 0x11d, 0, 1, $el, 255 - $dl - $el); + + if($rs == NULL) return -1; + + for($i=0; $iecccode,$eccPos); + $this->rsblocks[$blockNo] = new QRrsblock($dl, array_slice($this->datacode, $dataPos), $el, $ecc, $rs); + $this->ecccode = array_merge(array_slice($this->ecccode,0, $eccPos), $ecc); + + $dataPos += $dl; + $eccPos += $el; + $blockNo++; + } + + return 0; + } + + //---------------------------------------------------------------------- + public function getCode() + { + $ret; + + if($this->count < $this->dataLength) { + $row = $this->count % $this->blocks; + $col = $this->count / $this->blocks; + if($col >= $this->rsblocks[0]->dataLength) { + $row += $this->b1; + } + $ret = $this->rsblocks[$row]->data[$col]; + } else if($this->count < $this->dataLength + $this->eccLength) { + $row = ($this->count - $this->dataLength) % $this->blocks; + $col = ($this->count - $this->dataLength) / $this->blocks; + $ret = $this->rsblocks[$row]->ecc[$col]; + } else { + return 0; + } + $this->count++; + + return $ret; + } + } + + //########################################################################## + + class QRcode { + + public $version; + public $width; + public $data; + + //---------------------------------------------------------------------- + public function encodeMask(QRinput $input, $mask) + { + if($input->getVersion() < 0 || $input->getVersion() > QRSPEC_VERSION_MAX) { + throw new Exception('wrong version'); + } + if($input->getErrorCorrectionLevel() > QR_ECLEVEL_H) { + throw new Exception('wrong level'); + } + + $raw = new QRrawcode($input); + + QRtools::markTime('after_raw'); + + $version = $raw->version; + $width = QRspec::getWidth($version); + $frame = QRspec::newFrame($version); + + $filler = new FrameFiller($width, $frame); + if(is_null($filler)) { + return NULL; + } + + // inteleaved data and ecc codes + for($i=0; $i<$raw->dataLength + $raw->eccLength; $i++) { + $code = $raw->getCode(); + $bit = 0x80; + for($j=0; $j<8; $j++) { + $addr = $filler->next(); + $filler->setFrameAt($addr, 0x02 | (($bit & $code) != 0)); + $bit = $bit >> 1; + } + } + + QRtools::markTime('after_filler'); + + unset($raw); + + // remainder bits + $j = QRspec::getRemainder($version); + for($i=0; $i<$j; $i++) { + $addr = $filler->next(); + $filler->setFrameAt($addr, 0x02); + } + + $frame = $filler->frame; + unset($filler); + + + // masking + $maskObj = new QRmask(); + if($mask < 0) { + + if (QR_FIND_BEST_MASK) { + $masked = $maskObj->mask($width, $frame, $input->getErrorCorrectionLevel()); + } else { + $masked = $maskObj->makeMask($width, $frame, (intval(QR_DEFAULT_MASK) % 8), $input->getErrorCorrectionLevel()); + } + } else { + $masked = $maskObj->makeMask($width, $frame, $mask, $input->getErrorCorrectionLevel()); + } + + if($masked == NULL) { + return NULL; + } + + QRtools::markTime('after_mask'); + + $this->version = $version; + $this->width = $width; + $this->data = $masked; + + return $this; + } + + //---------------------------------------------------------------------- + public function encodeInput(QRinput $input) + { + return $this->encodeMask($input, -1); + } + + //---------------------------------------------------------------------- + public function encodeString8bit($string, $version, $level) + { + if(string == NULL) { + throw new Exception('empty string!'); + return NULL; + } + + $input = new QRinput($version, $level); + if($input == NULL) return NULL; + + $ret = $input->append($input, QR_MODE_8, strlen($string), str_split($string)); + if($ret < 0) { + unset($input); + return NULL; + } + return $this->encodeInput($input); + } + + //---------------------------------------------------------------------- + public function encodeString($string, $version, $level, $hint, $casesensitive) + { + + if($hint != QR_MODE_8 && $hint != QR_MODE_KANJI) { + throw new Exception('bad hint'); + return NULL; + } + + $input = new QRinput($version, $level); + if($input == NULL) return NULL; + + $ret = QRsplit::splitStringToQRinput($string, $input, $hint, $casesensitive); + if($ret < 0) { + return NULL; + } + + return $this->encodeInput($input); + } + + //---------------------------------------------------------------------- + public static function png($text, $outfile = false, $level = QR_ECLEVEL_L, $size = 3, $margin = 4, $saveandprint=false) + { + $enc = QRencode::factory($level, $size, $margin); + return $enc->encodePNG($text, $outfile, $saveandprint=false); + } + + //---------------------------------------------------------------------- + public static function text($text, $outfile = false, $level = QR_ECLEVEL_L, $size = 3, $margin = 4) + { + $enc = QRencode::factory($level, $size, $margin); + return $enc->encode($text, $outfile); + } + + //---------------------------------------------------------------------- + public static function raw($text, $outfile = false, $level = QR_ECLEVEL_L, $size = 3, $margin = 4) + { + $enc = QRencode::factory($level, $size, $margin); + return $enc->encodeRAW($text, $outfile); + } + } + + //########################################################################## + + class FrameFiller { + + public $width; + public $frame; + public $x; + public $y; + public $dir; + public $bit; + + //---------------------------------------------------------------------- + public function __construct($width, &$frame) + { + $this->width = $width; + $this->frame = $frame; + $this->x = $width - 1; + $this->y = $width - 1; + $this->dir = -1; + $this->bit = -1; + } + + //---------------------------------------------------------------------- + public function setFrameAt($at, $val) + { + $this->frame[$at['y']][$at['x']] = chr($val); + } + + //---------------------------------------------------------------------- + public function getFrameAt($at) + { + return ord($this->frame[$at['y']][$at['x']]); + } + + //---------------------------------------------------------------------- + public function next() + { + do { + + if($this->bit == -1) { + $this->bit = 0; + return array('x'=>$this->x, 'y'=>$this->y); + } + + $x = $this->x; + $y = $this->y; + $w = $this->width; + + if($this->bit == 0) { + $x--; + $this->bit++; + } else { + $x++; + $y += $this->dir; + $this->bit--; + } + + if($this->dir < 0) { + if($y < 0) { + $y = 0; + $x -= 2; + $this->dir = 1; + if($x == 6) { + $x--; + $y = 9; + } + } + } else { + if($y == $w) { + $y = $w - 1; + $x -= 2; + $this->dir = -1; + if($x == 6) { + $x--; + $y -= 8; + } + } + } + if($x < 0 || $y < 0) return null; + + $this->x = $x; + $this->y = $y; + + } while(ord($this->frame[$y][$x]) & 0x80); + + return array('x'=>$x, 'y'=>$y); + } + + } ; + + //########################################################################## + + class QRencode { + + public $casesensitive = true; + public $eightbit = false; + + public $version = 0; + public $size = 3; + public $margin = 4; + + public $structured = 0; // not supported yet + + public $level = QR_ECLEVEL_L; + public $hint = QR_MODE_8; + + //---------------------------------------------------------------------- + public static function factory($level = QR_ECLEVEL_L, $size = 3, $margin = 4) + { + $enc = new QRencode(); + $enc->size = $size; + $enc->margin = $margin; + + switch ($level.'') { + case '0': + case '1': + case '2': + case '3': + $enc->level = $level; + break; + case 'l': + case 'L': + $enc->level = QR_ECLEVEL_L; + break; + case 'm': + case 'M': + $enc->level = QR_ECLEVEL_M; + break; + case 'q': + case 'Q': + $enc->level = QR_ECLEVEL_Q; + break; + case 'h': + case 'H': + $enc->level = QR_ECLEVEL_H; + break; + } + + return $enc; + } + + //---------------------------------------------------------------------- + public function encodeRAW($intext, $outfile = false) + { + $code = new QRcode(); + + if($this->eightbit) { + $code->encodeString8bit($intext, $this->version, $this->level); + } else { + $code->encodeString($intext, $this->version, $this->level, $this->hint, $this->casesensitive); + } + + return $code->data; + } + + //---------------------------------------------------------------------- + public function encode($intext, $outfile = false) + { + $code = new QRcode(); + + if($this->eightbit) { + $code->encodeString8bit($intext, $this->version, $this->level); + } else { + $code->encodeString($intext, $this->version, $this->level, $this->hint, $this->casesensitive); + } + + QRtools::markTime('after_encode'); + + if ($outfile!== false) { + file_put_contents($outfile, join("\n", QRtools::binarize($code->data))); + } else { + return QRtools::binarize($code->data); + } + } + + //---------------------------------------------------------------------- + public function encodePNG($intext, $outfile = false,$saveandprint=false) + { + try { + + ob_start(); + $tab = $this->encode($intext); + $err = ob_get_contents(); + ob_end_clean(); + + if ($err != '') + QRtools::log($outfile, $err); + + $maxSize = (int)(QR_PNG_MAXIMUM_SIZE / (count($tab)+2*$this->margin)); + + QRimage::png($tab, $outfile, min(max(1, $this->size), $maxSize), $this->margin,$saveandprint); + + } catch (Exception $e) { + + QRtools::log($outfile, $e->getMessage()); + + } + } + } + + diff --git a/application/libraries/qrcode/qrbitstream.php b/application/libraries/qrcode/qrbitstream.php new file mode 100644 index 00000000..c8d11661 --- /dev/null +++ b/application/libraries/qrcode/qrbitstream.php @@ -0,0 +1,180 @@ + + * + * PHP QR Code is distributed under LGPL 3 + * Copyright (C) 2010 Dominik Dzienia + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ + + class QRbitstream { + + public $data = array(); + + //---------------------------------------------------------------------- + public function size() + { + return count($this->data); + } + + //---------------------------------------------------------------------- + public function allocate($setLength) + { + $this->data = array_fill(0, $setLength, 0); + return 0; + } + + //---------------------------------------------------------------------- + public static function newFromNum($bits, $num) + { + $bstream = new QRbitstream(); + $bstream->allocate($bits); + + $mask = 1 << ($bits - 1); + for($i=0; $i<$bits; $i++) { + if($num & $mask) { + $bstream->data[$i] = 1; + } else { + $bstream->data[$i] = 0; + } + $mask = $mask >> 1; + } + + return $bstream; + } + + //---------------------------------------------------------------------- + public static function newFromBytes($size, $data) + { + $bstream = new QRbitstream(); + $bstream->allocate($size * 8); + $p=0; + + for($i=0; $i<$size; $i++) { + $mask = 0x80; + for($j=0; $j<8; $j++) { + if($data[$i] & $mask) { + $bstream->data[$p] = 1; + } else { + $bstream->data[$p] = 0; + } + $p++; + $mask = $mask >> 1; + } + } + + return $bstream; + } + + //---------------------------------------------------------------------- + public function append(QRbitstream $arg) + { + if (is_null($arg)) { + return -1; + } + + if($arg->size() == 0) { + return 0; + } + + if($this->size() == 0) { + $this->data = $arg->data; + return 0; + } + + $this->data = array_values(array_merge($this->data, $arg->data)); + + return 0; + } + + //---------------------------------------------------------------------- + public function appendNum($bits, $num) + { + if ($bits == 0) + return 0; + + $b = QRbitstream::newFromNum($bits, $num); + + if(is_null($b)) + return -1; + + $ret = $this->append($b); + unset($b); + + return $ret; + } + + //---------------------------------------------------------------------- + public function appendBytes($size, $data) + { + if ($size == 0) + return 0; + + $b = QRbitstream::newFromBytes($size, $data); + + if(is_null($b)) + return -1; + + $ret = $this->append($b); + unset($b); + + return $ret; + } + + //---------------------------------------------------------------------- + public function toByte() + { + + $size = $this->size(); + + if($size == 0) { + return array(); + } + + $data = array_fill(0, (int)(($size + 7) / 8), 0); + $bytes = (int)($size / 8); + + $p = 0; + + for($i=0; $i<$bytes; $i++) { + $v = 0; + for($j=0; $j<8; $j++) { + $v = $v << 1; + $v |= $this->data[$p]; + $p++; + } + $data[$i] = $v; + } + + if($size & 7) { + $v = 0; + for($j=0; $j<($size & 7); $j++) { + $v = $v << 1; + $v |= $this->data[$p]; + $p++; + } + $data[$bytes] = $v; + } + + return $data; + } + + } diff --git a/application/libraries/qrcode/qrconfig.php b/application/libraries/qrcode/qrconfig.php new file mode 100644 index 00000000..62e7f974 --- /dev/null +++ b/application/libraries/qrcode/qrconfig.php @@ -0,0 +1,17 @@ + + * + * PHP QR Code is distributed under LGPL 3 + * Copyright (C) 2010 Dominik Dzienia + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ + + // Encoding modes + + define('QR_MODE_NUL', -1); + define('QR_MODE_NUM', 0); + define('QR_MODE_AN', 1); + define('QR_MODE_8', 2); + define('QR_MODE_KANJI', 3); + define('QR_MODE_STRUCTURE', 4); + + // Levels of error correction. + + define('QR_ECLEVEL_L', 0); + define('QR_ECLEVEL_M', 1); + define('QR_ECLEVEL_Q', 2); + define('QR_ECLEVEL_H', 3); + + // Supported output formats + + define('QR_FORMAT_TEXT', 0); + define('QR_FORMAT_PNG', 1); + + class qrstr { + public static function set(&$srctab, $x, $y, $repl, $replLen = false) { + $srctab[$y] = substr_replace($srctab[$y], ($replLen !== false)?substr($repl,0,$replLen):$repl, $x, ($replLen !== false)?$replLen:strlen($repl)); + } + } \ No newline at end of file diff --git a/application/libraries/qrcode/qrencode.php b/application/libraries/qrcode/qrencode.php new file mode 100644 index 00000000..fc909fa7 --- /dev/null +++ b/application/libraries/qrcode/qrencode.php @@ -0,0 +1,502 @@ + + * + * PHP QR Code is distributed under LGPL 3 + * Copyright (C) 2010 Dominik Dzienia + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ + + class QRrsblock { + public $dataLength; + public $data = array(); + public $eccLength; + public $ecc = array(); + + public function __construct($dl, $data, $el, &$ecc, QRrsItem $rs) + { + $rs->encode_rs_char($data, $ecc); + + $this->dataLength = $dl; + $this->data = $data; + $this->eccLength = $el; + $this->ecc = $ecc; + } + }; + + //########################################################################## + + class QRrawcode { + public $version; + public $datacode = array(); + public $ecccode = array(); + public $blocks; + public $rsblocks = array(); //of RSblock + public $count; + public $dataLength; + public $eccLength; + public $b1; + + //---------------------------------------------------------------------- + public function __construct(QRinput $input) + { + $spec = array(0,0,0,0,0); + + $this->datacode = $input->getByteStream(); + if(is_null($this->datacode)) { + throw new Exception('null imput string'); + } + + QRspec::getEccSpec($input->getVersion(), $input->getErrorCorrectionLevel(), $spec); + + $this->version = $input->getVersion(); + $this->b1 = QRspec::rsBlockNum1($spec); + $this->dataLength = QRspec::rsDataLength($spec); + $this->eccLength = QRspec::rsEccLength($spec); + $this->ecccode = array_fill(0, $this->eccLength, 0); + $this->blocks = QRspec::rsBlockNum($spec); + + $ret = $this->init($spec); + if($ret < 0) { + throw new Exception('block alloc error'); + return null; + } + + $this->count = 0; + } + + //---------------------------------------------------------------------- + public function init(array $spec) + { + $dl = QRspec::rsDataCodes1($spec); + $el = QRspec::rsEccCodes1($spec); + $rs = QRrs::init_rs(8, 0x11d, 0, 1, $el, 255 - $dl - $el); + + + $blockNo = 0; + $dataPos = 0; + $eccPos = 0; + for($i=0; $iecccode,$eccPos); + $this->rsblocks[$blockNo] = new QRrsblock($dl, array_slice($this->datacode, $dataPos), $el, $ecc, $rs); + $this->ecccode = array_merge(array_slice($this->ecccode,0, $eccPos), $ecc); + + $dataPos += $dl; + $eccPos += $el; + $blockNo++; + } + + if(QRspec::rsBlockNum2($spec) == 0) + return 0; + + $dl = QRspec::rsDataCodes2($spec); + $el = QRspec::rsEccCodes2($spec); + $rs = QRrs::init_rs(8, 0x11d, 0, 1, $el, 255 - $dl - $el); + + if($rs == NULL) return -1; + + for($i=0; $iecccode,$eccPos); + $this->rsblocks[$blockNo] = new QRrsblock($dl, array_slice($this->datacode, $dataPos), $el, $ecc, $rs); + $this->ecccode = array_merge(array_slice($this->ecccode,0, $eccPos), $ecc); + + $dataPos += $dl; + $eccPos += $el; + $blockNo++; + } + + return 0; + } + + //---------------------------------------------------------------------- + public function getCode() + { + $ret; + + if($this->count < $this->dataLength) { + $row = $this->count % $this->blocks; + $col = $this->count / $this->blocks; + if($col >= $this->rsblocks[0]->dataLength) { + $row += $this->b1; + } + $ret = $this->rsblocks[$row]->data[$col]; + } else if($this->count < $this->dataLength + $this->eccLength) { + $row = ($this->count - $this->dataLength) % $this->blocks; + $col = ($this->count - $this->dataLength) / $this->blocks; + $ret = $this->rsblocks[$row]->ecc[$col]; + } else { + return 0; + } + $this->count++; + + return $ret; + } + } + + //########################################################################## + + class QRcode { + + public $version; + public $width; + public $data; + + //---------------------------------------------------------------------- + public function encodeMask(QRinput $input, $mask) + { + if($input->getVersion() < 0 || $input->getVersion() > QRSPEC_VERSION_MAX) { + throw new Exception('wrong version'); + } + if($input->getErrorCorrectionLevel() > QR_ECLEVEL_H) { + throw new Exception('wrong level'); + } + + $raw = new QRrawcode($input); + + QRtools::markTime('after_raw'); + + $version = $raw->version; + $width = QRspec::getWidth($version); + $frame = QRspec::newFrame($version); + + $filler = new FrameFiller($width, $frame); + if(is_null($filler)) { + return NULL; + } + + // inteleaved data and ecc codes + for($i=0; $i<$raw->dataLength + $raw->eccLength; $i++) { + $code = $raw->getCode(); + $bit = 0x80; + for($j=0; $j<8; $j++) { + $addr = $filler->next(); + $filler->setFrameAt($addr, 0x02 | (($bit & $code) != 0)); + $bit = $bit >> 1; + } + } + + QRtools::markTime('after_filler'); + + unset($raw); + + // remainder bits + $j = QRspec::getRemainder($version); + for($i=0; $i<$j; $i++) { + $addr = $filler->next(); + $filler->setFrameAt($addr, 0x02); + } + + $frame = $filler->frame; + unset($filler); + + + // masking + $maskObj = new QRmask(); + if($mask < 0) { + + if (QR_FIND_BEST_MASK) { + $masked = $maskObj->mask($width, $frame, $input->getErrorCorrectionLevel()); + } else { + $masked = $maskObj->makeMask($width, $frame, (intval(QR_DEFAULT_MASK) % 8), $input->getErrorCorrectionLevel()); + } + } else { + $masked = $maskObj->makeMask($width, $frame, $mask, $input->getErrorCorrectionLevel()); + } + + if($masked == NULL) { + return NULL; + } + + QRtools::markTime('after_mask'); + + $this->version = $version; + $this->width = $width; + $this->data = $masked; + + return $this; + } + + //---------------------------------------------------------------------- + public function encodeInput(QRinput $input) + { + return $this->encodeMask($input, -1); + } + + //---------------------------------------------------------------------- + public function encodeString8bit($string, $version, $level) + { + if(string == NULL) { + throw new Exception('empty string!'); + return NULL; + } + + $input = new QRinput($version, $level); + if($input == NULL) return NULL; + + $ret = $input->append($input, QR_MODE_8, strlen($string), str_split($string)); + if($ret < 0) { + unset($input); + return NULL; + } + return $this->encodeInput($input); + } + + //---------------------------------------------------------------------- + public function encodeString($string, $version, $level, $hint, $casesensitive) + { + + if($hint != QR_MODE_8 && $hint != QR_MODE_KANJI) { + throw new Exception('bad hint'); + return NULL; + } + + $input = new QRinput($version, $level); + if($input == NULL) return NULL; + + $ret = QRsplit::splitStringToQRinput($string, $input, $hint, $casesensitive); + if($ret < 0) { + return NULL; + } + + return $this->encodeInput($input); + } + + //---------------------------------------------------------------------- + public static function png($text, $outfile = false, $level = QR_ECLEVEL_L, $size = 3, $margin = 4, $saveandprint=false) + { + $enc = QRencode::factory($level, $size, $margin); + return $enc->encodePNG($text, $outfile, $saveandprint=false); + } + + //---------------------------------------------------------------------- + public static function text($text, $outfile = false, $level = QR_ECLEVEL_L, $size = 3, $margin = 4) + { + $enc = QRencode::factory($level, $size, $margin); + return $enc->encode($text, $outfile); + } + + //---------------------------------------------------------------------- + public static function raw($text, $outfile = false, $level = QR_ECLEVEL_L, $size = 3, $margin = 4) + { + $enc = QRencode::factory($level, $size, $margin); + return $enc->encodeRAW($text, $outfile); + } + } + + //########################################################################## + + class FrameFiller { + + public $width; + public $frame; + public $x; + public $y; + public $dir; + public $bit; + + //---------------------------------------------------------------------- + public function __construct($width, &$frame) + { + $this->width = $width; + $this->frame = $frame; + $this->x = $width - 1; + $this->y = $width - 1; + $this->dir = -1; + $this->bit = -1; + } + + //---------------------------------------------------------------------- + public function setFrameAt($at, $val) + { + $this->frame[$at['y']][$at['x']] = chr($val); + } + + //---------------------------------------------------------------------- + public function getFrameAt($at) + { + return ord($this->frame[$at['y']][$at['x']]); + } + + //---------------------------------------------------------------------- + public function next() + { + do { + + if($this->bit == -1) { + $this->bit = 0; + return array('x'=>$this->x, 'y'=>$this->y); + } + + $x = $this->x; + $y = $this->y; + $w = $this->width; + + if($this->bit == 0) { + $x--; + $this->bit++; + } else { + $x++; + $y += $this->dir; + $this->bit--; + } + + if($this->dir < 0) { + if($y < 0) { + $y = 0; + $x -= 2; + $this->dir = 1; + if($x == 6) { + $x--; + $y = 9; + } + } + } else { + if($y == $w) { + $y = $w - 1; + $x -= 2; + $this->dir = -1; + if($x == 6) { + $x--; + $y -= 8; + } + } + } + if($x < 0 || $y < 0) return null; + + $this->x = $x; + $this->y = $y; + + } while(ord($this->frame[$y][$x]) & 0x80); + + return array('x'=>$x, 'y'=>$y); + } + + } ; + + //########################################################################## + + class QRencode { + + public $casesensitive = true; + public $eightbit = false; + + public $version = 0; + public $size = 3; + public $margin = 4; + + public $structured = 0; // not supported yet + + public $level = QR_ECLEVEL_L; + public $hint = QR_MODE_8; + + //---------------------------------------------------------------------- + public static function factory($level = QR_ECLEVEL_L, $size = 3, $margin = 4) + { + $enc = new QRencode(); + $enc->size = $size; + $enc->margin = $margin; + + switch ($level.'') { + case '0': + case '1': + case '2': + case '3': + $enc->level = $level; + break; + case 'l': + case 'L': + $enc->level = QR_ECLEVEL_L; + break; + case 'm': + case 'M': + $enc->level = QR_ECLEVEL_M; + break; + case 'q': + case 'Q': + $enc->level = QR_ECLEVEL_Q; + break; + case 'h': + case 'H': + $enc->level = QR_ECLEVEL_H; + break; + } + + return $enc; + } + + //---------------------------------------------------------------------- + public function encodeRAW($intext, $outfile = false) + { + $code = new QRcode(); + + if($this->eightbit) { + $code->encodeString8bit($intext, $this->version, $this->level); + } else { + $code->encodeString($intext, $this->version, $this->level, $this->hint, $this->casesensitive); + } + + return $code->data; + } + + //---------------------------------------------------------------------- + public function encode($intext, $outfile = false) + { + $code = new QRcode(); + + if($this->eightbit) { + $code->encodeString8bit($intext, $this->version, $this->level); + } else { + $code->encodeString($intext, $this->version, $this->level, $this->hint, $this->casesensitive); + } + + QRtools::markTime('after_encode'); + + if ($outfile!== false) { + file_put_contents($outfile, join("\n", QRtools::binarize($code->data))); + } else { + return QRtools::binarize($code->data); + } + } + + //---------------------------------------------------------------------- + public function encodePNG($intext, $outfile = false,$saveandprint=false) + { + try { + + ob_start(); + $tab = $this->encode($intext); + $err = ob_get_contents(); + ob_end_clean(); + + if ($err != '') + QRtools::log($outfile, $err); + + $maxSize = (int)(QR_PNG_MAXIMUM_SIZE / (count($tab)+2*$this->margin)); + + QRimage::png($tab, $outfile, min(max(1, $this->size), $maxSize), $this->margin,$saveandprint); + + } catch (Exception $e) { + + QRtools::log($outfile, $e->getMessage()); + + } + } + } diff --git a/application/libraries/qrcode/qrimage.php b/application/libraries/qrcode/qrimage.php new file mode 100644 index 00000000..46586375 --- /dev/null +++ b/application/libraries/qrcode/qrimage.php @@ -0,0 +1,98 @@ + + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ + + define('QR_IMAGE', true); + + class QRimage { + + public static $black = array(255,255,255); + public static $white = array(0,0,0); + + //---------------------------------------------------------------------- + public static function png($frame, $filename = false, $pixelPerPoint = 4, $outerFrame = 4,$saveandprint=FALSE) + { + $image = self::image($frame, $pixelPerPoint, $outerFrame); + + if ($filename === false) { + Header("Content-type: image/png"); + ImagePng($image); + } else { + if($saveandprint===TRUE){ + ImagePng($image, $filename); + header("Content-type: image/png"); + ImagePng($image); + }else{ + ImagePng($image, $filename); + } + } + + ImageDestroy($image); + } + + //---------------------------------------------------------------------- + public static function jpg($frame, $filename = false, $pixelPerPoint = 8, $outerFrame = 4, $q = 85) + { + $image = self::image($frame, $pixelPerPoint, $outerFrame); + + if ($filename === false) { + Header("Content-type: image/jpeg"); + ImageJpeg($image, null, $q); + } else { + ImageJpeg($image, $filename, $q); + } + + ImageDestroy($image); + } + + //---------------------------------------------------------------------- + private static function image($frame, $pixelPerPoint = 4, $outerFrame = 4) + { + $h = count($frame); + $w = strlen($frame[0]); + + $imgW = $w + 2*$outerFrame; + $imgH = $h + 2*$outerFrame; + + $base_image =ImageCreate($imgW, $imgH); + + $col[0] = ImageColorAllocate($base_image,QRImage::$black[0],QRImage::$black[1],QRImage::$black[2]); + $col[1] = ImageColorAllocate($base_image,QRImage::$white[0],QRImage::$white[1],QRImage::$white[2]); + + imagefill($base_image, 0, 0, $col[0]); + + for($y=0; $y<$h; $y++) { + for($x=0; $x<$w; $x++) { + if ($frame[$y][$x] == '1') { + ImageSetPixel($base_image,$x+$outerFrame,$y+$outerFrame,$col[1]); + } + } + } + + $target_image =ImageCreate($imgW * $pixelPerPoint, $imgH * $pixelPerPoint); + ImageCopyResized($target_image, $base_image, 0, 0, 0, 0, $imgW * $pixelPerPoint, $imgH * $pixelPerPoint, $imgW, $imgH); + ImageDestroy($base_image); + + return $target_image; + } + } \ No newline at end of file diff --git a/application/libraries/qrcode/qrinput.php b/application/libraries/qrcode/qrinput.php new file mode 100644 index 00000000..c65f91a2 --- /dev/null +++ b/application/libraries/qrcode/qrinput.php @@ -0,0 +1,729 @@ + + * + * PHP QR Code is distributed under LGPL 3 + * Copyright (C) 2010 Dominik Dzienia + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ + + define('STRUCTURE_HEADER_BITS', 20); + define('MAX_STRUCTURED_SYMBOLS', 16); + + class QRinputItem { + + public $mode; + public $size; + public $data; + public $bstream; + + public function __construct($mode, $size, $data, $bstream = null) + { + $setData = array_slice($data, 0, $size); + + if (count($setData) < $size) { + $setData = array_merge($setData, array_fill(0,$size-count($setData),0)); + } + + if(!QRinput::check($mode, $size, $setData)) { + throw new Exception('Error m:'.$mode.',s:'.$size.',d:'.join(',',$setData)); + return null; + } + + $this->mode = $mode; + $this->size = $size; + $this->data = $setData; + $this->bstream = $bstream; + } + + //---------------------------------------------------------------------- + public function encodeModeNum($version) + { + try { + + $words = (int)($this->size / 3); + $bs = new QRbitstream(); + + $val = 0x1; + $bs->appendNum(4, $val); + $bs->appendNum(QRspec::lengthIndicator(QR_MODE_NUM, $version), $this->size); + + for($i=0; $i<$words; $i++) { + $val = (ord($this->data[$i*3 ]) - ord('0')) * 100; + $val += (ord($this->data[$i*3+1]) - ord('0')) * 10; + $val += (ord($this->data[$i*3+2]) - ord('0')); + $bs->appendNum(10, $val); + } + + if($this->size - $words * 3 == 1) { + $val = ord($this->data[$words*3]) - ord('0'); + $bs->appendNum(4, $val); + } else if($this->size - $words * 3 == 2) { + $val = (ord($this->data[$words*3 ]) - ord('0')) * 10; + $val += (ord($this->data[$words*3+1]) - ord('0')); + $bs->appendNum(7, $val); + } + + $this->bstream = $bs; + return 0; + + } catch (Exception $e) { + return -1; + } + } + + //---------------------------------------------------------------------- + public function encodeModeAn($version) + { + try { + $words = (int)($this->size / 2); + $bs = new QRbitstream(); + + $bs->appendNum(4, 0x02); + $bs->appendNum(QRspec::lengthIndicator(QR_MODE_AN, $version), $this->size); + + for($i=0; $i<$words; $i++) { + $val = (int)QRinput::lookAnTable(ord($this->data[$i*2 ])) * 45; + $val += (int)QRinput::lookAnTable(ord($this->data[$i*2+1])); + + $bs->appendNum(11, $val); + } + + if($this->size & 1) { + $val = QRinput::lookAnTable(ord($this->data[$words * 2])); + $bs->appendNum(6, $val); + } + + $this->bstream = $bs; + return 0; + + } catch (Exception $e) { + return -1; + } + } + + //---------------------------------------------------------------------- + public function encodeMode8($version) + { + try { + $bs = new QRbitstream(); + + $bs->appendNum(4, 0x4); + $bs->appendNum(QRspec::lengthIndicator(QR_MODE_8, $version), $this->size); + + for($i=0; $i<$this->size; $i++) { + $bs->appendNum(8, ord($this->data[$i])); + } + + $this->bstream = $bs; + return 0; + + } catch (Exception $e) { + return -1; + } + } + + //---------------------------------------------------------------------- + public function encodeModeKanji($version) + { + try { + + $bs = new QRbitrtream(); + + $bs->appendNum(4, 0x8); + $bs->appendNum(QRspec::lengthIndicator(QR_MODE_KANJI, $version), (int)($this->size / 2)); + + for($i=0; $i<$this->size; $i+=2) { + $val = (ord($this->data[$i]) << 8) | ord($this->data[$i+1]); + if($val <= 0x9ffc) { + $val -= 0x8140; + } else { + $val -= 0xc140; + } + + $h = ($val >> 8) * 0xc0; + $val = ($val & 0xff) + $h; + + $bs->appendNum(13, $val); + } + + $this->bstream = $bs; + return 0; + + } catch (Exception $e) { + return -1; + } + } + + //---------------------------------------------------------------------- + public function encodeModeStructure() + { + try { + $bs = new QRbitstream(); + + $bs->appendNum(4, 0x03); + $bs->appendNum(4, ord($this->data[1]) - 1); + $bs->appendNum(4, ord($this->data[0]) - 1); + $bs->appendNum(8, ord($this->data[2])); + + $this->bstream = $bs; + return 0; + + } catch (Exception $e) { + return -1; + } + } + + //---------------------------------------------------------------------- + public function estimateBitStreamSizeOfEntry($version) + { + $bits = 0; + + if($version == 0) + $version = 1; + + switch($this->mode) { + case QR_MODE_NUM: $bits = QRinput::estimateBitsModeNum($this->size); break; + case QR_MODE_AN: $bits = QRinput::estimateBitsModeAn($this->size); break; + case QR_MODE_8: $bits = QRinput::estimateBitsMode8($this->size); break; + case QR_MODE_KANJI: $bits = QRinput::estimateBitsModeKanji($this->size);break; + case QR_MODE_STRUCTURE: return STRUCTURE_HEADER_BITS; + default: + return 0; + } + + $l = QRspec::lengthIndicator($this->mode, $version); + $m = 1 << $l; + $num = (int)(($this->size + $m - 1) / $m); + + $bits += $num * (4 + $l); + + return $bits; + } + + //---------------------------------------------------------------------- + public function encodeBitStream($version) + { + try { + + unset($this->bstream); + $words = QRspec::maximumWords($this->mode, $version); + + if($this->size > $words) { + + $st1 = new QRinputItem($this->mode, $words, $this->data); + $st2 = new QRinputItem($this->mode, $this->size - $words, array_slice($this->data, $words)); + + $st1->encodeBitStream($version); + $st2->encodeBitStream($version); + + $this->bstream = new QRbitstream(); + $this->bstream->append($st1->bstream); + $this->bstream->append($st2->bstream); + + unset($st1); + unset($st2); + + } else { + + $ret = 0; + + switch($this->mode) { + case QR_MODE_NUM: $ret = $this->encodeModeNum($version); break; + case QR_MODE_AN: $ret = $this->encodeModeAn($version); break; + case QR_MODE_8: $ret = $this->encodeMode8($version); break; + case QR_MODE_KANJI: $ret = $this->encodeModeKanji($version);break; + case QR_MODE_STRUCTURE: $ret = $this->encodeModeStructure(); break; + + default: + break; + } + + if($ret < 0) + return -1; + } + + return $this->bstream->size(); + + } catch (Exception $e) { + return -1; + } + } + }; + + //########################################################################## + + class QRinput { + + public $items; + + private $version; + private $level; + + //---------------------------------------------------------------------- + public function __construct($version = 0, $level = QR_ECLEVEL_L) + { + if ($version < 0 || $version > QRSPEC_VERSION_MAX || $level > QR_ECLEVEL_H) { + throw new Exception('Invalid version no'); + return NULL; + } + + $this->version = $version; + $this->level = $level; + } + + //---------------------------------------------------------------------- + public function getVersion() + { + return $this->version; + } + + //---------------------------------------------------------------------- + public function setVersion($version) + { + if($version < 0 || $version > QRSPEC_VERSION_MAX) { + throw new Exception('Invalid version no'); + return -1; + } + + $this->version = $version; + + return 0; + } + + //---------------------------------------------------------------------- + public function getErrorCorrectionLevel() + { + return $this->level; + } + + //---------------------------------------------------------------------- + public function setErrorCorrectionLevel($level) + { + if($level > QR_ECLEVEL_H) { + throw new Exception('Invalid ECLEVEL'); + return -1; + } + + $this->level = $level; + + return 0; + } + + //---------------------------------------------------------------------- + public function appendEntry(QRinputItem $entry) + { + $this->items[] = $entry; + } + + //---------------------------------------------------------------------- + public function append($mode, $size, $data) + { + try { + $entry = new QRinputItem($mode, $size, $data); + $this->items[] = $entry; + return 0; + } catch (Exception $e) { + return -1; + } + } + + //---------------------------------------------------------------------- + + public function insertStructuredAppendHeader($size, $index, $parity) + { + if( $size > MAX_STRUCTURED_SYMBOLS ) { + throw new Exception('insertStructuredAppendHeader wrong size'); + } + + if( $index <= 0 || $index > MAX_STRUCTURED_SYMBOLS ) { + throw new Exception('insertStructuredAppendHeader wrong index'); + } + + $buf = array($size, $index, $parity); + + try { + $entry = new QRinputItem(QR_MODE_STRUCTURE, 3, buf); + array_unshift($this->items, $entry); + return 0; + } catch (Exception $e) { + return -1; + } + } + + //---------------------------------------------------------------------- + public function calcParity() + { + $parity = 0; + + foreach($this->items as $item) { + if($item->mode != QR_MODE_STRUCTURE) { + for($i=$item->size-1; $i>=0; $i--) { + $parity ^= $item->data[$i]; + } + } + } + + return $parity; + } + + //---------------------------------------------------------------------- + public static function checkModeNum($size, $data) + { + for($i=0; $i<$size; $i++) { + if((ord($data[$i]) < ord('0')) || (ord($data[$i]) > ord('9'))){ + return false; + } + } + + return true; + } + + //---------------------------------------------------------------------- + public static function estimateBitsModeNum($size) + { + $w = (int)$size / 3; + $bits = $w * 10; + + switch($size - $w * 3) { + case 1: + $bits += 4; + break; + case 2: + $bits += 7; + break; + default: + break; + } + + return $bits; + } + + //---------------------------------------------------------------------- + public static $anTable = array( + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + 36, -1, -1, -1, 37, 38, -1, -1, -1, -1, 39, 40, -1, 41, 42, 43, + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 44, -1, -1, -1, -1, -1, + -1, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, + 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 + ); + + //---------------------------------------------------------------------- + public static function lookAnTable($c) + { + return (($c > 127)?-1:self::$anTable[$c]); + } + + //---------------------------------------------------------------------- + public static function checkModeAn($size, $data) + { + for($i=0; $i<$size; $i++) { + if (self::lookAnTable(ord($data[$i])) == -1) { + return false; + } + } + + return true; + } + + //---------------------------------------------------------------------- + public static function estimateBitsModeAn($size) + { + $w = (int)($size / 2); + $bits = $w * 11; + + if($size & 1) { + $bits += 6; + } + + return $bits; + } + + //---------------------------------------------------------------------- + public static function estimateBitsMode8($size) + { + return $size * 8; + } + + //---------------------------------------------------------------------- + public function estimateBitsModeKanji($size) + { + return (int)(($size / 2) * 13); + } + + //---------------------------------------------------------------------- + public static function checkModeKanji($size, $data) + { + if($size & 1) + return false; + + for($i=0; $i<$size; $i+=2) { + $val = (ord($data[$i]) << 8) | ord($data[$i+1]); + if( $val < 0x8140 + || ($val > 0x9ffc && $val < 0xe040) + || $val > 0xebbf) { + return false; + } + } + + return true; + } + + /*********************************************************************** + * Validation + **********************************************************************/ + + public static function check($mode, $size, $data) + { + if($size <= 0) + return false; + + switch($mode) { + case QR_MODE_NUM: return self::checkModeNum($size, $data); break; + case QR_MODE_AN: return self::checkModeAn($size, $data); break; + case QR_MODE_KANJI: return self::checkModeKanji($size, $data); break; + case QR_MODE_8: return true; break; + case QR_MODE_STRUCTURE: return true; break; + + default: + break; + } + + return false; + } + + + //---------------------------------------------------------------------- + public function estimateBitStreamSize($version) + { + $bits = 0; + + foreach($this->items as $item) { + $bits += $item->estimateBitStreamSizeOfEntry($version); + } + + return $bits; + } + + //---------------------------------------------------------------------- + public function estimateVersion() + { + $version = 0; + $prev = 0; + do { + $prev = $version; + $bits = $this->estimateBitStreamSize($prev); + $version = QRspec::getMinimumVersion((int)(($bits + 7) / 8), $this->level); + if ($version < 0) { + return -1; + } + } while ($version > $prev); + + return $version; + } + + //---------------------------------------------------------------------- + public static function lengthOfCode($mode, $version, $bits) + { + $payload = $bits - 4 - QRspec::lengthIndicator($mode, $version); + switch($mode) { + case QR_MODE_NUM: + $chunks = (int)($payload / 10); + $remain = $payload - $chunks * 10; + $size = $chunks * 3; + if($remain >= 7) { + $size += 2; + } else if($remain >= 4) { + $size += 1; + } + break; + case QR_MODE_AN: + $chunks = (int)($payload / 11); + $remain = $payload - $chunks * 11; + $size = $chunks * 2; + if($remain >= 6) + $size++; + break; + case QR_MODE_8: + $size = (int)($payload / 8); + break; + case QR_MODE_KANJI: + $size = (int)(($payload / 13) * 2); + break; + case QR_MODE_STRUCTURE: + $size = (int)($payload / 8); + break; + default: + $size = 0; + break; + } + + $maxsize = QRspec::maximumWords($mode, $version); + if($size < 0) $size = 0; + if($size > $maxsize) $size = $maxsize; + + return $size; + } + + //---------------------------------------------------------------------- + public function createBitStream() + { + $total = 0; + + foreach($this->items as $item) { + $bits = $item->encodeBitStream($this->version); + + if($bits < 0) + return -1; + + $total += $bits; + } + + return $total; + } + + //---------------------------------------------------------------------- + public function convertData() + { + $ver = $this->estimateVersion(); + if($ver > $this->getVersion()) { + $this->setVersion($ver); + } + + for(;;) { + $bits = $this->createBitStream(); + + if($bits < 0) + return -1; + + $ver = QRspec::getMinimumVersion((int)(($bits + 7) / 8), $this->level); + if($ver < 0) { + throw new Exception('WRONG VERSION'); + return -1; + } else if($ver > $this->getVersion()) { + $this->setVersion($ver); + } else { + break; + } + } + + return 0; + } + + //---------------------------------------------------------------------- + public function appendPaddingBit(&$bstream) + { + $bits = $bstream->size(); + $maxwords = QRspec::getDataLength($this->version, $this->level); + $maxbits = $maxwords * 8; + + if ($maxbits == $bits) { + return 0; + } + + if ($maxbits - $bits < 5) { + return $bstream->appendNum($maxbits - $bits, 0); + } + + $bits += 4; + $words = (int)(($bits + 7) / 8); + + $padding = new QRbitstream(); + $ret = $padding->appendNum($words * 8 - $bits + 4, 0); + + if($ret < 0) + return $ret; + + $padlen = $maxwords - $words; + + if($padlen > 0) { + + $padbuf = array(); + for($i=0; $i<$padlen; $i++) { + $padbuf[$i] = ($i&1)?0x11:0xec; + } + + $ret = $padding->appendBytes($padlen, $padbuf); + + if($ret < 0) + return $ret; + + } + + $ret = $bstream->append($padding); + + return $ret; + } + + //---------------------------------------------------------------------- + public function mergeBitStream() + { + if($this->convertData() < 0) { + return null; + } + + $bstream = new QRbitstream(); + + foreach($this->items as $item) { + $ret = $bstream->append($item->bstream); + if($ret < 0) { + return null; + } + } + + return $bstream; + } + + //---------------------------------------------------------------------- + public function getBitStream() + { + + $bstream = $this->mergeBitStream(); + + if($bstream == null) { + return null; + } + + $ret = $this->appendPaddingBit($bstream); + if($ret < 0) { + return null; + } + + return $bstream; + } + + //---------------------------------------------------------------------- + public function getByteStream() + { + $bstream = $this->getBitStream(); + if($bstream == null) { + return null; + } + + return $bstream->toByte(); + } + } + + + \ No newline at end of file diff --git a/application/libraries/qrcode/qrlib.php b/application/libraries/qrcode/qrlib.php new file mode 100644 index 00000000..43059b9d --- /dev/null +++ b/application/libraries/qrcode/qrlib.php @@ -0,0 +1,43 @@ + + * + * PHP QR Code is distributed under LGPL 3 + * Copyright (C) 2010 Dominik Dzienia + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ + + $QR_BASEDIR = dirname(__FILE__).DIRECTORY_SEPARATOR; + + // Required libs + + include $QR_BASEDIR."qrconst.php"; + include $QR_BASEDIR."qrconfig.php"; + include $QR_BASEDIR."qrtools.php"; + include $QR_BASEDIR."qrspec.php"; + include $QR_BASEDIR."qrimage.php"; + include $QR_BASEDIR."qrinput.php"; + include $QR_BASEDIR."qrbitstream.php"; + include $QR_BASEDIR."qrsplit.php"; + include $QR_BASEDIR."qrrscode.php"; + include $QR_BASEDIR."qrmask.php"; + include $QR_BASEDIR."qrencode.php"; + diff --git a/application/libraries/qrcode/qrmask.php b/application/libraries/qrcode/qrmask.php new file mode 100644 index 00000000..2d388e0e --- /dev/null +++ b/application/libraries/qrcode/qrmask.php @@ -0,0 +1,328 @@ + + * + * PHP QR Code is distributed under LGPL 3 + * Copyright (C) 2010 Dominik Dzienia + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ + + define('N1', 3); + define('N2', 3); + define('N3', 40); + define('N4', 10); + + class QRmask { + + public $runLength = array(); + + //---------------------------------------------------------------------- + public function __construct() + { + $this->runLength = array_fill(0, QRSPEC_WIDTH_MAX + 1, 0); + } + + //---------------------------------------------------------------------- + public function writeFormatInformation($width, &$frame, $mask, $level) + { + $blacks = 0; + $format = QRspec::getFormatInfo($mask, $level); + + for($i=0; $i<8; $i++) { + if($format & 1) { + $blacks += 2; + $v = 0x85; + } else { + $v = 0x84; + } + + $frame[8][$width - 1 - $i] = chr($v); + if($i < 6) { + $frame[$i][8] = chr($v); + } else { + $frame[$i + 1][8] = chr($v); + } + $format = $format >> 1; + } + + for($i=0; $i<7; $i++) { + if($format & 1) { + $blacks += 2; + $v = 0x85; + } else { + $v = 0x84; + } + + $frame[$width - 7 + $i][8] = chr($v); + if($i == 0) { + $frame[8][7] = chr($v); + } else { + $frame[8][6 - $i] = chr($v); + } + + $format = $format >> 1; + } + + return $blacks; + } + + //---------------------------------------------------------------------- + public function mask0($x, $y) { return ($x+$y)&1; } + public function mask1($x, $y) { return ($y&1); } + public function mask2($x, $y) { return ($x%3); } + public function mask3($x, $y) { return ($x+$y)%3; } + public function mask4($x, $y) { return (((int)($y/2))+((int)($x/3)))&1; } + public function mask5($x, $y) { return (($x*$y)&1)+($x*$y)%3; } + public function mask6($x, $y) { return ((($x*$y)&1)+($x*$y)%3)&1; } + public function mask7($x, $y) { return ((($x*$y)%3)+(($x+$y)&1))&1; } + + //---------------------------------------------------------------------- + private function generateMaskNo($maskNo, $width, $frame) + { + $bitMask = array_fill(0, $width, array_fill(0, $width, 0)); + + for($y=0; $y<$width; $y++) { + for($x=0; $x<$width; $x++) { + if(ord($frame[$y][$x]) & 0x80) { + $bitMask[$y][$x] = 0; + } else { + $maskFunc = call_user_func(array($this, 'mask'.$maskNo), $x, $y); + $bitMask[$y][$x] = ($maskFunc == 0)?1:0; + } + + } + } + + return $bitMask; + } + + //---------------------------------------------------------------------- + public static function serial($bitFrame) + { + $codeArr = array(); + + foreach ($bitFrame as $line) + $codeArr[] = join('', $line); + + return gzcompress(join("\n", $codeArr), 9); + } + + //---------------------------------------------------------------------- + public static function unserial($code) + { + $codeArr = array(); + + $codeLines = explode("\n", gzuncompress($code)); + foreach ($codeLines as $line) + $codeArr[] = str_split($line); + + return $codeArr; + } + + //---------------------------------------------------------------------- + public function makeMaskNo($maskNo, $width, $s, &$d, $maskGenOnly = false) + { + $b = 0; + $bitMask = array(); + + $fileName = QR_CACHE_DIR.'mask_'.$maskNo.DIRECTORY_SEPARATOR.'mask_'.$width.'_'.$maskNo.'.dat'; + + if (QR_CACHEABLE) { + if (file_exists($fileName)) { + $bitMask = self::unserial(file_get_contents($fileName)); + } else { + $bitMask = $this->generateMaskNo($maskNo, $width, $s, $d); + if (!file_exists(QR_CACHE_DIR.'mask_'.$maskNo)) + mkdir(QR_CACHE_DIR.'mask_'.$maskNo); + file_put_contents($fileName, self::serial($bitMask)); + } + } else { + $bitMask = $this->generateMaskNo($maskNo, $width, $s, $d); + } + + if ($maskGenOnly) + return; + + $d = $s; + + for($y=0; $y<$width; $y++) { + for($x=0; $x<$width; $x++) { + if($bitMask[$y][$x] == 1) { + $d[$y][$x] = chr(ord($s[$y][$x]) ^ (int)$bitMask[$y][$x]); + } + $b += (int)(ord($d[$y][$x]) & 1); + } + } + + return $b; + } + + //---------------------------------------------------------------------- + public function makeMask($width, $frame, $maskNo, $level) + { + $masked = array_fill(0, $width, str_repeat("\0", $width)); + $this->makeMaskNo($maskNo, $width, $frame, $masked); + $this->writeFormatInformation($width, $masked, $maskNo, $level); + + return $masked; + } + + //---------------------------------------------------------------------- + public function calcN1N3($length) + { + $demerit = 0; + + for($i=0; $i<$length; $i++) { + + if($this->runLength[$i] >= 5) { + $demerit += (N1 + ($this->runLength[$i] - 5)); + } + if($i & 1) { + if(($i >= 3) && ($i < ($length-2)) && ($this->runLength[$i] % 3 == 0)) { + $fact = (int)($this->runLength[$i] / 3); + if(($this->runLength[$i-2] == $fact) && + ($this->runLength[$i-1] == $fact) && + ($this->runLength[$i+1] == $fact) && + ($this->runLength[$i+2] == $fact)) { + if(($this->runLength[$i-3] < 0) || ($this->runLength[$i-3] >= (4 * $fact))) { + $demerit += N3; + } else if((($i+3) >= $length) || ($this->runLength[$i+3] >= (4 * $fact))) { + $demerit += N3; + } + } + } + } + } + return $demerit; + } + + //---------------------------------------------------------------------- + public function evaluateSymbol($width, $frame) + { + $head = 0; + $demerit = 0; + + for($y=0; $y<$width; $y++) { + $head = 0; + $this->runLength[0] = 1; + + $frameY = $frame[$y]; + + if ($y>0) + $frameYM = $frame[$y-1]; + + for($x=0; $x<$width; $x++) { + if(($x > 0) && ($y > 0)) { + $b22 = ord($frameY[$x]) & ord($frameY[$x-1]) & ord($frameYM[$x]) & ord($frameYM[$x-1]); + $w22 = ord($frameY[$x]) | ord($frameY[$x-1]) | ord($frameYM[$x]) | ord($frameYM[$x-1]); + + if(($b22 | ($w22 ^ 1))&1) { + $demerit += N2; + } + } + if(($x == 0) && (ord($frameY[$x]) & 1)) { + $this->runLength[0] = -1; + $head = 1; + $this->runLength[$head] = 1; + } else if($x > 0) { + if((ord($frameY[$x]) ^ ord($frameY[$x-1])) & 1) { + $head++; + $this->runLength[$head] = 1; + } else { + $this->runLength[$head]++; + } + } + } + + $demerit += $this->calcN1N3($head+1); + } + + for($x=0; $x<$width; $x++) { + $head = 0; + $this->runLength[0] = 1; + + for($y=0; $y<$width; $y++) { + if($y == 0 && (ord($frame[$y][$x]) & 1)) { + $this->runLength[0] = -1; + $head = 1; + $this->runLength[$head] = 1; + } else if($y > 0) { + if((ord($frame[$y][$x]) ^ ord($frame[$y-1][$x])) & 1) { + $head++; + $this->runLength[$head] = 1; + } else { + $this->runLength[$head]++; + } + } + } + + $demerit += $this->calcN1N3($head+1); + } + + return $demerit; + } + + + //---------------------------------------------------------------------- + public function mask($width, $frame, $level) + { + $minDemerit = PHP_INT_MAX; + $bestMaskNum = 0; + $bestMask = array(); + + $checked_masks = array(0,1,2,3,4,5,6,7); + + if (QR_FIND_FROM_RANDOM !== false) { + + $howManuOut = 8-(QR_FIND_FROM_RANDOM % 9); + for ($i = 0; $i < $howManuOut; $i++) { + $remPos = rand (0, count($checked_masks)-1); + unset($checked_masks[$remPos]); + $checked_masks = array_values($checked_masks); + } + + } + + $bestMask = $frame; + + foreach($checked_masks as $i) { + $mask = array_fill(0, $width, str_repeat("\0", $width)); + + $demerit = 0; + $blacks = 0; + $blacks = $this->makeMaskNo($i, $width, $frame, $mask); + $blacks += $this->writeFormatInformation($width, $mask, $i, $level); + $blacks = (int)(100 * $blacks / ($width * $width)); + $demerit = (int)((int)(abs($blacks - 50) / 5) * N4); + $demerit += $this->evaluateSymbol($width, $mask); + + if($demerit < $minDemerit) { + $minDemerit = $demerit; + $bestMask = $mask; + $bestMaskNum = $i; + } + } + + return $bestMask; + } + + //---------------------------------------------------------------------- + } diff --git a/application/libraries/qrcode/qrrscode.php b/application/libraries/qrcode/qrrscode.php new file mode 100644 index 00000000..d7a97d9a --- /dev/null +++ b/application/libraries/qrcode/qrrscode.php @@ -0,0 +1,210 @@ + + * + * PHP QR Code is distributed under LGPL 3 + * Copyright (C) 2010 Dominik Dzienia + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ + + class QRrsItem { + + public $mm; // Bits per symbol + public $nn; // Symbols per block (= (1<= $this->nn) { + $x -= $this->nn; + $x = ($x >> $this->mm) + ($x & $this->nn); + } + + return $x; + } + + //---------------------------------------------------------------------- + public static function init_rs_char($symsize, $gfpoly, $fcr, $prim, $nroots, $pad) + { + // Common code for intializing a Reed-Solomon control block (char or int symbols) + // Copyright 2004 Phil Karn, KA9Q + // May be used under the terms of the GNU Lesser General Public License (LGPL) + + $rs = null; + + // Check parameter ranges + if($symsize < 0 || $symsize > 8) return $rs; + if($fcr < 0 || $fcr >= (1<<$symsize)) return $rs; + if($prim <= 0 || $prim >= (1<<$symsize)) return $rs; + if($nroots < 0 || $nroots >= (1<<$symsize)) return $rs; // Can't have more roots than symbol values! + if($pad < 0 || $pad >= ((1<<$symsize) -1 - $nroots)) return $rs; // Too much padding + + $rs = new QRrsItem(); + $rs->mm = $symsize; + $rs->nn = (1<<$symsize)-1; + $rs->pad = $pad; + + $rs->alpha_to = array_fill(0, $rs->nn+1, 0); + $rs->index_of = array_fill(0, $rs->nn+1, 0); + + // PHP style macro replacement ;) + $NN =& $rs->nn; + $A0 =& $NN; + + // Generate Galois field lookup tables + $rs->index_of[0] = $A0; // log(zero) = -inf + $rs->alpha_to[$A0] = 0; // alpha**-inf = 0 + $sr = 1; + + for($i=0; $i<$rs->nn; $i++) { + $rs->index_of[$sr] = $i; + $rs->alpha_to[$i] = $sr; + $sr <<= 1; + if($sr & (1<<$symsize)) { + $sr ^= $gfpoly; + } + $sr &= $rs->nn; + } + + if($sr != 1){ + // field generator polynomial is not primitive! + $rs = NULL; + return $rs; + } + + /* Form RS code generator polynomial from its roots */ + $rs->genpoly = array_fill(0, $nroots+1, 0); + + $rs->fcr = $fcr; + $rs->prim = $prim; + $rs->nroots = $nroots; + $rs->gfpoly = $gfpoly; + + /* Find prim-th root of 1, used in decoding */ + for($iprim=1;($iprim % $prim) != 0;$iprim += $rs->nn) + ; // intentional empty-body loop! + + $rs->iprim = (int)($iprim / $prim); + $rs->genpoly[0] = 1; + + for ($i = 0,$root=$fcr*$prim; $i < $nroots; $i++, $root += $prim) { + $rs->genpoly[$i+1] = 1; + + // Multiply rs->genpoly[] by @**(root + x) + for ($j = $i; $j > 0; $j--) { + if ($rs->genpoly[$j] != 0) { + $rs->genpoly[$j] = $rs->genpoly[$j-1] ^ $rs->alpha_to[$rs->modnn($rs->index_of[$rs->genpoly[$j]] + $root)]; + } else { + $rs->genpoly[$j] = $rs->genpoly[$j-1]; + } + } + // rs->genpoly[0] can never be zero + $rs->genpoly[0] = $rs->alpha_to[$rs->modnn($rs->index_of[$rs->genpoly[0]] + $root)]; + } + + // convert rs->genpoly[] to index form for quicker encoding + for ($i = 0; $i <= $nroots; $i++) + $rs->genpoly[$i] = $rs->index_of[$rs->genpoly[$i]]; + + return $rs; + } + + //---------------------------------------------------------------------- + public function encode_rs_char($data, &$parity) + { + $MM =& $this->mm; + $NN =& $this->nn; + $ALPHA_TO =& $this->alpha_to; + $INDEX_OF =& $this->index_of; + $GENPOLY =& $this->genpoly; + $NROOTS =& $this->nroots; + $FCR =& $this->fcr; + $PRIM =& $this->prim; + $IPRIM =& $this->iprim; + $PAD =& $this->pad; + $A0 =& $NN; + + $parity = array_fill(0, $NROOTS, 0); + + for($i=0; $i< ($NN-$NROOTS-$PAD); $i++) { + + $feedback = $INDEX_OF[$data[$i] ^ $parity[0]]; + if($feedback != $A0) { + // feedback term is non-zero + + // This line is unnecessary when GENPOLY[NROOTS] is unity, as it must + // always be for the polynomials constructed by init_rs() + $feedback = $this->modnn($NN - $GENPOLY[$NROOTS] + $feedback); + + for($j=1;$j<$NROOTS;$j++) { + $parity[$j] ^= $ALPHA_TO[$this->modnn($feedback + $GENPOLY[$NROOTS-$j])]; + } + } + + // Shift + array_shift($parity); + if($feedback != $A0) { + array_push($parity, $ALPHA_TO[$this->modnn($feedback + $GENPOLY[0])]); + } else { + array_push($parity, 0); + } + } + } + } + + //########################################################################## + + class QRrs { + + public static $items = array(); + + //---------------------------------------------------------------------- + public static function init_rs($symsize, $gfpoly, $fcr, $prim, $nroots, $pad) + { + foreach(self::$items as $rs) { + if($rs->pad != $pad) continue; + if($rs->nroots != $nroots) continue; + if($rs->mm != $symsize) continue; + if($rs->gfpoly != $gfpoly) continue; + if($rs->fcr != $fcr) continue; + if($rs->prim != $prim) continue; + + return $rs; + } + + $rs = QRrsItem::init_rs_char($symsize, $gfpoly, $fcr, $prim, $nroots, $pad); + array_unshift(self::$items, $rs); + + return $rs; + } + } \ No newline at end of file diff --git a/application/libraries/qrcode/qrspec.php b/application/libraries/qrcode/qrspec.php new file mode 100644 index 00000000..5a0c4b3c --- /dev/null +++ b/application/libraries/qrcode/qrspec.php @@ -0,0 +1,592 @@ + + * + * PHP QR Code is distributed under LGPL 3 + * Copyright (C) 2010 Dominik Dzienia + * + * The following data / specifications are taken from + * "Two dimensional symbol -- QR-code -- Basic Specification" (JIS X0510:2004) + * or + * "Automatic identification and data capture techniques -- + * QR Code 2005 bar code symbology specification" (ISO/IEC 18004:2006) + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ + + define('QRSPEC_VERSION_MAX', 40); + define('QRSPEC_WIDTH_MAX', 177); + + define('QRCAP_WIDTH', 0); + define('QRCAP_WORDS', 1); + define('QRCAP_REMINDER', 2); + define('QRCAP_EC', 3); + + class QRspec { + + public static $capacity = array( + array( 0, 0, 0, array( 0, 0, 0, 0)), + array( 21, 26, 0, array( 7, 10, 13, 17)), // 1 + array( 25, 44, 7, array( 10, 16, 22, 28)), + array( 29, 70, 7, array( 15, 26, 36, 44)), + array( 33, 100, 7, array( 20, 36, 52, 64)), + array( 37, 134, 7, array( 26, 48, 72, 88)), // 5 + array( 41, 172, 7, array( 36, 64, 96, 112)), + array( 45, 196, 0, array( 40, 72, 108, 130)), + array( 49, 242, 0, array( 48, 88, 132, 156)), + array( 53, 292, 0, array( 60, 110, 160, 192)), + array( 57, 346, 0, array( 72, 130, 192, 224)), //10 + array( 61, 404, 0, array( 80, 150, 224, 264)), + array( 65, 466, 0, array( 96, 176, 260, 308)), + array( 69, 532, 0, array( 104, 198, 288, 352)), + array( 73, 581, 3, array( 120, 216, 320, 384)), + array( 77, 655, 3, array( 132, 240, 360, 432)), //15 + array( 81, 733, 3, array( 144, 280, 408, 480)), + array( 85, 815, 3, array( 168, 308, 448, 532)), + array( 89, 901, 3, array( 180, 338, 504, 588)), + array( 93, 991, 3, array( 196, 364, 546, 650)), + array( 97, 1085, 3, array( 224, 416, 600, 700)), //20 + array(101, 1156, 4, array( 224, 442, 644, 750)), + array(105, 1258, 4, array( 252, 476, 690, 816)), + array(109, 1364, 4, array( 270, 504, 750, 900)), + array(113, 1474, 4, array( 300, 560, 810, 960)), + array(117, 1588, 4, array( 312, 588, 870, 1050)), //25 + array(121, 1706, 4, array( 336, 644, 952, 1110)), + array(125, 1828, 4, array( 360, 700, 1020, 1200)), + array(129, 1921, 3, array( 390, 728, 1050, 1260)), + array(133, 2051, 3, array( 420, 784, 1140, 1350)), + array(137, 2185, 3, array( 450, 812, 1200, 1440)), //30 + array(141, 2323, 3, array( 480, 868, 1290, 1530)), + array(145, 2465, 3, array( 510, 924, 1350, 1620)), + array(149, 2611, 3, array( 540, 980, 1440, 1710)), + array(153, 2761, 3, array( 570, 1036, 1530, 1800)), + array(157, 2876, 0, array( 570, 1064, 1590, 1890)), //35 + array(161, 3034, 0, array( 600, 1120, 1680, 1980)), + array(165, 3196, 0, array( 630, 1204, 1770, 2100)), + array(169, 3362, 0, array( 660, 1260, 1860, 2220)), + array(173, 3532, 0, array( 720, 1316, 1950, 2310)), + array(177, 3706, 0, array( 750, 1372, 2040, 2430)) //40 + ); + + //---------------------------------------------------------------------- + public static function getDataLength($version, $level) + { + return self::$capacity[$version][QRCAP_WORDS] - self::$capacity[$version][QRCAP_EC][$level]; + } + + //---------------------------------------------------------------------- + public static function getECCLength($version, $level) + { + return self::$capacity[$version][QRCAP_EC][$level]; + } + + //---------------------------------------------------------------------- + public static function getWidth($version) + { + return self::$capacity[$version][QRCAP_WIDTH]; + } + + //---------------------------------------------------------------------- + public static function getRemainder($version) + { + return self::$capacity[$version][QRCAP_REMINDER]; + } + + //---------------------------------------------------------------------- + public static function getMinimumVersion($size, $level) + { + + for($i=1; $i<= QRSPEC_VERSION_MAX; $i++) { + $words = self::$capacity[$i][QRCAP_WORDS] - self::$capacity[$i][QRCAP_EC][$level]; + if($words >= $size) + return $i; + } + + return -1; + } + + //###################################################################### + + public static $lengthTableBits = array( + array(10, 12, 14), + array( 9, 11, 13), + array( 8, 16, 16), + array( 8, 10, 12) + ); + + //---------------------------------------------------------------------- + public static function lengthIndicator($mode, $version) + { + if ($mode == QR_MODE_STRUCTURE) + return 0; + + if ($version <= 9) { + $l = 0; + } else if ($version <= 26) { + $l = 1; + } else { + $l = 2; + } + + return self::$lengthTableBits[$mode][$l]; + } + + //---------------------------------------------------------------------- + public static function maximumWords($mode, $version) + { + if($mode == QR_MODE_STRUCTURE) + return 3; + + if($version <= 9) { + $l = 0; + } else if($version <= 26) { + $l = 1; + } else { + $l = 2; + } + + $bits = self::$lengthTableBits[$mode][$l]; + $words = (1 << $bits) - 1; + + if($mode == QR_MODE_KANJI) { + $words *= 2; // the number of bytes is required + } + + return $words; + } + + // Error correction code ----------------------------------------------- + // Table of the error correction code (Reed-Solomon block) + // See Table 12-16 (pp.30-36), JIS X0510:2004. + + public static $eccTable = array( + array(array( 0, 0), array( 0, 0), array( 0, 0), array( 0, 0)), + array(array( 1, 0), array( 1, 0), array( 1, 0), array( 1, 0)), // 1 + array(array( 1, 0), array( 1, 0), array( 1, 0), array( 1, 0)), + array(array( 1, 0), array( 1, 0), array( 2, 0), array( 2, 0)), + array(array( 1, 0), array( 2, 0), array( 2, 0), array( 4, 0)), + array(array( 1, 0), array( 2, 0), array( 2, 2), array( 2, 2)), // 5 + array(array( 2, 0), array( 4, 0), array( 4, 0), array( 4, 0)), + array(array( 2, 0), array( 4, 0), array( 2, 4), array( 4, 1)), + array(array( 2, 0), array( 2, 2), array( 4, 2), array( 4, 2)), + array(array( 2, 0), array( 3, 2), array( 4, 4), array( 4, 4)), + array(array( 2, 2), array( 4, 1), array( 6, 2), array( 6, 2)), //10 + array(array( 4, 0), array( 1, 4), array( 4, 4), array( 3, 8)), + array(array( 2, 2), array( 6, 2), array( 4, 6), array( 7, 4)), + array(array( 4, 0), array( 8, 1), array( 8, 4), array(12, 4)), + array(array( 3, 1), array( 4, 5), array(11, 5), array(11, 5)), + array(array( 5, 1), array( 5, 5), array( 5, 7), array(11, 7)), //15 + array(array( 5, 1), array( 7, 3), array(15, 2), array( 3, 13)), + array(array( 1, 5), array(10, 1), array( 1, 15), array( 2, 17)), + array(array( 5, 1), array( 9, 4), array(17, 1), array( 2, 19)), + array(array( 3, 4), array( 3, 11), array(17, 4), array( 9, 16)), + array(array( 3, 5), array( 3, 13), array(15, 5), array(15, 10)), //20 + array(array( 4, 4), array(17, 0), array(17, 6), array(19, 6)), + array(array( 2, 7), array(17, 0), array( 7, 16), array(34, 0)), + array(array( 4, 5), array( 4, 14), array(11, 14), array(16, 14)), + array(array( 6, 4), array( 6, 14), array(11, 16), array(30, 2)), + array(array( 8, 4), array( 8, 13), array( 7, 22), array(22, 13)), //25 + array(array(10, 2), array(19, 4), array(28, 6), array(33, 4)), + array(array( 8, 4), array(22, 3), array( 8, 26), array(12, 28)), + array(array( 3, 10), array( 3, 23), array( 4, 31), array(11, 31)), + array(array( 7, 7), array(21, 7), array( 1, 37), array(19, 26)), + array(array( 5, 10), array(19, 10), array(15, 25), array(23, 25)), //30 + array(array(13, 3), array( 2, 29), array(42, 1), array(23, 28)), + array(array(17, 0), array(10, 23), array(10, 35), array(19, 35)), + array(array(17, 1), array(14, 21), array(29, 19), array(11, 46)), + array(array(13, 6), array(14, 23), array(44, 7), array(59, 1)), + array(array(12, 7), array(12, 26), array(39, 14), array(22, 41)), //35 + array(array( 6, 14), array( 6, 34), array(46, 10), array( 2, 64)), + array(array(17, 4), array(29, 14), array(49, 10), array(24, 46)), + array(array( 4, 18), array(13, 32), array(48, 14), array(42, 32)), + array(array(20, 4), array(40, 7), array(43, 22), array(10, 67)), + array(array(19, 6), array(18, 31), array(34, 34), array(20, 61)),//40 + ); + + //---------------------------------------------------------------------- + // CACHEABLE!!! + + public static function getEccSpec($version, $level, array &$spec) + { + if (count($spec) < 5) { + $spec = array(0,0,0,0,0); + } + + $b1 = self::$eccTable[$version][$level][0]; + $b2 = self::$eccTable[$version][$level][1]; + $data = self::getDataLength($version, $level); + $ecc = self::getECCLength($version, $level); + + if($b2 == 0) { + $spec[0] = $b1; + $spec[1] = (int)($data / $b1); + $spec[2] = (int)($ecc / $b1); + $spec[3] = 0; + $spec[4] = 0; + } else { + $spec[0] = $b1; + $spec[1] = (int)($data / ($b1 + $b2)); + $spec[2] = (int)($ecc / ($b1 + $b2)); + $spec[3] = $b2; + $spec[4] = $spec[1] + 1; + } + } + + // Alignment pattern --------------------------------------------------- + + // Positions of alignment patterns. + // This array includes only the second and the third position of the + // alignment patterns. Rest of them can be calculated from the distance + // between them. + + // See Table 1 in Appendix E (pp.71) of JIS X0510:2004. + + public static $alignmentPattern = array( + array( 0, 0), + array( 0, 0), array(18, 0), array(22, 0), array(26, 0), array(30, 0), // 1- 5 + array(34, 0), array(22, 38), array(24, 42), array(26, 46), array(28, 50), // 6-10 + array(30, 54), array(32, 58), array(34, 62), array(26, 46), array(26, 48), //11-15 + array(26, 50), array(30, 54), array(30, 56), array(30, 58), array(34, 62), //16-20 + array(28, 50), array(26, 50), array(30, 54), array(28, 54), array(32, 58), //21-25 + array(30, 58), array(34, 62), array(26, 50), array(30, 54), array(26, 52), //26-30 + array(30, 56), array(34, 60), array(30, 58), array(34, 62), array(30, 54), //31-35 + array(24, 50), array(28, 54), array(32, 58), array(26, 54), array(30, 58), //35-40 + ); + + + /** -------------------------------------------------------------------- + * Put an alignment marker. + * @param frame + * @param width + * @param ox,oy center coordinate of the pattern + */ + public static function putAlignmentMarker(array &$frame, $ox, $oy) + { + $finder = array( + "\xa1\xa1\xa1\xa1\xa1", + "\xa1\xa0\xa0\xa0\xa1", + "\xa1\xa0\xa1\xa0\xa1", + "\xa1\xa0\xa0\xa0\xa1", + "\xa1\xa1\xa1\xa1\xa1" + ); + + $yStart = $oy-2; + $xStart = $ox-2; + + for($y=0; $y<5; $y++) { + QRstr::set($frame, $xStart, $yStart+$y, $finder[$y]); + } + } + + //---------------------------------------------------------------------- + public static function putAlignmentPattern($version, &$frame, $width) + { + if($version < 2) + return; + + $d = self::$alignmentPattern[$version][1] - self::$alignmentPattern[$version][0]; + if($d < 0) { + $w = 2; + } else { + $w = (int)(($width - self::$alignmentPattern[$version][0]) / $d + 2); + } + + if($w * $w - 3 == 1) { + $x = self::$alignmentPattern[$version][0]; + $y = self::$alignmentPattern[$version][0]; + self::putAlignmentMarker($frame, $x, $y); + return; + } + + $cx = self::$alignmentPattern[$version][0]; + for($x=1; $x<$w - 1; $x++) { + self::putAlignmentMarker($frame, 6, $cx); + self::putAlignmentMarker($frame, $cx, 6); + $cx += $d; + } + + $cy = self::$alignmentPattern[$version][0]; + for($y=0; $y<$w-1; $y++) { + $cx = self::$alignmentPattern[$version][0]; + for($x=0; $x<$w-1; $x++) { + self::putAlignmentMarker($frame, $cx, $cy); + $cx += $d; + } + $cy += $d; + } + } + + // Version information pattern ----------------------------------------- + + // Version information pattern (BCH coded). + // See Table 1 in Appendix D (pp.68) of JIS X0510:2004. + + // size: [QRSPEC_VERSION_MAX - 6] + + public static $versionPattern = array( + 0x07c94, 0x085bc, 0x09a99, 0x0a4d3, 0x0bbf6, 0x0c762, 0x0d847, 0x0e60d, + 0x0f928, 0x10b78, 0x1145d, 0x12a17, 0x13532, 0x149a6, 0x15683, 0x168c9, + 0x177ec, 0x18ec4, 0x191e1, 0x1afab, 0x1b08e, 0x1cc1a, 0x1d33f, 0x1ed75, + 0x1f250, 0x209d5, 0x216f0, 0x228ba, 0x2379f, 0x24b0b, 0x2542e, 0x26a64, + 0x27541, 0x28c69 + ); + + //---------------------------------------------------------------------- + public static function getVersionPattern($version) + { + if($version < 7 || $version > QRSPEC_VERSION_MAX) + return 0; + + return self::$versionPattern[$version -7]; + } + + // Format information -------------------------------------------------- + // See calcFormatInfo in tests/test_qrspec.c (orginal qrencode c lib) + + public static $formatInfo = array( + array(0x77c4, 0x72f3, 0x7daa, 0x789d, 0x662f, 0x6318, 0x6c41, 0x6976), + array(0x5412, 0x5125, 0x5e7c, 0x5b4b, 0x45f9, 0x40ce, 0x4f97, 0x4aa0), + array(0x355f, 0x3068, 0x3f31, 0x3a06, 0x24b4, 0x2183, 0x2eda, 0x2bed), + array(0x1689, 0x13be, 0x1ce7, 0x19d0, 0x0762, 0x0255, 0x0d0c, 0x083b) + ); + + public static function getFormatInfo($mask, $level) + { + if($mask < 0 || $mask > 7) + return 0; + + if($level < 0 || $level > 3) + return 0; + + return self::$formatInfo[$level][$mask]; + } + + // Frame --------------------------------------------------------------- + // Cache of initial frames. + + public static $frames = array(); + + /** -------------------------------------------------------------------- + * Put a finder pattern. + * @param frame + * @param width + * @param ox,oy upper-left coordinate of the pattern + */ + public static function putFinderPattern(&$frame, $ox, $oy) + { + $finder = array( + "\xc1\xc1\xc1\xc1\xc1\xc1\xc1", + "\xc1\xc0\xc0\xc0\xc0\xc0\xc1", + "\xc1\xc0\xc1\xc1\xc1\xc0\xc1", + "\xc1\xc0\xc1\xc1\xc1\xc0\xc1", + "\xc1\xc0\xc1\xc1\xc1\xc0\xc1", + "\xc1\xc0\xc0\xc0\xc0\xc0\xc1", + "\xc1\xc1\xc1\xc1\xc1\xc1\xc1" + ); + + for($y=0; $y<7; $y++) { + QRstr::set($frame, $ox, $oy+$y, $finder[$y]); + } + } + + //---------------------------------------------------------------------- + public static function createFrame($version) + { + $width = self::$capacity[$version][QRCAP_WIDTH]; + $frameLine = str_repeat ("\0", $width); + $frame = array_fill(0, $width, $frameLine); + + // Finder pattern + self::putFinderPattern($frame, 0, 0); + self::putFinderPattern($frame, $width - 7, 0); + self::putFinderPattern($frame, 0, $width - 7); + + // Separator + $yOffset = $width - 7; + + for($y=0; $y<7; $y++) { + $frame[$y][7] = "\xc0"; + $frame[$y][$width - 8] = "\xc0"; + $frame[$yOffset][7] = "\xc0"; + $yOffset++; + } + + $setPattern = str_repeat("\xc0", 8); + + QRstr::set($frame, 0, 7, $setPattern); + QRstr::set($frame, $width-8, 7, $setPattern); + QRstr::set($frame, 0, $width - 8, $setPattern); + + // Format info + $setPattern = str_repeat("\x84", 9); + QRstr::set($frame, 0, 8, $setPattern); + QRstr::set($frame, $width - 8, 8, $setPattern, 8); + + $yOffset = $width - 8; + + for($y=0; $y<8; $y++,$yOffset++) { + $frame[$y][8] = "\x84"; + $frame[$yOffset][8] = "\x84"; + } + + // Timing pattern + + for($i=1; $i<$width-15; $i++) { + $frame[6][7+$i] = chr(0x90 | ($i & 1)); + $frame[7+$i][6] = chr(0x90 | ($i & 1)); + } + + // Alignment pattern + self::putAlignmentPattern($version, $frame, $width); + + // Version information + if($version >= 7) { + $vinf = self::getVersionPattern($version); + + $v = $vinf; + + for($x=0; $x<6; $x++) { + for($y=0; $y<3; $y++) { + $frame[($width - 11)+$y][$x] = chr(0x88 | ($v & 1)); + $v = $v >> 1; + } + } + + $v = $vinf; + for($y=0; $y<6; $y++) { + for($x=0; $x<3; $x++) { + $frame[$y][$x+($width - 11)] = chr(0x88 | ($v & 1)); + $v = $v >> 1; + } + } + } + + // and a little bit... + $frame[$width - 8][8] = "\x81"; + + return $frame; + } + + //---------------------------------------------------------------------- + public static function debug($frame, $binary_mode = false) + { + if ($binary_mode) { + + foreach ($frame as &$frameLine) { + $frameLine = join('  ', explode('0', $frameLine)); + $frameLine = join('██', explode('1', $frameLine)); + } + + ?> + +


        '; + echo join("
        ", $frame); + echo '






'; + + } else { + + foreach ($frame as &$frameLine) { + $frameLine = join(' ', explode("\xc0", $frameLine)); + $frameLine = join('', explode("\xc1", $frameLine)); + $frameLine = join(' ', explode("\xa0", $frameLine)); + $frameLine = join('', explode("\xa1", $frameLine)); + $frameLine = join('', explode("\x84", $frameLine)); //format 0 + $frameLine = join('', explode("\x85", $frameLine)); //format 1 + $frameLine = join('', explode("\x81", $frameLine)); //special bit + $frameLine = join(' ', explode("\x90", $frameLine)); //clock 0 + $frameLine = join('', explode("\x91", $frameLine)); //clock 1 + $frameLine = join(' ', explode("\x88", $frameLine)); //version + $frameLine = join('', explode("\x89", $frameLine)); //version + $frameLine = join('♦', explode("\x01", $frameLine)); + $frameLine = join('⋅', explode("\0", $frameLine)); + } + + ?> + + "; + echo join("
", $frame); + echo "
"; + + } + } + + //---------------------------------------------------------------------- + public static function serial($frame) + { + return gzcompress(join("\n", $frame), 9); + } + + //---------------------------------------------------------------------- + public static function unserial($code) + { + return explode("\n", gzuncompress($code)); + } + + //---------------------------------------------------------------------- + public static function newFrame($version) + { + if($version < 1 || $version > QRSPEC_VERSION_MAX) + return null; + + if(!isset(self::$frames[$version])) { + + $fileName = QR_CACHE_DIR.'frame_'.$version.'.dat'; + + if (QR_CACHEABLE) { + if (file_exists($fileName)) { + self::$frames[$version] = self::unserial(file_get_contents($fileName)); + } else { + self::$frames[$version] = self::createFrame($version); + file_put_contents($fileName, self::serial(self::$frames[$version])); + } + } else { + self::$frames[$version] = self::createFrame($version); + } + } + + if(is_null(self::$frames[$version])) + return null; + + return self::$frames[$version]; + } + + //---------------------------------------------------------------------- + public static function rsBlockNum($spec) { return $spec[0] + $spec[3]; } + public static function rsBlockNum1($spec) { return $spec[0]; } + public static function rsDataCodes1($spec) { return $spec[1]; } + public static function rsEccCodes1($spec) { return $spec[2]; } + public static function rsBlockNum2($spec) { return $spec[3]; } + public static function rsDataCodes2($spec) { return $spec[4]; } + public static function rsEccCodes2($spec) { return $spec[2]; } + public static function rsDataLength($spec) { return ($spec[0] * $spec[1]) + ($spec[3] * $spec[4]); } + public static function rsEccLength($spec) { return ($spec[0] + $spec[3]) * $spec[2]; } + + } \ No newline at end of file diff --git a/application/libraries/qrcode/qrsplit.php b/application/libraries/qrcode/qrsplit.php new file mode 100644 index 00000000..8099c416 --- /dev/null +++ b/application/libraries/qrcode/qrsplit.php @@ -0,0 +1,311 @@ + + * + * PHP QR Code is distributed under LGPL 3 + * Copyright (C) 2010 Dominik Dzienia + * + * The following data / specifications are taken from + * "Two dimensional symbol -- QR-code -- Basic Specification" (JIS X0510:2004) + * or + * "Automatic identification and data capture techniques -- + * QR Code 2005 bar code symbology specification" (ISO/IEC 18004:2006) + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ + class QRsplit { + + public $dataStr = ''; + public $input; + public $modeHint; + + //---------------------------------------------------------------------- + public function __construct($dataStr, $input, $modeHint) + { + $this->dataStr = $dataStr; + $this->input = $input; + $this->modeHint = $modeHint; + } + + //---------------------------------------------------------------------- + public static function isdigitat($str, $pos) + { + if ($pos >= strlen($str)) + return false; + + return ((ord($str[$pos]) >= ord('0'))&&(ord($str[$pos]) <= ord('9'))); + } + + //---------------------------------------------------------------------- + public static function isalnumat($str, $pos) + { + if ($pos >= strlen($str)) + return false; + + return (QRinput::lookAnTable(ord($str[$pos])) >= 0); + } + + //---------------------------------------------------------------------- + public function identifyMode($pos) + { + if ($pos >= strlen($this->dataStr)) + return QR_MODE_NUL; + + $c = $this->dataStr[$pos]; + + if(self::isdigitat($this->dataStr, $pos)) { + return QR_MODE_NUM; + } else if(self::isalnumat($this->dataStr, $pos)) { + return QR_MODE_AN; + } else if($this->modeHint == QR_MODE_KANJI) { + + if ($pos+1 < strlen($this->dataStr)) + { + $d = $this->dataStr[$pos+1]; + $word = (ord($c) << 8) | ord($d); + if(($word >= 0x8140 && $word <= 0x9ffc) || ($word >= 0xe040 && $word <= 0xebbf)) { + return QR_MODE_KANJI; + } + } + } + + return QR_MODE_8; + } + + //---------------------------------------------------------------------- + public function eatNum() + { + $ln = QRspec::lengthIndicator(QR_MODE_NUM, $this->input->getVersion()); + + $p = 0; + while(self::isdigitat($this->dataStr, $p)) { + $p++; + } + + $run = $p; + $mode = $this->identifyMode($p); + + if($mode == QR_MODE_8) { + $dif = QRinput::estimateBitsModeNum($run) + 4 + $ln + + QRinput::estimateBitsMode8(1) // + 4 + l8 + - QRinput::estimateBitsMode8($run + 1); // - 4 - l8 + if($dif > 0) { + return $this->eat8(); + } + } + if($mode == QR_MODE_AN) { + $dif = QRinput::estimateBitsModeNum($run) + 4 + $ln + + QRinput::estimateBitsModeAn(1) // + 4 + la + - QRinput::estimateBitsModeAn($run + 1);// - 4 - la + if($dif > 0) { + return $this->eatAn(); + } + } + + $ret = $this->input->append(QR_MODE_NUM, $run, str_split($this->dataStr)); + if($ret < 0) + return -1; + + return $run; + } + + //---------------------------------------------------------------------- + public function eatAn() + { + $la = QRspec::lengthIndicator(QR_MODE_AN, $this->input->getVersion()); + $ln = QRspec::lengthIndicator(QR_MODE_NUM, $this->input->getVersion()); + + $p = 0; + + while(self::isalnumat($this->dataStr, $p)) { + if(self::isdigitat($this->dataStr, $p)) { + $q = $p; + while(self::isdigitat($this->dataStr, $q)) { + $q++; + } + + $dif = QRinput::estimateBitsModeAn($p) // + 4 + la + + QRinput::estimateBitsModeNum($q - $p) + 4 + $ln + - QRinput::estimateBitsModeAn($q); // - 4 - la + + if($dif < 0) { + break; + } else { + $p = $q; + } + } else { + $p++; + } + } + + $run = $p; + + if(!self::isalnumat($this->dataStr, $p)) { + $dif = QRinput::estimateBitsModeAn($run) + 4 + $la + + QRinput::estimateBitsMode8(1) // + 4 + l8 + - QRinput::estimateBitsMode8($run + 1); // - 4 - l8 + if($dif > 0) { + return $this->eat8(); + } + } + + $ret = $this->input->append(QR_MODE_AN, $run, str_split($this->dataStr)); + if($ret < 0) + return -1; + + return $run; + } + + //---------------------------------------------------------------------- + public function eatKanji() + { + $p = 0; + + while($this->identifyMode($p) == QR_MODE_KANJI) { + $p += 2; + } + + $ret = $this->input->append(QR_MODE_KANJI, $p, str_split($this->dataStr)); + if($ret < 0) + return -1; + + return $run; + } + + //---------------------------------------------------------------------- + public function eat8() + { + $la = QRspec::lengthIndicator(QR_MODE_AN, $this->input->getVersion()); + $ln = QRspec::lengthIndicator(QR_MODE_NUM, $this->input->getVersion()); + + $p = 1; + $dataStrLen = strlen($this->dataStr); + + while($p < $dataStrLen) { + + $mode = $this->identifyMode($p); + if($mode == QR_MODE_KANJI) { + break; + } + if($mode == QR_MODE_NUM) { + $q = $p; + while(self::isdigitat($this->dataStr, $q)) { + $q++; + } + $dif = QRinput::estimateBitsMode8($p) // + 4 + l8 + + QRinput::estimateBitsModeNum($q - $p) + 4 + $ln + - QRinput::estimateBitsMode8($q); // - 4 - l8 + if($dif < 0) { + break; + } else { + $p = $q; + } + } else if($mode == QR_MODE_AN) { + $q = $p; + while(self::isalnumat($this->dataStr, $q)) { + $q++; + } + $dif = QRinput::estimateBitsMode8($p) // + 4 + l8 + + QRinput::estimateBitsModeAn($q - $p) + 4 + $la + - QRinput::estimateBitsMode8($q); // - 4 - l8 + if($dif < 0) { + break; + } else { + $p = $q; + } + } else { + $p++; + } + } + + $run = $p; + $ret = $this->input->append(QR_MODE_8, $run, str_split($this->dataStr)); + + if($ret < 0) + return -1; + + return $run; + } + + //---------------------------------------------------------------------- + public function splitString() + { + while (strlen($this->dataStr) > 0) + { + if($this->dataStr == '') + return 0; + + $mode = $this->identifyMode(0); + + switch ($mode) { + case QR_MODE_NUM: $length = $this->eatNum(); break; + case QR_MODE_AN: $length = $this->eatAn(); break; + case QR_MODE_KANJI: + if ($hint == QR_MODE_KANJI) + $length = $this->eatKanji(); + else $length = $this->eat8(); + break; + default: $length = $this->eat8(); break; + + } + + if($length == 0) return 0; + if($length < 0) return -1; + + $this->dataStr = substr($this->dataStr, $length); + } + } + + //---------------------------------------------------------------------- + public function toUpper() + { + $stringLen = strlen($this->dataStr); + $p = 0; + + while ($p<$stringLen) { + $mode = self::identifyMode(substr($this->dataStr, $p), $this->modeHint); + if($mode == QR_MODE_KANJI) { + $p += 2; + } else { + if (ord($this->dataStr[$p]) >= ord('a') && ord($this->dataStr[$p]) <= ord('z')) { + $this->dataStr[$p] = chr(ord($this->dataStr[$p]) - 32); + } + $p++; + } + } + + return $this->dataStr; + } + + //---------------------------------------------------------------------- + public static function splitStringToQRinput($string, QRinput $input, $modeHint, $casesensitive = true) + { + if(is_null($string) || $string == '\0' || $string == '') { + throw new Exception('empty string!!!'); + } + + $split = new QRsplit($string, $input, $modeHint); + + if(!$casesensitive) + $split->toUpper(); + + return $split->splitString(); + } + } \ No newline at end of file diff --git a/application/libraries/qrcode/qrtools.php b/application/libraries/qrcode/qrtools.php new file mode 100644 index 00000000..e0412c43 --- /dev/null +++ b/application/libraries/qrcode/qrtools.php @@ -0,0 +1,172 @@ + + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ + + class QRtools { + + //---------------------------------------------------------------------- + public static function binarize($frame) + { + $len = count($frame); + foreach ($frame as &$frameLine) { + + for($i=0; $i<$len; $i++) { + $frameLine[$i] = (ord($frameLine[$i])&1)?'1':'0'; + } + } + + return $frame; + } + + //---------------------------------------------------------------------- + public static function tcpdfBarcodeArray($code, $mode = 'QR,L', $tcPdfVersion = '4.5.037') + { + $barcode_array = array(); + + if (!is_array($mode)) + $mode = explode(',', $mode); + + $eccLevel = 'L'; + + if (count($mode) > 1) { + $eccLevel = $mode[1]; + } + + $qrTab = QRcode::text($code, false, $eccLevel); + $size = count($qrTab); + + $barcode_array['num_rows'] = $size; + $barcode_array['num_cols'] = $size; + $barcode_array['bcode'] = array(); + + foreach ($qrTab as $line) { + $arrAdd = array(); + foreach(str_split($line) as $char) + $arrAdd[] = ($char=='1')?1:0; + $barcode_array['bcode'][] = $arrAdd; + } + + return $barcode_array; + } + + //---------------------------------------------------------------------- + public static function clearCache() + { + self::$frames = array(); + } + + //---------------------------------------------------------------------- + public static function buildCache() + { + QRtools::markTime('before_build_cache'); + + $mask = new QRmask(); + for ($a=1; $a <= QRSPEC_VERSION_MAX; $a++) { + $frame = QRspec::newFrame($a); + if (QR_IMAGE) { + $fileName = QR_CACHE_DIR.'frame_'.$a.'.png'; + QRimage::png(self::binarize($frame), $fileName, 1, 0); + } + + $width = count($frame); + $bitMask = array_fill(0, $width, array_fill(0, $width, 0)); + for ($maskNo=0; $maskNo<8; $maskNo++) + $mask->makeMaskNo($maskNo, $width, $frame, $bitMask, true); + } + + QRtools::markTime('after_build_cache'); + } + + //---------------------------------------------------------------------- + public static function log($outfile, $err) + { + if (QR_LOG_DIR !== false) { + if ($err != '') { + if ($outfile !== false) { + file_put_contents(QR_LOG_DIR.basename($outfile).'-errors.txt', date('Y-m-d H:i:s').': '.$err, FILE_APPEND); + } else { + file_put_contents(QR_LOG_DIR.'errors.txt', date('Y-m-d H:i:s').': '.$err, FILE_APPEND); + } + } + } + } + + //---------------------------------------------------------------------- + public static function dumpMask($frame) + { + $width = count($frame); + for($y=0;$y<$width;$y++) { + for($x=0;$x<$width;$x++) { + echo ord($frame[$y][$x]).','; + } + } + } + + //---------------------------------------------------------------------- + public static function markTime($markerId) + { + list($usec, $sec) = explode(" ", microtime()); + $time = ((float)$usec + (float)$sec); + + if (!isset($GLOBALS['qr_time_bench'])) + $GLOBALS['qr_time_bench'] = array(); + + $GLOBALS['qr_time_bench'][$markerId] = $time; + } + + //---------------------------------------------------------------------- + public static function timeBenchmark() + { + self::markTime('finish'); + + $lastTime = 0; + $startTime = 0; + $p = 0; + + echo ' + + '; + + foreach($GLOBALS['qr_time_bench'] as $markerId=>$thisTime) { + if ($p > 0) { + echo ''; + } else { + $startTime = $thisTime; + } + + $p++; + $lastTime = $thisTime; + } + + echo ' + + +
BENCHMARK
till '.$markerId.': '.number_format($thisTime-$lastTime, 6).'s
TOTAL: '.number_format($lastTime-$startTime, 6).'s
'; + } + + } + + //########################################################################## + + QRtools::markTime('start'); + \ No newline at end of file diff --git a/application/logs/index.html b/application/logs/index.html new file mode 100755 index 00000000..b702fbc3 --- /dev/null +++ b/application/logs/index.html @@ -0,0 +1,11 @@ + + + + 403 Forbidden + + + +

Directory access is forbidden.

+ + + diff --git a/application/models/index.html b/application/models/index.html new file mode 100755 index 00000000..b702fbc3 --- /dev/null +++ b/application/models/index.html @@ -0,0 +1,11 @@ + + + + 403 Forbidden + + + +

Directory access is forbidden.

+ + + diff --git a/application/views/errors/cli/error_404.php b/application/views/errors/cli/error_404.php new file mode 100755 index 00000000..6984b61e --- /dev/null +++ b/application/views/errors/cli/error_404.php @@ -0,0 +1,8 @@ + + +An uncaught Exception was encountered + +Type: +Message: +Filename: getFile(), "\n"; ?> +Line Number: getLine(); ?> + + + +Backtrace: +getTrace() as $error): ?> + + File: + Line: + Function: + + + + diff --git a/application/views/errors/cli/error_general.php b/application/views/errors/cli/error_general.php new file mode 100755 index 00000000..6984b61e --- /dev/null +++ b/application/views/errors/cli/error_general.php @@ -0,0 +1,8 @@ + + +A PHP Error was encountered + +Severity: +Message: +Filename: +Line Number: + + + +Backtrace: + + + File: + Line: + Function: + + + + diff --git a/application/views/errors/cli/index.html b/application/views/errors/cli/index.html new file mode 100755 index 00000000..b702fbc3 --- /dev/null +++ b/application/views/errors/cli/index.html @@ -0,0 +1,11 @@ + + + + 403 Forbidden + + + +

Directory access is forbidden.

+ + + diff --git a/application/views/errors/html/error_404.php b/application/views/errors/html/error_404.php new file mode 100755 index 00000000..756ea9d6 --- /dev/null +++ b/application/views/errors/html/error_404.php @@ -0,0 +1,64 @@ + + + + +404 Page Not Found + + + +
+

+ +
+ + \ No newline at end of file diff --git a/application/views/errors/html/error_db.php b/application/views/errors/html/error_db.php new file mode 100755 index 00000000..f5a43f63 --- /dev/null +++ b/application/views/errors/html/error_db.php @@ -0,0 +1,64 @@ + + + + +Database Error + + + +
+

+ +
+ + \ No newline at end of file diff --git a/application/views/errors/html/error_exception.php b/application/views/errors/html/error_exception.php new file mode 100755 index 00000000..87848866 --- /dev/null +++ b/application/views/errors/html/error_exception.php @@ -0,0 +1,32 @@ + + +
+ +

An uncaught Exception was encountered

+ +

Type:

+

Message:

+

Filename: getFile(); ?>

+

Line Number: getLine(); ?>

+ + + +

Backtrace:

+ getTrace() as $error): ?> + + + +

+ File:
+ Line:
+ Function: +

+ + + + + + +
\ No newline at end of file diff --git a/application/views/errors/html/error_general.php b/application/views/errors/html/error_general.php new file mode 100755 index 00000000..fc3b2eba --- /dev/null +++ b/application/views/errors/html/error_general.php @@ -0,0 +1,64 @@ + + + + +Error + + + +
+

+ +
+ + \ No newline at end of file diff --git a/application/views/errors/html/error_php.php b/application/views/errors/html/error_php.php new file mode 100755 index 00000000..b146f9c5 --- /dev/null +++ b/application/views/errors/html/error_php.php @@ -0,0 +1,33 @@ + + +
+ +

A PHP Error was encountered

+ +

Severity:

+

Message:

+

Filename:

+

Line Number:

+ + + +

Backtrace:

+ + + + +

+ File:
+ Line:
+ Function: +

+ + + + + + + +
\ No newline at end of file diff --git a/application/views/errors/html/index.html b/application/views/errors/html/index.html new file mode 100755 index 00000000..b702fbc3 --- /dev/null +++ b/application/views/errors/html/index.html @@ -0,0 +1,11 @@ + + + + 403 Forbidden + + + +

Directory access is forbidden.

+ + + diff --git a/application/views/errors/index.html b/application/views/errors/index.html new file mode 100755 index 00000000..b702fbc3 --- /dev/null +++ b/application/views/errors/index.html @@ -0,0 +1,11 @@ + + + + 403 Forbidden + + + +

Directory access is forbidden.

+ + + diff --git a/application/views/index.html b/application/views/index.html new file mode 100755 index 00000000..b702fbc3 --- /dev/null +++ b/application/views/index.html @@ -0,0 +1,11 @@ + + + + 403 Forbidden + + + +

Directory access is forbidden.

+ + + diff --git a/application/views/welcome_message.php b/application/views/welcome_message.php new file mode 100755 index 00000000..f5115630 --- /dev/null +++ b/application/views/welcome_message.php @@ -0,0 +1,89 @@ + + + + + Welcome to CodeIgniter + + + + + +
+

Welcome to CodeIgniter!

+ +
+

The page you are looking at is being generated dynamically by CodeIgniter.

+ +

If you would like to edit this page you'll find it located at:

+ application/views/welcome_message.php + +

The corresponding controller for this page is found at:

+ application/controllers/Welcome.php + +

If you are exploring CodeIgniter for the very first time, you should start by reading the User Guide.

+
+ + +
+ + + \ No newline at end of file