Esempio n. 1
0
 /**
  * Translate text using google api
  *
  * @param   string $text   text to translate
  * @param   string $source source language
  * @param   string $target target language
  *
  * @return string
  *
  * @throws Exception
  */
 public function translate($text, $source, $target)
 {
     // Convert from JISO to ISO codes
     $source = $this->convertFromJisoToIso($source);
     $target = $this->convertFromJisoToIso($target);
     $apiKey = NenoSettings::get('translator_api_key');
     $url = 'https://www.googleapis.com/language/translate/v2';
     //Chunk the text if need be
     $chunks = NenoHelper::chunkHTMLString($text, 4900);
     $translatedChunks = array();
     foreach ($chunks as $chunk) {
         // Invoke the POST request.
         $response = $this->post($url, array('key' => $apiKey, 'q' => $chunk, 'source' => $source, 'target' => $target), array('X-HTTP-Method-Override' => 'GET'));
         // Log it if server response is not OK.
         if ($response->code != 200) {
             NenoLog::log('Google API failed with response: ' . $response->code, 1);
             $responseData = json_decode($response->body, true);
             throw new Exception($responseData['error']['errors'][0]['message'] . ' (' . $responseData['error']['errors'][0]['reason'] . ')', $response->code);
         } else {
             $responseBody = json_decode($response->body);
             $translatedChunks[] = $responseBody->data->translations[0]->translatedText;
         }
     }
     return implode(' ', $translatedChunks);
 }
Esempio n. 2
0
 /**
  * Translate text using yandex api
  *
  * @param   string $text   text to translate
  * @param   string $source source language
  * @param   string $target target language
  *
  * @return string
  *
  * @throws Exception
  */
 public function translate($text, $source, $target)
 {
     // Convert from JISO to ISO codes
     $target = $this->convertFromJisoToIso($target);
     // Language parameter for url
     $source = $this->convertFromJisoToIso($source);
     $lang = $source . "-" . $target;
     $apiKey = NenoSettings::get('translator_api_key');
     //Chunk the text if need be
     $chunks = NenoHelper::chunkHTMLString($text, 9900);
     $translatedChunks = array();
     foreach ($chunks as $chunk) {
         $url = 'https://translate.yandex.net/api/v1.5/tr.json/translate?key=' . $apiKey . '&lang=' . $lang;
         // Invoke the POST request.
         $response = $this->post($url, array('text' => $chunk));
         // Log it if server response is not OK.
         if ($response->code != 200) {
             NenoLog::log('Yandex API failed with response: ' . $response->code, 1);
             $responseData = json_decode($response->body, true);
             throw new Exception(JText::_('COM_NENO_EDITOR_YANDEX_ERROR_CODE_' . $responseData['code']), $responseData['code']);
         } else {
             $responseBody = json_decode($response->body);
             $translatedChunks[] = $responseBody->text[0];
         }
     }
     return implode(' ', $translatedChunks);
 }
Esempio n. 3
0
 /**
  * Execute the task
  *
  * @param   array $taskData Task data
  *
  * @return bool True on success, false otherwise
  */
 public function run($taskData)
 {
     $languages = NenoHelper::getLanguages();
     $defaultLanguage = NenoSettings::get('source_language');
     $profiler = new JProfiler();
     foreach ($languages as $language) {
         if ($language->lang_code !== $defaultLanguage) {
             $profiler->mark('Before create job' . $language->lang_code . ' Method: Machine');
             $machineJob = NenoJob::createJob($language->lang_code, NenoContentElementTranslation::MACHINE_TRANSLATION_METHOD);
             $profiler->mark('After create job' . $language->lang_code . ' Method: Machine');
             // If there are translations for this language and for this translation method
             if ($machineJob !== null) {
                 NenoLog::add(count($machineJob->getTranslations()) . ' translations have been found to translate through machine translation');
             }
             $proJob = NenoJob::createJob($language->lang_code, NenoContentElementTranslation::PROFESSIONAL_TRANSLATION_METHOD);
             // If there are translations for this language and for this translation method
             if ($proJob !== null) {
                 NenoLog::add(count($proJob->getTranslations()) . ' translations have been found to translate through professional translation');
             }
             if ($machineJob !== null || $proJob !== null) {
                 NenoTaskMonitor::addTask('job_sender');
             }
         }
     }
 }
