Skip to content

Commit

Permalink
Set translations admin and tests
Browse files Browse the repository at this point in the history
  • Loading branch information
rantes committed Jan 10, 2022
1 parent 9f7095e commit 1d814a8
Show file tree
Hide file tree
Showing 70 changed files with 2,502 additions and 307 deletions.
4 changes: 3 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
.env
tmp/
*.log
app/webroot/test.html
app/webroot/test.html
*.po~
*.po
110 changes: 84 additions & 26 deletions app/controllers/admin_base_trait.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,55 +2,113 @@

trait AdminBaseTrait {
private $_model = '';
private $_model_camelized = '';
private $_response = [
'd' => [],
'message' => ''
];
private $_is_routed = false;
private $_actions = [];

private function _init() {
parent::__construct();
private function _additional_before_filter() {}

$this->layout = 'layout';
$this->helper = ['Sessions','Menu'];
private function _prepare_data() {
if(in_array($this->action, $this->_actions)):
$this->_model = Singulars($this->action);
$this->_model_camelized = Camelize($this->_model);
$this->_is_routed = true;
$this->action = 'landing';
endif;
}

public function before_filter() {
Require_login();
$this->menuLinks = adminMenu();
private function _edit_reg() {
$this->layout = false;
if(empty($this->params[1])):
throw new Exception('ID param must be given');
else:
$this->render = ['file'=>"{$this->controller}/{$this->_model}_addedit.phtml"];
$this->data = $this->{$this->_model_camelized}->Find($this->params[1]);
endif;
}

private function _add_reg() {
$this->layout = false;
$this->render = ['file'=>"{$this->controller}/{$this->_model}_addedit.phtml"];
$this->data = $this->{$this->_model_camelized}->Niu();
}

private function _list_regs() {
$this->render = ['file'=>"{$this->controller}/{$this->_model}_list.phtml"];
$conditions = '';
$this->searchterm = '';

if(!empty($_POST['search']) and !empty($_POST['search']['term']) and !empty($_POST['search']['fields'])):
$this->searchterm = $_POST['search']['term'];
while(null !== ($field = array_shift($_POST['search']['fields']))):
empty($conditions) or ($conditions = "{$conditions} OR ");
$conditions = "{$conditions}`{$field}` LIKE '%{$_POST['search']['term']}%'";
endwhile;
endif;

$this->data = $this->{$this->_model_camelized}->Paginate(['conditions'=>$conditions]);
}

public function deleteregAction() {
private function _delete_reg() {
$code = HTTP_422;
/** message key is a kinda standard, if an error occurs, message is the same attribute as in exception object */
$response = [
'd' => [],
'message' => ''
];
if (!empty($this->_model) and !empty($this->params['id'])):
$model = Camelize(Singulars($this->_model));

$obj = $this->{$model}->Find((integer)$this->params['id']);
($obj->Delete() and ($code = HTTP_200) and ($response['message'] = 'Success')) or ($response['m'] = (string)$obj->_error);
$obj = $this->{$this->_model_camelized}->Find((integer)$this->params['id']);
($obj->Delete() and ($code = HTTP_200) and ($this->_response['message'] = _('general.save.success'))) or ($this->_response['m'] = (string)$obj->_error);
endif;

http_response_code($code);
$this->respondToAJAX(json_encode($response));
$this->respondToAJAX(json_encode($this->_response));
}

public function addregAction() {
private function _save_reg() {
$code = HTTP_422;
$response = [
'd' => [],
'message' => 'Error Saving'
];

if(!empty($this->_model) and !empty($_POST[$this->_model])):
$model = Camelize(Singulars($this->_model));
$data = $this->{$model}->Niu($_POST[$this->_model]);
$data = $this->{$this->_model_camelized}->Niu($_POST[$this->_model]);
(
$data->Save()
and ($response['d'] = $data and ($response['message'] = 'Success') and $code = HTTP_200)
and ($response['d'] = $data and ($response['message'] = _('general.save.success')) and $code = HTTP_200)
)
or ($response['message'] = (string)$data->_error);
endif;

http_response_code($code);
$this->respondToAJAX(json_encode($response));
}

public function before_filter() {
Require_login();
$this->menuLinks = adminMenu();
$this->_additional_before_filter();
$this->_prepare_data();
}

public function landingAction() {
$this->render = ['text'=>'noop'];

if($this->_is_routed):
empty($this->params[0]) and ($this->params[0] = 'list');
switch($this->params[0]):
case 'edit':
$this->_edit_reg();
break;
case 'add':
$this->_add_reg();
break;
case 'delete':
$this->_delete_reg();
break;
case 'list':
$this->_list_regs();
break;
case 'save':
$this->_save_reg();
break;
endswitch;
endif;
}
}
41 changes: 20 additions & 21 deletions app/controllers/admin_controller.php
Original file line number Diff line number Diff line change
@@ -1,36 +1,35 @@
<?php
require_once INST_PATH.'app/controllers/admin_base_trait.php';
require_once INST_PATH.'app/controllers/common_trait.php';
class AdminController extends Page {
use AdminBaseTrait;
use CommonTrait;

public function __construct() {
$this->_init();
}
public $layout = 'layout';
public $helper = ['Sessions','Menu'];

public function indexAction() {
$this->render = ['text'=>'noop'];
}
public function __construct() {
parent::__construct();

public function usersAction() {
$this->users = $this->User->Find();
textdomain('translations');
}

public function deleteuserAction() {
$this->_model = 'user';
$this->deleteregAction();
private function _additional_before_filter() {
$this->_actions = [
'users',
'projects',
'estates',
'translations'
];
}

public function useraddregAction() {
$this->_model = 'user';
$this->addregAction();
public function indexAction() {
$this->render = ['text'=>'noop'];
}

public function useraddeditAction() {
$this->layout = false;
if(empty($this->params['id'])):
$this->data = $this->ProjectGroup->Niu();
else:
$this->data = $this->ProjectGroup->Find($this->params['id']);
endif;
public function buildlanguagesAction() {
chdir(INST_PATH);
system('dumbo run background/gettext > /dev/null 2>&1 &');
$this->respondToAJAX('{}');
}
}
154 changes: 154 additions & 0 deletions app/controllers/background_controller.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,154 @@
<?php
/**
* Tasks management in background.
*
* @author Javier Serrano <[email protected]>
* @version 1.0
* @package MUYCCTV
* @subpackage Controllers
*/
class BackgroundController extends Page {
public $layout = false;
public $noTemplate = [
'index',
'gettext',
'serverdata'
];
private $_colorMsg = null;
public $shellOutput = true;

public function __construct() {
parent::__construct();
class_exists('DumboShellColors') or require_once('DumboShellColors.php');
$this->_colorMsg = new DumboShellColors();
}

private function _logger($source, $message) {
if (empty($source) or empty($message) or !is_string($source) or !is_string($message)):
return false;
endif;
$logdir = INST_PATH.'tmp/logs/';
is_dir($logdir) or mkdir($logdir, 0775);
$file = "{$source}.log";
$stamp = date('d-m-Y H:i:s');

file_exists("{$logdir}{$file}") and filesize("{$logdir}{$file}") >= 524288000 and rename("{$logdir}{$file}", "{$logdir}{$stamp}_{$file}");
$this->shellOutput and fwrite(STDOUT, $this->_colorMsg->getColoredString($message, 'white', 'green') . "\n");
file_put_contents("{$logdir}{$file}", "[{$stamp}] - {$message}\n", FILE_APPEND);
return true;
}

private function _readFiles($path, $pattern) {
$files = [];
$dir = opendir($path);
//first level, not subdirectories
while(false !== ($file = readdir($dir))):
$file !== '.' and $file !== '..' and is_file("{$path}{$file}") and preg_match($pattern, $file, $matches) === 1 and ($files[] = "{$path}{$file}");
endwhile;
closedir($dir);
//Second level, subdirectories
$dir = opendir($path);
while(false !== ($file = readdir($dir))):
$npath = "{$path}{$file}";
if ($file !== '.' and $file !== '..' and is_dir($npath) and is_readable($npath)):
$dir1 = opendir("{$path}{$file}");
if(false !== $dir1):
while(false !== ($file1 = readdir($dir1))):
is_file("{$path}{$file}/{$file1}") and preg_match($pattern, $file1, $matches) === 1 and ($files[] = "{$path}{$file}/{$file1}");
endwhile;
closedir($dir1);
endif;
endif;
endwhile;
closedir($dir);
sort($files);

return $files;
}

public function gettextAction() {
$files = array_merge(
$this->_readFiles(INST_PATH.'app/', '/(.+)\.php/'),
$this->_readFiles(INST_PATH.'app/views/', '/(.+)\.phtml/')
);

$tmpFile = tempnam('/tmp', 'gettext');
file_put_contents($tmpFile, implode(PHP_EOL, $files));
$languages = [
'en_US' => 'English',
'es_CO' => 'Spanish',
'es_MX' => 'Spanish',
'pt_BR' => 'Portuguese'
];
$locales = [
'en_US',
'es_CO',
'es_MX',
'pt_BR'
];
file_exists(INST_PATH.'locale') or mkdir(INST_PATH.'locale');
while (null !== ($locale = array_shift($locales))):
file_exists(INST_PATH."locale/{$locale}.utf8") or mkdir(INST_PATH."locale/{$locale}.utf8");
file_exists(INST_PATH."locale/{$locale}.utf8/LC_MESSAGES") or mkdir(INST_PATH."locale/{$locale}.utf8/LC_MESSAGES");
$srclangpo = INST_PATH."locale/{$locale}.po";
exec("xgettext --language=PHP --sort-output --files-from={$tmpFile} -o {$srclangpo} > /dev/null 2>&1 ");
$tgtlang = INST_PATH."locale/{$locale}.utf8/LC_MESSAGES/translations.po";
file_exists($tgtlang) or copy($srclangpo, $tgtlang);
exec("msgmerge --update {$tgtlang} {$srclangpo} > /dev/null 2>&1");
unlink($srclangpo);

$moHeader = <<<DUMBO
# LOCALE TRANSLATIONS FILE.
# FIRST AUTHOR Javier Serrano <[email protected]>, 2021.
#
#, fuzzy
msgid ""
msgstr ""
"Project-Id-Version: KOMODO-1.0\\n"
"Report-Msgid-Bugs-To: [email protected]\\n"
"POT-Creation-Date: 2020-05-08 03:01-0500\\n"
"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\\n"
"Last-Translator: Javier Serrano <[email protected]>\\n"
"Language-Team: DEVELOPMENT <[email protected]>\\n"
"Language: {$languages[$locale]}\\n"
"MIME-Version: 1.0\\n"
"Content-Type: text/plain; charset=UTF-8\\n"
"Content-Transfer-Encoding: 8bit\\n"
\n
DUMBO;

$fp = fopen($tgtlang, 'r');
if($fp):
while(false !== ($buffer = fgets($fp, 1024))):
if (preg_match('@^msgid[ ]{1}\"[a-zA-Z0-9.]+\"$@i', $buffer)) {
$id = trim(str_replace('"', '', str_replace('msgid ', '', $buffer)));
$str = trim(str_replace('"', '', str_replace('msgstr ', '', fgets($fp, 1024))));

$this->Translation->Find([
'first',
'conditions' => "`locale` = '{$locale}' AND `keyid` = '{$id}'"
])->counter() === 0 and $this->Translation->Niu([
'locale' => $locale,
'translation' => $str,
'keyid' => $id
])->Save();
}
endwhile;
fclose($fp);
endif;

file_put_contents($tgtlang, $moHeader);

$translations = $this->Translation->Find_by_locale($locale)->getArray();
while(null !== ($reg = array_shift($translations))):
$ent = html_entity_decode($reg['translation'], ENT_QUOTES, 'UTF-8');
$str = "msgid \"{$reg['keyid']}\"\nmsgstr \"{$ent}\"\n\n";
file_put_contents($tgtlang, $str, FILE_APPEND);
endwhile;
$tgtlang = substr($tgtlang, 0, -2);
exec("msgfmt --output-file={$tgtlang}mo {$tgtlang}po > /dev/null 2>&1");
endwhile;
unlink($tmpFile);
}

}
31 changes: 31 additions & 0 deletions app/controllers/common_trait.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
<?php

trait CommonTrait {
private $_loginLevel = 1;

public function loginAction() {
$this->layout = false;
}

public function signinAction() {
$code = HTTP_401;

if (!empty($_POST['e']) and !empty($_POST['p'])):
$id = $this->User->login($_POST['e'], $_POST['p'], $this->_loginLevel);
$id > 0 and ($code = HTTP_202) and ($_SESSION['user'] = $id);
endif;

http_response_code($code);
$this->respondToAJAX('{}');
}
/**
* Destroy all registered information of a session and redirect to the login page.
*/
public function logoutAction() {
$this->layout = false;
php_sapi_name() !== 'cli' && session_destroy();
$_SESSION = null;
unset($_SESSION);
header("Location: /{$this->controller}/login");
}
}
Loading

0 comments on commit 1d814a8

Please sign in to comment.