EDI update bugs solved, PHP linting

This commit is contained in:
Juan 2018-05-23 12:14:20 +02:00
parent 063d9b92e8
commit a57498548f
60 changed files with 1121 additions and 1431 deletions

2
debian/changelog vendored
View File

@ -1,4 +1,4 @@
hedera-web (1.406.02) stable; urgency=low
hedera-web (1.406.03) stable; urgency=low
* Initial Release.

View File

@ -1,6 +1,6 @@
{
"name": "hedera-web",
"version": "1.406.02",
"version": "1.406.03",
"description": "Verdnatura web page",
"license": "GPL-3.0",
"repository": {

View File

@ -1,9 +1,7 @@
<?php
class Account
{
static function trySync ($db, $userName, $password = NULL)
{
class Account {
static function trySync($db, $userName, $password = NULL) {
$isSync = $db->getValue(
'SELECT sync FROM account.user WHERE name = #',
[$userName]
@ -15,8 +13,7 @@ class Account
self::sync($db, $userName, $password);
}
static function sync ($db, $userName, $password = NULL, $force = TRUE)
{
static function sync($db, $userName, $password = NULL, $force = TRUE) {
$hasAccount = $db->getValue(
'SELECT COUNT(*) > 0
FROM account.user u
@ -25,8 +22,7 @@ class Account
[$userName]
);
if ($hasAccount)
{
if ($hasAccount) {
self::ldapSync($db, $userName, $password);
self::sambaSync($db, $userName, $password);
}
@ -40,8 +36,7 @@ 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(
@ -110,28 +105,24 @@ class Account
$classes = ldap_get_values($ds, $entry, 'objectClass');
if (!in_array ('inetOrgPerson', $classes))
{
if (!in_array('inetOrgPerson', $classes)) {
ldap_delete($ds, $dn);
$entry = NULL;
}
if ($entry)
{
if ($entry) {
$modifs = [];
$curAttrs = ldap_get_attributes($ds, $entry);
foreach($attrs as $attribute => $value)
if (!empty ($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
@ -140,8 +131,7 @@ class Account
$updated = ldap_modify_batch($ds, $dn, $modifs);
}
else
{
else {
$addAttrs = [];
foreach($attrs as $attribute => $value)
@ -158,8 +148,7 @@ class Account
if (!$updated)
throw new Exception("Can't update the LDAP entry: ". ldapError($ds));
}
catch (Exception $e)
{
catch (Exception $e) {
ldap_unbind($ds);
throw $e;
}
@ -168,8 +157,7 @@ class Account
/**
* Synchronizes the user credentials in the Samba server.
*/
static function sambaSync ($db, $userName, $password)
{
static function sambaSync($db, $userName, $password) {
$conf = $db->getObject(
'SELECT host, sshUser, sshPass, uidBase
FROM account.sambaConfig'
@ -207,21 +195,18 @@ class Account
}
}
function ldapError ($ds)
{
function ldapError($ds) {
return ldap_errno($ds) .': '. ldap_error($ds);
}
function sshaEncode ($value)
{
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)
{
function sshaVerify($hash, $value) {
$ohash = base64_decode(substr($hash, 6));
$osalt = substr($ohash, 20);
$ohash = substr($ohash, 0, 20);
@ -229,15 +214,13 @@ function sshaVerify ($hash, $value)
return $ohash == $nhash;
}
class SshConnection
{
class SshConnection {
var $connection;
/**
* Abrebiated method to make SSH connections.
*/
function __construct ($host, $user, $password)
{
function __construct($host, $user, $password) {
$this->connection = $connection = ssh2_connect($host);
if (!$connection)
@ -254,8 +237,7 @@ class SshConnection
/**
* Executes a command on the host.
*/
function exec ()
{
function exec() {
$nargs = func_num_args();
$args = func_get_args();
@ -269,8 +251,7 @@ class SshConnection
/**
* Escapes the double quotes from an string.
*/
static function escape ($str)
{
static function escape($str) {
return '"'. str_replace('"', '\\"', $str) .'"';
}
}

View File

@ -3,10 +3,8 @@
require_once('PEAR.php');
require_once('Text/CAPTCHA.php');
class Captcha extends Vn\Web\RestRequest
{
function run ($db)
{
class Captcha extends Vn\Web\RestRequest {
function run($db) {
$options =
[
'width' => 130

View File

@ -5,12 +5,10 @@ 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'];

View File

@ -1,7 +1,6 @@
<?php
class Log extends Vn\Web\JsonRequest
{
class Log extends Vn\Web\JsonRequest {
const PARAMS = [
'file'
,'line'
@ -9,8 +8,7 @@ class Log extends Vn\Web\JsonRequest
,'stack'
];
function run ($db)
{
function run($db) {
$user = isset($_SESSION['user']) ? $_SESSION['user'] : 'guest';
error_log(sprintf("Javascript: User: %s: %s(%d): %s.\n%s"
,$user

View File

@ -2,18 +2,15 @@
include __DIR__.'/account.php';
class Login extends Vn\Web\JsonRequest
{
function run ($db)
{
class Login extends Vn\Web\JsonRequest {
function run($db) {
try {
Account::trySync($db
,strtolower($_POST['user'])
,$_POST['password']
);
}
catch (Exception $e)
{
catch (Exception $e) {
error_log($e->getMessage());
}

View File

@ -1,9 +1,7 @@
<?php
class Logout extends Vn\Web\JsonRequest
{
function run ($db)
{
class Logout extends Vn\Web\JsonRequest {
function run($db) {
$this->service->logout();
return TRUE;
}

View File

@ -4,13 +4,11 @@ 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 {
@ -19,8 +17,7 @@ class Query extends Vn\Web\JsonRequest
do {
$result = $db->storeResult();
if ($result !== FALSE)
{
if ($result !== FALSE) {
$results[] = $this->transformResult($result);
$result->free();
}
@ -32,13 +29,11 @@ class Query extends Vn\Web\JsonRequest
// Checks for warnings
if ($db->checkWarnings()
&& ($result = $db->query ('SHOW WARNINGS')))
{
&&($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);
@ -51,10 +46,8 @@ class Query extends Vn\Web\JsonRequest
$db->checkError();
}
catch (Vn\Db\Exception $e)
{
if ($e->getCode () == 1644)
{
catch (Vn\Db\Exception $e) {
if ($e->getCode() == 1644) {
$dbMessage = $e->getMessage();
$sql = 'SELECT `description` FROM `message` WHERE `code` = #';
$message = $db->getValue($sql, [$dbMessage]);
@ -72,8 +65,7 @@ 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();
@ -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,
@ -151,8 +140,7 @@ 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']);
@ -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,8 +164,7 @@ class Query extends Vn\Web\JsonRequest
return (float) $value;
case Type::DATE:
case Type::DATE_TIME:
return mktime
(
return mktime(
substr($value, 11 , 2)
,substr($value, 14 , 2)
,substr($value, 17 , 2)

View File

@ -2,12 +2,10 @@
use Vn\Web;
class RecoverPassword extends Vn\Web\JsonRequest
{
class RecoverPassword extends Vn\Web\JsonRequest {
const PARAMS = ['recoverUser'];
function run ($db)
{
function run($db) {
$user = $db->getRow(
'SELECT email, active FROM account.user WHERE name = #',
[$_REQUEST['recoverUser']]
@ -31,8 +29,7 @@ class RecoverPassword extends Vn\Web\JsonRequest
const DIGITS = '1234567890';
const SYMBOLS = '!$%&()=.';
function genPassword ($db)
{
function genPassword($db) {
$restrictions = $db->getRow(
'SELECT length, nUpper, nDigits, nPunct FROM account.userPassword');
@ -49,8 +46,7 @@ class RecoverPassword extends Vn\Web\JsonRequest
$this->genRands($pass, self::DIGITS, $restrictions['nDigits']);
$this->genRands($pass, self::SYMBOLS, $restrictions['nPunct']);
for ($i = count ($pass) - 1; $i >= 0; $i--)
{
for ($i = count($pass) - 1; $i >= 0; $i--) {
$rand = rand(0, $i);
$newPass .= $pass[$rand];
array_splice($pass, $rand, 1);
@ -59,8 +55,7 @@ class RecoverPassword extends Vn\Web\JsonRequest
return $newPass;
}
function genRands (&$pass, $chars, $max)
{
function genRands(&$pass, $chars, $max) {
$len = strlen($chars) - 1;
for ($i = 0; $i < $max; $i++)

View File

@ -5,15 +5,13 @@ 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'];

View File

@ -1,11 +1,9 @@
<?php
class Supplant extends Vn\Web\JsonRequest
{
class Supplant extends Vn\Web\JsonRequest {
const PARAMS = ['supplantUser'];
function run ($db)
{
function run($db) {
return $this->service->createToken($_REQUEST['supplantUser']);
}
}

View File

@ -6,12 +6,10 @@ 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)
{
function run($db) {
Account::sync($db, $_REQUEST['syncUser'], NULL);
return TRUE;
}

View File

@ -5,10 +5,8 @@ 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';
@ -58,10 +56,8 @@ class Add extends Vn\Web\JsonRequest
$dirLevels = $db->getValue(
'SELECT dir_levels FROM dms_config FOR UPDATE');
if ($dirLevels < $neededLevels)
{
if (is_dir ($docsDir))
{
if ($dirLevels < $neededLevels) {
if (is_dir($docsDir)) {
$dif =($neededLevels - $dirLevels) - 1;
$newDir = $docsDir;
@ -101,8 +97,7 @@ class Add extends Vn\Web\JsonRequest
return $docId;
}
catch (Exception $e)
{
catch (Exception $e) {
$db->query('ROLLBACK');
throw $e;
}

View File

@ -4,13 +4,11 @@ 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)
{
function run($db) {
$pdfPath = $db->getValueFromFile(__DIR__ .'/invoice',
['invoice' =>(int) $_GET['invoice']]);

View File

@ -2,10 +2,8 @@
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');
@ -21,10 +19,8 @@ class Clean extends Edi\Method
];
foreach($folders as $folder)
if (imap_reopen ($imap, "{$this->mailbox}$folder"))
{
if ($messages = imap_search ($imap, $filter))
{
if (imap_reopen($imap, "{$this->mailbox}$folder")) {
if ($messages = imap_search($imap, $filter)) {
foreach($messages as $message)
imap_delete($imap, $message);

View File

@ -4,19 +4,16 @@ namespace Edi;
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)
{
static function loadSchema($schemaName) {
$ediSchemaStr = file_get_contents(__DIR__."/$schemaName.json", TRUE);
if ($ediSchemaStr !== FALSE)
@ -25,13 +22,11 @@ class Message
return NULL;
}
static function isEdiString (&$string)
{
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))
@ -50,8 +45,7 @@ class Message
$topInfo = $info;
try {
while (TRUE)
{
while (TRUE) {
$segment = $this->parseSegment($string, $pos);
if (!$segment &&(!$endTag || !$info))
@ -60,16 +54,13 @@ class Message
if (!$segment ||($segment && !$info))
throw new \Exception();
if ($firstLoop)
{
if ($firstLoop) {
if ($segment->name != $info->schema['mainTag'])
throw new \Exception();
}
else
{
else {
for ($i = $info; $i; $i = $i->parentInfo)
if (isset ($i->schema['childs'][$segment->name]))
{
if (isset($i->schema['childs'][$segment->name])) {
$info = new SectionInfo();
$info->schema = $i->schema['childs'][$segment->name];
$info->parentInfo = $i;
@ -78,14 +69,12 @@ class Message
}
}
if ($newSection)
{
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;
}
@ -96,14 +85,12 @@ class Message
$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,8 +100,7 @@ class Message
$firstLoop = FALSE;
}}
catch (\Exception $e)
{
catch (\Exception $e) {
throw new \Exception(sprintf('Parse error, something is wrong near "%s"',
substr($string, $pos, 10)));
}
@ -122,27 +108,22 @@ class Message
$this->section = $topInfo->section;
}
function parseSegment (&$string, &$pos)
{
function parseSegment(&$string, &$pos) {
$empty = TRUE;
$values = [];
while (TRUE)
{
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));
$empty = TRUE;
}
}
elseif ($empty)
{
elseif ($empty) {
$start = $pos;
$empty = FALSE;
}

View File

@ -2,16 +2,14 @@
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);
function run ($db)
{
function run($db) {
$db->selectDb('edi');
$imapConf = $db->getRow(
@ -28,8 +26,7 @@ abstract class Method extends \Vn\Lib\Method
$this->imap = $imap;
$this->imapConf = $imapConf;
if ($imap)
{
if ($imap) {
$this->ediRun($db);
imap_expunge($imap);
imap_close($imap);

View File

@ -4,15 +4,13 @@ namespace Edi;
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)
{
function getValue($name, $key, $type = NULL, $subname = NULL) {
foreach($this->segments as $segment)
if ($segment->name == $name
&&(!$subname || $segment->values[1] == $subname))

View File

@ -6,20 +6,17 @@ 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)
{
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));

View File

@ -5,10 +5,8 @@ require_once (__DIR__.'/lib/message.php');
use Vn\Lib\Type;
class Load extends Edi\Method
{
function ediRun ($db)
{
class Load extends Edi\Method {
function ediRun($db) {
$this->ediSchema = Edi\Message::loadSchema('CLOCKT');
if (!$this->ediSchema)
@ -19,8 +17,7 @@ class Load extends Edi\Method
$inbox = imap_search($this->imap, 'ALL');
if ($inbox)
{
if ($inbox) {
foreach($inbox as $msg)
$this->loadMail($db, $msg);
@ -31,8 +28,7 @@ class Load extends Edi\Method
}
}
function loadMail ($db, $msg)
{
function loadMail($db, $msg) {
$imap = $this->imap;
// Gets EKT messages from email
@ -60,13 +56,11 @@ class Load extends Edi\Method
$error = NULL;
foreach($result as $msgSection)
try
{
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);
break;
@ -94,18 +88,15 @@ class Load extends Edi\Method
$unhs = $unb->childs['UNH'];
foreach($unhs as $unh)
foreach ($lins = $unh->childs['LIN'] as $lin)
{
foreach($lins = $unh->childs['LIN'] as $lin) {
$ediValues = [];
// Gets the exchange params
$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;
@ -144,8 +135,7 @@ class Load extends Edi\Method
);
if ($res)
while ($row = $res->fetch_assoc ())
{
while ($row = $res->fetch_assoc()) {
$value = $lin->getValue('IMD', 2, Type::INTEGER, $row['feature']);
$ediValues['s'.$row['presentation_order']] = $value;
}
@ -168,8 +158,7 @@ class Load extends Edi\Method
$db->query('COMMIT');
}
catch (Exception $e)
{
catch (Exception $e) {
$db->query('ROLLBACK');
$error = $e->getMessage();
break;
@ -180,13 +169,11 @@ 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";
}
@ -202,18 +189,15 @@ class Load extends Edi\Method
);
}
function imapFindParts (&$part, &$matchTypes, $section, &$result)
{
if (in_array ($part->type, $matchTypes))
{
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)
{
foreach($part->parts as $i => $subpart) {
array_push($section, $i + 1);
$this->imapFindParts($subpart, $matchTypes, $section, $result);
array_pop($section);

View File

@ -1,15 +1,13 @@
<?php
class Update extends Vn\Lib\Method
{
function run ($db)
{
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<78>n FTP
// Establish the FTP connection
$ftpConf = $db->getRow('SELECT host, user, password FROM ftp_config');
@ -22,7 +20,7 @@ class Update extends Vn\Lib\Method
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);
@ -40,8 +38,10 @@ class Update extends Vn\Lib\Method
$table = $row['to_table'];
$baseName = $row['file_name'];
if ($row['updated'])
if ($row['updated']) {
$updated = DateTime::createFromFormat('Y-m-d', $row['updated']);
$updated->setTime(0, 0, 0, 0);
}
else
$updated = NULL;
@ -49,10 +49,9 @@ 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";
@ -79,35 +78,30 @@ class Update extends Vn\Lib\Method
if (!$fileName)
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->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 ();
$db->query("COMMIT");
}
while ($db->moreResults () && $db->nextResult ());
}
catch (Exception $e)
{
catch (Exception $e) {
$db->query('ROLLBACK');
error_log($e->getMessage());
}

View File

@ -2,20 +2,17 @@
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)
{
static function create($srcFile) {
$imageType = exif_imagetype($srcFile);
if ($imageType !== FALSE)
switch ($imageType)
{
switch ($imageType) {
case IMAGETYPE_JPEG:
$image = imagecreatefromjpeg($srcFile);
break;
@ -44,8 +41,7 @@ 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)
{
static function resizeSave($image, $dstFile, $maxHeight, $maxWidth, $crop = FALSE, $symbolicSrc = NULL) {
$width = imagesx($image);
$height = imagesy($image);
@ -59,8 +55,7 @@ class Image
// 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,43 +63,36 @@ 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);
}
if ($dstHeight > $maxHeight)
{
if ($dstHeight > $maxHeight) {
$ratio = $dstHeight / $maxHeight;
$dstHeight = $maxHeight;
$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
{
else {
$srcWidth =(int)($maxWidth *($height / $maxHeight));
$srcHeight =(int)($maxHeight *($width / $maxWidth));
@ -129,12 +117,10 @@ class Image
$saved = imagepng($resizedImage, $dstFile);
imagedestroy($resizedImage);
}
elseif (isset ($symbolicSrc))
{
elseif (isset($symbolicSrc)) {
$saved = symlink($symbolicSrc, $dstFile);
}
else
{
else {
imagesavealpha($image, TRUE);
$saved = imagepng($image, $dstFile);
}

View File

@ -11,8 +11,7 @@ require_once (__DIR__.'/lib.php');
* @param integer $maxWidth The maximum width of resized image in pixels
* @param boolean $rewrite Wether to rewrite the destination file if it exits
*/
class Resize extends Vn\Lib\Method
{
class Resize extends Vn\Lib\Method {
const PARAMS = [
'srcDir'
,'dstDir'
@ -23,8 +22,7 @@ class Resize extends Vn\Lib\Method
,'symbolic'
];
function run ()
{
function run() {
$options = getopt('', $params);
if (!$this->checkParams($options, self::PARAMS))
@ -45,14 +43,12 @@ class Resize extends Vn\Lib\Method
if ($dir)
while ($fileName = readdir($dir))
if (!in_array ($fileName, ['.', '..']))
{
if (!in_array($fileName, ['.', '..'])) {
$srcFile = "$srcDir/$fileName";
$dstFile = "$dstDir/". substr($fileName, 0, -4).'.png';
if (!file_exists($dstFile) || $rewrite)
try
{
try {
$symbolicSrc =($symbolic) ? $srcFile : NULL;
$image = Image::create($srcFile);

View File

@ -6,20 +6,17 @@ require_once (__DIR__.'/util.php');
* Syncronizes the data directory with the database, this may take
* some time.
*/
class Sync extends Vn\Lib\Method
{
class Sync extends Vn\Lib\Method {
private $trashSubdir;
private $util;
function __construct ($app)
{
function __construct($app) {
parent::__construct($app);
$this->util = new Util($app);
$this->dataDir = $this->util->dataDir;
}
function run ($db)
{
function run($db) {
$db = $this->getSysConn();
set_time_limit(0);
@ -33,15 +30,13 @@ class Sync extends Vn\Lib\Method
if ($dir)
while ($schema = readdir($dir))
if (!in_array ($schema, ['.', '..']))
{
if (!in_array($schema, ['.', '..'])) {
$info = $this->loadInfo($schema);
$schemaPath = "{$this->dataDir}/$schema";
// Deletes unreferenced schemas.
if (!isset ($info))
{
if (!isset($info)) {
$this->moveTrash($schema);
continue;
}
@ -69,8 +64,7 @@ class Sync extends Vn\Lib\Method
$map = [];
while ($row = $result->fetch_row ())
{
while ($row = $result->fetch_row()) {
$map[$row[0]] = TRUE;
$checkCount++;
}
@ -88,8 +82,7 @@ class Sync extends Vn\Lib\Method
echo "Syncronization finished.\n";
}
function cleanImages ($schema, $size, &$map)
{
function cleanImages($schema, $size, &$map) {
$sizePath = "{$this->dataDir}/$schema/$size";
if (!is_dir($sizePath))
@ -98,8 +91,7 @@ class Sync extends Vn\Lib\Method
$iter = new DirectoryIterator($sizePath);
for (; $iter->valid(); $iter->next())
if (!$iter->isDir () && strripos ($iter->getFilename (), '.png', -4) !== FALSE)
{
if (!$iter->isDir() && strripos($iter->getFilename(), '.png', -4) !== FALSE) {
$name = substr($iter->getFilename(), 0, -4);
if (!isset($map[$name]))
@ -112,8 +104,7 @@ 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);

View File

@ -10,10 +10,8 @@ require_once (__DIR__.'/util.php');
* @param integer $width The width of the thumb
* @param integer $height The height of the thumb
*/
class Thumb extends Vn\Web\RestRequest
{
function run ()
{
class Thumb extends Vn\Web\RestRequest {
function run() {
// XXX: Uncomment only to test the script
//$_SERVER['REQUEST_URI'] = 'catalog/200x200/e_cinerea.png';
@ -84,8 +82,7 @@ class Thumb extends Vn\Web\RestRequest
$useXsendfile = $db->getValue('SELECT useXsendfile FROM imageConfig');
if ($useXsendfile)
{
if ($useXsendfile) {
header("X-Sendfile: $dstFile");
header("Content-Type: image/png");
}

View File

@ -8,15 +8,13 @@ use Vn\Lib\UserException;
/**
* Uploads a file creating its corresponding sizes.
*/
class Upload extends Vn\Web\JsonRequest
{
class Upload extends Vn\Web\JsonRequest {
const PARAMS = [
'name',
'schema'
];
function run ($db)
{
function run($db) {
$util = new Util($this->app);
$schema = $_REQUEST['schema'];
@ -39,10 +37,8 @@ class Upload extends Vn\Web\JsonRequest
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;
@ -88,8 +84,7 @@ class Upload extends Vn\Web\JsonRequest
$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);
}

View File

@ -5,13 +5,11 @@ require_once (__DIR__.'/image.php');
/**
* Base class for image methods.
*/
class Util
{
class Util {
var $app;
var $dataDir;
function __construct ($app)
{
function __construct($app) {
$this->app = $app;
$this->dataDir = _DATA_DIR .'/'. $app->getName() .'/image-db';
}
@ -21,8 +19,7 @@ class Util
*
* @param string $schema The schema name
*/
function loadInfo ($schema)
{
function loadInfo($schema) {
$db = $this->app->getSysConn();
$info = $db->getRow(
@ -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'],

View File

@ -6,15 +6,13 @@ 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'];
@ -22,10 +20,8 @@ class AccessVersion extends Vn\Web\JsonRequest
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;

View File

@ -4,8 +4,7 @@ require_once ('libphp-phpmailer/PHPMailerAutoload.php');
use Vn\Lib;
class Contact extends Vn\Web\JsonRequest
{
class Contact extends Vn\Web\JsonRequest {
const PARAMS = [
'name'
,'pc'
@ -15,8 +14,7 @@ class Contact extends Vn\Web\JsonRequest
,'captcha'
];
function run ($db)
{
function run($db) {
// Checks the antispam code
$lastCaptcha = $_SESSION['captcha'];
@ -40,8 +38,7 @@ class Contact extends Vn\Web\JsonRequest
$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);
@ -49,8 +46,7 @@ class Contact extends Vn\Web\JsonRequest
else
$mail->SMTPAuth = FALSE;
if ($conf->secure)
{
if ($conf->secure) {
$mail->SMTPSecure = 'ssl';
$mail->Port = 465;
}

View File

@ -4,10 +4,8 @@
* Ejemplo:
* <Cube><Cube time="2010-12-10"><Cube currency="USD" rate="1.3244"/>
*/
class ExchangeRate extends Vn\Lib\Method
{
function run ($db)
{
class ExchangeRate extends Vn\Lib\Method {
function run($db) {
$db->selectDb('vn2008');
// Indica la URL del archivo
@ -18,16 +16,14 @@ class ExchangeRate extends Vn\Lib\Method
$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)
{
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')
{
if ($subCube['currency'] == 'USD') {
$params = [
'date' => $xmlDate,
'rate' => $subCube['rate']

View File

@ -2,10 +2,8 @@
require_once('libphp-phpmailer/PHPMailerAutoload.php');
class Mail extends Vn\Lib\Method
{
function run ($db)
{
class Mail extends Vn\Lib\Method {
function run($db) {
$db->selectDb('vn2008');
$db->query('START TRANSACTION');
@ -16,8 +14,7 @@ class Mail extends Vn\Lib\Method
$count = 0;
while ($row = $res->fetch_object ())
{
while ($row = $res->fetch_object()) {
$sent = 1;
$status = 'OK';
@ -25,8 +22,7 @@ class Mail extends Vn\Lib\Method
$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))
@ -40,8 +36,7 @@ class Mail extends Vn\Lib\Method
$count++;
}
catch (Exception $e)
{
catch (Exception $e) {
$sent = 2;
$status = $e->getMessage();
}

View File

@ -1,11 +1,9 @@
<?php
class Production extends Vn\Web\JsonRequest
{
class Production extends Vn\Web\JsonRequest {
const PARAMS = ['deviceId'];
function run ($db)
{
function run($db) {
$row = $db->getObject(
'SELECT displayText, status
FROM vn.routeGate WHERE deviceId = #',

View File

@ -2,8 +2,7 @@
use Vn\Lib;
class Sms extends Vn\Web\JsonRequest
{
class Sms extends Vn\Web\JsonRequest {
const PARAMS = [
'destination'
,'message'
@ -14,8 +13,7 @@ class Sms extends Vn\Web\JsonRequest
200 // Processing
];
function run ($db)
{
function run($db) {
$smsConfig = $db->getObject('SELECT uri, user, password, title FROM vn.smsConfig');
$sClient = new SoapClient($smsConfig->uri);

View File

@ -1,17 +1,14 @@
<?php
class VisitsSync extends Vn\Lib\Method
{
function run ($db)
{
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
SET platform = ?, browser = ?, version = ?, javascript = ?, cookies = ? WHERE id = ?');
if ($result && $stmt)
{
if ($result && $stmt) {
set_time_limit(0);
$stmt->bind_param('sssiii'
@ -27,8 +24,7 @@ class VisitsSync extends Vn\Lib\Method
$count = 0;
while ($row = $result->fetch_assoc ())
{
while ($row = $result->fetch_assoc()) {
$info = get_browser($row['agent']);
$platform = $info->platform;
$browser = $info->browser;

View File

@ -5,10 +5,8 @@ require_once (__DIR__.'/tpv.php');
/**
* Gets transaction confirmations from the IMAP mailbox.
**/
class ConfirmMail extends Vn\Lib\Method
{
function run ($db)
{
class ConfirmMail extends Vn\Lib\Method {
function run($db) {
$imap = NULL;
$imapConf = $db->getObject(
'SELECT host, user, pass, cleanPeriod, successFolder, errorFolder
@ -32,16 +30,14 @@ class ConfirmMail extends Vn\Lib\Method
$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);
foreach ($strings as $string)
{
foreach($strings as $string) {
$x = explode(':', $string);
$params[trim($x[0])] = trim($x[1]);
}
@ -53,8 +49,7 @@ class ConfirmMail extends Vn\Lib\Method
try {
$success = Tpv::confirm($db, $params);
}
catch (\Exception $e)
{
catch (\Exception $e) {
trigger_error($e->getMessage(), E_USER_WARNING);
}
@ -77,8 +72,7 @@ class ConfirmMail extends Vn\Lib\Method
$deleted = 0;
if (rand (1, 20) == 1)
{
if (rand(1, 20) == 1) {
$folders = array(
$imapConf->successFolder
,$imapConf->errorFolder
@ -90,8 +84,7 @@ class ConfirmMail extends Vn\Lib\Method
foreach($folders as $folder)
if (imap_reopen($imap, $mailbox.'.'.$folder))
if ($messages = imap_search ($imap, $filter))
{
if ($messages = imap_search($imap, $filter)) {
foreach($messages as $message)
imap_delete($imap, $message);

View File

@ -5,10 +5,8 @@ require_once (__DIR__.'/tpv.php');
/**
* Gets transaction confirmation from HTTP POST.
**/
class ConfirmPost extends Vn\Web\RestRequest
{
function run ($db)
{
class ConfirmPost extends Vn\Web\RestRequest {
function run($db) {
Tpv::confirm($db, $_POST);
}
}

View File

@ -6,10 +6,8 @@ require_once (__DIR__.'/tpv.php');
/**
* Gets transaction confirmation from SOAP service.
**/
class ConfirmSoap extends Vn\Web\RestRequest
{
function run ($db)
{
class ConfirmSoap extends Vn\Web\RestRequest {
function run($db) {
global $tpvConfirmSoap;
$tpvConfirmSoap = $this;
@ -21,8 +19,7 @@ class ConfirmSoap extends Vn\Web\RestRequest
}
}
function procesaNotificacionSIS ($XML)
{
function procesaNotificacionSIS($XML) {
global $tpvConfirmSoap;
$db = $tpvConfirmSoap->app->getSysConn();
@ -61,8 +58,7 @@ function procesaNotificacionSIS ($XML)
Tpv::confirm($db, $params);
}
catch (Exception $e)
{
catch (Exception $e) {
$status = 'KO';
}

View File

@ -1,7 +1,6 @@
<?php
if (isset ($_POST['key']))
{
if (isset($_POST['key'])) {
ini_set('soap.wsdl_cache_enabled', FALSE);
$requestString = file_get_contents(__DIR__.'/soap-request.xml');
@ -22,8 +21,7 @@ if (isset ($_POST['key']))
$isValid = $xml->{'Signature'} == $shaHash;
}
else
{
else {
$key = '';
$result = '';
$shaHash = '';

View File

@ -1,12 +1,10 @@
<?php
class Tpv
{
class Tpv {
/**
* Tryes to confirm a transaction with the given params.
**/
static function confirm ($db, $params)
{
static function confirm($db, $params) {
if (!(isset($params['Ds_Amount'])
&& isset($params['Ds_Order'])
&& isset($params['Ds_MerchantCode'])

View File

@ -3,12 +3,10 @@
/**
* 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)
{
function run($db) {
$amount =(int) $_REQUEST['amount'];
$companyId = empty($_REQUEST['company']) ? NULL : $_REQUEST['company'];

View File

@ -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,8 +17,7 @@ class App extends \Vn\Lib\App
'json'
];
function run ()
{
function run() {
$this->init();
$srv = empty($_REQUEST['srv']) ? '' : $_REQUEST['srv'];
@ -32,8 +30,7 @@ class App extends \Vn\Lib\App
$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);
@ -53,11 +50,9 @@ class App extends \Vn\Lib\App
*
* @return string The config file name
**/
function getConfigFile ()
{
function getConfigFile() {
if (!empty($_SERVER['SERVER_NAME'])
&& preg_match ('/^[\w\-\.]+$/', $_SERVER['SERVER_NAME']))
{
&& preg_match('/^[\w\-\.]+$/', $_SERVER['SERVER_NAME'])) {
$hostSplit = explode('.', $_SERVER['SERVER_NAME']);
array_splice($hostSplit, -2);
$subdomain = implode('.', $hostSplit);

View File

@ -2,34 +2,28 @@
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)
{
function read($sessionId) {
$sessionData = $this->db->getValue(
'SELECT data FROM userSession WHERE ssid = #', [$sessionId]);
return isset($sessionData) ? $sessionData : '';
}
function write ($sessionId, $sessionData)
{
function write($sessionId, $sessionData) {
$this->db->query(
'INSERT INTO userSession SET
ssid = #, data = #, lastUpdate = NOW()
@ -39,14 +33,12 @@ class DbSessionHandler implements \SessionHandlerInterface
return TRUE;
}
function destroy ($sessionId)
{
function destroy($sessionId) {
$this->db->query('DELETE FROM userSession WHERE ssid = #', [$sessionId]);
return TRUE;
}
function gc ($maxLifeTime)
{
function gc($maxLifeTime) {
$this->db->query('DELETE FROM userSession
WHERE lastUpdate < TIMESTAMPADD(SECOND, -#, NOW())',
[$maxLifeTime]

View File

@ -7,10 +7,8 @@ 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;
@ -22,8 +20,7 @@ class HtmlService extends Service
$db = $this->db;
if (!$this->isHttps()
&& $db->getValue ('SELECT https FROM config') && !_DEV_MODE)
{
&& $db->getValue('SELECT https FROM config') && !_DEV_MODE) {
header("Location: https://{$this->getUri()}");
exit(0);
}
@ -39,14 +36,12 @@ class HtmlService extends Service
// Checking the browser version
if (!isset ($_SESSION['skipBrowser']) && $page != 'update-browser')
{
if (!isset($_SESSION['skipBrowser']) && $page != 'update-browser') {
$updateBrowser = FALSE;
if (!isset($_GET['skipBrowser'])
&& isset($_SERVER['HTTP_USER_AGENT'])
&& ($browser = get_browser ($_SERVER['HTTP_USER_AGENT'])))
{
&&($browser = get_browser($_SERVER['HTTP_USER_AGENT']))) {
$browserVersion =(double) $browser->version;
$minVersion = $db->getValue(
'SELECT version FROM browser WHERE name = #', [$browser->browser]);
@ -54,8 +49,7 @@ class HtmlService extends Service
&& isset($minVersion) && $browserVersion < $minVersion;
}
if ($updateBrowser)
{
if ($updateBrowser) {
header('Location: ?method=update-browser');
exit(0);
}
@ -66,8 +60,7 @@ 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'))
{
&& $db->getValue('SELECT testDomain FROM config')) {
$_SESSION['skipVersionMenu'] = TRUE;
header('Location: ?method=version-menu');
}
@ -80,8 +73,7 @@ class HtmlService extends Service
$basePath = "pages/$page";
if (file_exists ($basePath))
{
if (file_exists($basePath)) {
Locale::addPath($basePath);
$phpFile = "./$basePath/$page.php";
@ -98,14 +90,12 @@ class HtmlService extends Service
header('Location: ./');
}
function printHeader ()
{
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');
@ -113,8 +103,7 @@ class HtmlService extends Service
return FALSE;
}
function isMobile ()
{
function isMobile() {
$re = '/(Android|webOS|iPhone|iPad|iPod|BlackBerry|Windows Phone)/i';
return preg_match($re, $_SERVER['HTTP_USER_AGENT']);
}

View File

@ -3,8 +3,7 @@
$lang = isset($_SESSION['lang']) ? $_SESSION['lang'] : 'en';
$version = $this->getVersion();
function getUrl ($fileName)
{
function getUrl($fileName) {
global $version;
if (file_exists($fileName))
@ -15,18 +14,15 @@ function getUrl ($fileName)
return "$fileName?$fileVersion";
}
function js ($fileName)
{
function js($fileName) {
return '<script type="text/javascript" src="'. getUrl("$fileName.js") .'"></script>'."\n";
}
function css ($fileName)
{
function css($fileName) {
return '<link rel="stylesheet" type="text/css" href="'. getUrl("$fileName.css") .'"/>'."\n";
}
function getWebpackAssets ()
{
function getWebpackAssets() {
$wpConfig = json_decode(file_get_contents('webpack.config.json'));
$buildDir = $wpConfig->buildDir;
$devServerPort = $wpConfig->devServerPort;
@ -34,8 +30,7 @@ function getWebpackAssets ()
$host = $_SERVER['SERVER_NAME'];
$assets = new stdClass();
if (!_DEV_MODE)
{
if (!_DEV_MODE) {
$wpAssets = json_decode(file_get_contents("$buildDir/webpack-assets.json"));
$manifestJs = $wpAssets->manifest->js;
@ -47,8 +42,7 @@ function getWebpackAssets ()
if (property_exists($asset, 'js'))
$assets->$name = $asset->js;
}
else
{
else {
$devServerPath = "http://$host:$devServerPort/$buildDir";
$manifestJs = "$devServerPath/manifest.js";
$mainJs = "$devServerPath/main.js";

View File

@ -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;

View File

@ -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;
}

View File

@ -7,12 +7,10 @@ use Vn\Lib;
/**
* Base class for JSON application.
*/
class JsonService extends RestService
{
class JsonService extends RestService {
private $warnings = NULL;
function run ()
{
function run() {
ini_set('display_errors', FALSE);
set_error_handler([$this, 'errorHandler'], E_ALL);
set_exception_handler([$this, 'exceptionHandler']);
@ -25,8 +23,7 @@ class JsonService extends RestService
$this->replyJson($json);
}
function replyJson ($jsonData)
{
function replyJson($jsonData) {
$reply = new JsonReply();
$reply->data = $jsonData;
$reply->warnings = $this->warnings;
@ -35,8 +32,7 @@ class JsonService extends RestService
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
@ -56,22 +52,19 @@ class JsonService extends RestService
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 ($errno & $eWarn) {
if (!isset($this->warnings))
$this->warnings = [];
$this->warnings[] = $json;
}
else
{
else {
http_response_code(500);
$this->replyJson($json);
exit();
@ -80,23 +73,19 @@ class JsonService extends RestService
return !($errno & $eUser);
}
function exceptionHandler ($e)
{
function exceptionHandler($e) {
$json = new JsonException();
if (_ENABLE_DEBUG || $e instanceof Lib\UserException)
{
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)
{
if (_ENABLE_DEBUG) {
$json->code = $e->getCode();
$json->file = $e->getFile();
$json->line = $e->getLine();

View File

@ -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,8 +16,7 @@ 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'
@ -38,8 +36,7 @@ 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)
{
static function decode($token, $key) {
$parts = explode('.', $token);
if (count($parts) !== 3)
@ -58,29 +55,24 @@ class Jwt
return $payload;
}
static function getSignature ($b64Header, $b64Payload, $key)
{
static function getSignature($b64Header, $b64Payload, $key) {
$signature = hash_hmac('sha256', "$b64Header.$b64Payload", $key, TRUE);
return self::base64UrlEncode($signature);
}
static function jsonB64Encode ($data)
{
static function jsonB64Encode($data) {
return self::base64UrlEncode(json_encode($data));
}
static function jsonB64Decode ($data)
{
static function jsonB64Decode($data) {
return json_decode(self::base64UrlDecode($data), TRUE);
}
static function base64UrlEncode ($data)
{
static function base64UrlEncode($data) {
return rtrim(strtr(base64_encode($data), '+/', '-_'), '=');
}
static function base64UrlDecode ($data)
{
static function base64UrlDecode($data) {
$remainder = strlen($data) % 4;
$data = strtr($data, '-_', '+/');
return base64_decode(str_pad($data, $remainder, '=', STR_PAD_RIGHT));

View File

@ -6,28 +6,24 @@ require_once 'libphp-phpmailer/PHPMailerAutoload.php';
use Vn\Lib\UserException;
class Mailer
{
class Mailer {
private $conf;
function __construct ($db)
{
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->Host = $conf->host;
if (!empty ($conf->user))
{
if (!empty($conf->user)) {
$mail->SMTPAuth = TRUE;
$mail->Username = $conf->user;
$mail->Password = base64_decode($conf->password);
@ -35,8 +31,7 @@ class Mailer
else
$mail->SMTPAuth = FALSE;
if ($conf->secure)
{
if ($conf->secure) {
$mail->SMTPSecure = 'ssl';
$mail->Port = 465;
}
@ -55,8 +50,7 @@ class Mailer
return $mail;
}
function send ($mailTo, $body, $subject)
{
function send($mailTo, $body, $subject) {
$mail = $this->createObject($mailTo, $body, $subject);
if (!$mail->Send())

View File

@ -2,14 +2,12 @@
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;
@ -26,18 +24,15 @@ class Report
$this->title = $title;
}
function getTitle ()
{
function getTitle() {
return $this->title;
}
function getHtml ()
{
function getHtml() {
return $this->html;
}
function sendMail ($mail)
{
function sendMail($mail) {
$mailer = new Mailer($this->db);
$mailer->send($mail, $this->html, $this->title);
}

View File

@ -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;

View File

@ -9,10 +9,8 @@ use Vn\Lib\UserException;
/**
* Base class for REST application.
*/
class RestService extends Service
{
function run ()
{
class RestService extends Service {
function run() {
ini_set('display_errors', _ENABLE_DEBUG);
set_error_handler([$this, 'errorHandler'], E_ALL);
set_exception_handler([$this, 'exceptionHandler']);
@ -25,8 +23,7 @@ class RestService extends Service
/**
* Runs a REST method.
*/
function loadMethod ($class)
{
function loadMethod($class) {
$db = $this->db;
$this->login();
@ -34,8 +31,7 @@ class RestService extends Service
$_REQUEST['method'], $class, './rest');
$method->service = $this;
if ($method::SECURITY == Security::DEFINER)
{
if ($method::SECURITY == Security::DEFINER) {
$isAuthorized = $db->getValue('SELECT userCheckRestPriv(#)',
[$_REQUEST['method']]);
@ -57,8 +53,7 @@ class RestService extends Service
try {
$res = $method->run($methodDb);
}
catch (Db\Exception $e)
{
catch (Db\Exception $e) {
if ($e->getCode() == 1644)
throw new UserException(s($e->getMessage()));
}
@ -71,25 +66,19 @@ class RestService extends Service
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);
}
function errorHandler ($errno, $message, $file, $line, $context)
{
function errorHandler($errno, $message, $file, $line, $context) {
$eFlag =
E_USER_NOTICE
| E_USER_WARNING
@ -104,8 +93,7 @@ class RestService extends Service
return FALSE;
}
function exceptionHandler ($e)
{
function exceptionHandler($e) {
$this->statusFromException($e);
throw $e;
}

View File

@ -29,27 +29,23 @@ 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 ()
{
function init() {
$this->db = $this->app->getSysConn();
}
/**
* Starts the user session.
*/
function startSession ()
{
function startSession() {
$db = $this->app->getSysConn();
ini_set('session.cookie_secure', $this->isHttps());
@ -62,16 +58,14 @@ abstract class Service
if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE']))
if (!isset($_SESSION['httpLanguage'])
|| $_SESSION['httpLanguage'] != $_SERVER['HTTP_ACCEPT_LANGUAGE'])
{
|| $_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);
foreach($languages[1] as $lang)
if (TRUE || stream_resolve_include_path ("locale/$lang"))
{
if (TRUE || stream_resolve_include_path("locale/$lang")) {
$_SESSION['lang'] = $lang;
break;
}
@ -94,8 +88,7 @@ abstract class Service
$agent = $_SERVER['HTTP_USER_AGENT'];
$browser = get_browser($agent, TRUE);
if (!empty ($browser['crawler']))
{
if (!empty($browser['crawler'])) {
$_SESSION['skipVisit'] = TRUE;
return;
}
@ -118,8 +111,7 @@ abstract class Service
]
);
if (isset ($row['access']))
{
if (isset($row['access'])) {
setcookie('vnVisit', $row['visit'], time() + 31536000); // 1 Year
$_SESSION['access'] = $row['access'];
}
@ -137,23 +129,19 @@ 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']))
{
if (isset($_POST['user']) && isset($_POST['password'])) {
$user = strtolower($_POST['user']);
try {
$db->query('CALL account.userLogin(#, #)',
[$user, $_POST['password']]);
}
catch (Db\Exception $e)
{
if ($e->getMessage () == 'INVALID_CREDENTIALS')
{
catch (Db\Exception $e) {
if ($e->getMessage() == 'INVALID_CREDENTIALS') {
sleep(3);
throw new BadLoginException();
}
@ -161,10 +149,8 @@ abstract class Service
throw $e;
}
}
else
{
if (isset ($_POST['token']) || isset ($_GET['token']))
{
else {
if (isset($_POST['token']) || isset($_GET['token'])) {
if (isset($_POST['token']))
$token = $_POST['token'];
if (isset($_GET['token']))
@ -175,8 +161,7 @@ abstract class Service
try {
$jwtPayload = Jwt::decode($token, $key);
}
catch (\Exception $e)
{
catch (\Exception $e) {
throw new BadLoginException($e->getMessage());
}
@ -194,8 +179,7 @@ abstract class Service
[$user]
);
}
else
{
else {
$user = $db->getValue('SELECT guestUser FROM config');
$anonymousUser = TRUE;
}
@ -220,8 +204,7 @@ abstract class Service
/**
* Logouts the current user. Cleans the last saved used credentials.
*/
function logout ()
{
function logout() {
unset($_SESSION['user']);
}
@ -231,8 +214,7 @@ abstract class Service
*
* @return {Db\Conn} The database connection
*/
function getUserDb ($user)
{
function getUserDb($user) {
if ($this->userDb)
return $this->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
@ -287,15 +268,12 @@ abstract class Service
*
* @return string The version number
*/
function getVersion ()
{
function getVersion() {
$appName = $this->app->getName();
$version = apc_fetch("$appName.version", $success);
if (!$success)
{
if (file_exists ('package.json'))
{
if (!$success) {
if (file_exists('package.json')) {
$package = json_decode(file_get_contents('package.json'));
$version = $package->version;
}
@ -311,8 +289,7 @@ abstract class Service
/**
* Checks the client version.
*/
function checkVersion ()
{
function checkVersion() {
if (!empty($_COOKIE['vnVersion']))
$clientVersion = $_COOKIE['vnVersion'];
@ -326,8 +303,7 @@ abstract class Service
*
* @return boolean Return %TRUE if its secure, %FALSE otherwise
*/
function isHttps ()
{
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,8 +321,7 @@ abstract class Service
*
* @return string The current URL
*/
function getUrl ()
{
function getUrl() {
$proto = $this->isHttps() ? 'https' : 'http';
return "$proto://{$this->getUri()}";
}

View File

@ -5,13 +5,11 @@
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<title>Not available - Verdnatura</title>
<style type="text/css">
body
{
body {
font-size: 16pt;
font-family: Sans;
}
div
{
div {
position: absolute;
width: 32em;
margin-top: -7em;
@ -20,12 +18,10 @@
left: 50%;
text-align: center;
}
div h2
{
div h2 {
font-weight: normal;
}
div a
{
div a {
color: #2962FF;
text-decoration: none;
}

View File

@ -2,18 +2,15 @@
namespace Vn\Web;
class Util
{
class Util {
/**
* Reads a file and writes it to the output buffer.
*
* @param string file The file path
* @param boolean useXsendfile Wether to use the apache module Xsendfile
*/
static function printFile ($file, $useXsendfile = FALSE)
{
if (!file_exists ($file))
{
static function printFile($file, $useXsendfile = FALSE) {
if (!file_exists($file)) {
http_response_code(404);
return;
}
@ -21,13 +18,11 @@ class Util
$finfo = new \finfo(FILEINFO_MIME_TYPE);
$mimeType = $finfo->file($file);
if ($useXsendfile)
{
if ($useXsendfile) {
header("X-Sendfile: $file");
header("Content-Type: $mimeType");
}
else
{
else {
header('Content-Description: File Transfer');
header("Content-Type: $mimeType");
header('Content-Disposition: attachment; filename="'. basename($file) .'"');