Esempio n. 4
0
 /**
  * Translate text using google api
  *
  * @param   string $text   text to translate
  * @param   string $source source language
  * @param   string $target target language
  *
  * @return string
  *
  * @throws Exception
  */
 public function translate($text, $source, $target)
 {
     // Convert from JISO to ISO codes
     $source = $this->convertFromJisoToIso($source);
     $target = $this->convertFromJisoToIso($target);
     $apiKey = NenoSettings::get('translator_api_key');
     $url = 'https://www.googleapis.com/language/translate/v2';
     if (mb_strlen($text) < 5000) {
         // Invoke the POST request.
         $response = $this->post($url, array('key' => $apiKey, 'q' => $text, 'source' => $source, 'target' => $target), array('X-HTTP-Method-Override' => 'GET'));
         $text = null;
         // Log it if server response is not OK.
         if ($response->code != 200) {
             NenoLog::log('Google API failed with response: ' . $response->code, 1);
             $responseData = json_decode($response->body, true);
             throw new Exception($responseData['error']['errors'][0]['message'] . ' (' . $responseData['error']['errors'][0]['reason'] . ')', $response->code);
         } else {
             $responseBody = json_decode($response->body);
             $text = $responseBody->data->translations[0]->translatedText;
         }
         return $text;
     } else {
         throw new Exception(JText::_('COM_NENO_EDITOR_GOOGLE_ERROR_TEXT_TOO_LONG'), 413);
     }
 }
Esempio n. 5
0
 /**
  * Translate text using google api
  *
  * @param   string $text   text to translate
  * @param   string $source source language
  * @param   string $target target language
  *
  * @return string
  *
  * @throws Exception
  */
 public function translate($text, $source, $target)
 {
     // Convert from JISO to ISO codes
     $source = $this->convertFromJisoToIso($source);
     $target = $this->convertFromJisoToIso($target);
     list($clientId, $clientSecret) = explode(':', NenoSettings::get('translator_api_key'));
     $accessToken = $this->requestAccessToken($clientId, $clientSecret);
     $url = 'http://api.microsofttranslator.com/V2/Http.svc/Translate';
     //Chunk the text if need be
     $chunks = NenoHelper::chunkHTMLString($text, 4900);
     $translatedChunks = array();
     foreach ($chunks as $chunk) {
         $query = http_build_query(array('from' => $source, 'text' => $chunk, 'to' => $target));
         // Invoke the POST request.
         $response = $this->get($url . '?' . $query, array('Authorization' => 'Bearer ' . $accessToken));
         $responseBody = (array) simplexml_load_string($response->body);
         // Log it if server response is not OK.
         if ($response->code != 200) {
             NenoLog::log('Bing API failed with response: ' . $response->code, 1);
             throw new Exception((string) $responseBody['body']->p[1], $response->code);
         } else {
             $translatedChunks[] = $responseBody[0];
         }
     }
     return implode(' ', $translatedChunks);
 }
Esempio n. 6
0
 /**
  * Translate text using yandex api
  *
  * @param   string $text   text to translate
  * @param   string $source source language
  * @param   string $target target language
  *
  * @return string
  *
  * @throws Exception
  */
 public function translate($text, $source, $target)
 {
     // Convert from JISO to ISO codes
     $target = $this->convertFromJisoToIso($target);
     // Language parameter for url
     $source = $this->convertFromJisoToIso($source);
     $lang = $source . "-" . $target;
     $apiKey = NenoSettings::get('translator_api_key');
     // For POST requests, the maximum size of the text being passed is 10000 characters.
     if (mb_strlen($text) <= 10000) {
         $url = 'https://translate.yandex.net/api/v1.5/tr.json/translate?key=' . $apiKey . '&lang=' . $lang;
         // Invoke the POST request.
         $response = $this->post($url, array('text' => $text));
         $text = null;
         // Log it if server response is not OK.
         if ($response->code != 200) {
             NenoLog::log('Yandex API failed with response: ' . $response->code, 1);
             $responseData = json_decode($response->body, true);
             throw new Exception(JText::_('COM_NENO_EDITOR_YANDEX_ERROR_CODE_' . $responseData['code']), $responseData['code']);
         } else {
             $responseBody = json_decode($response->body);
             $text = $responseBody->text[0];
         }
         return $text;
     } else {
         throw new Exception(JText::_('COM_NENO_EDITOR_YANDEX_ERROR_TEXT_TOO_LONG'), 413);
     }
 }
