diff --git a/debian/changelog b/debian/changelog index ccad4f97..a44286db 100644 --- a/debian/changelog +++ b/debian/changelog @@ -1,4 +1,4 @@ -hedera-web (1.406.02) stable; urgency=low +hedera-web (1.406.03) stable; urgency=low * Initial Release. diff --git a/env.php b/env.php index 7cefb9ad..e75811c3 100644 --- a/env.php +++ b/env.php @@ -2,7 +2,7 @@ require_once __DIR__.'/../php-vn-lib/env.php'; -set_include_path (__DIR__.PATH_SEPARATOR.get_include_path ()); +set_include_path(__DIR__.PATH_SEPARATOR.get_include_path()); $vnAutoloadMap['vn/web'] = __DIR__.'/web'; diff --git a/hedera-web.php b/hedera-web.php index 64b37b43..0d015db5 100755 --- a/hedera-web.php +++ b/hedera-web.php @@ -4,5 +4,5 @@ @include_once __DIR__.'/env.php'; require_once 'vn-autoload.php'; -$cliApp = new Vn\Lib\CliApp ('hedera-web', __DIR__.'/rest'); -$cliApp->run (); +$cliApp = new Vn\Lib\CliApp('hedera-web', __DIR__.'/rest'); +$cliApp->run(); diff --git a/index.php b/index.php index 02b59a37..65eaed97 100644 --- a/index.php +++ b/index.php @@ -3,5 +3,5 @@ @include_once __DIR__.'/env.php'; require_once 'vn-autoload.php'; -$webApp = new Vn\Web\App ('hedera-web'); -$webApp->run (); +$webApp = new Vn\Web\App('hedera-web'); +$webApp->run(); diff --git a/package.json b/package.json index f1abb847..6687e44a 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "hedera-web", - "version": "1.406.02", + "version": "1.406.03", "description": "Verdnatura web page", "license": "GPL-3.0", "repository": { diff --git a/pages/main/ui.php b/pages/main/ui.php index 9d842d74..d3cb3081 100644 --- a/pages/main/ui.php +++ b/pages/main/ui.php @@ -1,7 +1,7 @@ query ('SELECT name, content FROM metatag'); +$lang = Vn\Lib\Locale::get(); +$result = $db->query('SELECT name, content FROM metatag'); ?> @@ -18,11 +18,11 @@ $result = $db->query ('SELECT name, content FROM metatag'); - fetch_object ()): ?> + fetch_object()): ?> - + diff --git a/rest/core/account.php b/rest/core/account.php index 17403c97..c0f35398 100644 --- a/rest/core/account.php +++ b/rest/core/account.php @@ -1,10 +1,8 @@ getValue ( +class Account { + static function trySync($db, $userName, $password = NULL) { + $isSync = $db->getValue( 'SELECT sync FROM account.user WHERE name = #', [$userName] ); @@ -12,12 +10,11 @@ class Account if ($isSync) return; - self::sync ($db, $userName, $password); + self::sync($db, $userName, $password); } - static function sync ($db, $userName, $password = NULL, $force = TRUE) - { - $hasAccount = $db->getValue ( + static function sync($db, $userName, $password = NULL, $force = TRUE) { + $hasAccount = $db->getValue( 'SELECT COUNT(*) > 0 FROM account.user u JOIN account.account a ON u.id = a.id @@ -25,13 +22,12 @@ class Account [$userName] ); - if ($hasAccount) - { - self::ldapSync ($db, $userName, $password); - self::sambaSync ($db, $userName, $password); + if ($hasAccount) { + self::ldapSync($db, $userName, $password); + self::sambaSync($db, $userName, $password); } - $db->query ( + $db->query( 'UPDATE account.user SET sync = TRUE WHERE name = #', [$userName] ); @@ -40,47 +36,46 @@ class Account /** * Synchronizes the user credentials in the LDAP server. */ - static function ldapSync ($db, $userName, $password) - { + static function ldapSync($db, $userName, $password) { // Gets LDAP configuration parameters - $conf = $db->getObject ( + $conf = $db->getObject( 'SELECT host, rdn, password, baseDn, filter FROM account.ldapConfig'); // Connects an authenticates against server - $ds = ldap_connect ($conf->host); + $ds = ldap_connect($conf->host); if (!$ds) - throw new Exception ("Can't connect to LDAP server: ". ldapError ($ds)); + throw new Exception("Can't connect to LDAP server: ". ldapError($ds)); try { ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3); - $bind = ldap_bind ($ds, $conf->rdn, base64_decode ($conf->password)); + $bind = ldap_bind($ds, $conf->rdn, base64_decode($conf->password)); if (!$bind) - throw new Exception ("Authentication failed on LDAP server: ". ldapError ($ds)); + throw new Exception("Authentication failed on LDAP server: ". ldapError($ds)); // Prepares the data - $domain = $db->getValue ('SELECT domain FROM account.mailConfig'); + $domain = $db->getValue('SELECT domain FROM account.mailConfig'); - $user = $db->getObject ( + $user = $db->getObject( 'SELECT id, nickname, lang FROM account.user WHERE name = #', [$userName] ); - $cn = empty ($user->nickname) ? $userName : $user->nickname; + $cn = empty($user->nickname) ? $userName : $user->nickname; - $nameArgs = explode (' ', $user->nickname); + $nameArgs = explode(' ', $user->nickname); $givenName = $nameArgs[0]; - if (count ($nameArgs) > 1) + if (count($nameArgs) > 1) $sn = $nameArgs[1]; - if (empty ($sn)) + if (empty($sn)) $sn = 'Empty'; $attrs = [ @@ -89,7 +84,7 @@ class Account 'givenName' => $givenName, 'sn' => $sn, 'mail' => "$userName@{$domain}", - 'userPassword' => sshaEncode ($password), + 'userPassword' => sshaEncode($password), 'preferredLanguage' => $user->lang ]; @@ -100,67 +95,61 @@ class Account if (!empty($conf->filter)) $filter = "(&($filter)($conf->filter))"; - $res = ldap_search ($ds, $conf->baseDn, $filter); + $res = ldap_search($ds, $conf->baseDn, $filter); if (!$res) - throw new Exception ("Can't get the LDAP entry: ". ldapError ($ds)); + throw new Exception("Can't get the LDAP entry: ". ldapError($ds)); $dn = "uid=$userName,{$conf->baseDn}"; - $entry = ldap_first_entry ($ds, $res); + $entry = ldap_first_entry($ds, $res); - $classes = ldap_get_values ($ds, $entry, 'objectClass'); + $classes = ldap_get_values($ds, $entry, 'objectClass'); - if (!in_array ('inetOrgPerson', $classes)) - { - ldap_delete ($ds, $dn); + if (!in_array('inetOrgPerson', $classes)) { + ldap_delete($ds, $dn); $entry = NULL; } - if ($entry) - { + if ($entry) { $modifs = []; - $curAttrs = ldap_get_attributes ($ds, $entry); + $curAttrs = ldap_get_attributes($ds, $entry); - foreach ($attrs as $attribute => $value) - if (!empty ($value)) - { + foreach($attrs as $attribute => $value) + if (!empty($value)) { $modifs[] = [ 'attrib' => $attribute, 'modtype' => LDAP_MODIFY_BATCH_REPLACE, 'values' => [$value] ]; } - elseif (isset ($curAttrs[$attribute])) - { + elseif (isset($curAttrs[$attribute])) { $modifs[] = [ 'attrib' => $attribute, 'modtype' => LDAP_MODIFY_BATCH_REMOVE_ALL ]; } - $updated = ldap_modify_batch ($ds, $dn, $modifs); + $updated = ldap_modify_batch($ds, $dn, $modifs); } - else - { + else { $addAttrs = []; - foreach ($attrs as $attribute => $value) - if (!empty ($value)) + foreach($attrs as $attribute => $value) + if (!empty($value)) $addAttrs[$attribute] = $value; - $addAttrs = array_merge ($addAttrs, [ + $addAttrs = array_merge($addAttrs, [ 'objectClass' => ['inetOrgPerson'], 'uid' => $userName ]); - $updated = ldap_add ($ds, $dn, $addAttrs); + $updated = ldap_add($ds, $dn, $addAttrs); } if (!$updated) - throw new Exception ("Can't update the LDAP entry: ". ldapError ($ds)); + throw new Exception("Can't update the LDAP entry: ". ldapError($ds)); } - catch (Exception $e) - { - ldap_unbind ($ds); + catch (Exception $e) { + ldap_unbind($ds); throw $e; } } @@ -168,28 +157,27 @@ class Account /** * Synchronizes the user credentials in the Samba server. */ - static function sambaSync ($db, $userName, $password) - { - $conf = $db->getObject ( + static function sambaSync($db, $userName, $password) { + $conf = $db->getObject( 'SELECT host, sshUser, sshPass, uidBase FROM account.sambaConfig' ); - $domain = $db->getValue ('SELECT domain FROM account.mailConfig'); + $domain = $db->getValue('SELECT domain FROM account.mailConfig'); - $samba = new SshConnection ($conf->host + $samba = new SshConnection($conf->host ,$conf->sshUser - ,base64_decode ($conf->sshPass) + ,base64_decode($conf->sshPass) ); $scriptDir = '/mnt/cluster/scripts'; // Creates the Samba user and initializes it's home directory - $userId = $db->getValue ( + $userId = $db->getValue( 'SELECT id FROM account.user WHERE name = #', [$userName]); - $samba->exec ("$scriptDir/create-user.sh %s %s %s" + $samba->exec("$scriptDir/create-user.sh %s %s %s" ,$userName ,$conf->uidBase + $userId ,"$userName@{$domain}" @@ -197,56 +185,51 @@ class Account // Syncronizes the Samba password - if (empty ($password)) + if (empty($password)) return; - $samba->exec ("$scriptDir/set-password.sh %s %s" + $samba->exec("$scriptDir/set-password.sh %s %s" ,$userName ,$password ); } } -function ldapError ($ds) -{ - return ldap_errno ($ds) .': '. ldap_error ($ds); +function ldapError($ds) { + return ldap_errno($ds) .': '. ldap_error($ds); } -function sshaEncode ($value) -{ - mt_srand ((double) microtime () * 1000000); - $salt = pack ('CCCC', mt_rand (), mt_rand (), mt_rand (), mt_rand ()); - $hash = '{SSHA}' . base64_encode (pack ('H*', sha1 ($value . $salt)) . $salt); +function sshaEncode($value) { + mt_srand((double) microtime() * 1000000); + $salt = pack('CCCC', mt_rand(), mt_rand(), mt_rand(), mt_rand()); + $hash = '{SSHA}' . base64_encode(pack('H*', sha1($value . $salt)) . $salt); return $hash; } -function sshaVerify ($hash, $value) -{ - $ohash = base64_decode (substr ($hash, 6)); - $osalt = substr ($ohash, 20); - $ohash = substr ($ohash, 0, 20); - $nhash = pack ('H*', sha1 ($value . $osalt)); +function sshaVerify($hash, $value) { + $ohash = base64_decode(substr($hash, 6)); + $osalt = substr($ohash, 20); + $ohash = substr($ohash, 0, 20); + $nhash = pack('H*', sha1($value . $osalt)); return $ohash == $nhash; } -class SshConnection -{ +class SshConnection { var $connection; /** * Abrebiated method to make SSH connections. */ - function __construct ($host, $user, $password) - { - $this->connection = $connection = ssh2_connect ($host); + function __construct($host, $user, $password) { + $this->connection = $connection = ssh2_connect($host); if (!$connection) - throw new Exception ("Can't connect to SSH server $host"); + throw new Exception("Can't connect to SSH server $host"); - $authOk = ssh2_auth_password ($connection, $user, $password); + $authOk = ssh2_auth_password($connection, $user, $password); if (!$authOk) - throw new Exception ("SSH authentication failed on server $host"); + throw new Exception("SSH authentication failed on server $host"); return $connection; } @@ -254,23 +237,21 @@ class SshConnection /** * Executes a command on the host. */ - function exec () - { - $nargs = func_num_args (); - $args = func_get_args (); + function exec() { + $nargs = func_num_args(); + $args = func_get_args(); for ($i = 1; $i < $nargs; $i++) - $args[$i] = self::escape ($args[$i]); + $args[$i] = self::escape($args[$i]); - $command = call_user_func_array ('sprintf', $args); - return ssh2_exec ($this->connection, $command); + $command = call_user_func_array('sprintf', $args); + return ssh2_exec($this->connection, $command); } /** * Escapes the double quotes from an string. */ - static function escape ($str) - { - return '"'. str_replace ('"', '\\"', $str) .'"'; + static function escape($str) { + return '"'. str_replace('"', '\\"', $str) .'"'; } } diff --git a/rest/core/captcha.php b/rest/core/captcha.php index c3fb6d67..62b88fba 100644 --- a/rest/core/captcha.php +++ b/rest/core/captcha.php @@ -1,12 +1,10 @@ 130 @@ -24,23 +22,23 @@ class Captcha extends Vn\Web\RestRequest ] ]; - $captcha = Text_CAPTCHA::factory ('Image'); - $retval = $captcha->init ($options); + $captcha = Text_CAPTCHA::factory('Image'); + $retval = $captcha->init($options); - if (PEAR::isError ($retval)) - throw new Exception ('Error initializing CAPTCHA: %s!', + if (PEAR::isError($retval)) + throw new Exception('Error initializing CAPTCHA: %s!', $retval->getMessage()); - $png = $captcha->getCAPTCHA (); + $png = $captcha->getCAPTCHA(); - if (PEAR::isError ($png)) - throw new Exception ('Error generating CAPTCHA: %s!', - $png->getMessage ()); + if (PEAR::isError($png)) + throw new Exception('Error generating CAPTCHA: %s!', + $png->getMessage()); // Get secret passphrase - $_SESSION['captcha'] = $captcha->getPhrase (); + $_SESSION['captcha'] = $captcha->getPhrase(); - header ('Content-Type: image/png'); + header('Content-Type: image/png'); echo $png; } } diff --git a/rest/core/change-password.php b/rest/core/change-password.php index bcec4a98..cb421b0a 100644 --- a/rest/core/change-password.php +++ b/rest/core/change-password.php @@ -5,18 +5,16 @@ include __DIR__.'/account.php'; /** * Updates the user password. **/ -class ChangePassword extends Vn\Web\JsonRequest -{ +class ChangePassword extends Vn\Web\JsonRequest { const PARAMS = ['newPassword']; - function run ($db) - { + function run($db) { $newPassword = $_REQUEST['newPassword']; $oldPassword = $_REQUEST['oldPassword']; - $db->query ('CALL account.myUserChangePassword (#, #)', + $db->query('CALL account.myUserChangePassword(#, #)', [$oldPassword, $newPassword]); - Account::sync ($db, $_SESSION['user'], $newPassword); + Account::sync($db, $_SESSION['user'], $newPassword); return TRUE; } } diff --git a/rest/core/log.php b/rest/core/log.php index a0208251..12b44a69 100644 --- a/rest/core/log.php +++ b/rest/core/log.php @@ -1,7 +1,6 @@ getMessage()); + catch (Exception $e) { + error_log($e->getMessage()); } - $token = $this->service->createToken ( + $token = $this->service->createToken( $_SESSION['user'], - !empty ($_POST['remember']) + !empty($_POST['remember']) ); return [ diff --git a/rest/core/logout.php b/rest/core/logout.php index ad4b8945..632c5461 100644 --- a/rest/core/logout.php +++ b/rest/core/logout.php @@ -1,10 +1,8 @@ service->logout (); +class Logout extends Vn\Web\JsonRequest { + function run($db) { + $this->service->logout(); return TRUE; } } diff --git a/rest/core/query.php b/rest/core/query.php index cce67e9b..56a5e98a 100644 --- a/rest/core/query.php +++ b/rest/core/query.php @@ -4,63 +4,56 @@ use Vn\Lib; use Vn\Web\Security; use Vn\Lib\Type; -class Query extends Vn\Web\JsonRequest -{ +class Query extends Vn\Web\JsonRequest { const PARAMS = ['sql']; const SECURITY = Security::INVOKER; - function run ($db) - { + function run($db) { $results = []; try { - $db->multiQuery ($_REQUEST['sql']); + $db->multiQuery($_REQUEST['sql']); do { - $result = $db->storeResult (); + $result = $db->storeResult(); - if ($result !== FALSE) - { - $results[] = $this->transformResult ($result); - $result->free (); + if ($result !== FALSE) { + $results[] = $this->transformResult($result); + $result->free(); } else $results[] = TRUE; } - while ($db->moreResults () && $db->nextResult ()); + while ($db->moreResults() && $db->nextResult()); // Checks for warnings - if ($db->checkWarnings () - && ($result = $db->query ('SHOW WARNINGS'))) - { + if ($db->checkWarnings() + &&($result = $db->query('SHOW WARNINGS'))) { $sql = 'SELECT `description`, @warn `code` FROM `message` WHERE `code` = @warn'; - while ($row = $result->fetch_object ()) - { + while ($row = $result->fetch_object()) { if ($row->Code == 1265 - && ($warning = $db->getObject ($sql))) - trigger_error ("{$warning->code}: {$warning->description}", E_USER_WARNING); + &&($warning = $db->getObject($sql))) + trigger_error("{$warning->code}: {$warning->description}", E_USER_WARNING); else - trigger_error ("{$row->Code}: {$row->Message}", E_USER_WARNING); + trigger_error("{$row->Code}: {$row->Message}", E_USER_WARNING); } } // Checks for errors - $db->checkError (); + $db->checkError(); } - catch (Vn\Db\Exception $e) - { - if ($e->getCode () == 1644) - { - $dbMessage = $e->getMessage (); + catch (Vn\Db\Exception $e) { + if ($e->getCode() == 1644) { + $dbMessage = $e->getMessage(); $sql = 'SELECT `description` FROM `message` WHERE `code` = #'; - $message = $db->getValue ($sql, [$dbMessage]); + $message = $db->getValue($sql, [$dbMessage]); if ($message) - throw new Lib\UserException ($message, $dbMessage); + throw new Lib\UserException($message, $dbMessage); } throw $e; @@ -72,10 +65,9 @@ class Query extends Vn\Web\JsonRequest /** * Transforms the database result into a JSON parseable object. **/ - function transformResult ($result) - { + function transformResult($result) { $tableMap = []; - $columns = $result->fetch_fields (); + $columns = $result->fetch_fields(); $resultMap = [ @@ -84,12 +76,10 @@ class Query extends Vn\Web\JsonRequest 'tables' => [] ]; - for ($i = 0; $i < $result->field_count; $i++) - { + for ($i = 0; $i < $result->field_count; $i++) { $column = $columns[$i]; - switch ($column->type) - { + switch ($column->type) { case MYSQLI_TYPE_BIT: $type = Type::BOOLEAN; break; @@ -118,8 +108,7 @@ class Query extends Vn\Web\JsonRequest $type = Type::STRING; } - if (!isset ($tableMap[$column->table])) - { + if (!isset($tableMap[$column->table])) { $resultMap['tables'][] = [ 'name' => $column->table, @@ -127,7 +116,7 @@ class Query extends Vn\Web\JsonRequest 'schema' => $column->db, 'pks' => [] ]; - $tableIndex = count ($resultMap['tables']) - 1; + $tableIndex = count($resultMap['tables']) - 1; $tableMap[$column->table] = $tableIndex; } else @@ -136,7 +125,7 @@ class Query extends Vn\Web\JsonRequest if ($column->flags & MYSQLI_PRI_KEY_FLAG) $resultMap['tables'][$tableIndex]['pks'][] = $i; - $default = $this->castValue ($column->def, $type); + $default = $this->castValue($column->def, $type); $resultMap['columns'][] = [ @@ -151,10 +140,9 @@ class Query extends Vn\Web\JsonRequest $columns = $resultMap['columns']; - while ($row = $result->fetch_row ()) - { + while ($row = $result->fetch_row()) { for ($j = 0; $j < $result->field_count; $j++) - $row[$j] = $this->castValue ($row[$j], $columns[$j]['type']); + $row[$j] = $this->castValue($row[$j], $columns[$j]['type']); $resultMap['data'][] = $row; } @@ -165,11 +153,9 @@ class Query extends Vn\Web\JsonRequest /** * Transforms the database value into a JSON parseable value. **/ - function castValue ($value, $type) - { + function castValue($value, $type) { if ($value !== NULL) - switch ($type) - { + switch ($type) { case Type::BOOLEAN: return (bool) $value; case Type::INTEGER: @@ -178,14 +164,13 @@ class Query extends Vn\Web\JsonRequest return (float) $value; case Type::DATE: case Type::DATE_TIME: - return mktime - ( - substr ($value, 11 , 2) - ,substr ($value, 14 , 2) - ,substr ($value, 17 , 2) - ,substr ($value, 5 , 2) - ,substr ($value, 8 , 2) - ,substr ($value, 0 , 4) + return mktime( + substr($value, 11 , 2) + ,substr($value, 14 , 2) + ,substr($value, 17 , 2) + ,substr($value, 5 , 2) + ,substr($value, 8 , 2) + ,substr($value, 0 , 4) ); break; } diff --git a/rest/core/recover-password.php b/rest/core/recover-password.php index 18bf11ce..9e59d0d7 100644 --- a/rest/core/recover-password.php +++ b/rest/core/recover-password.php @@ -2,13 +2,11 @@ use Vn\Web; -class RecoverPassword extends Vn\Web\JsonRequest -{ +class RecoverPassword extends Vn\Web\JsonRequest { const PARAMS = ['recoverUser']; - function run ($db) - { - $user = $db->getRow ( + function run($db) { + $user = $db->getRow( 'SELECT email, active FROM account.user WHERE name = #', [$_REQUEST['recoverUser']] ); @@ -17,11 +15,11 @@ class RecoverPassword extends Vn\Web\JsonRequest return TRUE; $service = $this->service; - $token = $service->createToken ($_REQUEST['recoverUser'], FALSE, TRUE); - $url = $service->getUrl () ."#!form=account/conf&token=$token"; + $token = $service->createToken($_REQUEST['recoverUser'], FALSE, TRUE); + $url = $service->getUrl() ."#!form=account/conf&token=$token"; - $report = new Vn\Web\Report ($db, 'recover-password', ['url' => $url]); - $report->sendMail ($user['email']); + $report = new Vn\Web\Report($db, 'recover-password', ['url' => $url]); + $report->sendMail($user['email']); return TRUE; } @@ -31,40 +29,37 @@ class RecoverPassword extends Vn\Web\JsonRequest const DIGITS = '1234567890'; const SYMBOLS = '!$%&()=.'; - function genPassword ($db) - { - $restrictions = $db->getRow ( + function genPassword($db) { + $restrictions = $db->getRow( 'SELECT length, nUpper, nDigits, nPunct FROM account.userPassword'); $pass = []; $newPass = ''; - $nAlpha = $restrictions['length'] - ( + $nAlpha = $restrictions['length'] -( $restrictions['nUpper'] + $restrictions['nDigits'] + $restrictions['nPunct']); - $this->genRands ($pass, self::LOWERS, $nAlpha); - $this->genRands ($pass, self::UPPERS, $restrictions['nUpper']); - $this->genRands ($pass, self::DIGITS, $restrictions['nDigits']); - $this->genRands ($pass, self::SYMBOLS, $restrictions['nPunct']); + $this->genRands($pass, self::LOWERS, $nAlpha); + $this->genRands($pass, self::UPPERS, $restrictions['nUpper']); + $this->genRands($pass, self::DIGITS, $restrictions['nDigits']); + $this->genRands($pass, self::SYMBOLS, $restrictions['nPunct']); - for ($i = count ($pass) - 1; $i >= 0; $i--) - { - $rand = rand (0, $i); + for ($i = count($pass) - 1; $i >= 0; $i--) { + $rand = rand(0, $i); $newPass .= $pass[$rand]; - array_splice ($pass, $rand, 1); + array_splice($pass, $rand, 1); } return $newPass; } - function genRands (&$pass, $chars, $max) - { - $len = strlen ($chars) - 1; + function genRands(&$pass, $chars, $max) { + $len = strlen($chars) - 1; for ($i = 0; $i < $max; $i++) - $pass[] = $chars[rand (0, $len)]; + $pass[] = $chars[rand(0, $len)]; } } diff --git a/rest/core/set-password.php b/rest/core/set-password.php index fb74615b..78d05686 100644 --- a/rest/core/set-password.php +++ b/rest/core/set-password.php @@ -5,21 +5,19 @@ include __DIR__.'/account.php'; /** * Sets the user password. **/ -class SetPassword extends Vn\Web\JsonRequest -{ +class SetPassword extends Vn\Web\JsonRequest { const PARAMS = [ 'setUser' ,'setPassword' ]; - function run ($db) - { + function run($db) { $setUser = $_REQUEST['setUser']; $setPassword = $_REQUEST['setPassword']; - $db->query ('CALL account.userSetPassword (#, #)', + $db->query('CALL account.userSetPassword(#, #)', [$setUser, $setPassword]); - Account::sync ($db, $setUser, $setPassword); + Account::sync($db, $setUser, $setPassword); return TRUE; } } diff --git a/rest/core/supplant.php b/rest/core/supplant.php index a7cf0ea1..885f6d66 100644 --- a/rest/core/supplant.php +++ b/rest/core/supplant.php @@ -1,12 +1,10 @@ service->createToken ($_REQUEST['supplantUser']); + function run($db) { + return $this->service->createToken($_REQUEST['supplantUser']); } } diff --git a/rest/core/sync-user.php b/rest/core/sync-user.php index 0d6198de..b85639dc 100644 --- a/rest/core/sync-user.php +++ b/rest/core/sync-user.php @@ -6,13 +6,11 @@ include __DIR__.'/account.php'; * Updates the user credentials on external systems like Samba, create * home directory, create mailbox, etc. **/ -class SyncUser extends Vn\Web\JsonRequest -{ +class SyncUser extends Vn\Web\JsonRequest { const PARAMS = ['syncUser']; - function run ($db) - { - Account::sync ($db, $_REQUEST['syncUser'], NULL); + function run($db) { + Account::sync($db, $_REQUEST['syncUser'], NULL); return TRUE; } } diff --git a/rest/dms/add.php b/rest/dms/add.php index 81b00ce9..59bb936c 100644 --- a/rest/dms/add.php +++ b/rest/dms/add.php @@ -5,17 +5,15 @@ use Vn\Lib; /** * Adds a document to the Document Management System. **/ -class Add extends Vn\Web\JsonRequest -{ - function run ($db) - { +class Add extends Vn\Web\JsonRequest { + function run($db) { // XXX: Uncomment only to test the script //$_REQUEST['description'] = 'description'; - $description = empty ($_REQUEST['description']) ? + $description = empty($_REQUEST['description']) ? NULL : $_REQUEST['description']; - $baseDir = _DATA_DIR .'/'. $this->app->getName (); + $baseDir = _DATA_DIR .'/'. $this->app->getName(); $docsDir = "$baseDir/dms"; $tempDir = "$baseDir/.dms"; @@ -27,26 +25,26 @@ class Add extends Vn\Web\JsonRequest // Checks document restrictions - if (empty ($_FILES['doc']['name'])) - throw new Lib\UserException ('File not choosed'); + if (empty($_FILES['doc']['name'])) + throw new Lib\UserException('File not choosed'); - $maxSize = $db->getValue ('SELECT max_size FROM dms_config'); + $maxSize = $db->getValue('SELECT max_size FROM dms_config'); if ($_FILES['doc']['size'] > $maxSize * 1048576) - throw new Lib\UserException (sprintf ('File size exceeds size: %d MB', $maxSize)); + throw new Lib\UserException(sprintf('File size exceeds size: %d MB', $maxSize)); try { // Registers the document in the database - $db->query ('START TRANSACTION'); + $db->query('START TRANSACTION'); - $db->query ('INSERT INTO dms_document SET description = #', [$description]); - $docId = (string) $db->getValue ('SELECT LAST_INSERT_ID()'); + $db->query('INSERT INTO dms_document SET description = #', [$description]); + $docId =(string) $db->getValue('SELECT LAST_INSERT_ID()'); - $len = strlen ($docId); - $neededLevels = ceil ($len / $digXDir) - 1; + $len = strlen($docId); + $neededLevels = ceil($len / $digXDir) - 1; - $dirLevels = $db->getValue ( + $dirLevels = $db->getValue( 'SELECT dir_levels FROM dms_config LOCK IN SHARE MODE'); if ($dirLevels > $neededLevels) @@ -55,55 +53,52 @@ class Add extends Vn\Web\JsonRequest // Reorganizes the file repository if necessary if ($dirLevels < $neededLevels) - $dirLevels = $db->getValue ( + $dirLevels = $db->getValue( 'SELECT dir_levels FROM dms_config FOR UPDATE'); - if ($dirLevels < $neededLevels) - { - if (is_dir ($docsDir)) - { - $dif = ($neededLevels - $dirLevels) - 1; + if ($dirLevels < $neededLevels) { + if (is_dir($docsDir)) { + $dif =($neededLevels - $dirLevels) - 1; $newDir = $docsDir; for ($i = 0; $i < $dif; $i++) $newDir .= "/$zerosDir"; - $success = rename ($docsDir, $tempDir) - && mkdir ($newDir, 0770, TRUE) - && rename ($tempDir, "$newDir/$zerosDir"); + $success = rename($docsDir, $tempDir) + && mkdir($newDir, 0770, TRUE) + && rename($tempDir, "$newDir/$zerosDir"); if (!$success) - throw new Exception ('Error while reorganizing directory tree'); + throw new Exception('Error while reorganizing directory tree'); } - $curLevels = $db->query ('UPDATE dms_config SET dir_levels = #', + $curLevels = $db->query('UPDATE dms_config SET dir_levels = #', [$neededLevels]); } // Saves the document to the repository - $padLen = ($neededLevels + 1) * $digXDir; - $paddedId = str_pad ($docId, $padLen, '0', STR_PAD_LEFT); + $padLen =($neededLevels + 1) * $digXDir; + $paddedId = str_pad($docId, $padLen, '0', STR_PAD_LEFT); $saveDir = $docsDir; for ($i = 0; $i < $neededLevels; $i++) - $saveDir .= '/'. substr ($paddedId, $i * $digXDir, $digXDir); + $saveDir .= '/'. substr($paddedId, $i * $digXDir, $digXDir); - if (!file_exists ($saveDir)) - mkdir ($saveDir, 0770, TRUE); + if (!file_exists($saveDir)) + mkdir($saveDir, 0770, TRUE); - $savePath = "$saveDir/". substr ($paddedId, -$digXDir); + $savePath = "$saveDir/". substr($paddedId, -$digXDir); - move_uploaded_file ($_FILES['doc']['tmp_name'], $savePath); + move_uploaded_file($_FILES['doc']['tmp_name'], $savePath); - $db->query ('COMMIT'); + $db->query('COMMIT'); return $docId; } - catch (Exception $e) - { - $db->query ('ROLLBACK'); + catch (Exception $e) { + $db->query('ROLLBACK'); throw $e; } } diff --git a/rest/dms/invoice.php b/rest/dms/invoice.php index 1b2e9cad..4afa3f4c 100644 --- a/rest/dms/invoice.php +++ b/rest/dms/invoice.php @@ -4,20 +4,18 @@ use Vn\Web\Security; use Vn\Web\Util; use Vn\Lib; -class Invoice extends Vn\Web\RestRequest -{ +class Invoice extends Vn\Web\RestRequest { const PARAMS = ['invoice']; const SECURITY = Security::INVOKER; - function run ($db) - { - $pdfPath = $db->getValueFromFile (__DIR__ .'/invoice', - ['invoice' => (int) $_GET['invoice']]); + function run($db) { + $pdfPath = $db->getValueFromFile(__DIR__ .'/invoice', + ['invoice' =>(int) $_GET['invoice']]); if (!$pdfPath) - throw new Lib\UserException (s('Invoice id not found')); + throw new Lib\UserException(s('Invoice id not found')); - Util::printFile ($pdfPath); + Util::printFile($pdfPath); } } diff --git a/rest/edi/clean.php b/rest/edi/clean.php index 55a61515..a6e5d743 100644 --- a/rest/edi/clean.php +++ b/rest/edi/clean.php @@ -2,34 +2,30 @@ require_once __DIR__.'/lib/method.php'; -class Clean extends Edi\Method -{ - function ediRun ($db) - { +class Clean extends Edi\Method { + function ediRun($db) { $imap = $this->imap; - $cleanPeriod = $db->getValue ('SELECT clean_period FROM imap_config'); + $cleanPeriod = $db->getValue('SELECT clean_period FROM imap_config'); $deleted = 0; - $date = new DateTime (NULL); - $date->sub (new DateInterval ($cleanPeriod)); - $filter = sprintf ('BEFORE "%s"', $date->format('D, j M Y')); + $date = new DateTime(NULL); + $date->sub(new DateInterval($cleanPeriod)); + $filter = sprintf('BEFORE "%s"', $date->format('D, j M Y')); $folders = [ $this->imapConf['success_folder'] ,$this->imapConf['error_folder'] ]; - foreach ($folders as $folder) - if (imap_reopen ($imap, "{$this->mailbox}$folder")) - { - if ($messages = imap_search ($imap, $filter)) - { - foreach ($messages as $message) - imap_delete ($imap, $message); + foreach($folders as $folder) + if (imap_reopen($imap, "{$this->mailbox}$folder")) { + if ($messages = imap_search($imap, $filter)) { + foreach($messages as $message) + imap_delete($imap, $message); - imap_expunge ($imap); - $count = count ($messages); + imap_expunge($imap); + $count = count($messages); $deleted += $count; } else @@ -41,7 +37,7 @@ class Clean extends Edi\Method echo "Total $deleted mails deleted\n"; echo "Deleting records from database\n"; - $db->query ('DELETE FROM message WHERE created < #', [$date]); + $db->query('DELETE FROM message WHERE created < #', [$date]); echo "Done\n"; } } diff --git a/rest/edi/lib/message.php b/rest/edi/lib/message.php index 73dc6823..22a0ba2d 100644 --- a/rest/edi/lib/message.php +++ b/rest/edi/lib/message.php @@ -2,40 +2,35 @@ namespace Edi; -require_once (__DIR__.'/section.php'); +require_once(__DIR__.'/section.php'); -class SectionInfo -{ +class SectionInfo { var $schema; var $parentInfo; var $section; } -class Message -{ +class Message { var $section; - static function loadSchema ($schemaName) - { - $ediSchemaStr = file_get_contents (__DIR__."/$schemaName.json", TRUE); + static function loadSchema($schemaName) { + $ediSchemaStr = file_get_contents(__DIR__."/$schemaName.json", TRUE); if ($ediSchemaStr !== FALSE) - return json_decode ($ediSchemaStr, TRUE); + return json_decode($ediSchemaStr, TRUE); return NULL; } - static function isEdiString (&$string) - { - return substr ($string, 0, 4) == 'UNB+'; + static function isEdiString(&$string) { + return substr($string, 0, 4) == 'UNB+'; } - function parse (&$string, &$schema = NULL) - { + function parse(&$string, &$schema = NULL) { global $delimiters; - if (!self::isEdiString ($string)) - throw new \Exception ('Not an EDI string.'); + if (!self::isEdiString($string)) + throw new \Exception('Not an EDI string.'); $pos = 0; $error = FALSE; @@ -43,34 +38,30 @@ class Message $firstLoop = TRUE; $newSection = TRUE; - $info = new SectionInfo (); + $info = new SectionInfo(); $info->schema = $schema; $info->parentInfo = NULL; $info->section = NULL; $topInfo = $info; try { - while (TRUE) - { - $segment = $this->parseSegment ($string, $pos); + while (TRUE) { + $segment = $this->parseSegment($string, $pos); - if (!$segment && (!$endTag || !$info)) + if (!$segment &&(!$endTag || !$info)) break; - if (!$segment || ($segment && !$info)) - throw new \Exception (); + if (!$segment ||($segment && !$info)) + throw new \Exception(); - if ($firstLoop) - { + if ($firstLoop) { if ($segment->name != $info->schema['mainTag']) - throw new \Exception (); + throw new \Exception(); } - else - { + else { for ($i = $info; $i; $i = $i->parentInfo) - if (isset ($i->schema['childs'][$segment->name])) - { - $info = new SectionInfo (); + if (isset($i->schema['childs'][$segment->name])) { + $info = new SectionInfo(); $info->schema = $i->schema['childs'][$segment->name]; $info->parentInfo = $i; $newSection = TRUE; @@ -78,32 +69,28 @@ class Message } } - if ($newSection) - { - $section = new Section (); + if ($newSection) { + $section = new Section(); $section->name = $segment->name; $info->section = $section; - if ($info->parentInfo) - { + if ($info->parentInfo) { $section->parent = $info->parentInfo->section; $section->parent->childs[$segment->name][] = $section; } - if (isset ($info->schema['endTag'])) + if (isset($info->schema['endTag'])) $endTag = $info; $newSection = FALSE; } - if ($endTag && $endTag->schema['endTag'] == $segment->name) - { + if ($endTag && $endTag->schema['endTag'] == $segment->name) { $endTag->section->segments[] = $segment; $info = $endTag->parentInfo; for ($i = $info; $i; $i = $i->parentInfo) - if (isset ($i->schema['endTag'])) - { + if (isset($i->schema['endTag'])) { $endTag = $i; break; } @@ -113,36 +100,30 @@ class Message $firstLoop = FALSE; }} - catch (\Exception $e) - { - throw new \Exception (sprintf ('Parse error, something is wrong near "%s"', - substr ($string, $pos, 10))); + catch (\Exception $e) { + throw new \Exception(sprintf('Parse error, something is wrong near "%s"', + substr($string, $pos, 10))); } $this->section = $topInfo->section; } - function parseSegment (&$string, &$pos) - { + function parseSegment(&$string, &$pos) { $empty = TRUE; $values = []; - while (TRUE) - { - if (!isset ($string{$pos})) + while (TRUE) { + if (!isset($string{$pos})) return NULL; - if (in_array ($string{$pos}, ['+', ':', '\''])) - { - if (!$empty) - { + if (in_array($string{$pos}, ['+', ':', '\''])) { + if (!$empty) { $values[] = - trim (substr ($string, $start, $pos - $start)); + trim(substr($string, $start, $pos - $start)); $empty = TRUE; } } - elseif ($empty) - { + elseif ($empty) { $start = $pos; $empty = FALSE; } @@ -155,7 +136,7 @@ class Message $pos++; - $segment = new Segment (); + $segment = new Segment(); $segment->name = $values[0]; $segment->values = $values; return $segment; diff --git a/rest/edi/lib/method.php b/rest/edi/lib/method.php index f208bc17..80fa1bfd 100644 --- a/rest/edi/lib/method.php +++ b/rest/edi/lib/method.php @@ -2,40 +2,37 @@ namespace Edi; -abstract class Method extends \Vn\Lib\Method -{ +abstract class Method extends \Vn\Lib\Method { protected $imap; protected $imapConf; protected $mailbox; - abstract function ediRun ($db); + abstract function ediRun($db); - function run ($db) - { - $db->selectDb ('edi'); + function run($db) { + $db->selectDb('edi'); - $imapConf = $db->getRow ( + $imapConf = $db->getRow( 'SELECT host, user, pass, success_folder, error_folder FROM imap_config'); - $this->mailbox = sprintf ('{%s/imap/ssl/novalidate-cert}', + $this->mailbox = sprintf('{%s/imap/ssl/novalidate-cert}', $imapConf['host']); - $imap = imap_open ($this->mailbox + $imap = imap_open($this->mailbox ,$imapConf['user'] - ,base64_decode ($imapConf['pass']) + ,base64_decode($imapConf['pass']) ); $this->imap = $imap; $this->imapConf = $imapConf; - if ($imap) - { - $this->ediRun ($db); - imap_expunge ($imap); - imap_close ($imap); + if ($imap) { + $this->ediRun($db); + imap_expunge($imap); + imap_close($imap); } else - error_log (imap_last_error ()); + error_log(imap_last_error()); } } diff --git a/rest/edi/lib/section.php b/rest/edi/lib/section.php index abef926a..9c36aafa 100644 --- a/rest/edi/lib/section.php +++ b/rest/edi/lib/section.php @@ -2,24 +2,22 @@ namespace Edi; -require_once (__DIR__.'/segment.php'); +require_once(__DIR__.'/segment.php'); -class Section -{ +class Section { var $name; var $parent = NULL; var $segments = []; var $childs = []; - function getValue ($name, $key, $type = NULL, $subname = NULL) - { - foreach ($this->segments as $segment) + function getValue($name, $key, $type = NULL, $subname = NULL) { + foreach($this->segments as $segment) if ($segment->name == $name - && (!$subname || $segment->values[1] == $subname)) - return $segment->getValue ($key, $type); + &&(!$subname || $segment->values[1] == $subname)) + return $segment->getValue($key, $type); if ($this->parent) - return $this->parent->getValue ($name, $key, $type, $subname); + return $this->parent->getValue($name, $key, $type, $subname); return NULL; } diff --git a/rest/edi/lib/segment.php b/rest/edi/lib/segment.php index 555d4695..6e6f52b3 100644 --- a/rest/edi/lib/segment.php +++ b/rest/edi/lib/segment.php @@ -6,31 +6,28 @@ use Vn\Lib\Type; use Vn\Lib\Date; use Vn\Lib\Time; -class Segment -{ +class Segment { var $name; var $values = []; - function getValue ($key, $type = NULL) - { - if ($key < 0 || $key >= count ($this->values)) + function getValue($key, $type = NULL) { + if ($key < 0 || $key >= count($this->values)) return NULL; $v = $this->values[$key]; - switch ($type) - { + switch ($type) { case Type::DATE: - $tmp = new Date (); - $tmp->setDate (substr ($v, 0, 4), substr ($v, 4, 2), substr ($v, 6, 2)); + $tmp = new Date(); + $tmp->setDate(substr($v, 0, 4), substr($v, 4, 2), substr($v, 6, 2)); return $tmp; case Type::TIME: - $tmp = new Time (); - $tmp->setTime (substr ($v, 0, 2), substr ($v, 2, 2)); + $tmp = new Time(); + $tmp->setTime(substr($v, 0, 2), substr($v, 2, 2)); return $tmp; case Type::DOUBLE: case Type::INTEGER: - Type::set ($v, $type); + Type::set($v, $type); default: return $v; } diff --git a/rest/edi/load.php b/rest/edi/load.php index 03f5c9d3..e5d45574 100644 --- a/rest/edi/load.php +++ b/rest/edi/load.php @@ -1,52 +1,48 @@ ediSchema = Edi\Message::loadSchema ('CLOCKT'); +class Load extends Edi\Method { + function ediRun($db) { + $this->ediSchema = Edi\Message::loadSchema('CLOCKT'); if (!$this->ediSchema) - throw new Exception ('Can not load EDI schema.'); + throw new Exception('Can not load EDI schema.'); - $this->params = $db->query ( + $this->params = $db->query( 'SELECT code, name, subname, position, type, required FROM param'); - $inbox = imap_search ($this->imap, 'ALL'); + $inbox = imap_search($this->imap, 'ALL'); - if ($inbox) - { - foreach ($inbox as $msg) - $this->loadMail ($db, $msg); + if ($inbox) { + foreach($inbox as $msg) + $this->loadMail($db, $msg); - $inboxCount = count ($inbox); + $inboxCount = count($inbox); if ($inboxCount > 0) echo "Total $inboxCount messages readed\n"; } } - function loadMail ($db, $msg) - { + function loadMail($db, $msg) { $imap = $this->imap; // Gets EKT messages from email - $msgStructure = imap_fetchstructure ($imap, $msg); + $msgStructure = imap_fetchstructure($imap, $msg); $result = []; // Gets the mail sender and Message-ID - $header = imap_headerinfo ($imap, $msg); + $header = imap_headerinfo($imap, $msg); $from = $header->from; - $mailId = trim ($header->message_id, '<>'); + $mailId = trim($header->message_id, '<>'); - if ($from && count ($from) > 0) + if ($from && count($from) > 0) $sender = $from[0]->mailbox .'@'. $from[0]->host; else $sender = NULL; @@ -54,37 +50,35 @@ class Load extends Edi\Method // Searches the EDI message on mail parts $matchTypes = [TYPEAPPLICATION, TYPETEXT]; - $this->imapFindParts ($msgStructure, $matchTypes, [], $result); + $this->imapFindParts($msgStructure, $matchTypes, [], $result); $count = 0; $error = NULL; - foreach ($result as $msgSection) - try - { - $part = imap_bodystruct ($imap, $msg, $msgSection); - $ediString = imap_fetchbody ($imap, $msg, $msgSection); + foreach($result as $msgSection) + try { + $part = imap_bodystruct($imap, $msg, $msgSection); + $ediString = imap_fetchbody($imap, $msg, $msgSection); - switch ($part->encoding) - { + switch ($part->encoding) { case ENCBASE64: - $ediString = imap_base64 ($ediString); + $ediString = imap_base64($ediString); break; case ENCQUOTEDPRINTABLE: - $ediString = imap_qprint ($ediString); + $ediString = imap_qprint($ediString); break; } - if (!Edi\Message::isEdiString ($ediString)) + if (!Edi\Message::isEdiString($ediString)) continue; // Creates the EDI object and loads its exchanges - $ediMessage = new Edi\Message (); - $ediMessage->parse ($ediString, $this->ediSchema); + $ediMessage = new Edi\Message(); + $ediMessage->parse($ediString, $this->ediSchema); - $db->query ('START TRANSACTION'); - $db->query ('CALL messageNew (#mailId, #sender, @message)', + $db->query('START TRANSACTION'); + $db->query('CALL messageNew(#mailId, #sender, @message)', [ 'mailId' => $mailId, 'sender' => $sender @@ -93,19 +87,16 @@ class Load extends Edi\Method $unb = $ediMessage->section; $unhs = $unb->childs['UNH']; - foreach ($unhs as $unh) - foreach ($lins = $unh->childs['LIN'] as $lin) - { + foreach($unhs as $unh) + foreach($lins = $unh->childs['LIN'] as $lin) { $ediValues = []; // Gets the exchange params - $this->params->data_seek (0); + $this->params->data_seek(0); - while ($row = $this->params->fetch_assoc ()) - { - switch ($row['type']) - { + while ($row = $this->params->fetch_assoc()) { + switch ($row['type']) { case 'INTEGER': $type = Type::INTEGER; break; @@ -122,56 +113,54 @@ class Load extends Edi\Method $type = Type::STRING; } - $value = $lin->getValue ( + $value = $lin->getValue( $row['name'], $row['position'], $type, $row['subname']); - if (!isset ($value) && $row['required']) - throw new Exception ('Missing required parameter: '. $row['code']); + if (!isset($value) && $row['required']) + throw new Exception('Missing required parameter: '. $row['code']); $ediValues[$row['code']] = $value; } // Gets the exchange features - $res = $db->query ( + $res = $db->query( 'SELECT presentation_order, feature FROM item_feature WHERE item_id = #ref AND entry_date <= CURDATE() - AND (expiry_date IS NULL OR expiry_date >= CURDATE()) + AND(expiry_date IS NULL OR expiry_date >= CURDATE()) GROUP BY presentation_order' ,$ediValues ); if ($res) - while ($row = $res->fetch_assoc ()) - { - $value = $lin->getValue ('IMD', 2, Type::INTEGER, $row['feature']); + while ($row = $res->fetch_assoc()) { + $value = $lin->getValue('IMD', 2, Type::INTEGER, $row['feature']); $ediValues['s'.$row['presentation_order']] = $value; } else - throw new Exception ('Can\'t get the item features.'); + throw new Exception('Can\'t get the item features.'); for ($i = 1; $i <= 6; $i++) - if (!isset ($ediValues['s'.$i])) + if (!isset($ediValues['s'.$i])) $ediValues['s'.$i] = NULL; // Adds the exchange to the Database - $res = $db->queryFromFile (__DIR__.'/sql/batch-add', $ediValues); + $res = $db->queryFromFile(__DIR__.'/sql/batch-add', $ediValues); if (!$res) - throw new Exception ('Failed to insert the line.'); + throw new Exception('Failed to insert the line.'); $count++; } - $db->query ('COMMIT'); + $db->query('COMMIT'); } - catch (Exception $e) - { - $db->query ('ROLLBACK'); - $error = $e->getMessage (); + catch (Exception $e) { + $db->query('ROLLBACK'); + $error = $e->getMessage(); break; } @@ -180,43 +169,38 @@ class Load extends Edi\Method // Logs information of realized operations - if (!$error) - { + if (!$error) { $folder = $this->imapConf['success_folder']; echo "Mail loaded with $count lines.\n"; } - else - { + else { $folder = $this->imapConf['error_folder']; echo "Mail error: $error\n"; } // Moves the mail to another folder - $folder = sprintf ('%s', $folder); + $folder = sprintf('%s', $folder); - if (!imap_mail_move ($imap, $msg, $folder)) - error_log ('Can\'t move message to %s: %s' + if (!imap_mail_move($imap, $msg, $folder)) + error_log('Can\'t move message to %s: %s' ,$folder - ,imap_last_error () + ,imap_last_error() ); } - function imapFindParts (&$part, &$matchTypes, $section, &$result) - { - if (in_array ($part->type, $matchTypes)) - { - if (count ($section) > 0) - $result[] = implode ('.', $section); + function imapFindParts(&$part, &$matchTypes, $section, &$result) { + if (in_array($part->type, $matchTypes)) { + if (count($section) > 0) + $result[] = implode('.', $section); else $result[] = '1'; } elseif ($part->type == TYPEMULTIPART) - foreach ($part->parts as $i => $subpart) - { - array_push ($section, $i + 1); - $this->imapFindParts ($subpart, $matchTypes, $section, $result); - array_pop ($section); + foreach($part->parts as $i => $subpart) { + array_push($section, $i + 1); + $this->imapFindParts($subpart, $matchTypes, $section, $result); + array_pop($section); } } } diff --git a/rest/edi/update.php b/rest/edi/update.php index 39fa1c00..562c293f 100644 --- a/rest/edi/update.php +++ b/rest/edi/update.php @@ -1,47 +1,47 @@ selectDb ('edi'); - //$db->options (MYSQLI_OPT_LOCAL_INFILE, TRUE); +class Update extends Vn\Lib\Method { + function run($db) { + $db->selectDb('edi'); + //$db->options(MYSQLI_OPT_LOCAL_INFILE, TRUE); $tmpDir = '/tmp/floricode'; - // Establece una conexi�n FTP + // Establish the FTP connection - $ftpConf = $db->getRow ('SELECT host, user, password FROM ftp_config'); + $ftpConf = $db->getRow('SELECT host, user, password FROM ftp_config'); echo "Openning FTP connection to {$ftpConf['host']}\n"; - $ftpConn = ftp_connect ($ftpConf['host']); + $ftpConn = ftp_connect($ftpConf['host']); if (!$ftpConn) - throw new Exception ('Can not connect to '. $ftpConf['host']); + throw new Exception('Can not connect to '. $ftpConf['host']); - if (!ftp_login ($ftpConn, $ftpConf['user'], $ftpConf['password'])) - throw new Exception ('Can not login to '. $ftpConf['user'] .'@'. $ftpConf['host']); + if (!ftp_login($ftpConn, $ftpConf['user'], $ftpConf['password'])) + throw new Exception('Can not login to '. $ftpConf['user'] .'@'. $ftpConf['host']); - // Obtiene el listado de tablas a actualizar + // Gets the list with the tables to update - set_time_limit (0); + set_time_limit(0); - $res = $db->query ( + $res = $db->query( 'SELECT file_name, to_table, file, updated FROM file_config'); $dwFiles = []; - if (!file_exists ($tmpDir)) - mkdir ($tmpDir); + if (!file_exists($tmpDir)) + mkdir($tmpDir); - while ($row = $res->fetch_assoc ()) + while ($row = $res->fetch_assoc()) try { $file = $row['file']; $table = $row['to_table']; $baseName = $row['file_name']; - if ($row['updated']) - $updated = DateTime::createFromFormat ('Y-m-d', $row['updated']); + if ($row['updated']) { + $updated = DateTime::createFromFormat('Y-m-d', $row['updated']); + $updated->setTime(0, 0, 0, 0); + } else $updated = NULL; @@ -49,71 +49,65 @@ class Update extends Vn\Lib\Method $zipFile = "$tmpDir/$file.zip"; $ucDir = "$tmpDir/$file"; - // Intenta descargar y descomprimir el fichero con los datos + // Downloads and decompress the file with the data - if (!isset ($dwFiles[$file])) - { + if (!isset($dwFiles[$file])) { $dwFiles[$file] = TRUE; echo "Downloading $remoteFile\n"; - if (!ftp_get ($ftpConn, $zipFile, $remoteFile, FTP_BINARY)) - throw new Exception ("Error downloading $remoteFile to $zipFile"); + if (!ftp_get($ftpConn, $zipFile, $remoteFile, FTP_BINARY)) + throw new Exception("Error downloading $remoteFile to $zipFile"); $zip = new ZipArchive; - if ($zip->open ($zipFile) !== TRUE) - throw new Exception ("Can not open $zipFile"); + if ($zip->open($zipFile) !== TRUE) + throw new Exception("Can not open $zipFile"); - @mkdir ($ucDir, 0774, TRUE); + @mkdir($ucDir, 0774, TRUE); - if (!$zip->extractTo ($ucDir)) - throw new Exception ("Can not uncompress file $zipFile"); + if (!$zip->extractTo($ucDir)) + throw new Exception("Can not uncompress file $zipFile"); $zip->close(); - unlink ($zipFile); + unlink($zipFile); } - foreach (glob ("$ucDir/$baseName*.txt") as $fileName) + foreach(glob("$ucDir/$baseName*.txt") as $fileName) break; if (!$fileName) - throw new Exception ("Import file for table $table does not exist"); + throw new Exception("Import file for table $table does not exist"); - // Si los datos están actualizados omite la tabla + // If data is updated, omits the table - $lastUpdated = substr ($fileName, -10, 6); - $lastUpdated = DateTime::createFromFormat ('dmy', $lastUpdated); + $lastUpdated = substr($fileName, -10, 6); + $lastUpdated = DateTime::createFromFormat('dmy', $lastUpdated); + $lastUpdated->setTime(0, 0, 0, 0); - if ($updated && $lastUpdated <= $updated) + if (isset($updated) && $lastUpdated <= $updated) { + echo "Table $table is updated, omitted\n"; continue; + } - // Actualiza los datos de la tabla - + // Updates the table + echo "Dumping data to table $table\n"; - $importQuery = $db->loadFromFile (__DIR__."/sql/$table", ['file' => $fileName]); - $db->multiQuery ( - "START TRANSACTION; - DELETE FROM $table; - $importQuery; - UPDATE file_config SET updated = # WHERE file_name = #; - COMMIT;", + $db->query("START TRANSACTION"); + $db->query("DELETE FROM {$db->quote($table)}"); + $db->queryFromFile(__DIR__."/sql/$table", ['file' => $fileName]); + $db->query("UPDATE file_config SET updated = # WHERE file_name = #", [$lastUpdated, $baseName] ); - - do { - $db->storeResult (); - } - while ($db->moreResults () && $db->nextResult ()); + $db->query("COMMIT"); } - catch (Exception $e) - { - $db->query ('ROLLBACK'); - error_log ($e->getMessage ()); + catch (Exception $e) { + $db->query('ROLLBACK'); + error_log($e->getMessage()); } - shell_exec ("rm -R $tmpDir"); - ftp_close ($ftpConn); + shell_exec("rm -R $tmpDir"); + ftp_close($ftpConn); echo "Update completed\n"; } diff --git a/rest/image/image.php b/rest/image/image.php index 56095a6b..f0cd4387 100644 --- a/rest/image/image.php +++ b/rest/image/image.php @@ -2,34 +2,31 @@ use Vn\Lib\UserException; -class Image -{ +class Image { /** * Creates an image resource from a valid image file. * * @param string $srcFile The source file name **/ - static function create ($srcFile) - { - $imageType = exif_imagetype ($srcFile); + static function create($srcFile) { + $imageType = exif_imagetype($srcFile); if ($imageType !== FALSE) - switch ($imageType) - { + switch ($imageType) { case IMAGETYPE_JPEG: - $image = imagecreatefromjpeg ($srcFile); + $image = imagecreatefromjpeg($srcFile); break; case IMAGETYPE_PNG: - $image = imagecreatefrompng ($srcFile); + $image = imagecreatefrompng($srcFile); break; case IMAGETYPE_GIF: $image = imagecreatefromgif ($srcFile); break; default: - throw new UserException (s('Bad file format')); + throw new UserException(s('Bad file format')); } else - throw new UserException (s('Image open error')); + throw new UserException(s('Image open error')); return $image; } @@ -44,23 +41,21 @@ class Image * @param boolean $crop Wether to crop the image * @param boolean $symbolicSrc If it is not necessary to resize the image creates a symbolic link using the passed path as source **/ - static function resizeSave ($image, $dstFile, $maxHeight, $maxWidth, $crop = FALSE, $symbolicSrc = NULL) - { - $width = imagesx ($image); - $height = imagesy ($image); + static function resizeSave($image, $dstFile, $maxHeight, $maxWidth, $crop = FALSE, $symbolicSrc = NULL) { + $width = imagesx($image); + $height = imagesy($image); - $dirname = dirname ($dstFile); + $dirname = dirname($dstFile); - if (!is_dir ($dirname)) - mkdir ($dirname, 0775, TRUE); + if (!is_dir($dirname)) + mkdir($dirname, 0775, TRUE); - if (file_exists ($dstFile)) - @unlink ($dstFile); + if (file_exists($dstFile)) + @unlink($dstFile); // Check if it is necessary to resize the image - if ($height > $maxHeight || $width > $maxWidth) - { + if ($height > $maxHeight || $width > $maxWidth) { $srcX = 0; $srcY = 0; $srcWidth = $width; @@ -68,45 +63,38 @@ class Image $dstWidth = $width; $dstHeight = $height; - if (!$crop) // Resize - { + if (!$crop) // Resize { $ratio = NULL; - if ($dstWidth > $maxWidth) - { + if ($dstWidth > $maxWidth) { $ratio = $dstWidth / $maxWidth; $dstWidth = $maxWidth; - $dstHeight = (int) ($dstHeight / $ratio); + $dstHeight =(int)($dstHeight / $ratio); } - if ($dstHeight > $maxHeight) - { + if ($dstHeight > $maxHeight) { $ratio = $dstHeight / $maxHeight; $dstHeight = $maxHeight; - $dstWidth = (int) ($dstWidth / $ratio); + $dstWidth =(int)($dstWidth / $ratio); } } - else // Cut & resize - { + else // Cut & resize { if ($width > $maxWidth) $dstWidth = $maxWidth; if ($height > $maxWidth) $dstHeight = $maxHeight; - if ($width <= $maxWidth) - { + if ($width <= $maxWidth) { if ($height > $srcHeight) $srcHeight = $maxHeight; } - elseif ($height <= $maxHeight) - { + elseif ($height <= $maxHeight) { if ($width > $maxWidth) $srcWidth = $maxWidth; } - else - { - $srcWidth = (int) ($maxWidth * ($height / $maxHeight)); - $srcHeight = (int) ($maxHeight * ($width / $maxWidth)); + else { + $srcWidth =(int)($maxWidth *($height / $maxHeight)); + $srcHeight =(int)($maxHeight *($width / $maxWidth)); if ($srcWidth <= $width) $srcHeight = $height; @@ -115,32 +103,30 @@ class Image } if ($width !== $srcWidth) - $srcX = (int) (($width / 2) - ($srcWidth / 2)); + $srcX =(int)(($width / 2) -($srcWidth / 2)); if ($height !== $srcHeight) - $srcY = (int) (($height / 2) - ($srcHeight / 2)); + $srcY =(int)(($height / 2) -($srcHeight / 2)); } - $resizedImage = imagecreatetruecolor ($dstWidth, $dstHeight); - imagealphablending ($resizedImage, FALSE); - imagesavealpha ($resizedImage, TRUE); - imagecopyresampled ($resizedImage, $image, + $resizedImage = imagecreatetruecolor($dstWidth, $dstHeight); + imagealphablending($resizedImage, FALSE); + imagesavealpha($resizedImage, TRUE); + imagecopyresampled($resizedImage, $image, 0, 0, $srcX, $srcY, $dstWidth, $dstHeight, $srcWidth, $srcHeight); - $saved = imagepng ($resizedImage, $dstFile); - imagedestroy ($resizedImage); + $saved = imagepng($resizedImage, $dstFile); + imagedestroy($resizedImage); } - elseif (isset ($symbolicSrc)) - { - $saved = symlink ($symbolicSrc, $dstFile); + elseif (isset($symbolicSrc)) { + $saved = symlink($symbolicSrc, $dstFile); } - else - { - imagesavealpha ($image, TRUE); - $saved = imagepng ($image, $dstFile); + else { + imagesavealpha($image, TRUE); + $saved = imagepng($image, $dstFile); } if (!$saved) - throw new UserException (sprintf (s('File save error: %s'), $dstFile)); + throw new UserException(sprintf(s('File save error: %s'), $dstFile)); } } diff --git a/rest/image/resize.php b/rest/image/resize.php index 6bca0ba1..952d70ee 100644 --- a/rest/image/resize.php +++ b/rest/image/resize.php @@ -1,6 +1,6 @@ checkParams ($options, self::PARAMS)) - $this->usage (); + if (!$this->checkParams($options, self::PARAMS)) + $this->usage(); $srcDir = $options['srcDir']; $dstDir = $options['dstDir']; $maxHeight = $options['maxHeight']; $maxWidth = $options['maxWidth']; - $rewrite = isset ($options['rewrite']); - $crop = isset ($options['crop']); - $symbolic = isset ($options['symbolic']); + $rewrite = isset($options['rewrite']); + $crop = isset($options['crop']); + $symbolic = isset($options['symbolic']); - set_time_limit (0); + set_time_limit(0); $count = 0; - $dir = opendir ($srcDir); + $dir = opendir($srcDir); if ($dir) - while ($fileName = readdir ($dir)) - if (!in_array ($fileName, ['.', '..'])) - { + while ($fileName = readdir($dir)) + if (!in_array($fileName, ['.', '..'])) { $srcFile = "$srcDir/$fileName"; - $dstFile = "$dstDir/". substr ($fileName, 0, -4).'.png'; + $dstFile = "$dstDir/". substr($fileName, 0, -4).'.png'; - if (!file_exists ($dstFile) || $rewrite) - try - { - $symbolicSrc = ($symbolic) ? $srcFile : NULL; + if (!file_exists($dstFile) || $rewrite) + try { + $symbolicSrc =($symbolic) ? $srcFile : NULL; - $image = Image::create ($srcFile); - Image::resizeSave ($image, $dstFile, $maxHeight, $maxWidth, $crop, $symbolicSrc); - imagedestroy ($image); + $image = Image::create($srcFile); + Image::resizeSave($image, $dstFile, $maxHeight, $maxWidth, $crop, $symbolicSrc); + imagedestroy($image); $count++; } catch (\Exception $e) {} diff --git a/rest/image/sync.php b/rest/image/sync.php index 23b620d6..eb73090a 100644 --- a/rest/image/sync.php +++ b/rest/image/sync.php @@ -1,64 +1,59 @@ util = new Util ($app); + function __construct($app) { + parent::__construct($app); + $this->util = new Util($app); $this->dataDir = $this->util->dataDir; } - function run ($db) - { - $db = $this->getSysConn (); + function run($db) { + $db = $this->getSysConn(); - set_time_limit (0); - $this->trashSubdir = date ('YmdHis'); + set_time_limit(0); + $this->trashSubdir = date('YmdHis'); $checkCount = 0; $query = 'SELECT DISTINCT `%3$s` FROM `%1$s`.`%2$s` WHERE `%3$s` IS NOT NULL AND `%3$s` != \'\''; - $dir = opendir ($this->dataDir); + $dir = opendir($this->dataDir); if ($dir) - while ($schema = readdir ($dir)) - if (!in_array ($schema, ['.', '..'])) - { - $info = $this->loadInfo ($schema); + while ($schema = readdir($dir)) + if (!in_array($schema, ['.', '..'])) { + $info = $this->loadInfo($schema); $schemaPath = "{$this->dataDir}/$schema"; // Deletes unreferenced schemas. - if (!isset ($info)) - { - $this->moveTrash ($schema); + if (!isset($info)) { + $this->moveTrash($schema); continue; } // Deletes unreferenced sizes. - $schemaDir = opendir ($schemaPath); + $schemaDir = opendir($schemaPath); if ($schemaDir) - while ($size = readdir ($schemaDir)) - if (!in_array ($size, ['.', '..', 'full']) - && !isset ($info['sizes'][$size])) - $this->moveTrash ("$schema/$size"); + while ($size = readdir($schemaDir)) + if (!in_array($size, ['.', '..', 'full']) + && !isset($info['sizes'][$size])) + $this->moveTrash("$schema/$size"); // Gets a list of referenced images from the database. - $result = $db->query (sprintf ($query + $result = $db->query(sprintf($query ,$info['schema'] ,$info['table'] ,$info['column'] @@ -69,41 +64,38 @@ class Sync extends Vn\Lib\Method $map = []; - while ($row = $result->fetch_row ()) - { + while ($row = $result->fetch_row()) { $map[$row[0]] = TRUE; $checkCount++; } - $result->free (); + $result->free(); // Deletes unreferenced images. - $this->cleanImages ($schema, 'full', $map); + $this->cleanImages($schema, 'full', $map); - foreach ($info['sizes'] as $size => $i) - $this->cleanImages ($schema, $size, $map); + foreach($info['sizes'] as $size => $i) + $this->cleanImages($schema, $size, $map); } echo "Syncronization finished.\n"; } - function cleanImages ($schema, $size, &$map) - { + function cleanImages($schema, $size, &$map) { $sizePath = "{$this->dataDir}/$schema/$size"; - if (!is_dir ($sizePath)) + if (!is_dir($sizePath)) return; - $iter = new DirectoryIterator ($sizePath); + $iter = new DirectoryIterator($sizePath); - for (; $iter->valid (); $iter->next ()) - if (!$iter->isDir () && strripos ($iter->getFilename (), '.png', -4) !== FALSE) - { - $name = substr ($iter->getFilename (), 0, -4); + for (; $iter->valid(); $iter->next()) + if (!$iter->isDir() && strripos($iter->getFilename(), '.png', -4) !== FALSE) { + $name = substr($iter->getFilename(), 0, -4); - if (!isset ($map[$name])) - $this->moveTrash ("$schema/$size/". $iter->getFilename ()); + if (!isset($map[$name])) + $this->moveTrash("$schema/$size/". $iter->getFilename()); } } @@ -112,15 +104,14 @@ class Sync extends Vn\Lib\Method * * @param string $file The file to move to the trash */ - function moveTrash ($file) - { + function moveTrash($file) { $trashBasedir = "{$this->dataDir}/.trash/". $this->$trashSubdir; - $trashdir = "$trashBasedir/". dirname ($file); + $trashdir = "$trashBasedir/". dirname($file); - if (!is_dir ($trashdir)) - mkdir ($trashdir, 0775, TRUE); + if (!is_dir($trashdir)) + mkdir($trashdir, 0775, TRUE); - rename ( + rename( "{$this->dataDir}/$file", "$trashBasedir/$file" ); diff --git a/rest/image/thumb.php b/rest/image/thumb.php index 2fad4584..0e1cd2d6 100644 --- a/rest/image/thumb.php +++ b/rest/image/thumb.php @@ -1,6 +1,6 @@ getSysConn (); + $db = $this->getSysConn(); // Gets parameters from URI. - $uriSplit = explode ('/', $_SERVER['REQUEST_URI']); - $uriSplit = array_slice ($uriSplit, count ($uriSplit) - 3, 3); + $uriSplit = explode('/', $_SERVER['REQUEST_URI']); + $uriSplit = array_slice($uriSplit, count($uriSplit) - 3, 3); - if (count ($uriSplit) < 3) - throw new Exception ('Bad request'); + if (count($uriSplit) < 3) + throw new Exception('Bad request'); $schema = $uriSplit[0]; $orgFile = $uriSplit[2]; $file = $orgFile; - if (strrpos ($file, '.') === FALSE) + if (strrpos($file, '.') === FALSE) $file .= '.png'; - $size = explode ('x', $uriSplit[1]); + $size = explode('x', $uriSplit[1]); - if (count ($size) < 2) - throw new Exception ('Bad request'); + if (count($size) < 2) + throw new Exception('Bad request'); - $width = (int) $size[0]; - $height = (int) $size[1]; + $width =(int) $size[0]; + $height =(int) $size[1]; // Verifies that it is an allowed size. @@ -50,7 +48,7 @@ class Thumb extends Vn\Web\RestRequest ,'height' => $height ]; - $row = $db->getValue ( + $row = $db->getValue( 'SELECT crop FROM imageCollection s JOIN imageCollectionSize z ON z.collectionFk = s.id @@ -60,37 +58,36 @@ class Thumb extends Vn\Web\RestRequest ,$params ); - if (!isset ($row)) - throw new Exception ('Size not allowed'); + if (!isset($row)) + throw new Exception('Size not allowed'); // Creates the thumb. - $util = new Util ($this->app); + $util = new Util($this->app); $baseDir = "{$util->dataDir}/$schema"; $srcFile = "$baseDir/full/$file"; $dstFile = "$baseDir/{$width}x{$height}/$file"; $symbolicSrc = "../full/$file"; - if (!file_exists ($srcFile)) - throw new Exception ('Source not exists'); - if (file_exists ($dstFile)) - throw new Exception ('Destination already exists'); + if (!file_exists($srcFile)) + throw new Exception('Source not exists'); + if (file_exists($dstFile)) + throw new Exception('Destination already exists'); - $image = Image::create ($srcFile); - Image::resizeSave ($image, $dstFile, $height, $width, $row, $symbolicSrc); - imagedestroy ($image); + $image = Image::create($srcFile); + Image::resizeSave($image, $dstFile, $height, $width, $row, $symbolicSrc); + imagedestroy($image); // Sends the thumb to the client - $useXsendfile = $db->getValue ('SELECT useXsendfile FROM imageConfig'); + $useXsendfile = $db->getValue('SELECT useXsendfile FROM imageConfig'); - if ($useXsendfile) - { - header ("X-Sendfile: $dstFile"); - header ("Content-Type: image/png"); + if ($useXsendfile) { + header("X-Sendfile: $dstFile"); + header("Content-Type: image/png"); } else - header ("Location: {$_SERVER['REQUEST_URI']}"); + header("Location: {$_SERVER['REQUEST_URI']}"); } } diff --git a/rest/image/upload.php b/rest/image/upload.php index 2d88cf18..ba72c29f 100644 --- a/rest/image/upload.php +++ b/rest/image/upload.php @@ -1,6 +1,6 @@ app); + function run($db) { + $util = new Util($this->app); $schema = $_REQUEST['schema']; $name = $_REQUEST['name']; // Checks schema - $info = $util->loadInfo ($schema); + $info = $util->loadInfo($schema); if (!$info) - throw new UserException (s('Schema not exists')); + throw new UserException(s('Schema not exists')); // Checks file name - if (preg_match ('/[^a-z0-9_]/', $_REQUEST['name']) !== 0) - throw new UserException (s('Bad file name')); + if (preg_match('/[^a-z0-9_]/', $_REQUEST['name']) !== 0) + throw new UserException(s('Bad file name')); // Checks for file errors - if (empty ($_FILES['image']['name'])) - throw new UserException (s('File not choosed')); + if (empty($_FILES['image']['name'])) + throw new UserException(s('File not choosed')); - if ($_FILES['image']['error'] != 0) - { - switch ($_FILES['image']['error']) - { + if ($_FILES['image']['error'] != 0) { + switch ($_FILES['image']['error']) { case UPLOAD_ERR_INI_SIZE: $message = 'ErrIniSize'; break; @@ -69,13 +65,13 @@ class Upload extends Vn\Web\JsonRequest break; } - throw new Lib\Exception (s($message)); + throw new Lib\Exception(s($message)); } - $maxSize = $db->getValue ('SELECT maxSize FROM imageConfig'); + $maxSize = $db->getValue('SELECT maxSize FROM imageConfig'); if ($_FILES['image']['size'] > $maxSize * 1048576) - throw new UserException (sprintf (s('File size error'), $maxSize)); + throw new UserException(sprintf(s('File size error'), $maxSize)); // Resizes and saves the image @@ -85,17 +81,16 @@ class Upload extends Vn\Web\JsonRequest $fullFile = "$schemaPath/full/$fileName"; $symbolicSrc = "../full/$fileName"; - $image = Image::create ($tmpName); - Image::resizeSave ($image, $fullFile, $info['maxHeight'], $info['maxWidth']); + $image = Image::create($tmpName); + Image::resizeSave($image, $fullFile, $info['maxHeight'], $info['maxWidth']); - foreach ($info['sizes'] as $size => $i) - { + foreach($info['sizes'] as $size => $i) { $dstFile = "$schemaPath/$size/$fileName"; - Image::resizeSave ($image, $dstFile, $i['height'], $i['width'], $i['crop'], $symbolicSrc); + Image::resizeSave($image, $dstFile, $i['height'], $i['width'], $i['crop'], $symbolicSrc); } - imagedestroy ($image); - unlink ($tmpName); + imagedestroy($image); + unlink($tmpName); return TRUE; } } diff --git a/rest/image/util.php b/rest/image/util.php index a3d2de2b..2b43d561 100644 --- a/rest/image/util.php +++ b/rest/image/util.php @@ -1,19 +1,17 @@ app = $app; - $this->dataDir = _DATA_DIR .'/'. $app->getName () .'/image-db'; + $this->dataDir = _DATA_DIR .'/'. $app->getName() .'/image-db'; } /** @@ -21,11 +19,10 @@ class Util * * @param string $schema The schema name */ - function loadInfo ($schema) - { - $db = $this->app->getSysConn (); + function loadInfo($schema) { + $db = $this->app->getSysConn(); - $info = $db->getRow ( + $info = $db->getRow( 'SELECT id, maxWidth, maxHeight, `schema`, `table`, `column` FROM imageCollection WHERE name = #schema' ,['schema' => $schema] @@ -34,7 +31,7 @@ class Util if (!$info) return NULL; - $res = $db->query ( + $res = $db->query( 'SELECT width, height, crop FROM imageCollectionSize WHERE collectionFk = #id' ,['id' => $info['id']] @@ -42,8 +39,7 @@ class Util $info['sizes'] = []; - while ($r = $res->fetch_assoc ()) - { + while ($r = $res->fetch_assoc()) { $size = "{$r['width']}x{$r['height']}"; $info['sizes'][$size] = [ 'width' => $r['width'], diff --git a/rest/misc/access-version.php b/rest/misc/access-version.php index b8ac47a8..b938536a 100644 --- a/rest/misc/access-version.php +++ b/rest/misc/access-version.php @@ -6,26 +6,22 @@ use Vn\Lib\UserException; /** * Uploads a access module. */ -class AccessVersion extends Vn\Web\JsonRequest -{ +class AccessVersion extends Vn\Web\JsonRequest { const PARAMS = [ 'appName' ,'newVersion' ]; - function run ($db) - { + function run($db) { // Checks for file errors. $moduleFile = $_FILES['moduleFile']; - if (empty ($moduleFile['name'])) - throw new UserException (s('File not choosed')); + if (empty($moduleFile['name'])) + throw new UserException(s('File not choosed')); - if ($moduleFile['error'] != 0) - { - switch ($_FILES['image']['error']) - { + if ($moduleFile['error'] != 0) { + switch ($_FILES['image']['error']) { case UPLOAD_ERR_INI_SIZE: $message = 'ErrIniSize'; break; @@ -52,7 +48,7 @@ class AccessVersion extends Vn\Web\JsonRequest break; } - throw new Lib\Exception (s($message)); + throw new Lib\Exception(s($message)); } // Defining parameters @@ -67,8 +63,8 @@ class AccessVersion extends Vn\Web\JsonRequest // Updates the application - copy ($moduleFile['tmp_name'], $archiveFile); - rename ($moduleFile['tmp_name'], $uploadFile); + copy($moduleFile['tmp_name'], $archiveFile); + rename($moduleFile['tmp_name'], $uploadFile); return TRUE; } diff --git a/rest/misc/contact.php b/rest/misc/contact.php index 15d8a87a..31ae1c5b 100644 --- a/rest/misc/contact.php +++ b/rest/misc/contact.php @@ -1,11 +1,10 @@ queryFromFile (__DIR__.'/contact', $_REQUEST); - //$customerId = $db->getValue ('SELECT @id'); + //$db->queryFromFile(__DIR__.'/contact', $_REQUEST); + //$customerId = $db->getValue('SELECT @id'); - $conf = $db->getObject ( + $conf = $db->getObject( 'SELECT m.host, m.port, m.secure, m.sender, m.user, m.password, c.recipient FROM mailConfig m JOIN contact c' ); - $mail = new PHPMailer (); - $mail->isSMTP (); + $mail = new PHPMailer(); + $mail->isSMTP(); $mail->Host = $conf->host; - if (!empty ($conf->user)) - { + if (!empty($conf->user)) { $mail->SMTPAuth = TRUE; $mail->Username = $conf->user; - $mail->Password = base64_decode ($conf->password); + $mail->Password = base64_decode($conf->password); } else $mail->SMTPAuth = FALSE; - if ($conf->secure) - { + if ($conf->secure) { $mail->SMTPSecure = 'ssl'; $mail->Port = 465; } - $mail->setFrom ($conf->sender, 'Web'); - $mail->addAddress ($conf->recipient); - $mail->isHTML (TRUE); + $mail->setFrom($conf->sender, 'Web'); + $mail->addAddress($conf->recipient); + $mail->isHTML(TRUE); $mail->Subject = s('New customer request'); - $mail->Body = '
'. print_r ($_REQUEST, TRUE) .'
'; + $mail->Body = '
'. print_r($_REQUEST, TRUE) .'
'; - if (!$mail->send ()) - throw new Exception ($mail->ErrorInfo); + if (!$mail->send()) + throw new Exception ($mail->ErrorInfo); return TRUE; } diff --git a/rest/misc/exchange-rate.php b/rest/misc/exchange-rate.php index 5fdb0658..f76fa3a9 100644 --- a/rest/misc/exchange-rate.php +++ b/rest/misc/exchange-rate.php @@ -4,42 +4,38 @@ * Ejemplo: * */ -class ExchangeRate extends Vn\Lib\Method -{ - function run ($db) - { - $db->selectDb ('vn2008'); +class ExchangeRate extends Vn\Lib\Method { + function run($db) { + $db->selectDb('vn2008'); // Indica la URL del archivo - $xml = new SimpleXMLElement ( + $xml = new SimpleXMLElement( 'http://www.ecb.europa.eu/stats/eurofxref/eurofxref-hist-90d.xml', 0, TRUE); - $date = $db->getValue ("SELECT MAX(date) fecha FROM reference_rate"); - $maxDate = $date ? DateTime::createFromFormat ('Y-m-d', $date) : NULL; + $date = $db->getValue("SELECT MAX(date) fecha FROM reference_rate"); + $maxDate = $date ? DateTime::createFromFormat('Y-m-d', $date) : NULL; - foreach ($xml->Cube[0]->Cube as $cube) - { - $xmlDate = new DateTime ($cube['time']); + foreach($xml->Cube[0]->Cube as $cube) { + $xmlDate = new DateTime($cube['time']); // Si existen datos más recientes de la máxima fecha los añade if ($maxDate <= $xmlDate) - foreach ($cube->Cube as $subCube) - if ($subCube['currency'] == 'USD') - { + foreach($cube->Cube as $subCube) + if ($subCube['currency'] == 'USD') { $params = [ 'date' => $xmlDate, 'rate' => $subCube['rate'] ]; - $db->query ( - 'REPLACE INTO reference_rate (moneda_id, date, rate) - VALUES (2, #date, #rate)', + $db->query( + 'REPLACE INTO reference_rate(moneda_id, date, rate) + VALUES(2, #date, #rate)', $params ); } } - $db->queryFromFile (__DIR__.'/exrate-add'); + $db->queryFromFile(__DIR__.'/exrate-add'); } } diff --git a/rest/misc/mail.php b/rest/misc/mail.php index 3fb0c6f5..155e0980 100644 --- a/rest/misc/mail.php +++ b/rest/misc/mail.php @@ -1,56 +1,51 @@ selectDb ('vn2008'); - $db->query ('START TRANSACTION'); +class Mail extends Vn\Lib\Method { + function run($db) { + $db->selectDb('vn2008'); + $db->query('START TRANSACTION'); - $mailer = new Vn\Web\Mailer ($db); - $res = $db->query ( + $mailer = new Vn\Web\Mailer($db); + $res = $db->query( 'SELECT * FROM mail WHERE sent = 0 ORDER BY DATE_ODBC DESC LIMIT 20 FOR UPDATE'); $count = 0; - while ($row = $res->fetch_object ()) - { + while ($row = $res->fetch_object()) { $sent = 1; $status = 'OK'; try { - $mail = $mailer->createObject ($row->to, $row->text, $row->subject); - $mail->AddReplyTo ($row->reply_to, $row->reply_to); + $mail = $mailer->createObject($row->to, $row->text, $row->subject); + $mail->AddReplyTo($row->reply_to, $row->reply_to); - if (!empty ($row->path)) - { + if (!empty($row->path)) { $attachment = '/mnt/cluster/pdfs/'. $row->path; - if (file_exists ($attachment)) - $mail->AddAttachment ($attachment, ''); + if (file_exists($attachment)) + $mail->AddAttachment($attachment, ''); else - throw new Exception ("Attachment file could not be found: $attachment"); + throw new Exception("Attachment file could not be found: $attachment"); } - if (!$mail->Send ()) - throw new Exception ('Send error: '.$mail->ErrorInfo); + if (!$mail->Send()) + throw new Exception('Send error: '.$mail->ErrorInfo); $count++; } - catch (Exception $e) - { + catch (Exception $e) { $sent = 2; - $status = $e->getMessage (); + $status = $e->getMessage(); } - $db->query ('UPDATE mail SET sent = #, error = # WHERE id = #', + $db->query('UPDATE mail SET sent = #, error = # WHERE id = #', [$sent, $status, $row->id]); } - $db->query ('COMMIT'); + $db->query('COMMIT'); echo "Total $count mails sent\n"; } } diff --git a/rest/misc/production.php b/rest/misc/production.php index 91f7e0b6..5372b415 100644 --- a/rest/misc/production.php +++ b/rest/misc/production.php @@ -1,19 +1,17 @@ getObject ( + function run($db) { + $row = $db->getObject( 'SELECT displayText, status FROM vn.routeGate WHERE deviceId = #', [$_REQUEST['deviceId']] ); if (!isset($row)) - throw new Vn\Lib\UserException ('Device not found'); + throw new Vn\Lib\UserException('Device not found'); return $row; } diff --git a/rest/misc/sms.php b/rest/misc/sms.php index b358a1dd..b3e20308 100644 --- a/rest/misc/sms.php +++ b/rest/misc/sms.php @@ -2,8 +2,7 @@ use Vn\Lib; -class Sms extends Vn\Web\JsonRequest -{ +class Sms extends Vn\Web\JsonRequest { const PARAMS = [ 'destination' ,'message' @@ -14,22 +13,21 @@ class Sms extends Vn\Web\JsonRequest 200 // Processing ]; - function run ($db) - { - $smsConfig = $db->getObject ('SELECT uri, user, password, title FROM vn.smsConfig'); + function run($db) { + $smsConfig = $db->getObject('SELECT uri, user, password, title FROM vn.smsConfig'); - $sClient = new SoapClient ($smsConfig->uri); - $xmlString = $sClient->sendSMS ( + $sClient = new SoapClient($smsConfig->uri); + $xmlString = $sClient->sendSMS( $smsConfig->user ,$smsConfig->password ,$smsConfig->title ,$_REQUEST['destination'] ,$_REQUEST['message'] ); - $xmlResponse = new SimpleXMLElement ($xmlString); + $xmlResponse = new SimpleXMLElement($xmlString); $res = $xmlResponse->sms; - $db->query ( + $db->query( 'INSERT INTO vn.sms SET `senderFk` = account.myUserGetId(), `destinationFk` = #, @@ -38,7 +36,7 @@ class Sms extends Vn\Web\JsonRequest `statusCode` = #, `status` = #', [ - empty ($_REQUEST['destinationId']) ? NULL : $_REQUEST['destinationId'] + empty($_REQUEST['destinationId']) ? NULL : $_REQUEST['destinationId'] ,$_REQUEST['destination'] ,$_REQUEST['message'] ,$res->codigo @@ -46,8 +44,8 @@ class Sms extends Vn\Web\JsonRequest ] ); - if (!in_array ((int) $res->codigo, self::OK_STATES)) - throw new Lib\UserException ($res->descripcion); + if (!in_array((int) $res->codigo, self::OK_STATES)) + throw new Lib\UserException($res->descripcion); return TRUE; } diff --git a/rest/misc/visits-sync.php b/rest/misc/visits-sync.php index 61c10a5c..f9ad1b16 100644 --- a/rest/misc/visits-sync.php +++ b/rest/misc/visits-sync.php @@ -1,18 +1,15 @@ query ("SELECT id, agent FROM visit_agent +class VisitsSync extends Vn\Lib\Method { + function run($db) { + $result = $db->query("SELECT id, agent FROM visit_agent WHERE version = '0.0' OR platform = 'unknown' OR cookies IS NULL ORDER BY id DESC"); - $stmt = $db->prepare ('UPDATE visit_agent + $stmt = $db->prepare('UPDATE visit_agent SET platform = ?, browser = ?, version = ?, javascript = ?, cookies = ? WHERE id = ?'); - if ($result && $stmt) - { - set_time_limit (0); + if ($result && $stmt) { + set_time_limit(0); $stmt->bind_param('sssiii' ,$platform @@ -27,16 +24,15 @@ class VisitsSync extends Vn\Lib\Method $count = 0; - while ($row = $result->fetch_assoc ()) - { - $info = get_browser ($row['agent']); + while ($row = $result->fetch_assoc()) { + $info = get_browser($row['agent']); $platform = $info->platform; $browser = $info->browser; $version = $info->version; $javascript = $info->javascript; $cookies = $info->cookies; $id = $row['id']; - $stmt->execute (); + $stmt->execute(); $count++; } @@ -45,8 +41,8 @@ class VisitsSync extends Vn\Lib\Method } if ($stmt) - $stmt->close (); + $stmt->close(); if ($result) - $result->free (); + $result->free(); } } diff --git a/rest/tpv/confirm-mail.php b/rest/tpv/confirm-mail.php index 6c12a38c..dc71a13a 100644 --- a/rest/tpv/confirm-mail.php +++ b/rest/tpv/confirm-mail.php @@ -1,49 +1,45 @@ getObject ( + $imapConf = $db->getObject( 'SELECT host, user, pass, cleanPeriod, successFolder, errorFolder FROM tpvImapConfig' ); - $mailbox = sprintf ('{%s/imap/ssl/novalidate-cert}', + $mailbox = sprintf('{%s/imap/ssl/novalidate-cert}', $imapConf->host); - $imap = imap_open ($mailbox + $imap = imap_open($mailbox ,$imapConf->user - ,base64_decode ($imapConf->pass) + ,base64_decode($imapConf->pass) ); if (!$imap) - throw new Exception (imap_last_error ()); + throw new Exception(imap_last_error()); // Fetchs and confirms new transaction mails $count = 0; - $inbox = imap_search ($imap, 'ALL'); + $inbox = imap_search($imap, 'ALL'); if ($inbox) - foreach ($inbox as $msg) - { + foreach($inbox as $msg) { // Decodes the mail body $params = []; - $body = imap_fetchbody ($imap, $msg, '1'); - $strings = explode (';', $body); + $body = imap_fetchbody($imap, $msg, '1'); + $strings = explode(';', $body); - foreach ($strings as $string) - { - $x = explode (':', $string); - $params[trim ($x[0])] = trim ($x[1]); + foreach($strings as $string) { + $x = explode(':', $string); + $params[trim($x[0])] = trim($x[1]); } // Confirms the transaction @@ -51,11 +47,10 @@ class ConfirmMail extends Vn\Lib\Method $success = FALSE; try { - $success = Tpv::confirm ($db, $params); + $success = Tpv::confirm($db, $params); } - catch (\Exception $e) - { - trigger_error ($e->getMessage (), E_USER_WARNING); + catch (\Exception $e) { + trigger_error($e->getMessage(), E_USER_WARNING); } // Moves the processed mail to another folder @@ -65,38 +60,36 @@ class ConfirmMail extends Vn\Lib\Method else $folder = $imapConf->errorFolder; - if (!imap_mail_move ($imap, $msg, "$folder")) - trigger_error (imap_last_error (), E_USER_WARNING); + if (!imap_mail_move($imap, $msg, "$folder")) + trigger_error(imap_last_error(), E_USER_WARNING); $count++; } - imap_expunge ($imap); + imap_expunge($imap); // Cleans the old mails $deleted = 0; - if (rand (1, 20) == 1) - { - $folders = array ( + if (rand(1, 20) == 1) { + $folders = array( $imapConf->successFolder ,$imapConf->errorFolder ); - $date = new \DateTime (NULL); - $date->sub (new \DateInterval ($imapConf->cleanPeriod)); - $filter = sprintf ('BEFORE "%s"', $date->format('D, j M Y')); + $date = new \DateTime(NULL); + $date->sub(new \DateInterval($imapConf->cleanPeriod)); + $filter = sprintf('BEFORE "%s"', $date->format('D, j M Y')); - foreach ($folders as $folder) - if (imap_reopen ($imap, $mailbox.'.'.$folder)) - if ($messages = imap_search ($imap, $filter)) - { - foreach ($messages as $message) - imap_delete ($imap, $message); + foreach($folders as $folder) + if (imap_reopen($imap, $mailbox.'.'.$folder)) + if ($messages = imap_search($imap, $filter)) { + foreach($messages as $message) + imap_delete($imap, $message); - imap_expunge ($imap); - $deleted += count ($messages); + imap_expunge($imap); + $deleted += count($messages); } } diff --git a/rest/tpv/confirm-post.php b/rest/tpv/confirm-post.php index 73975773..9aef1112 100644 --- a/rest/tpv/confirm-post.php +++ b/rest/tpv/confirm-post.php @@ -1,15 +1,13 @@ addFunction ('procesaNotificacionSIS'); - $server->handle (); + $server = new SoapServer(__DIR__ .'/soap.wsdl'); + $server->addFunction('procesaNotificacionSIS'); + $server->handle(); } } -function procesaNotificacionSIS ($XML) -{ +function procesaNotificacionSIS($XML) { global $tpvConfirmSoap; - $db = $tpvConfirmSoap->app->getSysConn (); + $db = $tpvConfirmSoap->app->getSysConn(); $status = 'OK'; $requestString = $XML; @@ -33,50 +30,49 @@ function procesaNotificacionSIS ($XML) // Processes the request try { - $xml = new SimpleXMLElement ($requestString); - $params = (array) $xml->{'Request'}; + $xml = new SimpleXMLElement($requestString); + $params =(array) $xml->{'Request'}; - if (!(isset ($params['Ds_Amount']) - && isset ($params['Ds_Order']) - && isset ($params['Ds_MerchantCode']) - && isset ($params['Ds_Currency']) - && isset ($params['Ds_Response']))) - throw new Exception ('Missing required parameters'); + if (!(isset($params['Ds_Amount']) + && isset($params['Ds_Order']) + && isset($params['Ds_MerchantCode']) + && isset($params['Ds_Currency']) + && isset($params['Ds_Response']))) + throw new Exception('Missing required parameters'); // Checks the signature - $start = strpos ($requestString, ''); - $shaString = substr ($requestString, $start, $end - $start + 10); + $start = strpos($requestString, ''); + $shaString = substr($requestString, $start, $end - $start + 10); - $key = $db->getValue ( + $key = $db->getValue( 'SELECT secretKey FROM tpvMerchant WHERE id = #' ,[$params['Ds_MerchantCode']] ); - if (sha1 ($shaString.$key) != $xml->{'Signature'}) - throw new Exception ('Invalid signature'); + if (sha1($shaString.$key) != $xml->{'Signature'}) + throw new Exception('Invalid signature'); // Confirms the transaction - Tpv::confirm ($db, $params); + Tpv::confirm($db, $params); } - catch (Exception $e) - { + catch (Exception $e) { $status = 'KO'; } // Generates the response - $responseString = file_get_contents (__DIR__ .'/soap-reply.xml'); - $xml = new SimpleXMLElement ($responseString); + $responseString = file_get_contents(__DIR__ .'/soap-reply.xml'); + $xml = new SimpleXMLElement($responseString); $response = $xml->{'Response'}; $response->{'Ds_Response_Merchant'} = $status; - $xml->{'Signature'} = sha1 ($response->asXML ().$key); + $xml->{'Signature'} = sha1($response->asXML().$key); - return $xml->asXML (); + return $xml->asXML(); /* // Another way to generate the response @@ -88,7 +84,7 @@ function procesaNotificacionSIS ($XML) $xmlMessage = ' '. $xmlResponse .' - '. sha1 ($xmlResponse.$key) .' + '. sha1($xmlResponse.$key) .' '; return $xmlMessage; diff --git a/rest/tpv/soap-test.php b/rest/tpv/soap-test.php index b9ea75cc..ab97760f 100644 --- a/rest/tpv/soap-test.php +++ b/rest/tpv/soap-test.php @@ -1,29 +1,27 @@ __soapCall ('procesaNotificacionSIS', [ + $client = new SoapClient(__DIR__.'/soap.wsdl'); + $result = $client->__soapCall('procesaNotificacionSIS', [ 'XML' => $requestString ]); - $xml = new SimpleXMLElement ($result); + $xml = new SimpleXMLElement($result); $key = $_POST['key']; - $start = strpos ($result, ''); - $shaString = substr ($result, $start, $end - $start + 11); - $shaHash = sha1 ($shaString.$key); + $start = strpos($result, ''); + $shaString = substr($result, $start, $end - $start + 11); + $shaHash = sha1($shaString.$key); $isValid = $xml->{'Signature'} == $shaHash; } -else -{ +else { $key = ''; $result = ''; $shaHash = ''; @@ -46,7 +44,7 @@ else

Response

-

+

Signature

diff --git a/rest/tpv/tpv.php b/rest/tpv/tpv.php index e5b63cd2..81d6d7f3 100644 --- a/rest/tpv/tpv.php +++ b/rest/tpv/tpv.php @@ -1,26 +1,24 @@ query ( - 'CALL tpvTransactionConfirm (#, #, #, #, #, #)', + return $db->query( + 'CALL tpvTransactionConfirm(#, #, #, #, #, #)', [ $params['Ds_Amount'] ,$params['Ds_Order'] diff --git a/rest/tpv/transaction.php b/rest/tpv/transaction.php index 293edf65..8033a18e 100644 --- a/rest/tpv/transaction.php +++ b/rest/tpv/transaction.php @@ -3,24 +3,22 @@ /** * Starts a new TPV transaction and returns the params. */ -class Transaction extends Vn\Web\JsonRequest -{ +class Transaction extends Vn\Web\JsonRequest { const PARAMS = ['amount']; - function run ($db) - { - $amount = (int) $_REQUEST['amount']; - $companyId = empty ($_REQUEST['company']) ? NULL : $_REQUEST['company']; + function run($db) { + $amount =(int) $_REQUEST['amount']; + $companyId = empty($_REQUEST['company']) ? NULL : $_REQUEST['company']; - $row = $db->getObject ('CALL tpvTransactionStart (#, #)', + $row = $db->getObject('CALL tpvTransactionStart(#, #)', [$amount, $companyId]); - if (!isset ($row)) - throw new Exception ('Transaction error'); + if (!isset($row)) + throw new Exception('Transaction error'); - $transactionId = str_pad ($row->transactionId, 12, '0', STR_PAD_LEFT); - $urlOk = empty ($_REQUEST['urlOk']) ? '' : sprintf ($_REQUEST['urlOk'], $transactionId); - $urlKo = empty ($_REQUEST['urlKo']) ? '' : sprintf ($_REQUEST['urlKo'], $transactionId); + $transactionId = str_pad($row->transactionId, 12, '0', STR_PAD_LEFT); + $urlOk = empty($_REQUEST['urlOk']) ? '' : sprintf($_REQUEST['urlOk'], $transactionId); + $urlKo = empty($_REQUEST['urlKo']) ? '' : sprintf($_REQUEST['urlKo'], $transactionId); $merchantUrl = $row->merchantUrl ? $row->merchantUrl : ''; $params = [ @@ -35,15 +33,15 @@ class Transaction extends Vn\Web\JsonRequest ,'Ds_Merchant_UrlKO' => $urlKo ]; - $encodedParams = base64_encode (json_encode ($params)); + $encodedParams = base64_encode(json_encode($params)); - $key = base64_decode ($row->secretKey); + $key = base64_decode($row->secretKey); $bytes = [0, 0, 0, 0, 0, 0, 0, 0]; - $iv = implode (array_map ('chr', $bytes)); - $key = mcrypt_encrypt (MCRYPT_3DES, $key, $transactionId, MCRYPT_MODE_CBC, $iv); + $iv = implode(array_map('chr', $bytes)); + $key = mcrypt_encrypt(MCRYPT_3DES, $key, $transactionId, MCRYPT_MODE_CBC, $iv); - $signature = base64_encode (hash_hmac ('sha256', $encodedParams, $key, TRUE)); + $signature = base64_encode(hash_hmac('sha256', $encodedParams, $key, TRUE)); $url = $row->url; $postValues = [ diff --git a/web/app.php b/web/app.php index 264f818b..22d0a06a 100644 --- a/web/app.php +++ b/web/app.php @@ -8,8 +8,7 @@ namespace Vn\Web; * Format for $_REQUEST['srv'] variable: * - [serviceName]:[requestDir]/[requestFile] **/ -class App extends \Vn\Lib\App -{ +class App extends \Vn\Lib\App { protected $conn = NULL; private $allowedServices = [ @@ -18,34 +17,32 @@ class App extends \Vn\Lib\App 'json' ]; - function run () - { - $this->init (); + function run() { + $this->init(); - $srv = empty ($_REQUEST['srv']) ? '' : $_REQUEST['srv']; - $explode = explode (':', $srv, 2); + $srv = empty($_REQUEST['srv']) ? '' : $_REQUEST['srv']; + $explode = explode(':', $srv, 2); - if (count ($explode) > 0) + if (count($explode) > 0) $_REQUEST['service'] = $explode[0]; - if (count ($explode) > 1) + if (count($explode) > 1) $_REQUEST['method'] = $explode[1]; - $service = empty ($_REQUEST['service']) ? 'html' : $_REQUEST['service']; + $service = empty($_REQUEST['service']) ? 'html' : $_REQUEST['service']; - if (in_array ($service, $this->allowedServices, TRUE)) - { + if (in_array($service, $this->allowedServices, TRUE)) { $includeFile = __DIR__."/$service-service.php"; - require_once ($includeFile); + require_once($includeFile); - $className = __NAMESPACE__ .'\\'. hyphenToCamelCase ($service, TRUE) .'Service'; - $service = new $className ($this); - $service->run (); + $className = __NAMESPACE__ .'\\'. hyphenToCamelCase($service, TRUE) .'Service'; + $service = new $className($this); + $service->run(); } else - http_response_code (400); + http_response_code(400); } - function deinit () {} + function deinit() {} /** * Gets the configuration file name associated to the current vhost @@ -53,23 +50,21 @@ class App extends \Vn\Lib\App * * @return string The config file name **/ - function getConfigFile () - { - if (!empty ($_SERVER['SERVER_NAME']) - && preg_match ('/^[\w\-\.]+$/', $_SERVER['SERVER_NAME'])) - { - $hostSplit = explode ('.', $_SERVER['SERVER_NAME']); - array_splice ($hostSplit, -2); - $subdomain = implode ('.', $hostSplit); + function getConfigFile() { + if (!empty($_SERVER['SERVER_NAME']) + && preg_match('/^[\w\-\.]+$/', $_SERVER['SERVER_NAME'])) { + $hostSplit = explode('.', $_SERVER['SERVER_NAME']); + array_splice($hostSplit, -2); + $subdomain = implode('.', $hostSplit); $configDir = _CONFIG_DIR .'/'. $this->name; $hostFile = "$configDir/config.$subdomain.php"; } - if (isset ($hostFile) && file_exists ($hostFile)) + if (isset($hostFile) && file_exists($hostFile)) return $hostFile; else - return parent::getConfigFile (); + return parent::getConfigFile(); } } diff --git a/web/db-session-handler.php b/web/db-session-handler.php index 72e563f1..bdfd5e3a 100644 --- a/web/db-session-handler.php +++ b/web/db-session-handler.php @@ -2,35 +2,29 @@ namespace Vn\Web; -class DbSessionHandler implements \SessionHandlerInterface -{ +class DbSessionHandler implements \SessionHandlerInterface { private $db; - function __construct ($db) - { + function __construct($db) { $this->db = $db; } - function open ($savePath, $name) - { + function open($savePath, $name) { return TRUE; } - function close () - { + function close() { return TRUE; } - function read ($sessionId) - { - $sessionData = $this->db->getValue ( + function read($sessionId) { + $sessionData = $this->db->getValue( 'SELECT data FROM userSession WHERE ssid = #', [$sessionId]); - return isset ($sessionData) ? $sessionData : ''; + return isset($sessionData) ? $sessionData : ''; } - function write ($sessionId, $sessionData) - { - $this->db->query ( + function write($sessionId, $sessionData) { + $this->db->query( 'INSERT INTO userSession SET ssid = #, data = #, lastUpdate = NOW() ON DUPLICATE KEY UPDATE @@ -39,15 +33,13 @@ class DbSessionHandler implements \SessionHandlerInterface return TRUE; } - function destroy ($sessionId) - { - $this->db->query ('DELETE FROM userSession WHERE ssid = #', [$sessionId]); + function destroy($sessionId) { + $this->db->query('DELETE FROM userSession WHERE ssid = #', [$sessionId]); return TRUE; } - function gc ($maxLifeTime) - { - $this->db->query ('DELETE FROM userSession + function gc($maxLifeTime) { + $this->db->query('DELETE FROM userSession WHERE lastUpdate < TIMESTAMPADD(SECOND, -#, NOW())', [$maxLifeTime] ); diff --git a/web/html-service.php b/web/html-service.php index 2cfb70fc..548e90d3 100644 --- a/web/html-service.php +++ b/web/html-service.php @@ -7,57 +7,51 @@ use Vn\Lib\Locale; /** * Base class for services that sends response as HTML format. */ -class HtmlService extends Service -{ - function run () - { +class HtmlService extends Service { + function run() { $eFlag = E_ERROR | E_USER_ERROR; - set_error_handler ([$this, 'errorHandler'], $eFlag); - set_exception_handler ([$this, 'errorHandler']); + set_error_handler([$this, 'errorHandler'], $eFlag); + set_exception_handler([$this, 'errorHandler']); - $this->init (); + $this->init(); $db = $this->db; - if (!$this->isHttps () - && $db->getValue ('SELECT https FROM config') && !_DEV_MODE) - { - header ("Location: https://{$this->getUri()}"); - exit (0); + if (!$this->isHttps() + && $db->getValue('SELECT https FROM config') && !_DEV_MODE) { + header("Location: https://{$this->getUri()}"); + exit(0); } - $this->startSession (); + $this->startSession(); // Getting the requested page - if (!empty ($_REQUEST['method']) && isHyphen ($_REQUEST['method'])) + if (!empty($_REQUEST['method']) && isHyphen($_REQUEST['method'])) $page = $_REQUEST['method']; else $page = 'main'; // Checking the browser version - if (!isset ($_SESSION['skipBrowser']) && $page != 'update-browser') - { + if (!isset($_SESSION['skipBrowser']) && $page != 'update-browser') { $updateBrowser = FALSE; - if (!isset ($_GET['skipBrowser']) + if (!isset($_GET['skipBrowser']) && isset($_SERVER['HTTP_USER_AGENT']) - && ($browser = get_browser ($_SERVER['HTTP_USER_AGENT']))) - { - $browserVersion = (double) $browser->version; - $minVersion = $db->getValue ( + &&($browser = get_browser($_SERVER['HTTP_USER_AGENT']))) { + $browserVersion =(double) $browser->version; + $minVersion = $db->getValue( 'SELECT version FROM browser WHERE name = #', [$browser->browser]); $updateBrowser = $browserVersion > 0 - && isset ($minVersion) && $browserVersion < $minVersion; + && isset($minVersion) && $browserVersion < $minVersion; } - if ($updateBrowser) - { - header ('Location: ?method=update-browser'); - exit (0); + if ($updateBrowser) { + header('Location: ?method=update-browser'); + exit(0); } else $_SESSION['skipBrowser'] = TRUE; @@ -65,57 +59,52 @@ class HtmlService extends Service // If enabled, requests the user to choose between two web versions - if (!isset ($_SESSION['skipVersionMenu']) - && $db->getValue ('SELECT testDomain FROM config')) - { + if (!isset($_SESSION['skipVersionMenu']) + && $db->getValue('SELECT testDomain FROM config')) { $_SESSION['skipVersionMenu'] = TRUE; - header ('Location: ?method=version-menu'); + header('Location: ?method=version-menu'); } // Setting the version - setcookie ('vnVersion', $this->getVersion ()); + setcookie('vnVersion', $this->getVersion()); // Loading the requested page $basePath = "pages/$page"; - if (file_exists ($basePath)) - { - Locale::addPath ($basePath); + if (file_exists($basePath)) { + Locale::addPath($basePath); $phpFile = "./$basePath/$page.php"; - if (file_exists ($phpFile)) - require ($phpFile); + if (file_exists($phpFile)) + require($phpFile); - $this->printHeader (); + $this->printHeader(); $dir = $basePath; include_once __DIR__.'/html.php'; - include ("./$basePath/ui.php"); + include("./$basePath/ui.php"); } else - header ('Location: ./'); + header('Location: ./'); } - function printHeader () - { - header ('Content-Type: text/html; charset=UTF-8'); - //header ("Content-Security-Policy: default-src *; img-src *;"); + function printHeader() { + header('Content-Type: text/html; charset=UTF-8'); + //header("Content-Security-Policy: default-src *; img-src *;"); } - function errorHandler ($err) - { + function errorHandler($err) { error_log("{$err->getMessage()} {$err->getTraceAsString()}"); - $this->printHeader (); - include (__DIR__.'/unavailable.html'); - exit (0); + $this->printHeader(); + include(__DIR__.'/unavailable.html'); + exit(0); return FALSE; } - function isMobile () - { + function isMobile() { $re = '/(Android|webOS|iPhone|iPad|iPod|BlackBerry|Windows Phone)/i'; - return preg_match ($re, $_SERVER['HTTP_USER_AGENT']); + return preg_match($re, $_SERVER['HTTP_USER_AGENT']); } } diff --git a/web/html.php b/web/html.php index c01d7b00..282904ea 100644 --- a/web/html.php +++ b/web/html.php @@ -3,66 +3,60 @@ $lang = isset($_SESSION['lang']) ? $_SESSION['lang'] : 'en'; $version = $this->getVersion(); -function getUrl ($fileName) -{ +function getUrl($fileName) { global $version; - if (file_exists ($fileName)) - $fileVersion = strftime ('%G%m%d%H%M%S', filemtime ($fileName)); + if (file_exists($fileName)) + $fileVersion = strftime('%G%m%d%H%M%S', filemtime($fileName)); else $fileVersion = $version; return "$fileName?$fileVersion"; } -function js ($fileName) -{ - return ''."\n"; +function js($fileName) { + return ''."\n"; } -function css ($fileName) -{ - return ''."\n"; +function css($fileName) { + return ''."\n"; } -function getWebpackAssets () -{ - $wpConfig = json_decode (file_get_contents ('webpack.config.json')); +function getWebpackAssets() { + $wpConfig = json_decode(file_get_contents('webpack.config.json')); $buildDir = $wpConfig->buildDir; $devServerPort = $wpConfig->devServerPort; $host = $_SERVER['SERVER_NAME']; $assets = new stdClass(); - if (!_DEV_MODE) - { - $wpAssets = json_decode (file_get_contents ("$buildDir/webpack-assets.json")); + if (!_DEV_MODE) { + $wpAssets = json_decode(file_get_contents("$buildDir/webpack-assets.json")); $manifestJs = $wpAssets->manifest->js; $mainJs = $wpAssets->main->js; - unset ($wpAssets->manifest); - unset ($wpAssets->main); + unset($wpAssets->manifest); + unset($wpAssets->main); - foreach ($wpAssets as $name => $asset) - if (property_exists ($asset, 'js')) + foreach($wpAssets as $name => $asset) + if (property_exists($asset, 'js')) $assets->$name = $asset->js; } - else - { + else { $devServerPath = "http://$host:$devServerPort/$buildDir"; $manifestJs = "$devServerPath/manifest.js"; $mainJs = "$devServerPath/main.js"; - unset ($wpConfig->entry->main); + unset($wpConfig->entry->main); - foreach ($wpConfig->entry as $asset => $files) + foreach($wpConfig->entry as $asset => $files) $assets->$asset = "$devServerPath/$asset.js"; } $jsFiles = []; $jsFiles[] = $manifestJs; - foreach ($assets as $jsFile) + foreach($assets as $jsFile) $jsFiles[] = $jsFile; $jsFiles[] = $mainJs; diff --git a/web/json-exception.php b/web/json-exception.php index e81bb677..d71e16f6 100644 --- a/web/json-exception.php +++ b/web/json-exception.php @@ -9,8 +9,7 @@ namespace Vn\Web; * @property string $message The message string * @property string $code The code of message **/ -class JsonException -{ +class JsonException { var $exception = NULL; var $message; var $code = NULL; diff --git a/web/json-reply.php b/web/json-reply.php index deacf41a..a3f7a4fa 100644 --- a/web/json-reply.php +++ b/web/json-reply.php @@ -8,8 +8,7 @@ namespace Vn\Web; * @property Object $data The returned data * @property array $warnings Array with warning messages **/ -class JsonReply -{ +class JsonReply { var $data = NULL; var $warnings = NULL; } diff --git a/web/json-service.php b/web/json-service.php index b8cb98ac..38257ec7 100644 --- a/web/json-service.php +++ b/web/json-service.php @@ -7,36 +7,32 @@ use Vn\Lib; /** * Base class for JSON application. */ -class JsonService extends RestService -{ +class JsonService extends RestService { private $warnings = NULL; - function run () - { - ini_set ('display_errors', FALSE); - set_error_handler ([$this, 'errorHandler'], E_ALL); - set_exception_handler ([$this, 'exceptionHandler']); + function run() { + ini_set('display_errors', FALSE); + set_error_handler([$this, 'errorHandler'], E_ALL); + set_exception_handler([$this, 'exceptionHandler']); - $this->init (); - $this->startSession (); - $this->checkVersion (); + $this->init(); + $this->startSession(); + $this->checkVersion(); - $json = $this->loadMethod (__NAMESPACE__.'\JsonRequest'); - $this->replyJson ($json); + $json = $this->loadMethod(__NAMESPACE__.'\JsonRequest'); + $this->replyJson($json); } - function replyJson ($jsonData) - { - $reply = new JsonReply (); + function replyJson($jsonData) { + $reply = new JsonReply(); $reply->data = $jsonData; $reply->warnings = $this->warnings; - header ('Content-Type: application/json; charset=UTF-8'); - echo json_encode ($reply); + header('Content-Type: application/json; charset=UTF-8'); + echo json_encode($reply); } - function errorHandler ($errno, $message, $file, $line, $context) - { + function errorHandler($errno, $message, $file, $line, $context) { $eUserWarn = E_USER_NOTICE | E_USER_WARNING @@ -49,62 +45,55 @@ class JsonService extends RestService $eWarn = $eUserWarn | $eCoreWarn; $eUser = $eUserWarn | E_USER_ERROR; - $json = new JsonException (); + $json = new JsonException(); if (_ENABLE_DEBUG || $errno & $eUser) $json->message = $message; else $json->message = s('Something went wrong'); - if (_ENABLE_DEBUG) - { + if (_ENABLE_DEBUG) { $json->code = $errno; $json->file = $file; $json->line = $line; } - if ($errno & $eWarn) - { - if (!isset ($this->warnings)) + if ($errno & $eWarn) { + if (!isset($this->warnings)) $this->warnings = []; $this->warnings[] = $json; } - else - { - http_response_code (500); - $this->replyJson ($json); - exit (); + else { + http_response_code(500); + $this->replyJson($json); + exit(); } return !($errno & $eUser); } - function exceptionHandler ($e) - { - $json = new JsonException (); + function exceptionHandler($e) { + $json = new JsonException(); - if (_ENABLE_DEBUG || $e instanceof Lib\UserException) - { - $json->exception = get_class ($e); - $json->message = $e->getMessage (); + if (_ENABLE_DEBUG || $e instanceof Lib\UserException) { + $json->exception = get_class($e); + $json->message = $e->getMessage(); } - else - { + else { $json->exception = 'Exception'; $json->message = s('Something went wrong'); } - if (_ENABLE_DEBUG) - { - $json->code = $e->getCode (); - $json->file = $e->getFile (); - $json->line = $e->getLine (); - $json->trace = $e->getTrace (); + if (_ENABLE_DEBUG) { + $json->code = $e->getCode(); + $json->file = $e->getFile(); + $json->line = $e->getLine(); + $json->trace = $e->getTrace(); } - $this->statusFromException ($e); - $this->replyJson ($json); + $this->statusFromException($e); + $this->replyJson($json); if (!($e instanceof Lib\UserException)) throw $e; diff --git a/web/jwt.php b/web/jwt.php index 562b20e3..121ac22a 100644 --- a/web/jwt.php +++ b/web/jwt.php @@ -8,8 +8,7 @@ use Exception; * Basic class to encode, decode and verify JWT tokens. It implements the HS256 * algorithm from the RFC 7519 standard. **/ -class Jwt -{ +class Jwt { /** * Creates a new JWT token with the passed $payload and $key. * @@ -17,16 +16,15 @@ class Jwt * @param {string} $key The key used to sign the token * @return {string} The new JWT token **/ - static function encode ($payload, $key) - { + static function encode($payload, $key) { $header = [ 'alg' => 'HS256', 'typ' => 'JWT' ]; - $b64Header = self::jsonB64Encode ($header); - $b64Payload = self::jsonB64Encode ($payload); - $b64Signature = self::getSignature ($b64Header, $b64Payload, $key); + $b64Header = self::jsonB64Encode($header); + $b64Payload = self::jsonB64Encode($payload); + $b64Signature = self::getSignature($b64Header, $b64Payload, $key); return "$b64Header.$b64Payload.$b64Signature"; } @@ -38,51 +36,45 @@ class Jwt * @param {string} $key The key used to validate the token * @return {string} The JWT validated and decoded data **/ - static function decode ($token, $key) - { - $parts = explode ('.', $token); + static function decode($token, $key) { + $parts = explode('.', $token); if (count($parts) !== 3) - throw new Exception ('Bad JWT token'); + throw new Exception('Bad JWT token'); $b64Header = $parts[0]; $b64Payload = $parts[1]; $b64Signature = $parts[2]; - $header = self::jsonB64Decode ($b64Header); - $payload = self::jsonB64Decode ($b64Payload); + $header = self::jsonB64Decode($b64Header); + $payload = self::jsonB64Decode($b64Payload); - if ($b64Signature != self::getSignature ($b64Header, $b64Payload, $key)) - throw new Exception ('Bad token signature'); + if ($b64Signature != self::getSignature($b64Header, $b64Payload, $key)) + throw new Exception('Bad token signature'); return $payload; } - static function getSignature ($b64Header, $b64Payload, $key) - { - $signature = hash_hmac ('sha256', "$b64Header.$b64Payload", $key, TRUE); - return self::base64UrlEncode ($signature); + static function getSignature($b64Header, $b64Payload, $key) { + $signature = hash_hmac('sha256', "$b64Header.$b64Payload", $key, TRUE); + return self::base64UrlEncode($signature); } - static function jsonB64Encode ($data) - { - return self::base64UrlEncode (json_encode ($data)); + static function jsonB64Encode($data) { + return self::base64UrlEncode(json_encode($data)); } - static function jsonB64Decode ($data) - { - return json_decode (self::base64UrlDecode ($data), TRUE); + static function jsonB64Decode($data) { + return json_decode(self::base64UrlDecode($data), TRUE); } - static function base64UrlEncode ($data) - { - return rtrim (strtr (base64_encode ($data), '+/', '-_'), '='); + static function base64UrlEncode($data) { + return rtrim(strtr(base64_encode($data), '+/', '-_'), '='); } - static function base64UrlDecode ($data) - { - $remainder = strlen ($data) % 4; - $data = strtr ($data, '-_', '+/'); - return base64_decode (str_pad ($data, $remainder, '=', STR_PAD_RIGHT)); + static function base64UrlDecode($data) { + $remainder = strlen($data) % 4; + $data = strtr($data, '-_', '+/'); + return base64_decode(str_pad($data, $remainder, '=', STR_PAD_RIGHT)); } } diff --git a/web/mailer.php b/web/mailer.php index aeaba74c..2070f53a 100644 --- a/web/mailer.php +++ b/web/mailer.php @@ -6,60 +6,54 @@ require_once 'libphp-phpmailer/PHPMailerAutoload.php'; use Vn\Lib\UserException; -class Mailer -{ +class Mailer { private $conf; - function __construct ($db) - { - $this->conf = $db->getObject ( + function __construct($db) { + $this->conf = $db->getObject( 'SELECT host, port, secure, sender, senderName, user, password FROM hedera.mailConfig' ); } - function createObject ($mailTo, $body, $subject) - { + function createObject($mailTo, $body, $subject) { $conf = $this->conf; - $mail = new \PHPMailer (); - $mail->isSMTP (); + $mail = new \PHPMailer(); + $mail->isSMTP(); $mail->Host = $conf->host; - if (!empty ($conf->user)) - { + if (!empty($conf->user)) { $mail->SMTPAuth = TRUE; $mail->Username = $conf->user; - $mail->Password = base64_decode ($conf->password); + $mail->Password = base64_decode($conf->password); } else $mail->SMTPAuth = FALSE; - if ($conf->secure) - { + if ($conf->secure) { $mail->SMTPSecure = 'ssl'; $mail->Port = 465; } - $mail->setFrom ($conf->sender, $conf->senderName); - $mail->IsHTML (TRUE); + $mail->setFrom($conf->sender, $conf->senderName); + $mail->IsHTML(TRUE); $mail->Subject = $subject; $mail->Body = $body; $mail->CharSet = 'UTF-8'; - $mailList = explode (',', $mailTo); + $mailList = explode(',', $mailTo); - foreach ($mailList as $to) - $mail->AddAddress ($to); + foreach($mailList as $to) + $mail->AddAddress($to); return $mail; } - function send ($mailTo, $body, $subject) - { - $mail = $this->createObject ($mailTo, $body, $subject); + function send($mailTo, $body, $subject) { + $mail = $this->createObject($mailTo, $body, $subject); - if (!$mail->Send ()) - throw new UserException ('Send error: '.$mail->ErrorInfo); + if (!$mail->Send()) + throw new UserException('Send error: '.$mail->ErrorInfo); } } diff --git a/web/report.php b/web/report.php index 8a376c71..40701cde 100644 --- a/web/report.php +++ b/web/report.php @@ -2,43 +2,38 @@ namespace Vn\Web; -class Report -{ +class Report { var $db; var $name; var $html; - function __construct ($db, $reportName, $params) - { + function __construct($db, $reportName, $params) { $this->db = $db; $this->name = $reportName; - extract ($params); + extract($params); - \Vn\Lib\Locale::addPath ("reports/$reportName"); + \Vn\Lib\Locale::addPath("reports/$reportName"); - ob_start (); + ob_start(); include __DIR__.'/report.html.php'; - $this->html = ob_get_contents (); - ob_end_clean (); + $this->html = ob_get_contents(); + ob_end_clean(); - if (isset ($title)) + if (isset($title)) $this->title = $title; } - function getTitle () - { + function getTitle() { return $this->title; } - function getHtml () - { + function getHtml() { return $this->html; } - function sendMail ($mail) - { - $mailer = new Mailer ($this->db); - $mailer->send ($mail, $this->html, $this->title); + function sendMail($mail) { + $mailer = new Mailer($this->db); + $mailer->send($mail, $this->html, $this->title); } } diff --git a/web/rest-request.php b/web/rest-request.php index ef1412da..78f6796a 100644 --- a/web/rest-request.php +++ b/web/rest-request.php @@ -2,8 +2,7 @@ namespace Vn\Web; -class Security -{ +class Security { const DEFINER = 1; const INVOKER = 2; } @@ -11,8 +10,7 @@ class Security /** * Base class for REST services. **/ -abstract class RestRequest extends \Vn\Lib\Method -{ +abstract class RestRequest extends \Vn\Lib\Method { const PARAMS = NULL; const SECURITY = Security::DEFINER; diff --git a/web/rest-service.php b/web/rest-service.php index 5ec5f97b..0405ab59 100644 --- a/web/rest-service.php +++ b/web/rest-service.php @@ -9,87 +9,76 @@ use Vn\Lib\UserException; /** * Base class for REST application. */ -class RestService extends Service -{ - function run () - { - ini_set ('display_errors', _ENABLE_DEBUG); - set_error_handler ([$this, 'errorHandler'], E_ALL); - set_exception_handler ([$this, 'exceptionHandler']); +class RestService extends Service { + function run() { + ini_set('display_errors', _ENABLE_DEBUG); + set_error_handler([$this, 'errorHandler'], E_ALL); + set_exception_handler([$this, 'exceptionHandler']); - $this->init (); - $this->startSession (); - $this->loadMethod (__NAMESPACE__.'\RestRequest'); + $this->init(); + $this->startSession(); + $this->loadMethod(__NAMESPACE__.'\RestRequest'); } /** * Runs a REST method. */ - function loadMethod ($class) - { + function loadMethod($class) { $db = $this->db; - $this->login (); + $this->login(); - $method = $this->app->loadMethod ( + $method = $this->app->loadMethod( $_REQUEST['method'], $class, './rest'); $method->service = $this; - if ($method::SECURITY == Security::DEFINER) - { - $isAuthorized = $db->getValue ('SELECT userCheckRestPriv (#)', + if ($method::SECURITY == Security::DEFINER) { + $isAuthorized = $db->getValue('SELECT userCheckRestPriv(#)', [$_REQUEST['method']]); if (!$isAuthorized) - throw new UserException (s('You don\'t have enough privileges')); + throw new UserException(s('You don\'t have enough privileges')); $methodDb = $db; } else - $methodDb = $this->getUserDb ($_SESSION['user']); + $methodDb = $this->getUserDb($_SESSION['user']); - if ($method::PARAMS !== NULL && !$method->checkParams ($_REQUEST, $method::PARAMS)) - throw new UserException (s('Missing parameters')); + if ($method::PARAMS !== NULL && !$method->checkParams($_REQUEST, $method::PARAMS)) + throw new UserException (s('Missing parameters')); - Locale::addPath ('rest/'. dirname ($_REQUEST['method'])); + Locale::addPath('rest/'. dirname($_REQUEST['method'])); $res = NULL; try { - $res = $method->run ($methodDb); + $res = $method->run($methodDb); } - catch (Db\Exception $e) - { - if ($e->getCode () == 1644) - throw new UserException (s($e->getMessage ())); + catch (Db\Exception $e) { + if ($e->getCode() == 1644) + throw new UserException(s($e->getMessage())); } if ($method::SECURITY == Security::DEFINER) - $methodDb->query ('CALL account.myUserLogout ()'); + $methodDb->query('CALL account.myUserLogout()'); - $db->query ('CALL account.myUserLogout ()'); + $db->query('CALL account.myUserLogout()'); return $res; } - function statusFromException ($e) - { + function statusFromException($e) { try { throw $e; } - catch (SessionExpiredException $e) - { $status = 401; } - catch (BadLoginException $e) - { $status = 401; } - catch (Lib\UserException $e) - { $status = 400; } - catch (\Exception $e) - { $status = 500; } + catch (SessionExpiredException $e) { $status = 401; } + catch (BadLoginException $e) { $status = 401; } + catch (Lib\UserException $e) { $status = 400; } + catch (\Exception $e) { $status = 500; } - http_response_code ($status); + http_response_code($status); } - function errorHandler ($errno, $message, $file, $line, $context) - { + function errorHandler($errno, $message, $file, $line, $context) { $eFlag = E_USER_NOTICE | E_USER_WARNING @@ -99,14 +88,13 @@ class RestService extends Service | E_DEPRECATED; if (!($errno & $eFlag)) - http_response_code (500); + http_response_code(500); return FALSE; } - function exceptionHandler ($e) - { - $this->statusFromException ($e); + function exceptionHandler($e) { + $this->statusFromException($e); throw $e; } } diff --git a/web/service.php b/web/service.php index 31333e1a..1a8c171e 100644 --- a/web/service.php +++ b/web/service.php @@ -29,98 +29,90 @@ class OutdatedVersionException extends UserException {} /** * Main class for web applications. */ -abstract class Service -{ +abstract class Service { protected $app; protected $db; protected $userDb = NULL; - function __construct ($app) - { + function __construct($app) { $this->app = $app; } - function init () - { - $this->db = $this->app->getSysConn (); + function init() { + $this->db = $this->app->getSysConn(); } /** * Starts the user session. */ - function startSession () - { - $db = $this->app->getSysConn (); + function startSession() { + $db = $this->app->getSysConn(); - ini_set ('session.cookie_secure', $this->isHttps ()); - ini_set ('session.hash_function', 'sha256'); + ini_set('session.cookie_secure', $this->isHttps()); + ini_set('session.hash_function', 'sha256'); - session_set_save_handler (new DbSessionHandler ($db)); - session_start (); + session_set_save_handler(new DbSessionHandler($db)); + session_start(); // Setting the locale - if (isset ($_SERVER['HTTP_ACCEPT_LANGUAGE'])) - if (!isset ($_SESSION['httpLanguage']) - || $_SESSION['httpLanguage'] != $_SERVER['HTTP_ACCEPT_LANGUAGE']) - { + if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) + if (!isset($_SESSION['httpLanguage']) + || $_SESSION['httpLanguage'] != $_SERVER['HTTP_ACCEPT_LANGUAGE']) { $_SESSION['httpLanguage'] = $_SERVER['HTTP_ACCEPT_LANGUAGE']; $regexp = '/([a-z]{1,4})(?:-[a-z]{1,4})?\s*(?:;\s*q\s*=\s*(?:1|0\.[0-9]+))?,?/i'; - preg_match_all ($regexp, $_SERVER['HTTP_ACCEPT_LANGUAGE'], $languages); + preg_match_all($regexp, $_SERVER['HTTP_ACCEPT_LANGUAGE'], $languages); - foreach ($languages[1] as $lang) - if (TRUE || stream_resolve_include_path ("locale/$lang")) - { + foreach($languages[1] as $lang) + if (TRUE || stream_resolve_include_path("locale/$lang")) { $_SESSION['lang'] = $lang; break; } } - if (!isset ($_SESSION['lang'])) + if (!isset($_SESSION['lang'])) $_SESSION['lang'] = NULL; - Locale::set ($_SESSION['lang']); - Locale::addPath ('vn/web'); + Locale::set($_SESSION['lang']); + Locale::addPath('vn/web'); // Registering the visit - if (isset ($_COOKIE['PHPSESSID']) - || isset ($_SESSION['access']) - || isset ($_SESSION['skipVisit']) - || !isset ($_SERVER['HTTP_USER_AGENT'])) + if (isset($_COOKIE['PHPSESSID']) + || isset($_SESSION['access']) + || isset($_SESSION['skipVisit']) + || !isset($_SERVER['HTTP_USER_AGENT'])) return; $agent = $_SERVER['HTTP_USER_AGENT']; - $browser = get_browser ($agent, TRUE); + $browser = get_browser($agent, TRUE); - if (!empty ($browser['crawler'])) - { + if (!empty($browser['crawler'])) { $_SESSION['skipVisit'] = TRUE; return; } - if (isset ($_SERVER['REMOTE_ADDR'])) - $ip = ip2long ($_SERVER['REMOTE_ADDR']); + if (isset($_SERVER['REMOTE_ADDR'])) + $ip = ip2long($_SERVER['REMOTE_ADDR']); - $row = $db->getRow ( - 'CALL visitRegister (#, #, #, #, #, #, #, #, #)', + $row = $db->getRow( + 'CALL visitRegister(#, #, #, #, #, #, #, #, #)', [ - nullIf ($_COOKIE, 'vnVisit') - ,nullIf ($browser, 'platform') - ,nullIf ($browser, 'browser') - ,nullIf ($browser, 'version') - ,nullIf ($browser, 'javascript') - ,nullIf ($browser, 'cookies') - ,isset ($agent) ? $agent : NULL - ,isset ($ip) && $ip ? $ip : NULL - ,nullIf ($_SERVER, 'HTTP_REFERER') + nullIf($_COOKIE, 'vnVisit') + ,nullIf($browser, 'platform') + ,nullIf($browser, 'browser') + ,nullIf($browser, 'version') + ,nullIf($browser, 'javascript') + ,nullIf($browser, 'cookies') + ,isset($agent) ? $agent : NULL + ,isset($ip) && $ip ? $ip : NULL + ,nullIf($_SERVER, 'HTTP_REFERER') ] ); - if (isset ($row['access'])) - { - setcookie ('vnVisit', $row['visit'], time () + 31536000); // 1 Year + if (isset($row['access'])) { + setcookie('vnVisit', $row['visit'], time() + 31536000); // 1 Year $_SESSION['access'] = $row['access']; } else @@ -137,92 +129,83 @@ abstract class Service * * return Db\Conn The database connection */ - function login () - { + function login() { $db = $this->db; $anonymousUser = FALSE; - if (isset ($_POST['user']) && isset ($_POST['password'])) - { - $user = strtolower ($_POST['user']); + if (isset($_POST['user']) && isset($_POST['password'])) { + $user = strtolower($_POST['user']); try { - $db->query ('CALL account.userLogin (#, #)', + $db->query('CALL account.userLogin(#, #)', [$user, $_POST['password']]); } - catch (Db\Exception $e) - { - if ($e->getMessage () == 'INVALID_CREDENTIALS') - { - sleep (3); - throw new BadLoginException (); + catch (Db\Exception $e) { + if ($e->getMessage() == 'INVALID_CREDENTIALS') { + sleep(3); + throw new BadLoginException(); } else throw $e; } } - else - { - if (isset ($_POST['token']) || isset ($_GET['token'])) - { - if (isset ($_POST['token'])) + else { + if (isset($_POST['token']) || isset($_GET['token'])) { + if (isset($_POST['token'])) $token = $_POST['token']; - if (isset ($_GET['token'])) + if (isset($_GET['token'])) $token = $_GET['token']; - $key = $db->getValue ('SELECT jwtKey FROM config'); + $key = $db->getValue('SELECT jwtKey FROM config'); try { - $jwtPayload = Jwt::decode ($token, $key); + $jwtPayload = Jwt::decode($token, $key); } - catch (\Exception $e) - { - throw new BadLoginException ($e->getMessage ()); + catch (\Exception $e) { + throw new BadLoginException($e->getMessage()); } $expiration = $jwtPayload['exp']; - if (empty ($expiration) || $expiration <= time()) - throw new SessionExpiredException (); + if (empty($expiration) || $expiration <= time()) + throw new SessionExpiredException(); $user = $jwtPayload['sub']; - if (!empty ($jwtPayload['recover'])) - $db->query ( + if (!empty($jwtPayload['recover'])) + $db->query( 'UPDATE account.user SET recoverPass = TRUE WHERE name = #', [$user] ); } - else - { - $user = $db->getValue ('SELECT guestUser FROM config'); + else { + $user = $db->getValue('SELECT guestUser FROM config'); $anonymousUser = TRUE; } - $db->query ('CALL account.userLoginWithName (#)', [$user]); + $db->query('CALL account.userLoginWithName(#)', [$user]); } $userChanged = !$anonymousUser - && (empty ($_SESSION['user']) || $_SESSION['user'] != $user); + &&(empty($_SESSION['user']) || $_SESSION['user'] != $user); $_SESSION['user'] = $user; // Registering the user access - if (isset ($_SESSION['access']) && $userChanged) - $db->query ( - 'CALL visitUserNew (#, #)', - [$_SESSION['access'], session_id ()] + if (isset($_SESSION['access']) && $userChanged) + $db->query( + 'CALL visitUserNew(#, #)', + [$_SESSION['access'], session_id()] ); } /** * Logouts the current user. Cleans the last saved used credentials. */ - function logout () - { - unset ($_SESSION['user']); + function logout() { + unset($_SESSION['user']); } /** @@ -231,12 +214,11 @@ abstract class Service * * @return {Db\Conn} The database connection */ - function getUserDb ($user) - { + function getUserDb($user) { if ($this->userDb) return $this->userDb; - $row = $this->db->getObject ( + $row = $this->db->getObject( 'SELECT r.name, rc.mysqlPassword, uc.loginKey FROM account.user u JOIN account.role r ON r.id = u.role @@ -247,10 +229,10 @@ abstract class Service ); $userName = "z-{$row->name}"; - $password = base64_decode ($row->mysqlPassword); - $userDb = $this->app->createConnection ($userName, $password, TRUE); + $password = base64_decode($row->mysqlPassword); + $userDb = $this->app->createConnection($userName, $password, TRUE); - $userDb->query ('CALL account.userLoginWithKey (#, #)', [$user, $row->loginKey]); + $userDb->query('CALL account.userLoginWithKey(#, #)', [$user, $row->loginKey]); return $userDb; } @@ -262,8 +244,7 @@ abstract class Service * @param {boolean} $recover Wether to enable recovery mode on login * @return {string} The JWT generated token */ - function createToken ($user, $remember = FALSE, $recover = FALSE) - { + function createToken($user, $remember = FALSE, $recover = FALSE) { if ($remember) $tokenLife = WEEK; else @@ -271,14 +252,14 @@ abstract class Service $payload = [ 'sub' => $user, - 'exp' => time () + $tokenLife + 'exp' => time() + $tokenLife ]; if ($recover) $payload['recover'] = 'TRUE'; - $key = $this->db->getValue ('SELECT jwtKey FROM config'); - return Jwt::encode ($payload, $key); + $key = $this->db->getValue('SELECT jwtKey FROM config'); + return Jwt::encode($payload, $key); } /** @@ -287,22 +268,19 @@ abstract class Service * * @return string The version number */ - function getVersion () - { - $appName = $this->app->getName (); + function getVersion() { + $appName = $this->app->getName(); $version = apc_fetch("$appName.version", $success); - if (!$success) - { - if (file_exists ('package.json')) - { - $package = json_decode (file_get_contents ('package.json')); + if (!$success) { + if (file_exists('package.json')) { + $package = json_decode(file_get_contents('package.json')); $version = $package->version; } else $version = '0.0.0'; - apc_store ("$appName.version", $version); + apc_store("$appName.version", $version); } return $version; @@ -311,14 +289,13 @@ abstract class Service /** * Checks the client version. */ - function checkVersion () - { - if (!empty ($_COOKIE['vnVersion'])) + function checkVersion() { + if (!empty($_COOKIE['vnVersion'])) $clientVersion = $_COOKIE['vnVersion']; - if (isset ($clientVersion) - && $clientVersion < $this->getVersion ()) - throw new OutdatedVersionException (); + if (isset($clientVersion) + && $clientVersion < $this->getVersion()) + throw new OutdatedVersionException(); } /** @@ -326,9 +303,8 @@ abstract class Service * * @return boolean Return %TRUE if its secure, %FALSE otherwise */ - function isHttps () - { - return isset ($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on'; + function isHttps() { + return isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on'; } /** @@ -336,8 +312,7 @@ abstract class Service * * @return string The current URI */ - function getUri () - { + function getUri() { return "{$_SERVER['SERVER_NAME']}{$_SERVER['REQUEST_URI']}"; } @@ -346,9 +321,8 @@ abstract class Service * * @return string The current URL */ - function getUrl () - { - $proto = $this->isHttps () ? 'https' : 'http'; + function getUrl() { + $proto = $this->isHttps() ? 'https' : 'http'; return "$proto://{$this->getUri()}"; } } diff --git a/web/unavailable.html b/web/unavailable.html index af574787..47efb70e 100644 --- a/web/unavailable.html +++ b/web/unavailable.html @@ -5,13 +5,11 @@ Not available - Verdnatura