/** * Add a translated message to headtitle * @param string $msg * @return App_Controller_Action */ protected function _addHeadTitle($msg) { $separator = " - "; $msg = self::$_translate->_($msg); $this->view->headTitle($separator . $msg); return $this; }
public function getMessages(\Zend_Translate $t) { if ($this->checkedRespondentTracks) { $messages[] = sprintf($t->_('Checked %d tracks.'), $this->checkedRespondentTracks); } if ($this->checkedTokens || !$this->checkedRespondentTracks) { $messages[] = sprintf($t->_('Checked %d tokens.'), $this->checkedTokens); } if ($this->hasChanged()) { if ($this->surveyCompletionChanges) { $messages[] = sprintf($t->_('Answers changed by survey completion event for %d tokens.'), $this->surveyCompletionChanges); } if ($this->resultDataChanges) { $messages[] = sprintf($t->_('Results and timing changed for %d tokens.'), $this->resultDataChanges); } if ($this->roundCompletionChanges) { $messages[] = sprintf($t->_('%d token round completion events caused changed to %d tokens.'), $this->roundCompletionCauses, $this->roundCompletionChanges); } if ($this->tokenDateChanges) { $messages[] = sprintf($t->_('%2$d token date changes in %1$d tracks.'), $this->tokenDateCauses, $this->tokenDateChanges); } if ($this->roundChangeUpdates) { $messages[] = sprintf($t->_('Round changes propagated to %d tokens.'), $this->roundChangeUpdates); } if ($this->deletedTokens) { $messages[] = sprintf($t->_('%d tokens deleted by round changes.'), $this->deletedTokens); } if ($this->createdTokens) { $messages[] = sprintf($t->_('%d tokens created to by round changes.'), $this->createdTokens); } } else { $messages[] = $t->_('No tokens were changed.'); } return $messages; }
/** * Returns true if and only if $value meets the validation requirements * * If $value fails validation, then this method returns false, and * getMessages() will return an array of messages that explain why the * validation failed. * * @param mixed $value * @param mixed $content * @return boolean * @throws \Zend_Validate_Exception If validation of $value is impossible */ public function isValid($value, $context = array()) { $this->_message = null; $user = $this->_userSource->getUser(); if (!($user->isActive() && $user->canResetPassword() && $user->isAllowedOrganization($context['organization']))) { $this->_message = $this->translate->_('User not found or no e-mail address known or user cannot be reset.'); } return (bool) (!$this->_message); }
/** * Open the dir, suppressing possible errors and try to * create when it does not exist * * @param type $directory * @return Directory */ protected function _checkDir($directory) { $eDir = @dir($directory); if (false == $eDir) { // Dir does probably not exist if (!is_dir($directory)) { if (false === @mkdir($directory, 0777, true)) { \MUtil_Echo::pre(sprintf($this->translate->_('Directory %s not found and unable to create'), $directory), 'OpenRosa ERROR'); } else { $eDir = @dir($directory); } } } return $eDir; }
/** * getContact * @author Cornelius Hansjakob <*****@*****.**> * @return string */ public function getContact($strTitle = '') { $strReturn = ''; $objPageContacts = $this->objPage->getContactsValues('contact'); if (count($objPageContacts) > 0) { $strReturn .= ' <div class="contact"> <h3>' . ($strTitle != '' ? $strTitle : $this->objTranslate->_('Contact')) . '</h3>'; foreach ($objPageContacts as $objContact) { $strReturn .= ' <div class="item"> <div class="name">' . htmlentities(($objContact->acTitle != '' ? $objContact->acTitle . ' ' : '') . $objContact->title, ENT_COMPAT, $this->core->sysConfig->encoding->default) . '</div> <div class="position">' . htmlentities($objContact->position, ENT_COMPAT, $this->core->sysConfig->encoding->default) . '</div> <!--<div class="address"> ' . strip_tags($objContact->street) . '</br> ' . $objContact->zip . ' ' . $objContact->city . '</br> ' . htmlentities($objContact->countryTitle, ENT_COMPAT, $this->core->sysConfig->encoding->default) . ' </div>--> <div class="numbers"> ' . ($objContact->phone != '' ? $this->objTranslate->_('Tel') . '. ' . $objContact->phone . '<br/>' : '') . ' ' . ($objContact->fax != '' ? $this->objTranslate->_('Fax') . ' ' . $objContact->fax : '') . ' </div> <div class="mail"> <a href="mailto:' . $objContact->email . '">' . $this->objTranslate->_('Email') . '</a> </div> </div>'; } $strReturn .= ' </div">'; } return $strReturn; }
private function _updateImage() { $this->_helper->viewRenderer->setNoRender(true); $layout = Zend_Layout::getMvcInstance(); $layout->disableLayout(); $return = array('msg' => '', 'file' => array('name' => '', 'size' => '', 'url' => '')); if ($this->getRequest()->isPost()) { $allowedExtensions = null; $maxSize = 999999; $path = ''; $options = $this->_getBootstrapOptions(); // UPLOAD of image $domainImage = new Media_Domain_Image(); $title = 'person_' . $this->_getParam('id'); $file = $domainImage->handleUpload(APPLICATION_DATA_PATH, array('AllowedExtensions' => $options['allowedExtensions'], 'SizeLimit' => $options['maxSize'], 'Dimensions' => $options['dimensions'])); if (isset($file['error'])) { $return['error'] = $file['error']; } else { // MEDIA MODEL $image = new Media_Model_Image(); $image->setFile($file['name']); $image->setFilesize($file['size']); $image->setMimetype($file['type']); $image->setTitle($title); // RECOVER Media from Person $domainPerson = new Persons_Domain_Person(); $person = $domainPerson->getById($this->_getParam('id')); $mp = $person->getMedia(); $createPersonMedia = !isset($mp) || $mp->getId() == null; if (!$createPersonMedia) { $image->setId($mp->getId()); } $domainImage->setImage($image); // DELETE previous image file from disk, only if they are not the same if (!$createPersonMedia) { if ($mp->getFile() != $image->getFile()) { $domainImage->setImage($mp); $domainImage->deleteFile(); $domainImage->setImage($image); } } try { // persisting media $imgId = $domainImage->save(); // persisting person media $image->setId($imgId); $person->setMedia($image); $domainPerson->setPerson($person); if ($createPersonMedia) { $domainPerson->createImageRelation(); } $return['msg'] = $this->_translate->_('File successfully uploaded'); $return['file'] = $file; } catch (Exception $e) { echo json_encode(array('error' => $e->getMessage())); } } echo json_encode($return); } }
/** * Hook for SECTION: i18n (translation) */ function _($msg) { ///////////////////////////// // ==> SECTION: i18n <== // Need volunteers to help create translations for the catalog in data/zfdemo.mo // Nice tool to help manage the gettext catalog: http://www.poedit.net/ static $translator = null; if ($translator === null) { require_once 'Zend/Translate.php'; $registry = Zend_Registry::getInstance(); $translator = new Zend_Translate('gettext', $registry['dataDir'] . 'zfdemo.mo', $registry['userLocale']); } if (func_num_args() === 1) { return $translator->_($msg); } else { $args = func_get_args(); array_shift($args); return vsprintf($translator->_($msg), $args); } ///////////////////////////// // ==> SECTION: mvc <== if (func_num_args() === 1) { return $msg; } else { $args = func_get_args(); array_shift($args); return vsprintf($msg, $args); } }
/** * Create Modal dialog business logic * @param App_Form $form * @param array $options */ public function ajaxFormProcessor(App_Form $form, $options) { $params = $this->_getAllParams(); $subaction = isset($params['subaction']) ? $params['subaction'] : null; switch ($subaction) { case 'submit': if (!$form->isValid($params)) { $this->view->isValid = $form->isValid($params); $this->view->message = $form->getErrorMessages(); } else { $this->view->isValid = $form->isValid($params); $modelClass = $options['model']['class']; $modelMethod = $options['model']['method']; // persist method call_user_func(array($modelClass, $modelMethod), $params); $this->setMessage(self::$_translate->_($options['success']['message'])); $this->createAjaxButton($options['success']['button']['title'], $options['success']['button']['action']); if (isset($options['success']['redirect'])) { $this->view->redirect = $this->baseUrl . $options['success']['redirect']; } break; } default: $this->view->title = self::$_translate->_($options['title']); $this->createAjaxButton(self::$_translate->_($options['button']), "submit", $params, $options['url']); $this->view->form = $form->toArray(); } }
static function translate($locale_code, $module_name, $key, $replace = null, $do_translation = true) { // DON'T EVER LEAVE THIS UNCOMMENTED // ob_clean(); // can be useful for debugging since using dd() will dump out into the existing markup and be hard to see // but this clears out all the other markup so the debug data can be seen clearly $translation = $key; if ($do_translation) { if (RivetyCore_Registry::get('enable_localization') == '1' && !is_null($module_name) && trim($module_name) != "" && !is_null($key) && trim($key) != "") { $locale_code = RivetyCore_Translate::cleanZendLocaleCode($locale_code); // TODO: account for core rivety module $path_to_csv = RivetyCore_Registry::get('basepath')."/modules/".$module_name."/languages/".$locale_code.".csv"; if (file_exists($path_to_csv)) { try { $translate = new Zend_Translate("csv", $path_to_csv, $locale_code, array('delimiter' => ",")); $translation = $translate->_($key); // this next bit will populate the locale file with untranslated terms // so it's easier for someone to go through and translate them if (RivetyCore_Registry::get('auto_populate_language_files') == '1') { if (!$translate->isTranslated($key, true, $locale_code)) { $key_no_quotes = str_replace('"', '"', $key); $str = '"'.$key_no_quotes.'","'.$key_no_quotes.'"'."\n"; file_put_contents($path_to_csv, $str, FILE_APPEND); } } } catch (Exception $e) { $translation = $key; } } else { // create the file file_put_contents($path_to_csv, $key.','.$key); } } } $output = ""; if (is_null($replace)) { // no replace, no sprintf $output = $translation; } else { if (is_array($replace)) { if (count($replace) > 1) { // there are multiple indices, use vsprintf $output = vsprintf($translation, $replace); } else { // there's only one index, use the cheaper sprintf instead $output = sprintf($translation, $replace[0]); } } else { // $replace is not an array, so try using it straight $output = sprintf($translation, $replace); } } return $output; }
/** * Retorna o elemento da lista para ser adicionado quando necessário * * @param $sNome * @return null * @throws Exception */ public static function getCampo($sNome) { if (isset(self::$aCampos[$sNome])) { return self::$aCampos[$sNome]; } else { throw new Exception(self::$oTranslate->_(sprintf('O elemento "%s" não foi encontrado.', $sNome))); } }
public function getDataLoaded() { if ($this->token) { if (parent::getDataLoaded()) { return true; } else { return false; } } else { $this->addMessage($this->translate->_('Token not found')); return false; } }
/** * Test the password for minimum number of numeric characters. * * @param mixed $parameter * @param string $password */ protected function numCount($parameter, $password) { $len = intval($parameter); if ($len) { $results = array(); // Not used but required $count = preg_match_all('/[0-9]/', $password, $results); if ($len > 0 && $count < $len) { $this->_addError(sprintf($this->translate->plural('should contain at least one number', 'should contain at least %d numbers', $len), $len)); } elseif ($len < 0 && ($count > 0 || null === $password)) { $this->_addError($this->translate->_('may not contain numbers')); } } }
/** * Seperate the incorrect tokens from the right tokens * * @param mixed $value * @return boolean */ protected function isValidToken($value) { // Make sure the value has the right format $value = $this->tracker->filterToken($value); $library = $this->tracker->getTokenLibrary(); $format = $library->getFormat(); $reuse = $library->hasReuse() ? $library->getReuse() : -1; if (strlen($value) !== strlen($format)) { $this->_messages = sprintf($this->translate->_('Not a valid token. The format for valid tokens is: %s.'), $format); return false; } $token = $this->tracker->getToken($value); if ($token && $token->exists) { $currentDate = new \MUtil_Date(); if ($completionTime = $token->getCompletionTime()) { // Reuse means a user can use an old token to check for new surveys if ($reuse >= 0) { // Oldest date AFTER completiondate. Oldest date is today minus reuse time if ($completionTime->diffDays($currentDate) <= $reuse) { // It is completed and may still be used to look // up other valid tokens. return true; } } $this->_messages = $this->translate->_('This token is no longer valid.'); return false; } $fromDate = $token->getValidFrom(); if (null === $fromDate || $currentDate->isEarlier($fromDate)) { // Current date is BEFORE from date $this->_messages = $this->translate->_('This token cannot (yet) be used.'); return false; } if ($untilDate = $token->getValidUntil()) { if ($currentDate->isLater($untilDate)) { //Current date is AFTER until date $this->_messages = $this->translate->_('This token is no longer valid.'); return false; } } return true; } else { $this->_messages = $this->translate->_('Unknown token.'); return false; } }
/** * Init Security */ protected function initSecurity() { $user = $this->getUser()->getBean(); if ($user == null) { $this->_redirect('auth/view-login'); } elseif ($user->isInactive()) { $this->setFlash('warning', $this->i18n->_('This user has been disabled')); $this->_redirect('auth/view-login'); } if (!$this->getAcl()->isAllowed($this->getUser()->getAccessRole()->getIdAccessRole(), $this->getRequest()->getControllerName() . '/' . $this->getRequest()->getActionName())) { $this->setFlash('warning', 'You are not allowed to check this section'); $this->_redirect('index'); // throw new AuthException('Acceso Restringido'); } $this->view->systemUser = $this->getUser()->getBean(); $this->view->systemAccessRole = $this->getUser()->getAccessRole(); }
/** * @param string message id * @param mixed ...args a long list of params */ public static function _($message) { //if ( !is_null(self::$_stringsWriter)) self::$_stringsWriter->_($message); if (!is_null(self::$_translator)) { if (false && APPLICATION_ENV == 'development') { return "#(" . self::$_translator->_($message) . ")"; } else { $return = self::$_translator->_($message); if (func_num_args() > 1) { $args = func_get_args(); array_shift($args); // remove warning output if ($message != $return) { $return = @vsprintf($return, $args); } else { $return = "#({$return}, " . implode(', ', $args) . ")"; } } return $return; } } }
/** * Returns an array containing fieldname => label for dropdown list etc.. * * @param string $forType Optional type filter * @return array fieldname => label */ public function getQuestionList($forType = false) { $map = $this->_getMap(); $results = array(); $question = null; foreach ($map as $name => $field) { // Always need the last field if (isset($field['question'])) { $question = $this->removeMarkup($field['question']); } // Optional type check if (!$forType || $field['type'] == $forType) { // Juggle the labels for sub-questions etc.. if (isset($field['sq_question1'])) { $squestion = sprintf($this->translate->_('%s: %s'), $this->removeMarkup($field['sq_question']), $this->removeMarkup($field['sq_question1'])); } elseif (isset($field['sq_question'])) { $squestion = $this->removeMarkup($field['sq_question']); } else { $squestion = null; } // Title does not have to be unique. So if a title is used // twice we only use it for the first result. if (isset($field['code']) && !isset($results[$field['code']])) { $name = $field['code']; } if ($question && $squestion) { $results[$name] = sprintf($this->translate->_('%s - %s'), $question, $squestion); } elseif ($question) { $results[$name] = $question; } elseif ($squestion) { $results[$name] = sprintf($this->translate->_('- %s'), $squestion); } } // \MUtil_Echo::track($field); } // \MUtil_Echo::track($results); return $results; }
/** * Calls the PDF convertor (wkhtmltopdf / phantom.js) to convert HTML to PDF * * @param string $content The HTML source * @return string The converted PDF file * @throws \Exception */ public function convertFromHtml($content) { $tempInputFilename = GEMS_ROOT_DIR . '/var/tmp/export-' . md5(time() . rand()) . '.html'; $tempOutputFilename = GEMS_ROOT_DIR . '/var/tmp/export-' . md5(time() . rand()) . '.pdf'; file_put_contents($tempInputFilename, $content); if (!file_exists($tempInputFilename)) { throw new \Exception("Unable to create temporary file '{$tempInputFilename}'"); } $command = sprintf($this->_pdfExportCommand, escapeshellarg($tempInputFilename), escapeshellarg($tempOutputFilename)); $lastLine = exec($command, $outputLines, $return); if ($return > 0) { @unlink($tempInputFilename); @unlink($tempOutputFilename); throw new \Exception(sprintf($this->translate->_('Unable to run PDF conversion (%s): "%s"'), $command, $lastLine)); } $pdfContents = file_get_contents($tempOutputFilename); @unlink($tempInputFilename); @unlink($tempOutputFilename); if ($pdfContents == '') { throw new \Exception(sprintf($this->translate->_('Unable to run PDF conversion (%s): "%s"'), $command, $lastLine)); } return $pdfContents; }
/** * Валидация элемента * * @param mixed $value * @return boolean */ public function isValid($value) { $this->setValue($value); $value = $this->getValue(); if (!is_array($value) && $this->isRequired()) { $this->_messages = array($this->translate->_('Значение обязательно для заполнения и не может быть пустым')); return false; } $result = true; $this->_messages = array(); $this->_errors = array(); if (is_array($value)) { foreach ($value as $key => $mini_form) { if (key_exists($key, $this->forms)) { $form = $this->forms[$key]; if (!$form->isValid($mini_form)) { $result = false; } } } } return $result; }
/** * Get the allowed display groups for tracks in this project. * * @return array */ public function getTrackDisplayGroups() { return array('tracks' => $this->translate->_('Tracks'), 'respondents' => $this->translate->_('Respondent'), 'staff' => $this->translate->_('Staff')); }
/** * Full installation process of plugin * * @param string $tempFileName * @param string $tempFilePath * @param stdclass $json * @return stdclass */ function install($tempFileName, $tempFilePath, $json) { // get config values $rmConfig = new RM_Config(); $chmodOctal = intval($rmConfig->getValue('rm_config_chmod_value'), 8); $rootPath = RM_Environment::getConnector()->getRootPath(); $chunks = explode('.', $tempFileName); $pluginName = $chunks[0]; //Plugin name will be always the first chunk, example: price.0.1.1.zip $pluginModel = new RM_Plugins(); $existingPlugin = $pluginModel->fetchByName($pluginName); if ($existingPlugin !== null) { unlink($tempFilePath); throw new RM_Exception($this->_translate->_('Admin.Plugins.InstallMsg', 'PluginAlreadyInstalled')); } $pluginFolderPath = $rootPath . DIRECTORY_SEPARATOR . 'RM' . DIRECTORY_SEPARATOR . 'plugins' . DIRECTORY_SEPARATOR . $pluginName; if (is_dir($pluginFolderPath)) { $result = RM_Filesystem::deleteFolder($pluginFolderPath); if ($result == false) { unlink($tempFilePath); throw new RM_Exception($this->_translate->_('Admin.Plugins.InstallMsg', 'PluginFolderAlreadyExists') . ': ' . $pluginFolderPath); } } $result = mkdir($pluginFolderPath, $chmodOctal); if ($result == false) { unlink($tempFilePath); throw new RM_Exception($this->_translate->_('Admin.Plugins.InstallMsg', 'CreatePluginFolderFailer')); } else { $json = $this->_addMessageToJson($json, $this->_translate->_('Admin.Plugins.InstallMsg', 'PluginFolderCreatedSuccessfully')); } //4. unzip plugin into new directory if (!extension_loaded('zlib')) { unlink($tempFilePath); RM_Filesystem::deleteFolder($pluginFolderPath); throw new RM_Exception($this->_translate->_('Admin.Plugins.InstallMsg', 'ZlibNotSupported')); } $zip = new PclZip($tempFilePath); $result = $zip->extract(PCLZIP_OPT_PATH, $pluginFolderPath); if (!$result) { unlink($tempFilePath); RM_Filesystem::deleteFolder($pluginFolderPath); throw new RM_Exception($this->_translate->_('Admin.Plugins.InstallMsg', 'UnzipFailed')); } else { $json = $this->_addMessageToJson($json, $this->_translate->_('Admin.Plugins.InstallMsg', 'UnzipSuccessfully')); } unlink($tempFilePath); chmod($pluginFolderPath, $chmodOctal); //4.0. create separate folder in 'userdata/plugins' for a new plugin $userdataFolderPath = $rootPath . DIRECTORY_SEPARATOR . 'RM' . DIRECTORY_SEPARATOR . 'userdata' . DIRECTORY_SEPARATOR . 'plugins' . DIRECTORY_SEPARATOR . $pluginName; if (is_dir($userdataFolderPath)) { $result = RM_Filesystem::deleteFolder($userdataFolderPath); if ($result == false) { throw new RM_Exception($this->_translate->_('Admin.Plugins.InstallMsg', 'PluginFolderAlreadyExists') . ': ' . $userdataFolderPath); } } $result = mkdir($userdataFolderPath . DIRECTORY_SEPARATOR, $chmodOctal); if ($result == false) { RM_Filesystem::deleteFolder($pluginFolderPath); throw new RM_Exception($this->_translate->_('Admin.Plugins.InstallMsg', 'CreatePluginUserdataFolderFailer')); } else { $json = $this->_addMessageToJson($json, $this->_translate->_('Admin.Plugins.InstallMsg', 'PluginFolderCreatedSuccessfully')); } @rename($pluginFolderPath . DIRECTORY_SEPARATOR . 'views', $userdataFolderPath . DIRECTORY_SEPARATOR . 'views'); @chmod($pluginFolderPath . DIRECTORY_SEPARATOR . 'views', $chmodOctal); @rename($pluginFolderPath . DIRECTORY_SEPARATOR . 'languages', $userdataFolderPath . DIRECTORY_SEPARATOR . 'languages'); @chmod($pluginFolderPath . DIRECTORY_SEPARATOR . 'languages', $chmodOctal); @rename($pluginFolderPath . DIRECTORY_SEPARATOR . 'css', $userdataFolderPath . DIRECTORY_SEPARATOR . 'css'); @chmod($pluginFolderPath . DIRECTORY_SEPARATOR . 'css', $chmodOctal); @rename($pluginFolderPath . DIRECTORY_SEPARATOR . 'images', $userdataFolderPath . DIRECTORY_SEPARATOR . 'images'); @chmod($pluginFolderPath . DIRECTORY_SEPARATOR . 'images', $chmodOctal); @chmod($userdataFolderPath, $chmodOctal); //5. get INI file $iniFilePath = $pluginFolderPath . DIRECTORY_SEPARATOR . self::$_iniFilename; if (is_file($iniFilePath) == false) { RM_Filesystem::deleteFolder($pluginFolderPath); throw new RM_Exception($this->_translate->_('Admin.Plugins.InstallMsg', 'NoIniFile')); } //6. parse INI file $parser = new RM_Plugin_Config_Parser(); try { $config = $parser->getConfig($iniFilePath); } catch (RM_Exception $e) { //Error in ini file parsing RM_Filesystem::deleteFolder($pluginFolderPath); throw new RM_Exception($e->getMessage()); } //Check: could be a module if no 'module' value is in config if ($config->information['module'] == "") { RM_Filesystem::deleteFolder($pluginFolderPath); throw new RM_Exception($this->_translate->_('Admin.Plugins.InstallMsg', 'WrongTryToInstallModule')); } $json = $this->_addMessageToJson($json, $this->_translate->_('Admin.Plugins.InstallMsg', 'UnzipSuccess')); //7. invoke SQL install file try { $result = self::installDatabase($pluginFolderPath); } catch (Exception $e) { self::uninstallDatabase($pluginFolderPath); RM_Filesystem::deleteFolder($pluginFolderPath); throw new RM_Exception($e->getMessage()); } if ($result == false) { self::uninstallDatabase($pluginFolderPath); RM_Filesystem::deleteFolder($pluginFolderPath); throw new RM_Exception($this->_translate->_('Admin.Plugins.InstallMsg', 'WrongInstallSQLQueries')); } else { $json = $this->_addMessageToJson($json, $this->_translate->_('Admin.Plugins.InstallMsg', 'InstallSQLSuccess')); } //8. create a new record in Plugin database $pluginRow = array(); $pluginRow = $config->information; $pluginRow['module_name'] = $pluginRow['module']; unset($pluginRow['module']); //convert creation date into MySQL format $rmConfig = new RM_Config(); $pluginRow['creation_date'] = $rmConfig->convertDates(strtotime($pluginRow['creation_date']), RM_Config::TIMESTAMP_DATEFORMAT, RM_Config::MYSQL_DATEFORMAT); //TODO: //1.check the insertions $pkey = $pluginModel->insert($pluginRow); //Create a new records in dependencies database table $model = new RM_Dependencies(); if (is_array($config->dependencies)) { foreach ($config->dependencies as $dependency) { $model->insert($dependency); } } //9. get the main class of the plugin $pluginClassFilepath = $pluginFolderPath . DIRECTORY_SEPARATOR . RM_Plugin_Config::CLASSES . DIRECTORY_SEPARATOR . 'RM' . DIRECTORY_SEPARATOR . 'Plugin' . DIRECTORY_SEPARATOR . $config->information['name'] . '.php'; if (is_file($pluginClassFilepath) == false) { self::uninstallDatabase($pluginFolderPath); RM_Filesystem::deleteFolder($pluginFolderPath); throw new RM_Exception($this->_translate->_('Admin.Plugins.InstallMsg', 'DoesntExists')); } require_once $pluginClassFilepath; $pluginClassName = 'RM_Plugin_' . $config->information['name']; if (class_exists($pluginClassName) == false) { self::uninstallDatabase($pluginFolderPath); RM_Filesystem::deleteFolder($pluginFolderPath); throw new RM_Exception($pluginClassName . $this->_translate->_('Admin.Plugins.InstallMsg', 'DoesntExists')); } $pluginObject = new $pluginClassName(); if (!$pluginObject instanceof RM_Plugin_Interface) { self::uninstallDatabase($pluginFolderPath); RM_Filesystem::deleteFolder($pluginFolderPath); throw new RM_Exception($pluginClassName . $this->_translate->_('Admin.Plugins.InstallMsg', 'WrongInterface')); } //10. invoke install method of that class (if we need something extra) $result = $pluginObject->install(); $json = $this->_addMessageToJson($json, $this->_translate->_('Admin.Plugins.InstallMsg', 'InstallSuccess')); //Check dependencies and if some of them is validate==false disable plugin $dependencyManager = new RM_Dependency_Manager(); $plugin = $pluginModel->find($pkey)->current(); $dependencies = $dependencyManager->getDependencies($plugin); foreach ($dependencies as $dependency) { if ($dependency->validate() == false) { try { $pluginModel->disable($plugin); break; } catch (Exception $e) { //TODO: add log message that we could not disable this module. } } } return $json; }
/** * A pretty name for use in dropdown selection boxes. * * @return string Name */ public function getEventName() { return $this->translate->_('Lookup answers in previous instance of survey in track.'); }
public function testTranslate() { $lang = new Zend_Translate(Zend_Translate::AN_ARRAY, array('msg1' => 'Message 1 (en)'), 'en'); $lang->addTranslation('ru', array('msg1' => 'Message 1 (ru)')); $this->assertEquals($lang->_('msg1'), 'Message 1 (en)'); $this->assertEquals($lang->_('msg1', 'ru'), 'Message 1 (ru)'); $this->assertEquals($lang->_('msg2'), 'msg2'); $this->assertEquals($lang->_('msg2', 'ru'), 'msg2'); $this->assertEquals($lang->translate('msg1'), 'Message 1 (en)'); $this->assertEquals($lang->translate('msg1', 'ru'), 'Message 1 (ru)'); $this->assertEquals($lang->translate('msg2'), 'msg2'); $this->assertEquals($lang->translate('msg2', 'ru'), 'msg2'); }
public function _($sentence) { $translation = parent::_($sentence); if ($this->debugMode) { $translation = "[{$translation}]"; } return $translation; }
/** * gets translated value * * NOTE: This is needed for values like Yes/No, Datetimes, etc. * * @param string $_field * @param mixed $_value * @param Zend_Translate $_translation * @param string $_timezone * @return string */ public static function getTranslatedValue($_field, $_value, $_translation, $_timezone) { if ($_value instanceof Tinebase_DateTime) { $locale = new Zend_Locale($_translation->getAdapter()->getLocale()); return Tinebase_Translation::dateToStringInTzAndLocaleFormat($_value, $_timezone, $locale, 'datetime', true); } switch ($_field) { case 'transp': return $_value && $_value == Calendar_Model_Event::TRANSP_TRANSP ? $_translation->_('No') : $_translation->_('Yes'); case 'organizer': if (!$_value instanceof Addressbook_Model_Contact) { $organizer = Addressbook_Controller_Contact::getInstance()->getMultiple($_value, TRUE)->getFirstRecord(); } return $organizer instanceof Addressbook_Model_Contact ? $organizer->n_fileas : ''; case 'rrule': if ($_value) { $rrule = $_value instanceof Calendar_Model_Rrule ? $_value : new Calendar_Model_Rrule($_value); return $rrule->getTranslatedRule($_translation); } default: return $_value; } }
/** * Устанавливает сообщение об ошибке в сессию пользователя и производит переадресацию по указанному адресу * * @param string $message Текст сообщения * @param string $redirect Путь для переадресации без siteUrl (если не указан, редирект происходит по рефереру) * @return true */ protected function composeErrorMessage($message = 'При заполнении формы были обнаружены ошибки', $redirect = null) { $this->_usersession->ErrorMessage = $this->_translate->_($message); return is_null($redirect) ? $this->_redirect($this->_request->getServer('HTTP_REFERER')) : $this->_redirect($this->view->siteUrl() . $redirect); }
public function zpracujobjednavkuAction() { $_t = new Zend_Translate('csv', CESTA . '/preklad/mfpshop.cs.csv', 'cs'); $_t->addTranslation(CESTA . '/preklad/mfpshop.sk.csv', 'sk'); $_t->addTranslation(CESTA . '/preklad/mfpshop.en.csv', 'en'); // Create a log instance $writer_preklad = new Zend_Log_Writer_Stream(CESTA . '/logy/preklad.log'); $log_preklad = new Zend_Log($writer_preklad); /* firma, osoba, datum, doprava, platba, poznamka, cena_celkem, cena_celkem_DPH */ #zjisteni celkove ceny $soucet = 0; $soucet_dph = 0; foreach ($_SESSION['kosik'] as $r) { $soucet += (double) $r['cena_radek']; $soucet_dph += (double) $r['cena_radek_dph']; } $sleva_obj = $soucet * (double) $_SESSION['objemova_sleva'] / 100; $sleva_obj_dph = $soucet_dph * (double) $_SESSION['objemova_sleva'] / 100; $cena_obj = $soucet - $sleva_obj; $cena_obj_dph = $soucet_dph - $sleva_obj_dph; $sleva_kupon = $cena_obj * (double) $_SESSION['objednavka']['kupon']['sleva'] / 100; $sleva_kupon_dph = $cena_obj_dph * (double) $_SESSION['objednavka']['kupon']['sleva'] / 100; $cena_kupon = $cena_obj - $sleva_kupon; $cena_kupon_dph = $cena_obj_dph - $sleva_kupon_dph; $_SESSION['objednavka']['doprava']['kod'] = isset($_SESSION['objednavka']['doprava']['kod']) ? $_SESSION['objednavka']['doprava']['kod'] : ''; $_SESSION['objednavka']['platba']['kod'] = isset($_SESSION['objednavka']['platba']['kod']) ? $_SESSION['objednavka']['platba']['kod'] : ''; $vysl = readData('objednavka_hl', array('firma' => $_SESSION['uzivatel']['firma'], 'osoba' => $_SESSION['uzivatel']['jmeno'], 'doprava' => $_SESSION['objednavka']['doprava']['kod'], 'platba' => $_SESSION['objednavka']['platba']['kod'], 'cena_celkem' => $cena_kupon, 'cena_celkem_dph' => $cena_kupon_dph, 'poznamka' => $_SESSION['objednavka']['ostatni']['poznamky'], 'objemova_sleva' => $_SESSION['objemova_sleva'], 'kupon' => $_SESSION['objednavka']['kupon']['cislo'], 'kupon_sleva' => $_SESSION['objednavka']['kupon']['sleva'])); #Firma, Poradi, Polozka, Produkt, Mj, Mj_v_bal, Mnozstvi, Cena_cenik, Sleva_proc, Cena_celkem, Cena_celkem_DPH #neplneni polozek objednavky - vzdy vlozeni do objednavky $rozpis = ''; #rozpis objednavky do mailu $rozpis_obch = ''; #rozpis objednavky do mailu $rozpis .= "=================================================================================================\r\n"; $rozpis .= sprintf('|%-15s|%-50s|%6s|%10s|%10s|' . "\r\n", "Produkt", iconv('UTF-8', 'iso-8859-2//TRANSLIT', "Název"), iconv('UTF-8', 'iso-8859-2//TRANSLIT', "Počet"), "Cena", "Cena s DPH"); $rozpis .= "=================================================================================================\r\n"; foreach ($_SESSION['kosik'] as $r) { $vysl_pol = readData('objednavka_pol', array('firma' => $_SESSION['uzivatel']['firma'], 'poradi' => (int) $vysl->o->row->cobj, 'produkt' => $r['produkt'], 'mj' => $r['mj'], 'mj_v_bal' => '1', 'mnozstvi' => $r['mj_evid'], 'zakl_cena' => $r['zakl_cena'], 'cena' => $r['cena'], 'sleva_proc' => $r['sleva'], 'cena_celkem' => $r['cena_radek'], 'cena_celkem_dph' => $r['cena_radek_dph'])); $rozpis .= sprintf('|%-15s|%-50s|%6.0F|%10.2F|%10.2F|' . "\r\n", iconv('UTF-8', 'iso-8859-2//TRANSLIT', $r['produkt']), iconv('UTF-8', 'iso-8859-2//TRANSLIT', $r['nazev']), $r['mj_evid'], $r['cena_radek'], $r['cena_radek_dph']); } // dokonceni objednavky - rozpusteni slev $vysl_pol = readData('dokonci_objednavku', array('firma' => $_SESSION['uzivatel']['firma'], 'poradi' => (int) $vysl->o->row->cobj)); $rozpis .= "=================================================================================================\r\n"; $rozpis .= sprintf('|%-73s|%10.2F|%10.2F|' . "\r\n", "Celkem", $soucet, $soucet_dph); if ((double) $_SESSION['objemova_sleva'] != 0) { $rozpis .= "=================================================================================================\r\n"; $rozpis .= sprintf('|%-73s|%10.2F|%10.2F|' . "\r\n", iconv('UTF-8', 'iso-8859-2//TRANSLIT', "Objemová sleva: ") . $_SESSION['objemova_sleva'] . "%", $sleva_obj, $sleva_obj_dph); } if ((double) $_SESSION['objednavka']['kupon']['sleva'] != 0) { $rozpis .= "=================================================================================================\r\n"; $rozpis .= sprintf('|%-73s|%10.2F|%10.2F|' . "\r\n", iconv('UTF-8', 'iso-8859-2//TRANSLIT', "Slevový kupon ") . $_SESSION['objednavka']['kupon']['cislo'] . ': ' . $_SESSION['objednavka']['kupon']['sleva'] . "%", $sleva_kupon, $sleva_kupon_dph); } $rozpis .= "=================================================================================================\r\n"; $rozpis .= sprintf('|%-73s|%10.2F|%10.2F|' . "\r\n", iconv('UTF-8', 'iso-8859-2//TRANSLIT', "Výsledná cena"), $cena_kupon, $cena_kupon_dph); $rozpis .= "=================================================================================================\r\n"; //$rozpis = ($rozpis); $rozpis .= "Doprava: " . iconv('UTF-8', 'iso-8859-2//TRANSLIT', $_SESSION['objednavka']['doprava']['popis']) . ", " . "cena: " . number_format($_SESSION['objednavka']['doprava']['cena'], 2, ',', ' ') . iconv('UTF-8', 'iso-8859-2//TRANSLIT', " Kč\r\n"); $rozpis .= "Platba: " . iconv('UTF-8', 'iso-8859-2//TRANSLIT', $_SESSION['objednavka']['platba']['popis']) . ", " . "cena: " . number_format($_SESSION['objednavka']['platba']['cena'], 2, ',', ' ') . iconv('UTF-8', 'iso-8859-2//TRANSLIT', " Kč\r\n"); $rozpis .= "=================================================================================================\r\n"; if (trim($_SESSION['objednavka']['ostatni']['poznamky']) != '') { $rozpis .= iconv('UTF-8', 'iso-8859-2//TRANSLIT', "Poznámky:\r\n" . $_SESSION['objednavka']['ostatni']['poznamky'] . "\r\n"); $rozpis .= "=================================================================================================\r\n"; } $rozpis_obch .= "Objednal:\r\n"; foreach ($_SESSION['objednavka']['osoba'] as $k => $h) { $rozpis_obch .= iconv('UTF-8', 'iso-8859-2//TRANSLIT', $_t->_($k) . ": {$h}\r\n"); } $rozpis_obch .= "=================================================================================================\r\n"; $rozpis_obch .= "Objednatel:\r\n"; foreach ($_SESSION['objednavka']['firma'] as $k => $h) { $rozpis_obch .= iconv('UTF-8', 'iso-8859-2//TRANSLIT', $_t->_($k) . ": {$h}\r\n"); } $rozpis_obch .= "=================================================================================================\r\n"; $rozpis_obch .= iconv('UTF-8', 'iso-8859-2//TRANSLIT', "Dodací místo:\r\n"); foreach ($_SESSION['objednavka']['doruceni'] as $k => $h) { $rozpis_obch .= iconv('UTF-8', 'iso-8859-2//TRANSLIT', $_t->_($k) . ": {$h}\r\n"); } $rozpis_obch .= "=================================================================================================\r\n"; //zjisteni textu a odeslani mailu $texty = zpracujTexty(readData('texty', array('jazyk' => $_SESSION['jazyk'], 'kody' => "'obj_zak','obj_obch'"))); #print_r($texty); #a nakonec vyprazdneni kosiku //echo "<pre>\n";die(str_replace('#COBJ#', (string) $vysl->o->row->cobj, str_replace('#ROZPIS#', $rozpis, $texty['obj_obch']))); //die(str_replace('#COBJ#', (string) $vysl->o->row->cobj, str_replace('#ROZPIS#', $rozpis, iconv('UTF-8', 'iso-8859-2//TRANSLIT', $texty['obj_zak'])))); //die("<pre>\n" . str_replace('#ROZPIS#', $rozpis . $rozpis_obch, iconv('UTF-8', 'iso-8859-2//TRANSLIT', $texty['obj_zak']))); @mailuj($_SESSION['uzivatel']['e_mail'], 'MFP shop - potvrzeni objednavky', str_replace('#COBJ#', (string) $vysl->o->row->cobj, str_replace('#ROZPIS#', $rozpis . $rozpis_obch, iconv('UTF-8', 'iso-8859-2//TRANSLIT', $texty['obj_zak']))), 'iso-8859-2'); @mailuj(EMAIL_OBCHODNIK, 'MFP shop - nova objednavka', str_replace('#COBJ#', (string) $vysl->o->row->cobj, str_replace('#ROZPIS#', $rozpis . $rozpis_obch, iconv('UTF-8', 'iso-8859-2//TRANSLIT', $texty['obj_obch']))), 'iso-8859-2'); //vyprazdnit klientsky kosik $_SESSION['kosik'] = array(); $_SESSION['objednavka'] = array(); //a jeste kosik na serveru readData('vysyp_kosik', array('osoba' => $_SESSION['uzivatel']['jmeno'])); unset($_t); unset($writer_preklad); unset($log_preklad); #$this->_Redirect(THIS_SERVER . '/katalog/index/index'); $this->_Redirect('/katalog/index/index'); #echo '<h1>Cislo objednavky: ' . (string) $vysl->o->row->cobj . '</h2>'; #echo '<pre>';print_r($_SESSION['objednavka']);echo "\n\n";print_r($_SESSION['kosik']);echo "\n\n";print_r($_SESSION['uzivatel']);echo '</pre>';die(); }
/** * Translating Object */ public function testObjectTranslation() { $lang = new Zend_Translate(Zend_Translate::AN_ARRAY, dirname(__FILE__) . '/Translate/Adapter/_files/testarray', 'en_GB', array('scan' => Zend_Translate::LOCALE_DIRECTORY)); $this->assertEquals('Message 1 (ja)', $lang->_('Message 1', 'ja')); $this->assertEquals($lang, $lang->translate($lang)); }
/** * Определяем массив опций и дергаем родительский конструктор * * @param mixed $spec * @param array $options */ public function __construct($spec, $options = null) { $this->translate = Zend_Controller_Front::getInstance()->getParam('bootstrap')->getResource('Translate'); /** * Получаем информацию о структуре или структурах */ if (isset($options['structures'])) { $options['structures'] = explode(',', $options['structures']); require_once 'Phorm/Structures.php'; $StructuresModel = new Phorm_Structures(); $structures = array(); $multioptions = array(); foreach ($options['structures'] as $key => $structureid) { if ($StructureInfo = $StructuresModel->getStructureFullInfo($structureid)) { $structures[$StructureInfo['structureid']] = $StructureInfo; } else { unset($options['structures'][$key]); } $multioptions[$StructureInfo['structureid']] = $StructureInfo['structurename']; $options['multioptions'] = $multioptions; } /** * Определяем шаблон формы для элементов структур */ $form_tpl = new Phorm_Form(null, null, array('elements' => $options['elements'])); /** * Создаем форму для каждой из структур */ require_once 'Phorm/Form.php'; foreach ($structures as $structure) { $form = new Phorm_Form(); $form->removeDecorator('Form'); $form->removeDecorator('DtDdWrapper'); foreach ($structure['groups'] as $group) { $form->setElementsBelongTo($spec . '[' . $structure['structureid'] . ']' . '[' . $group['groupid'] . ']'); /** * Добавляем элементы на форму * @todo Добавить обязательность заполнения */ $elements = array(); // массив элементов для добавления в DisplayGroup foreach ($group['properties'] as $property) { /** * Определяем тип используемого элемента */ $type = $property['propertytype']; $realtype = in_array($type, array('select', 'structure', 'dictionary')) && $property['ismultiple'] == 'yes' ? 'multiselect' : $type; if ($element = clone $form_tpl->getElement($realtype)) { // Устанавливаем имя и заголовок элемента $element->setLabel($property['propertyname'])->setName($property['propertyid']); // Допиливаем обычный селект if ($type == 'select' && !empty($property['propertyoptions'])) { $propertyoptions = array(); // ставим ключи массива опций в их значение foreach ($property['propertyoptions'] as $prop) { $propertyoptions[$prop] = $prop; } if ($property['ismultiple'] == 'no') { $propertyoptions = array(null => $this->translate->_('---Выберите---')) + $propertyoptions; } $element->setMultiOptions($propertyoptions); } // Допиливаем селект из другой структуры if ($type == 'structure' && $property['structureid'] > 0) { $propertyoptions = $StructuresModel->getStructureResourcesAsPairs($property['structureid']); if ($property['ismultiple'] == 'no') { $propertyoptions = array(null => $this->translate->_('---Выберите---')) + $propertyoptions; } $element->setMultiOptions($propertyoptions); } // Допиливаем селект из справочника if ($type == 'dictionary' && $property['dictionaryid'] > 0) { $DictionariesModel = new Phorm_Dictionaries(); $propertyoptions = $DictionariesModel->getEntriesListAsPairs($property['dictionaryid']); if ($property['ismultiple'] == 'no') { $propertyoptions = array(null => $this->translate->_('---Выберите---')) + $propertyoptions; } $element->setMultiOptions($propertyoptions); } $form->addElement($element); $elements[] = $property['propertyid']; } } /** * Если групп несколько, то добавляем DisplayGroup * @todo Добавить в опции возможность задавать css-классы */ if (count($structure['groups']) > 1) { $DisplayGroup = $form->addDisplayGroup($elements, 'group-' . $group['groupid'], array('legend' => $group['groupname'])); } } $this->forms[$structure['structureid']] = $form; $this->renderforms[$structure['structureid']] = $form->render(); } unset($options['elements']); } /** * Инициализируем родительский конструктор */ parent::__construct($spec, $options); }
/** * get translation string for interval (first, second, ...) * * @param integer $interval * @param Zend_Translate $translation * @return string */ protected function _getIntervalTranslation($interval, $translation) { switch ($interval) { case -2: $result = $translation->_('second to last'); break; case -1: $result = $translation->_('last'); break; case 0: throw new Tinebase_Exception_UnexpectedValue('0 is not supported'); break; case 1: $result = $translation->_('first'); break; case 2: $result = $translation->_('second'); break; case 3: $result = $translation->_('third'); break; case 4: $result = $translation->_('fourth'); break; case 5: $result = $translation->_('fifth'); break; default: switch ($interval % 10) { case 1: $result = $interval . $translation->_('st'); break; case 2: $result = $interval . $translation->_('nd'); break; case 3: $result = $interval . $translation->_('rd'); break; default: $result = $interval . $translation->_('th'); } } return $result; }
<?php $options = array('scan' => Zend_Translate::LOCALE_FILENAME); $translate = new Zend_Translate('array', APPPATH . 'languages/', null, $options); // $translate->setLocale('en_US'); // $translate->setLocale('nl'); var_dump($translate->getList()); var_dump($translate->getLocale()); echo $translate->_('ADMIN');