Esempio n. 7
0
 /**
  * Get a list of strings
  *
  * @return  string
  */
 public function getStrings()
 {
     NenoLog::log('Method getStrings of NenoControllerStrings called', 3);
     $input = JFactory::getApplication()->input;
     $filterJson = $input->getString('jsonGroupsElements');
     $filterArray = json_decode($filterJson);
     $filterGroups = array();
     $filterElements = array();
     $filterField = array();
     $filterFile = array();
     $filterMethods = array();
     $filterStatus = array();
     $outputLayout = strtolower($input->getString('outputLayout'));
     $filterSearch = strtolower($input->get('filter_search', '', 'RAW'));
     $app = JFactory::getApplication();
     NenoLog::log('Processing filtered json data for NenoControllerStrings::getStrings', 3);
     foreach ($filterArray as $filterItem) {
         if (NenoHelper::startsWith($filterItem, 'group-') !== false) {
             $filterGroups[] = str_replace('group-', '', $filterItem);
         } elseif (NenoHelper::startsWith($filterItem, 'table-') !== false) {
             $filterElements[] = str_replace('table-', '', $filterItem);
         } elseif (NenoHelper::startsWith($filterItem, 'field-') !== false) {
             $filterField[] = str_replace('field-', '', $filterItem);
         } elseif (NenoHelper::startsWith($filterItem, 'file-') !== false) {
             $filterFile[] = str_replace('file-', '', $filterItem);
         }
     }
     // Set filters into the request.
     $input->set('group', $filterGroups);
     $input->set('table', $filterElements);
     $input->set('field', $filterField);
     $input->set('file', $filterFile);
     $input->set('list', array('limit' => $input->get('limit'), 'start' => $input->get('limitStart')));
     $input->set('limitstart', $input->get('limitStart'));
     $filterJson = $input->getString('jsonMethod');
     $filterArray = json_decode($filterJson);
     foreach ($filterArray as $filterItem) {
         $filterMethods[] = str_replace('method-', '', $filterItem);
     }
     $input->set('type', $filterMethods);
     $filterJson = $input->getString('jsonStatus');
     $filterArray = json_decode($filterJson);
     foreach ($filterArray as $filterItem) {
         $filterStatus[] = (int) str_replace('status-', '', $filterItem);
     }
     $input->set('status', $filterStatus);
     $input->set('filter_search', $filterSearch);
     $app->setUserState('limit', $input->getInt('limit', 20));
     $app->setUserState('limitStart', $input->getInt('limitStart', 0));
     /* @var $stringsModel NenoModelStrings */
     $stringsModel = $this->getModel();
     $translations = $stringsModel->getItems();
     $displayData = new stdClass();
     $displayData->translations = $translations;
     $displayData->state = $stringsModel->getState();
     $displayData->pagination = $stringsModel->getPagination();
     echo JLayoutHelper::render($outputLayout, $displayData, JPATH_NENO_LAYOUTS);
     JFactory::getApplication()->close();
 }
Esempio n. 8
0
 /**
  * Execute the task
  *
  * @param   array $taskData Task data
  *
  * @return bool True on success, false otherwise
  */
 public function run($taskData)
 {
     $tasksNeedToBeCleanUp = NenoTask::load(array('_field' => 'numberOfAttemps', '_condition' => '>', '_value' => 3));
     /* @var $taskNeedToBeCleanUp NenoTask */
     foreach ($tasksNeedToBeCleanUp as $taskNeedToBeCleanUp) {
         NenoLog::add($taskNeedToBeCleanUp->getTask() . ' task has been deleted because reaches the maximum number of attempts allowed');
         $taskNeedToBeCleanUp->remove();
     }
     return false;
 }
Esempio n. 9
0
 public static function error($errorNumber, $errorMessage, $file, $line)
 {
     $errorType = 'none';
     switch ($errorNumber) {
         case E_ERROR:
             $errorType = 'error';
             break;
         case E_WARNING:
             $errorType = 'warning';
             break;
         case E_PARSE:
             $errorType = 'parse';
             break;
         case E_NOTICE:
             $errorType = 'notice';
             break;
         case E_CORE_ERROR:
             $errorType = 'core error';
             break;
         case E_CORE_WARNING:
             $errorType = 'core warning';
             break;
         case E_USER_ERROR:
             $errorType = 'user error';
             break;
         case E_USER_WARNING:
             $errorType = 'user warning';
             break;
         case E_USER_NOTICE:
             $errorType = 'user notice';
             break;
         case E_STRICT:
             $errorType = 'strict';
             break;
         case E_RECOVERABLE_ERROR:
             $errorType = 'recoverable error';
             break;
         case E_DEPRECATED:
             $errorType = 'deprecated';
             break;
         case E_USER_DEPRECATED:
             $errorType = 'user deprecated';
             break;
     }
     NenoLog::log("Encountered {$errorType} error in {$file}, line {$line}: {$errorMessage}", NenoLog::PRIORITY_ERROR);
 }
Esempio n. 10
0
 /**
  * Execute the task
  *
  * @param   array|null $taskData Task data
  *
  * @return bool True on success, false otherwise
  */
 public function run($taskData)
 {
     $jobs = NenoJob::load(array('state' => NenoJob::JOB_STATE_COMPLETED));
     // If there is only one job, let's transform it to an array
     if (!is_array($jobs)) {
         $jobs = array($jobs);
     }
     /* @var $job NenoJob */
     foreach ($jobs as $job) {
         if ($job->fetchJobFromServer() === true) {
             if ($job->processJobFinished() === true) {
                 $job->setState(NenoJob::JOB_STATE_PROCESSED)->persist();
                 NenoLog::add('Job #' . $job->getId() . ' has been successfully processed.');
             } else {
                 NenoLog::add('There as an error reading the content of the file.', NenoLog::PRIORITY_ERROR);
             }
         } else {
             NenoLog::add('There was an error fetching the file from the API server', NenoLog::PRIORITY_ERROR);
         }
     }
 }
Esempio n. 11
0
/**
 * @package    Neno
 *
 * @author     Jensen Technologies S.L. <*****@*****.**>
 * @copyright  Copyright (C) 2014 Jensen Technologies S.L. All rights reserved.
 * @license    GNU General Public License version 2 or later; see LICENSE.txt
 */
// No direct access
defined('_JEXEC') or die;
// Make sure that the Neno package is defined.
if (!defined('JPATH_NENO')) {
    $nenoLoader = JPATH_LIBRARIES . '/neno/loader.php';
    if (file_exists($nenoLoader)) {
        JLoader::register('NenoLoader', $nenoLoader);
        // Register the Class prefix in the autoloader
        NenoLoader::init();
    }
}
if (!NenoHelperBackend::isDatabaseDriverEnabled()) {
    $app = JFactory::getApplication();
    $app->enqueueMessage('Please enable the plugin to use Neno', 'error');
    NenoLog::log('Plugin disabled in frontend', 1);
    $app->setUserState('com_plugins.plugins.filter.search', 'neno');
    $app->redirect('index.php?option=com_plugins');
}
// Include dependencies
jimport('joomla.application.component.controller');
$controller = JControllerLegacy::getInstance('Neno');
$controller->execute(JFactory::getApplication()->input->get('task'));
$controller->redirect();
Esempio n. 12
0
 /**
  * Fetch the job file from the server
  *
  * @return bool|JError True on Success or false|JError if something goes wrong.
  */
 public function fetchJobFromServer()
 {
     $config = JFactory::getConfig();
     $tmpPath = $config->get('tmp_path');
     $filename = $this->getFileName();
     /* @var $zipAdapter JArchiveZip */
     $zipAdapter = JArchive::getAdapter('zip');
     $fullPath = JPATH_ROOT . '/tmp/' . $filename . '.json.zip';
     // Check if the file has been downloaded properly
     if (!NenoHelperApi::getJobFile($this->id, $fullPath)) {
         return false;
     }
     try {
         return $zipAdapter->extract($fullPath, $tmpPath . '/' . $filename . '.json');
     } catch (RuntimeException $e) {
         NenoLog::log($e->getMessage(), NenoLog::PRIORITY_ERROR, true);
         return false;
     }
 }
Esempio n. 13
0
 /**
  * Set a translation as ready
  *
  * @return void
  */
 public function translationReady()
 {
     $input = $this->input;
     $jobId = $input->get->getString('jobId');
     /* @var $job NenoJob */
     $job = NenoJob::load($jobId);
     if ($job === null) {
         NenoLog::add('Job not found. Job Id:' . $jobId, NenoLog::PRIORITY_ERROR);
     } else {
         // Set the job as completed by the server but the component hasn't processed it yet.
         $job->setState(NenoJob::JOB_STATE_COMPLETED)->persist();
         // Create task into the queue
         NenoTaskMonitor::addTask('job_fetcher');
         echo 'ok';
     }
     JFactory::getApplication()->close();
 }
Esempio n. 14
0
 /**
  * {@inheritdoc}
  *
  * @return bool
  */
 public function remove()
 {
     NenoLog::log('Element deleted successfully', 2);
     return parent::remove();
 }
Esempio n. 15
0
 /**
  * Toggle translate status for tables
  *
  * @return void
  */
 public function toggleContentElementTable()
 {
     NenoLog::log('Method toggleContentElementTable of NenoControllerGroupsElements called', 3);
     $input = JFactory::getApplication()->input;
     $tableId = $input->getInt('tableId');
     $translateStatus = $input->getBool('translateStatus');
     /* @var $table NenoContentElementTable */
     $table = NenoContentElementTable::getTableById($tableId);
     // If the table exists, let's work with it.
     if ($table !== false) {
         $table->setTranslate($translateStatus);
         if ($table->persist() === false) {
             NenoLog::log('Error saving new state!', NenoLog::PRIORITY_ERROR);
         }
     }
     JFactory::getApplication()->close();
 }
Esempio n. 16
0
 /**
  * {@inheritdoc}
  *
  * @return bool
  */
 public function remove()
 {
     // Get the tables
     $tables = $this->getTables();
     /* @var $table NenoContentElementTable */
     foreach ($tables as $table) {
         $table->remove();
     }
     // Get language strings
     $languageStrings = $this->getLanguageFiles();
     /* @var $languageString NenoContentElementLanguageString */
     foreach ($languageStrings as $languageString) {
         $languageString->remove();
     }
     $db = JFactory::getDbo();
     $query = $db->getQuery(true);
     $query->delete('#__neno_content_element_groups_x_translation_methods')->where('group_id = ' . $this->id);
     $db->setQuery($query);
     $db->execute();
     $query->clear()->delete('#__neno_content_element_groups_x_extensions')->where('group_id = ' . $this->id);
     $db->setQuery($query);
     $db->execute();
     NenoLog::log('Group deleted successfully', 2);
     return parent::remove();
 }
Esempio n. 17
0
 /**
  * Execute a particular task given by parameter
  *
  * @param   NenoTask|null $task Task to execute
  *
  * @return bool True on success, false otherwise
  */
 private static function executeTask($task)
 {
     NenoLog::log('Received translation job to execute', 2);
     // If there are task to execute, let's run it
     if (!empty($task)) {
         $task->execute();
         NenoLog::add($task->getTask() . ' task has been executed properly');
         $task->remove();
         return true;
     }
     return false;
 }
Esempio n. 18
0
 /**
  * Get all the languages files in a particular path
  *
  * @param   string      $path             Path
  * @param   null|string $language         Language tag
  * @param   bool        $recursive        If a recursive search should be applied
  * @param   bool        $ignoreJoomlaCore If Joomla core languages files should be ignored
  *
  * @return array
  */
 protected static function getLanguageFilesInPath($path, $language = null, $recursive = true, $ignoreJoomlaCore = true)
 {
     if (NenoHelper::endsWith($path, '/')) {
         $path = substr($path, 0, mb_strlen($path) - 1);
     }
     jimport('joomla.filesystem.folder');
     if (is_null($language)) {
         $filter = '\\.ini$';
     } else {
         $filter = '^' . $language . '.*\\.ini$';
     }
     NenoLog::log('Looking for language files in [' . $language . '] inside: ' . $path, 3);
     // Load list
     $files = JFolder::files($path, $filter, $recursive, true);
     // Remove Joomla core files if needed
     if ($ignoreJoomlaCore === true && !empty($files)) {
         $files = self::removeCoreLanguageFilesFromArray($files, $language);
     }
     // Debug
     if (!empty($files)) {
         foreach ($files as $file) {
             NenoLog::log('Found file: ' . $file, 3);
         }
     }
     return $files === false ? array() : $files;
 }
Esempio n. 19
0
 /**
  * Get client list in text/value format for a select field
  *
  * @return  array
  */
 public static function getGroupOptions()
 {
     $options = array();
     $db = JFactory::getDbo();
     $query = $db->getQuery(true)->select('id AS value, group_name AS text')->from('#__neno_content_element_groups AS n')->order('n.group_name');
     // Get the options.
     $db->setQuery($query);
     try {
         $options = $db->loadObjectList();
     } catch (RuntimeException $e) {
         NenoLog::log($e->getMessage(), NenoLog::PRIORITY_ERROR);
     }
     array_unshift($options, JHtml::_('select.option', '0', JText::_('COM_NENO_SELECT_GROUP')));
     return $options;
 }
Esempio n. 20
0
 /**
  * Toggle translate status for tables
  *
  * @return void
  */
 public function toggleContentElementTable()
 {
     NenoLog::log('Method toggleContentElementTable of NenoControllerGroupsElements called', 3);
     $input = JFactory::getApplication()->input;
     $tableId = $input->getInt('tableId');
     $translateStatus = $input->getInt('translateStatus');
     /* @var $table NenoContentElementTable */
     $table = NenoContentElementTable::getTableById($tableId);
     // If the table exists, let's work with it.
     if ($table !== false) {
         $table->setTranslate($translateStatus, true);
         if ($table->persist() !== false) {
             $fields = $table->getFields(false);
             /* @var $field NenoContentElementField */
             foreach ($fields as $field) {
                 $oldStatus = $field->isTranslate();
                 $field->setTranslate($translateStatus === true ? NenoContentElementField::isTranslatableType($field->getFieldType()) : $translateStatus, true);
                 // Only persist element that have changed their translate status
                 if ($oldStatus != $field->isTranslate()) {
                     $field->persist();
                 }
             }
         } else {
             NenoLog::log('Error saving new state!', NenoLog::PRIORITY_ERROR);
         }
     }
     JFactory::getApplication()->close();
 }
Esempio n. 21
0
 /**
  * Build an SQL query to load the list data.
  *
  * @return    JDatabaseQuery
  *
  * @since    1.6
  */
 protected function getListQuery()
 {
     $db = JFactory::getDbo();
     $workingLanguage = NenoHelper::getWorkingLanguage();
     NenoLog::log('Querying #__neno_content_element_tables from getListQuery of NenoModelStrings', 3);
     // Create a new query object.
     $dbStrings = parent::getListQuery();
     $languageFileStrings = parent::getListQuery();
     $dbStrings->select(array('tr1.*', 'f.field_name AS `key`', 't.table_name AS element_name', 'g1.group_name AS `group`', 'CHAR_LENGTH(tr1.string) AS characters'))->from('`#__neno_content_element_translations` AS tr1')->innerJoin('`#__neno_content_element_fields` AS f ON tr1.content_id = f.id')->innerJoin('`#__neno_content_element_tables` AS t ON t.id = f.table_id')->innerJoin('`#__neno_content_element_groups` AS g1 ON t.group_id = g1.id ')->where(array('tr1.language = ' . $db->quote($workingLanguage), 'tr1.content_type = ' . $db->quote('db_string'), 'f.translate = 1'))->group(array('tr1.string', 'tr1.state'))->order('tr1.id');
     $languageFileStrings->select(array('tr2.*', 'ls.constant AS `key`', 'lf.filename AS element_name', 'g2.group_name AS `group`', 'CHAR_LENGTH(tr2.string) AS characters'))->from('`#__neno_content_element_translations` AS tr2')->innerJoin('`#__neno_content_element_language_strings` AS ls ON tr2.content_id = ls.id')->innerJoin('`#__neno_content_element_language_files` AS lf ON lf.id = ls.languagefile_id')->innerJoin('`#__neno_content_element_groups` AS g2 ON lf.group_id = g2.id ')->where(array('tr2.language = ' . $db->quote($workingLanguage), 'tr2.content_type = ' . $db->quote('lang_string')))->group(array('tr2.string', 'tr2.state'))->order('tr2.id');
     $queryWhereDb = array();
     /* @var $groups array */
     $groups = $this->getState('filter.group_id', array());
     /* @var $element array */
     $element = $this->getState('filter.element', array());
     /* @var $field array */
     $field = $this->getState('filter.field', array());
     /* @var $file array */
     $file = $this->getState('filter.files', array());
     $groupIdAdded = false;
     if (!is_array($groups)) {
         $groups = array($groups);
     }
     if (!empty($groups) && !in_array('none', $groups)) {
         $queryWhereDb[] = 't.group_id IN (' . implode(', ', $groups) . ')';
         $languageFileStrings->where('lf.group_id IN (' . implode(', ', $groups) . ')');
     }
     if (!empty($element)) {
         if ($groupIdAdded === false) {
             $languageFileStrings->select('g2.id AS group_id');
             $dbStrings->select('g1.id AS group_id');
             $groupIdAdded = true;
         }
         $queryWhereDb[] = 't.id IN (' . implode(', ', $element) . ')';
         // Do not show any strings for this language file
         if (empty($file)) {
             $languageFileStrings->where('lf.id = 0');
         }
     }
     if (!empty($field)) {
         if ($groupIdAdded === false) {
             $languageFileStrings->select('g2.id AS group_id');
             $dbStrings->select('g1.id AS group_id');
             $groupIdAdded = true;
         }
         // Do not show any strings for this language file
         if (empty($file)) {
             $languageFileStrings->where('lf.id = 0');
         }
         $queryWhereDb[] = 'f.id IN (' . implode(', ', $field) . ')';
     }
     if (!empty($file)) {
         $languageFileStrings->where('lf.id IN (' . implode(',', $file) . ')');
         if (empty($field) && empty($element)) {
             $queryWhereDb[] = 'f.id = 0 AND t.id = 0';
         }
     }
     if (count($queryWhereDb)) {
         $dbStrings->where('(' . implode(' OR ', $queryWhereDb) . ')');
     }
     $method = (array) $this->getState('filter.translator_type', array());
     if (!empty($method) && !in_array('none', $method)) {
         $dbStrings->where('tr_x_tm1.translation_method_id IN ("' . implode('", "', $method) . '")')->leftJoin('`#__neno_content_element_translation_x_translation_methods` AS tr_x_tm1 ON tr1.id = tr_x_tm1.translation_id');
         $languageFileStrings->where('tr_x_tm2.translation_method_id IN ("' . implode('", "', $method) . '")')->leftJoin('`#__neno_content_element_translation_x_translation_methods` AS tr_x_tm2 ON tr2.id = tr_x_tm2.translation_id');
     }
     $status = (array) $this->getState('filter.translation_status', array());
     if (!empty($status) && $status[0] !== '' && !in_array('none', $status)) {
         $dbStrings->where('tr1.state IN (' . implode(', ', $status) . ')');
         $languageFileStrings->where('tr2.state IN (' . implode(', ', $status) . ')');
     }
     // Hide empty strings if the user wants to do that
     if (NenoSettings::get('hide_empty_strings', true)) {
         $dbStrings->where('tr1.string <> ' . $db->quote(''));
         $languageFileStrings->where('tr2.string <> ' . $db->quote(''));
     }
     $query = parent::getListQuery();
     $query->select('DISTINCT *')->from('((' . (string) $dbStrings . ') UNION (' . (string) $languageFileStrings . ')) AS a')->group('id');
     $search = $this->getState('filter.search');
     if (!empty($search)) {
         $search = $db->quote('%' . $search . '%');
         $query->where('(a.original_text LIKE ' . $search . ' OR a.string LIKE ' . $search . ')');
     }
     // Add the list ordering clause.
     $orderCol = $this->state->get('list.ordering');
     $orderDirection = $this->state->get('list.direction');
     if ($orderCol && $orderDirection) {
         $query->order($db->escape($orderCol . ' ' . $orderDirection));
     }
     return $query;
 }
Esempio n. 22
0
 /**
  * Get Worker related to a task
  *
  * @return NenoTaskWorker
  */
 protected function getWorker()
 {
     // Generate Worker class name
     $className = 'NenoTaskWorker' . ucfirst(NenoHelper::convertDatabaseColumnNameToPropertyName($this->task));
     // Check if the class exists, if it doesn't, let's try to load it.
     if (class_exists($className)) {
         $worker = new $className();
         return $worker;
     } else {
         NenoLog::log('Worker not found for this task', 1);
         throw new UnexpectedValueException('Worker not found for this task');
     }
 }
Esempio n. 23
0
 /**
  * Get a list of languages
  *
  * @param   bool $allSupported All the languages supported by Joomla
  *
  * @return array
  */
 public static function findLanguages($allSupported = false)
 {
     $enGbExtensionId = self::getEnGbExtensionId();
     NenoLog::log('en-GB Extension ID ' . $enGbExtensionId);
     $languagesFound = array();
     $db = JFactory::getDbo();
     $query = $db->getQuery(true);
     if (!empty($enGbExtensionId)) {
         // Let's enable it if it's disabled
         $query->select('a.update_site_id')->from('#__update_sites AS a')->innerJoin('#__update_sites_extensions AS b ON a.update_site_id = b.update_site_id')->where('b.extension_id = ' . (int) $enGbExtensionId);
         $db->setQuery($query);
         $updateId = $db->loadResult();
         if (!empty($updateId)) {
             $query->clear()->update('#__update_sites')->set('enabled = 1')->where('update_site_id = ' . (int) $updateId);
             $db->setQuery($query);
             $db->execute();
         }
         // Find updates for languages
         $updater = JUpdater::getInstance();
         $updater->findUpdates($enGbExtensionId);
         $updateSiteId = self::getLanguagesUpdateSite($enGbExtensionId);
         NenoLog::log('UpdateSiteID: ' . $updateSiteId);
         $updates = self::getUpdates($updateSiteId);
         NenoLog::log('Updates: ' . json_encode($updateSiteId));
         $languagesFound = $updates;
     }
     if ($allSupported) {
         $query->clear()->select(array('DISTINCT element AS iso', 'name'))->from('#__extensions')->where('type = ' . $db->quote('language'))->group('element');
         $db->setQuery($query);
         $languagesFound = array_merge($db->loadAssocList(), $languagesFound);
     }
     return $languagesFound;
 }
Esempio n. 24
0
 /**
  * {@inheritdoc}
  *
  * @return bool|mixed
  */
 public function execute()
 {
     $language = JFactory::getLanguage();
     $app = JFactory::getApplication();
     // Check if the user is trying to insert something in the front-end in different language
     if ($this->getQueryType((string) $this->sql) === self::INSERT_QUERY && $language->getTag() !== NenoSettings::get('source_language') && $app->isSite() && !$this->isNenoSql((string) $this->sql)) {
         $tables = null;
         preg_match('/insert into (\\w+)/', $this->sql, $tables);
         if (!empty($tables)) {
             /* @var $table NenoContentElementTable */
             $table = NenoContentElementTable::load(array('table_name' => $tables[1]));
             if (!empty($table) && $table->isTranslate()) {
                 $language->load('com_neno', JPATH_ADMINISTRATOR);
                 throw new Exception(JText::_('COM_NENO_CONTENT_IN_OTHER_LANGUAGES_ARE_NOT_ALLOWED'));
             }
         }
     } else {
         try {
             // Get query type
             $queryType = $this->getQueryType((string) $this->sql);
             $result = parent::execute();
             // If the query is creating/modifying/deleting a record, let's do the same on the shadow tables
             if (($queryType === self::INSERT_QUERY || $queryType === self::DELETE_QUERY || $queryType === self::UPDATE_QUERY || $queryType === self::REPLACE_QUERY) && $this->hasToBeParsed((string) $this->sql)) {
                 $sql = $this->sql;
                 foreach ($this->languages as $language) {
                     $newSql = $this->replaceTableNameStatements((string) $sql, $language->lang_code);
                     // Execute query if they are different.
                     if ($newSql != $sql) {
                         $this->executeQuery($newSql, false);
                     }
                 }
             }
             return $result;
         } catch (RuntimeException $ex) {
             NenoLog::log($ex->getMessage(), NenoLog::PRIORITY_ERROR);
         }
     }
     return false;
 }
Esempio n. 25
0
 /**
  * Download Job file from the API
  *
  * @param int    $jobId    Job ID
  * @param string $filePath File path where the file is going to be saved
  *
  * @return bool
  */
 public static function getJobFile($jobId, $filePath)
 {
     list($status, $fileContents) = self::makeApiCall('job', 'GET', array((int) $jobId));
     if ($status) {
         file_put_contents($filePath, $fileContents);
     } else {
         NenoLog::log($fileContents, NenoLog::PRIORITY_ERROR, true);
     }
     return $status;
 }
Esempio n. 26
0
 /**
  * Add an entry into the Log
  *
  * @param   mixed  $entry    Log entry
  * @param   int    $priority Entry Priority
  * @param   string $category Entry Category
  * @param   null   $date     Entry Date
  *
  * @return void
  */
 public static function add($entry, $priority = self::INFO, $category = '', $date = null)
 {
     // Automatically instantiate the singleton object if not already done.
     if (empty(self::$instance) || !self::$instance instanceof NenoLog) {
         self::$instance = new NenoLog();
     }
     // If the entry object isn't a JLogEntry object let's make one.
     if (!$entry instanceof JLogEntry) {
         $entry = new JLogEntry((string) $entry, $priority, $category, $date);
     }
     self::$instance->addLogEntry($entry);
 }