Page Menu
Home
In-Portal Phabricator
Search
Configure Global Search
Log In
Files
F726865
in-portal
No One
Temporary
Actions
View File
Edit File
Delete File
View Transforms
Subscribe
Mute Notifications
Award Token
Flag For Later
Subscribers
None
File Metadata
Details
File Info
Storage
Attached
Created
Mon, Jan 6, 2:03 AM
Size
66 KB
Mime Type
text/x-diff
Expires
Wed, Jan 8, 2:03 AM (1 d, 12 h ago)
Engine
blob
Format
Raw Data
Handle
536955
Attached To
rINP In-Portal
in-portal
View Options
Index: branches/5.2.x/core/units/helpers/multilanguage_helper.php
===================================================================
--- branches/5.2.x/core/units/helpers/multilanguage_helper.php (revision 15110)
+++ branches/5.2.x/core/units/helpers/multilanguage_helper.php (revision 15111)
@@ -1,377 +1,395 @@
<?php
/**
* @version $Id$
* @package In-Portal
* @copyright Copyright (C) 1997 - 2009 Intechnic. All rights reserved.
* @license GNU/GPL
* In-Portal is Open Source software.
* This means that this software may have been modified pursuant
* the GNU General Public License, and as distributed it includes
* or is derivative of works licensed under the GNU General Public License
* or other free or open source software licenses.
* See http://www.in-portal.org/license for copyright notices and details.
*/
defined('FULL_PATH') or die('restricted access!');
/**
* Performs action on multilingual fields
*
*/
class kMultiLanguageHelper extends kHelper {
/**
* Maximal language id
*
* @var int
*/
protected $languageCount = 0;
/**
* Languages created in system
*
* @var Array
*/
protected $languagesIDs = Array ();
/**
* Structure of table, that is currently processed
*
* @var Array
*/
var $curStructure = Array();
/**
* Field, to get structure information from
*
* @var string
*/
var $curSourceField = false;
/**
* Indexes used in table of 32
*
* @var int
*/
var $curIndexCount = 0;
/**
* Fields from config, that are currently used
*
* @var Array
*/
var $curFields = Array();
/**
* Updates language count in system (always is divisible by 5)
*
*/
protected function initLanguageCount()
{
static $init_made = false;
if (!$init_made) {
$this->languagesIDs = $this->getActualLanguages();
$this->languageCount = max( max($this->languagesIDs), 5 );
$init_made = true;
}
}
/**
* Returns language ids, that can be used
*
* @return Array
*/
protected function getActualLanguages()
{
$cache_key = 'language_ids[%LangSerial%]';
$ret = $this->Application->getCache($cache_key);
if ($ret === false) {
$this->Conn->nextQueryCachable = true;
$sql = 'SELECT ' . $this->Application->getUnitOption('lang', 'IDField') . '
FROM ' . $this->Application->getUnitOption('lang', 'TableName');
$ret = $this->Conn->GetCol($sql);
$this->Application->setCache($cache_key, $ret);
}
return $ret;
}
/**
* Checks if language with specified id is created
*
* @param int $language_id
* @return bool
*/
protected function LanguageFound($language_id)
{
return in_array($language_id, $this->languagesIDs) || $language_id <= 5;
}
/**
* Returns list of processable languages
*
* @return Array
*/
public function getLanguages()
{
static $languages = null;
if ( !isset($languages) ) {
$languages = Array ();
$this->initLanguageCount();
for ($language_id = 1; $language_id <= $this->languageCount; $language_id++) {
if ( $this->LanguageFound($language_id) ) {
$languages[] = $language_id;
}
}
}
return $languages;
}
function scanTable($mask)
{
$i = 0;
$fields_found = 0;
$fields = array_keys($this->curStructure);
foreach ($fields as $field_name) {
if (preg_match($mask, $field_name)) {
$fields_found++;
}
}
return $fields_found;
}
function readTableStructure($table_name, $refresh = false)
{
// if ($refresh || !getArrayValue($structure_status, $prefix.'.'.$table_name)) {
$this->curStructure = $this->Conn->Query('DESCRIBE '.$table_name, 'Field');
$this->curIndexCount = count($this->Conn->Query('SHOW INDEXES FROM '.$table_name));
// }
}
/**
+ * Creates missing multilingual fields for all unit configs, registered in system
+ *
+ * @param bool $reread_configs
+ * @return void
+ * @access public
+ */
+ public function massCreateFields($reread_configs = true)
+ {
+ if ( $reread_configs ) {
+ $this->Application->UnitConfigReader->ReReadConfigs();
+ }
+
+ foreach ($this->Application->UnitConfigReader->configData as $prefix => $config_data) {
+ $this->createFields($prefix);
+ }
+ }
+
+ /**
* Creates missing multilanguage fields in table by specified prefix
*
* @param string $prefix
* @param bool $refresh Forces config field structure to be re-read from database
* @return void
*/
function createFields($prefix, $refresh = false)
{
if ( $refresh && preg_match('/(.*)-cdata$/', $prefix, $regs) ) {
// call main item config to clone cdata table
$this->Application->UnitConfigReader->loadConfig($regs[1]);
$this->Application->UnitConfigReader->runAfterConfigRead($prefix);
}
$table_name = $this->Application->getUnitOption($prefix, 'TableName');
$this->curFields = $this->Application->getUnitOption($prefix, 'Fields');
if ( !($table_name && $this->curFields) || ($table_name && !$this->Conn->TableFound($table_name, kUtil::constOn('IS_INSTALL'))) ) {
// invalid config found or prefix not found
return ;
}
$this->initLanguageCount();
$sqls = Array ();
$this->readTableStructure($table_name, $refresh);
foreach ($this->curFields as $field_name => $field_options) {
if ( getArrayValue($field_options, 'formatter') == 'kMultiLanguage' ) {
if ( isset($field_options['master_field']) ) {
unset($this->curFields[$field_name]);
continue;
}
$this->setSourceField($field_name);
if ( $this->languageCount > 0 ) {
// `l77_Name` VARCHAR( 255 ) NULL DEFAULT '0';
$field_mask = Array ();
$field_mask['name'] = 'l%s_' . $field_name;
$field_mask['null'] = getArrayValue($field_options, 'not_null') ? 'NOT NULL' : 'NULL';
if ( $this->curSourceField ) {
$default_value = $this->getFieldParam('Default') != 'NULL'
? $this->Conn->qstr($this->getFieldParam('Default'))
: $this->getFieldParam('Default');
$field_mask['type'] = $this->getFieldParam('Type');
}
else {
$default_value = is_null($field_options['default']) ? 'NULL'
: $this->Conn->qstr($field_options['default']);
$field_mask['type'] = $field_options['db_type'];
}
$field_mask['default'] = ($field_mask['null'] == 'NOT NULL' && $default_value == 'NULL') ? '' : 'DEFAULT ' . $default_value;
if ( strtoupper($field_mask['type']) == 'TEXT' ) {
// text fields in mysql doesn't have default value
$field_mask = $field_mask['name'] . ' ' . $field_mask['type'] . ' ' . $field_mask['null'];
}
else {
$field_mask = $field_mask['name'] . ' ' . $field_mask['type'] . ' ' . $field_mask['null'] . ' ' . $field_mask['default'];
}
$alter_sqls = $this->generateAlterSQL($field_mask, 1, $this->languageCount);
if ( $alter_sqls ) {
$sqls[] = 'ALTER TABLE ' . $table_name . ' ' . $alter_sqls;
}
}
}
}
foreach ($sqls as $sql_query) {
$this->Conn->Query($sql_query);
}
}
/**
* Creates missing multilanguage fields in table by specified prefix
*
* @param string $prefix
* @param int $src_language
* @param int $dst_language
* @return void
* @access public
*/
public function copyMissingData($prefix, $src_language, $dst_language)
{
$table_name = $this->Application->getUnitOption($prefix, 'TableName');
$this->curFields = $this->Application->getUnitOption($prefix, 'Fields');
if ( !($table_name && $this->curFields) || ($table_name && !$this->Conn->TableFound($table_name, kUtil::constOn('IS_INSTALL'))) ) {
// invalid config found or prefix not found
return ;
}
foreach ($this->curFields as $field_name => $field_options) {
$formatter = isset($field_options['formatter']) ? $field_options['formatter'] : '';
if ( ($formatter == 'kMultiLanguage') && !isset($field_options['master_field']) ) {
$sql = 'UPDATE ' . $table_name . '
SET l' . $dst_language . '_' . $field_name . ' = l' . $src_language . '_' . $field_name . '
WHERE l' . $dst_language . '_' . $field_name . ' = "" OR l' . $dst_language . '_' . $field_name . ' IS NULL';
$this->Conn->Query($sql);
}
}
}
function deleteField($prefix, $custom_id)
{
$table_name = $this->Application->getUnitOption($prefix, 'TableName');
$sql = 'DESCRIBE '.$table_name.' "l%_cust_'.$custom_id.'"';
$fields = $this->Conn->GetCol($sql);
$sql = 'ALTER TABLE '.$table_name.' ';
$sql_template = 'DROP COLUMN %s, ';
foreach ($fields as $field_name) {
$sql .= sprintf($sql_template, $field_name);
}
$this->Conn->Query( substr($sql, 0, -2) );
}
/**
* Returns parameter requested of current source field
*
* @param string $param_name
* @return string
*/
function getFieldParam($param_name)
{
return $this->curStructure[$this->curSourceField][$param_name];
}
/**
* Detects field name to create other fields from
*
* @param string $field_name
*/
function setSourceField($field_name)
{
$ret = $this->scanTable('/^l[\d]+_'.preg_quote($field_name, '/').'$/');
if (!$ret) {
// no multilingual fields at all (but we have such field without language prefix)
$original_found = $this->scanTable('/^'.preg_quote($field_name, '$/').'/');
$this->curSourceField = $original_found ? $field_name : false;
}
else {
$this->curSourceField = 'l1_'.$field_name;
}
}
/**
* Returns ALTER statement part for adding required fields to table
*
* @param string $field_mask sql mask for creating field with correct definition (type & size)
* @param int $start_index add new fields starting from this index
* @param int $create_count create this much new multilingual field translations
* @return string
*/
function generateAlterSQL($field_mask, $start_index, $create_count)
{
static $single_lang = null;
if (!isset($single_lang)) {
// if single language mode, then create indexes only on primary columns
$table_name = $this->Application->getUnitOption('lang', 'TableName');
$sql = 'SELECT COUNT(*)
FROM '.$table_name.'
WHERE Enabled = 1';
// if language count = 0, then assume it's multi language mode
$single_lang = $this->Conn->GetOne($sql) == 1;
}
$ret = '';
$ml_field = preg_replace('/l(.*?)_(.*?) (.*)/', '\\2', $field_mask);
$i_count = $start_index + $create_count;
while ($start_index < $i_count) {
if (isset($this->curStructure['l'.$start_index.'_'.$ml_field]) || (!$this->LanguageFound($start_index)) ) {
$start_index++;
continue;
}
$prev_index = $start_index - 1;
do {
list($prev_field,$type) = explode(' ', sprintf($field_mask, $prev_index) );
} while ($prev_index > 0 && !$this->LanguageFound($prev_index--));
if (substr($prev_field, 0, 3) == 'l0_') {
$prev_field = substr($prev_field, 3, strlen($prev_field));
if (!$this->curSourceField) {
// get field name before this one
$fields = array_keys($this->curFields);
// $prev_field = key(end($this->curStructure));
$prev_field = $fields[array_search($prev_field, $fields) - 1];
if (getArrayValue($this->curFields[$prev_field], 'formatter') == 'kMultiLanguage') {
$prev_field = 'l'.$this->languageCount.'_'.$prev_field;
}
}
}
$field_expression = sprintf($field_mask, $start_index);
$ret .= 'ADD COLUMN '.$field_expression.' AFTER `'.$prev_field.'`, ';
if ($this->curIndexCount < 32 && ($start_index == $this->Application->GetDefaultLanguageId() || !$single_lang)) {
// create index for primary language column + for all others (if multiple languages installed)
list($field_name, $field_params) = explode(' ', $field_expression, 2);
$index_type = isset($this->curFields[$ml_field]['index_type']) ? $this->curFields[$prev_field]['index_type'] : 'string';
$ret .= $index_type == 'string' ? 'ADD INDEX (`'.$field_name.'` (5) ), ' : 'ADD INDEX (`'.$field_name.'`), ';
$this->curIndexCount++;
}
$start_index++;
}
return preg_replace('/, $/', ';', $ret);
}
}
Index: branches/5.2.x/core/units/languages/languages_event_handler.php
===================================================================
--- branches/5.2.x/core/units/languages/languages_event_handler.php (revision 15110)
+++ branches/5.2.x/core/units/languages/languages_event_handler.php (revision 15111)
@@ -1,675 +1,671 @@
<?php
/**
* @version $Id$
* @package In-Portal
* @copyright Copyright (C) 1997 - 2009 Intechnic. All rights reserved.
* @license GNU/GPL
* In-Portal is Open Source software.
* This means that this software may have been modified pursuant
* the GNU General Public License, and as distributed it includes
* or is derivative of works licensed under the GNU General Public License
* or other free or open source software licenses.
* See http://www.in-portal.org/license for copyright notices and details.
*/
defined('FULL_PATH') or die('restricted access!');
class LanguagesEventHandler extends kDBEventHandler
{
/**
* Allows to override standard permission mapping
*
* @return void
* @access protected
* @see kEventHandler::$permMapping
*/
protected function mapPermissions()
{
parent::mapPermissions();
$permissions = Array (
'OnChangeLanguage' => Array ('self' => true),
'OnSetPrimary' => Array ('self' => 'advanced:set_primary|add|edit'),
'OnImportLanguage' => Array ('self' => 'advanced:import'),
'OnExportLanguage' => Array ('self' => 'advanced:export'),
'OnExportProgress' => Array ('self' => 'advanced:export'),
'OnReflectMultiLingualFields' => Array ('self' => 'view'),
'OnSynchronizeLanguages' => Array ('self' => 'edit'),
);
$this->permMapping = array_merge($this->permMapping, $permissions);
}
/**
* Checks user permission to execute given $event
*
* @param kEvent $event
* @return bool
* @access public
*/
public function CheckPermission(kEvent &$event)
{
if ( $event->Name == 'OnItemBuild' ) {
// check permission without using $event->getSection(),
// so first cache rebuild won't lead to "ldefault_Name" field being used
return true;
}
return parent::CheckPermission($event);
}
/**
* Allows to get primary language object
*
* @param kEvent $event
* @return int
* @access public
*/
public function getPassedID(kEvent &$event)
{
if ( $event->Special == 'primary' ) {
return $this->Application->GetDefaultLanguageId();
}
return parent::getPassedID($event);
}
/**
* [HOOK] Updates table structure on new language adding/removing language
*
* @param kEvent $event
*/
function OnReflectMultiLingualFields(&$event)
{
if ($this->Application->GetVar('ajax') == 'yes') {
$event->status = kEvent::erSTOP;
}
if (is_object($event->MasterEvent)) {
if ($event->MasterEvent->status != kEvent::erSUCCESS) {
// only rebuild when all fields are validated
return ;
}
if (($event->MasterEvent->Name == 'OnSave') && !$this->Application->GetVar('new_language')) {
// only rebuild during new language adding
return ;
}
}
$ml_helper =& $this->Application->recallObject('kMultiLanguageHelper');
/* @var $ml_helper kMultiLanguageHelper */
- $this->Application->UnitConfigReader->ReReadConfigs();
- foreach ($this->Application->UnitConfigReader->configData as $prefix => $config_data) {
- $ml_helper->createFields($prefix);
- }
-
+ $ml_helper->massCreateFields();
$event->SetRedirectParam('action_completed', 1);
}
/**
* Allows to set selected language as primary
*
* @param kEvent $event
*/
function OnSetPrimary(&$event)
{
if ($this->Application->CheckPermission('SYSTEM_ACCESS.READONLY', 1)) {
$event->status = kEvent::erFAIL;
return;
}
$this->StoreSelectedIDs($event);
$ids = $this->getSelectedIDs($event);
if ($ids) {
$id = array_shift($ids);
$object =& $event->getObject( Array('skip_autoload' => true) );
/* @var $object LanguagesItem */
$object->Load($id);
$object->copyMissingData( $object->setPrimary() );
}
}
/**
* [HOOK] Reset primary status of other languages if we are saving primary language
*
* @param kEvent $event
*/
function OnUpdatePrimary(&$event)
{
if ($event->MasterEvent->status != kEvent::erSUCCESS) {
return ;
}
$object =& $event->getObject( Array('skip_autoload' => true) );
/* @var $object LanguagesItem */
$object->SwitchToLive();
// set primary for each languages, that have this checkbox checked
$ids = explode(',', $event->MasterEvent->getEventParam('ids'));
foreach ($ids as $id) {
$object->Load($id);
if ($object->GetDBField('PrimaryLang')) {
$object->copyMissingData( $object->setPrimary(true, false) );
}
if ($object->GetDBField('AdminInterfaceLang')) {
$object->setPrimary(true, true);
}
}
// if no primary language left, then set primary last language (not to load again) from edited list
$sql = 'SELECT '.$object->IDField.'
FROM '.$object->TableName.'
WHERE PrimaryLang = 1';
$primary_language = $this->Conn->GetOne($sql);
if (!$primary_language) {
$object->setPrimary(false, false); // set primary language
}
$sql = 'SELECT '.$object->IDField.'
FROM '.$object->TableName.'
WHERE AdminInterfaceLang = 1';
$primary_language = $this->Conn->GetOne($sql);
if (!$primary_language) {
$object->setPrimary(false, true); // set admin interface language
}
}
/**
* Prefills options with dynamic values
*
* @param kEvent $event
* @return void
* @access protected
*/
protected function OnAfterConfigRead(kEvent &$event)
{
parent::OnAfterConfigRead($event);
$fields = $this->Application->getUnitOption($event->Prefix, 'Fields');
// set dynamic hints for options in date format fields
$options = $fields['InputDateFormat']['options'];
if ($options) {
foreach ($options as $i => $v) {
$options[$i] = $v . ' (' . adodb_date($i) . ')';
}
$fields['InputDateFormat']['options'] = $options;
}
$options = $fields['InputTimeFormat']['options'];
if ($options) {
foreach ($options as $i => $v) {
$options[$i] = $v . ' (' . adodb_date($i) . ')';
}
$fields['InputTimeFormat']['options'] = $options;
}
$this->Application->setUnitOption($event->Prefix, 'Fields', $fields);
}
/**
* Occurs before updating item
*
* @param kEvent $event
* @return void
* @access protected
*/
protected function OnBeforeItemUpdate(kEvent &$event)
{
parent::OnBeforeItemUpdate($event);
$object =& $event->getObject();
/* @var $object kDBItem */
$status_fields = $this->Application->getUnitOption($event->Prefix, 'StatusField');
$status_field = array_shift($status_fields);
if ( $object->GetDBField('PrimaryLang') == 1 && $object->GetDBField($status_field) == 0 ) {
$object->SetDBField($status_field, 1);
}
}
/**
* Shows only enabled languages on front
*
* @param kEvent $event
* @return void
* @access protected
* @see kDBEventHandler::OnListBuild()
*/
protected function SetCustomQuery(kEvent &$event)
{
parent::SetCustomQuery($event);
$object =& $event->getObject();
/* @var $object kDBList */
if ( in_array($event->Special, Array ('enabled', 'selected', 'available')) ) {
$object->addFilter('enabled_filter', '%1$s.Enabled = ' . STATUS_ACTIVE);
}
// site domain language picker
if ( $event->Special == 'selected' || $event->Special == 'available' ) {
$edit_picker_helper =& $this->Application->recallObject('EditPickerHelper');
/* @var $edit_picker_helper EditPickerHelper */
$edit_picker_helper->applyFilter($event, 'Languages');
}
// apply domain-based language filtering
$languages = $this->Application->siteDomainField('Languages');
if ( strlen($languages) ) {
$languages = explode('|', substr($languages, 1, -1));
$object->addFilter('domain_filter', '%1$s.LanguageId IN (' . implode(',', $languages) . ')');
}
}
/**
* Copy labels from another language
*
* @param kEvent $event
* @return void
* @access protected
*/
protected function OnAfterItemCreate(kEvent &$event)
{
parent::OnAfterItemCreate($event);
$object =& $event->getObject();
/* @var $object kDBItem */
$src_language = $object->GetDBField('CopyFromLanguage');
if ( $object->GetDBField('CopyLabels') && $src_language ) {
$dst_language = $object->GetID();
// 1. schedule data copy after OnSave event is executed
$var_name = $event->getPrefixSpecial() . '_copy_data' . $this->Application->GetVar('m_wid');
$pending_actions = $this->Application->RecallVar($var_name, Array ());
if ( $pending_actions ) {
$pending_actions = unserialize($pending_actions);
}
$pending_actions[$src_language] = $dst_language;
$this->Application->StoreVar($var_name, serialize($pending_actions));
$object->SetDBField('CopyLabels', 0);
}
}
/**
* Saves language from temp table to live
*
* @param kEvent $event
* @return void
* @access protected
*/
protected function OnSave(kEvent &$event)
{
parent::OnSave($event);
if ( $event->status != kEvent::erSUCCESS ) {
return;
}
$var_name = $event->getPrefixSpecial() . '_copy_data' . $this->Application->GetVar('m_wid');
$pending_actions = $this->Application->RecallVar($var_name, Array ());
if ( $pending_actions ) {
$pending_actions = unserialize($pending_actions);
}
// create multilingual columns for phrases & email events table first (actual for 6+ language)
$ml_helper =& $this->Application->recallObject('kMultiLanguageHelper');
/* @var $ml_helper kMultiLanguageHelper */
$ml_helper->createFields('phrases');
$ml_helper->createFields('emailevents');
foreach ($pending_actions as $src_language => $dst_language) {
// phrases import
$sql = 'UPDATE ' . $this->Application->getUnitOption('phrases', 'TableName') . '
SET l' . $dst_language . '_Translation = l' . $src_language . '_Translation';
$this->Conn->Query($sql);
// events import
$sql = 'UPDATE ' . $this->Application->getUnitOption('emailevents', 'TableName') . '
SET
l' . $dst_language . '_Subject = l' . $src_language . '_Subject,
l' . $dst_language . '_Body = l' . $src_language . '_Body';
$this->Conn->Query($sql);
}
$this->Application->RemoveVar($var_name);
$event->CallSubEvent('OnReflectMultiLingualFields');
$event->CallSubEvent('OnUpdatePrimary');
}
/**
* Prepare temp tables for creating new item
* but does not create it. Actual create is
* done in OnPreSaveCreated
*
* @param kEvent $event
* @return void
* @access protected
*/
protected function OnPreCreate(kEvent &$event)
{
parent::OnPreCreate($event);
$object =& $event->getObject();
/* @var $object kDBItem */
$object->SetDBField('CopyLabels', 1);
$sql = 'SELECT ' . $object->IDField . '
FROM ' . $this->Application->getUnitOption($event->Prefix, 'TableName') . '
WHERE PrimaryLang = 1';
$primary_lang_id = $this->Conn->GetOne($sql);
$object->SetDBField('CopyFromLanguage', $primary_lang_id);
$object->SetDBField('SynchronizationModes', Language::SYNCHRONIZE_DEFAULT);
}
/**
* Sets new language mark
*
* @param kEvent $event
* @return void
* @access protected
*/
protected function OnBeforeDeleteFromLive(kEvent &$event)
{
parent::OnBeforeDeleteFromLive($event);
$id_field = $this->Application->getUnitOption($event->Prefix, 'IDField');
$sql = 'SELECT ' . $id_field . '
FROM ' . $this->Application->getUnitOption($event->Prefix, 'TableName') . '
WHERE ' . $id_field . ' = ' . $event->getEventParam('id');
$id = $this->Conn->GetOne($sql);
if ( !$id ) {
$this->Application->SetVar('new_language', 1);
}
}
function OnChangeLanguage(&$event)
{
$language_id = $this->Application->GetVar('language');
$language_field = $this->Application->isAdmin ? 'AdminLanguage' : 'FrontLanguage';
$this->Application->SetVar('m_lang', $language_id);
// set new language for this session
$this->Application->Session->SetField('Language', $language_id);
// remember last user language
if ($this->Application->RecallVar('user_id') == USER_ROOT) {
$this->Application->StorePersistentVar($language_field, $language_id);
}
else {
$object =& $this->Application->recallObject('u.current');
/* @var $object kDBItem */
$object->SetDBField($language_field, $language_id);
$object->Update();
}
// without this language change in admin will cause erase of last remembered tree section
$this->Application->SetVar('skip_last_template', 1);
}
/**
* Parse language XML file into temp tables and redirect to progress bar screen
*
* @param kEvent $event
*/
function OnImportLanguage(&$event)
{
if ($this->Application->CheckPermission('SYSTEM_ACCESS.READONLY', 1)) {
$event->status = kEvent::erFAIL;
return;
}
$items_info = $this->Application->GetVar('phrases_import');
if ($items_info) {
list ($id, $field_values) = each($items_info);
$object =& $this->Application->recallObject('phrases.import', 'phrases', Array('skip_autoload' => true));
/* @var $object kDBItem */
$object->setID($id);
$object->SetFieldsFromHash($field_values, $this->getRequestProtectedFields($field_values));
if (!$object->Validate()) {
$event->status = kEvent::erFAIL;
return ;
}
$filename = $object->GetField('LangFile', 'full_path');
if (!filesize($filename)) {
$object->SetError('LangFile', 'la_empty_file', 'la_EmptyFile');
$event->status = kEvent::erFAIL;
}
$language_import_helper =& $this->Application->recallObject('LanguageImportHelper');
/* @var $language_import_helper LanguageImportHelper */
$language_import_helper->performImport(
$filename,
$object->GetDBField('PhraseType'),
$object->GetDBField('Module'),
$object->GetDBField('ImportOverwrite') ? LANG_OVERWRITE_EXISTING : LANG_SKIP_EXISTING
);
// delete uploaded language pack after import is finished
unlink($filename);
$event->SetRedirectParam('opener', 'u');
}
}
/**
* Stores ids of selected languages and redirects to export language step 1
*
* @param kEvent $event
*/
function OnExportLanguage(&$event)
{
if ($this->Application->CheckPermission('SYSTEM_ACCESS.READONLY', 1)) {
$event->status = kEvent::erFAIL;
return;
}
$this->Application->setUnitOption('phrases','AutoLoad',false);
$this->StoreSelectedIDs($event);
$this->Application->StoreVar('export_language_ids', implode(',', $this->getSelectedIDs($event)) );
$event->setRedirectParams( Array('phrases.export_event' => 'OnNew', 'pass' => 'all,phrases.export') );
}
/**
* Saves selected languages to xml file passed
*
* @param kEvent $event
*/
function OnExportProgress(&$event)
{
$items_info = $this->Application->GetVar('phrases_export');
if ($items_info) {
list($id, $field_values) = each($items_info);
$object =& $this->Application->recallObject('phrases.export', null, Array('skip_autoload' => true));
/* @var $object kDBItem */
$object->setID($id);
$object->SetFieldsFromHash($field_values, $this->getRequestProtectedFields($field_values));
if (!$object->Validate()) {
$event->status = kEvent::erFAIL;
return ;
}
$file_helper =& $this->Application->recallObject('FileHelper');
/* @var $file_helper FileHelper */
$file_helper->CheckFolder(EXPORT_PATH);
if (!is_writable(EXPORT_PATH)) {
$event->status = kEvent::erFAIL;
$object->SetError('LangFile', 'write_error', 'la_ExportFolderNotWritable');
return ;
}
if ( substr($field_values['LangFile'], -5) != '.lang') {
$field_values['LangFile'] .= '.lang';
}
$filename = EXPORT_PATH . '/' . $field_values['LangFile'];
$language_import_helper =& $this->Application->recallObject('LanguageImportHelper');
/* @var $language_import_helper LanguageImportHelper */
if ($object->GetDBField('DoNotEncode')) {
$language_import_helper->setExportEncoding('plain');
}
$language_import_helper->setExportLimits($field_values['ExportPhrases'], $field_values['ExportEmailEvents']);
$lang_ids = explode(',', $this->Application->RecallVar('export_language_ids') );
$language_import_helper->performExport($filename, $field_values['PhraseType'], $lang_ids, $field_values['Module']);
}
$event->redirect = 'regional/languages_export_step2';
$event->SetRedirectParam('export_file', $field_values['LangFile']);
}
/**
* Returns to previous template in opener stack
*
* @param kEvent $event
* @return void
* @access protected
*/
protected function OnGoBack(kEvent &$event)
{
$event->SetRedirectParam('opener', 'u');
}
function OnScheduleTopFrameReload(&$event)
{
$this->Application->StoreVar('RefreshTopFrame',1);
}
/**
* Do now allow deleting current language
*
* @param kEvent $event
* @return void
* @access protected
*/
protected function OnBeforeItemDelete(kEvent &$event)
{
parent::OnBeforeItemDelete($event);
$object =& $event->getObject();
/* @var $object kDBItem */
if ( $object->GetDBField('PrimaryLang') || $object->GetDBField('AdminInterfaceLang') || $object->GetID() == $this->Application->GetVar('m_lang') ) {
$event->status = kEvent::erFAIL;
}
}
/**
* Deletes phrases and email events on given language
*
* @param kEvent $event
* @return void
* @access protected
*/
protected function OnAfterItemDelete(kEvent &$event)
{
parent::OnAfterItemDelete($event);
$object =& $event->getObject();
/* @var $object kDBItem */
// clean EmailEvents table
$fields_hash = Array (
'l' . $object->GetID() . '_Subject' => NULL,
'l' . $object->GetID() . '_Body' => NULL,
);
$this->Conn->doUpdate($fields_hash, $this->Application->getUnitOption('emailevents', 'TableName'), 1);
// clean Phrases table
$fields_hash = Array (
'l' . $object->GetID() . '_Translation' => NULL,
'l' . $object->GetID() . '_HintTranslation' => NULL,
'l' . $object->GetID() . '_ColumnTranslation' => NULL,
);
$this->Conn->doUpdate($fields_hash, $this->Application->getUnitOption('phrases', 'TableName'), 1);
}
/**
* Copy missing phrases across all system languages (starting from primary)
*
* @param kEvent $event
* @return void
* @access protected
*/
protected function OnSynchronizeLanguages(&$event)
{
if ( $this->Application->CheckPermission('SYSTEM_ACCESS.READONLY', 1) ) {
$event->status = kEvent::erFAIL;
return;
}
$source_languages = $target_languages = Array ();
// get language list with primary language first
$sql = 'SELECT SynchronizationModes, LanguageId
FROM ' . TABLE_PREFIX . 'Languages
WHERE SynchronizationModes <> ""
ORDER BY PrimaryLang DESC';
$languages = $this->Conn->GetCol($sql, 'LanguageId');
foreach ($languages as $language_id => $synchronization_modes) {
$synchronization_modes = explode('|', substr($synchronization_modes, 1, -1));
if ( in_array(Language::SYNCHRONIZE_TO_OTHERS, $synchronization_modes) ) {
$source_languages[] = $language_id;
}
if ( in_array(Language::SYNCHRONIZE_FROM_OTHERS, $synchronization_modes) ) {
$target_languages[] = $language_id;
}
}
foreach ($source_languages as $source_id) {
foreach ($target_languages as $target_id) {
if ( $source_id == $target_id ) {
continue;
}
$sql = 'UPDATE ' . TABLE_PREFIX . 'LanguageLabels
SET l' . $target_id . '_Translation = l' . $source_id . '_Translation
WHERE COALESCE(l' . $target_id . '_Translation, "") = "" AND COALESCE(l' . $source_id . '_Translation, "") <> ""';
$this->Conn->Query($sql);
}
}
}
}
\ No newline at end of file
Index: branches/5.2.x/core/install/install_toolkit.php
===================================================================
--- branches/5.2.x/core/install/install_toolkit.php (revision 15110)
+++ branches/5.2.x/core/install/install_toolkit.php (revision 15111)
@@ -1,1177 +1,1182 @@
<?php
/**
* @version $Id$
* @package In-Portal
* @copyright Copyright (C) 1997 - 2009 Intechnic. All rights reserved.
* @license GNU/GPL
* In-Portal is Open Source software.
* This means that this software may have been modified pursuant
* the GNU General Public License, and as distributed it includes
* or is derivative of works licensed under the GNU General Public License
* or other free or open source software licenses.
* See http://www.in-portal.org/license for copyright notices and details.
*/
defined('FULL_PATH') or die('restricted access!');
/**
* Upgrade sqls are located using this mask
*
*/
define('UPGRADES_FILE', FULL_PATH.'/%sinstall/upgrades.%s');
/**
* Prerequisit check classes are located using this mask
*
*/
define('PREREQUISITE_FILE', FULL_PATH.'/%sinstall/prerequisites.php');
/**
* Format of version identificator in upgrade files (normal, beta, release candidate)
*
*/
define('VERSION_MARK', '# ===== v ([\d]+\.[\d]+\.[\d]+|[\d]+\.[\d]+\.[\d]+-B[\d]+|[\d]+\.[\d]+\.[\d]+-RC[\d]+) =====');
if (!defined('GET_LICENSE_URL')) {
/**
* Url used for retrieving user licenses from Intechnic licensing server
*
*/
define('GET_LICENSE_URL', 'http://www.in-portal.com/license.php');
}
/**
* Misc functions, that are required during installation, when
*
*/
class kInstallToolkit {
/**
* Reference to kApplication class object
*
* @var kApplication
*/
var $Application = null;
/**
* Connection to database
*
* @var kDBConnection
*/
var $Conn = null;
/**
* Path to config.php
*
* @var string
*/
var $INIFile = '';
/**
* Parsed data from config.php
*
* @var Array
*/
var $systemConfig = Array ();
/**
* Tells, that system config was changed
*
* @var bool
* @access public
*/
public $systemConfigChanged = false;
/**
* Path, used by system to store data on filesystem
*
* @var string
*/
var $defaultWritablePath = '';
/**
* Installator instance
*
* @var kInstallator
*/
var $_installator = null;
function kInstallToolkit()
{
$this->defaultWritablePath = DIRECTORY_SEPARATOR . 'system';
if ( class_exists('kApplication') ) {
// auto-setup in case of separate module install
$this->Application =& kApplication::Instance();
$this->Application->Init(); // needed for standalone module install
$this->Conn =& $this->Application->GetADODBConnection();
}
$this->INIFile = FULL_PATH . $this->defaultWritablePath . DIRECTORY_SEPARATOR . 'config.php';
$this->systemConfig = $this->ParseConfig(true);
}
/**
* Sets installator
*
* @param kInstallator $instance
*/
function setInstallator(&$instance)
{
$this->_installator =& $instance;
}
/**
* Checks prerequisities before module install or upgrade
*
* @param string $module_path
* @param string $versions
* @param string $mode upgrade mode = {install, standalone, upgrade}
* @return bool
*/
function CheckPrerequisites($module_path, $versions, $mode)
{
if ( !$versions ) {
return Array ();
}
$prerequisite_object =& $this->getPrerequisiteObject($module_path);
/* @var $prerequisite_object InPortalPrerequisites */
// some errors possible
return is_object($prerequisite_object) ? $prerequisite_object->CheckPrerequisites($versions, $mode) : Array ();
}
/**
* Call prerequisites method
*
* @param string $module_path
* @param string $method
* @return array
*/
function CallPrerequisitesMethod($module_path, $method)
{
$prerequisite_object =& $this->getPrerequisiteObject($module_path);
/* @var $prerequisite_object InPortalPrerequisites */
return is_object($prerequisite_object) ? $prerequisite_object->$method() : false;
}
/**
* Returns prerequisite object to be used for checks
*
* @param string $module_path
* @return kHelper
* @access protected
*/
protected function &getPrerequisiteObject($module_path)
{
static $prerequisite_classes = Array ();
$prerequisites_file = sprintf(PREREQUISITE_FILE, $module_path);
if ( !file_exists($prerequisites_file) ) {
$false = false;
return $false;
}
if ( !isset($prerequisite_classes[$module_path]) ) {
// save class name, because 2nd time
// (in after call $prerequisite_class variable will not be present)
include_once $prerequisites_file;
$prerequisite_classes[$module_path] = $prerequisite_class;
}
$prerequisite_object = new $prerequisite_classes[$module_path]();
/* @var $prerequisite_object InPortalPrerequisites */
if ( method_exists($prerequisite_object, 'setToolkit') ) {
$prerequisite_object->setToolkit($this);
}
return $prerequisite_object;
}
/**
* Processes one license, received from server
*
* @param string $file_data
*/
function processLicense($file_data)
{
$modules_helper =& $this->Application->recallObject('ModulesHelper');
/* @var $modules_helper kModulesHelper */
$file_data = explode('Code==:', $file_data);
$file_data[0] = str_replace('In-Portal License File - do not edit!' . "\n", '', $file_data[0]);
$file_data = array_map('trim', $file_data);
if ($modules_helper->verifyLicense($file_data[0])) {
$this->setSystemConfig('Intechnic', 'License', $file_data[0]);
if (array_key_exists(1, $file_data)) {
$this->setSystemConfig('Intechnic', 'LicenseCode', $file_data[1]);
}
else {
$this->setSystemConfig('Intechnic', 'LicenseCode');
}
$this->SaveConfig();
}
else {
// invalid license received from licensing server
$this->_installator->errorMessage = 'Invalid License File';
}
}
/**
* Saves given configuration values to database
*
* @param Array $config
*/
function saveConfigValues($config)
{
foreach ($config as $config_var => $value) {
$sql = 'UPDATE ' . TABLE_PREFIX . 'SystemSettings
SET VariableValue = ' . $this->Conn->qstr($value) . '
WHERE VariableName = ' . $this->Conn->qstr($config_var);
$this->Conn->Query($sql);
}
}
/**
* Sets module version to passed
*
* @param string $module_name
* @param string|bool $module_path
* @param string|bool $version
*/
function SetModuleVersion($module_name, $module_path = false, $version = false)
{
if ($version === false) {
if (!$module_path) {
throw new Exception('Module path must be given to "SetModuleVersion" method to auto-detect version');
return ;
}
$version = $this->GetMaxModuleVersion($module_path);
}
// get table prefix from config, because application may not be available here
$table_prefix = $this->getSystemConfig('Database', 'TablePrefix');
if ($module_name == 'kernel') {
$module_name = 'in-portal';
}
// don't use "adodb_mktime" here, because it's not yet included
$sql = 'UPDATE ' . $table_prefix . 'Modules
SET Version = "' . $version . '", BuildDate = ' . time() . '
WHERE LOWER(Name) = "' . strtolower($module_name) . '"';
$this->Conn->Query($sql);
}
/**
* Sets module root category to passed
*
* @param string $module_name
* @param int $category_id
*/
function SetModuleRootCategory($module_name, $category_id = 0)
{
// get table prefix from config, because application may not be available here
$table_prefix = $this->getSystemConfig('Database', 'TablePrefix');
if ($module_name == 'kernel') {
$module_name = 'in-portal';
}
$sql = 'UPDATE ' . $table_prefix . 'Modules
SET RootCat = ' . $category_id . '
WHERE LOWER(Name) = "' . strtolower($module_name) . '"';
$this->Conn->Query($sql);
}
/**
* Returns maximal version of given module by scanning it's upgrade scripts
*
* @param string $module_path
* @return string
*/
function GetMaxModuleVersion($module_path)
{
$module_path = rtrim(mb_strtolower($module_path), '/');
$upgrades_file = sprintf(UPGRADES_FILE, $module_path . '/', 'sql');
if (!file_exists($upgrades_file)) {
// no upgrade file
return '5.0.0';
}
$sqls = file_get_contents($upgrades_file);
$versions_found = preg_match_all('/'.VERSION_MARK.'/s', $sqls, $regs);
if (!$versions_found) {
// upgrades file doesn't contain version definitions
return '5.0.0';
}
return end($regs[1]);
}
/**
* Runs SQLs from file
*
* @param string $filename
* @param mixed $replace_from
* @param mixed $replace_to
*/
function RunSQL($filename, $replace_from = null, $replace_to = null)
{
if (!file_exists(FULL_PATH.$filename)) {
return ;
}
$sqls = file_get_contents(FULL_PATH.$filename);
if (!$this->RunSQLText($sqls, $replace_from, $replace_to)) {
if (is_object($this->_installator)) {
$this->_installator->Done();
}
else {
if (isset($this->Application)) {
$this->Application->Done();
}
exit;
}
}
}
/**
* Runs SQLs from string
*
* @param string $sqls
* @param mixed $replace_from
* @param mixed $replace_to
* @param int $start_from
* @return bool
*/
function RunSQLText(&$sqls, $replace_from = null, $replace_to = null, $start_from = 0)
{
$table_prefix = $this->getSystemConfig('Database', 'TablePrefix');
// add prefix to all tables
if (strlen($table_prefix) > 0) {
$replacements = Array ('INSERT INTO ', 'UPDATE ', 'ALTER TABLE ', 'DELETE FROM ', 'REPLACE INTO ');
foreach ($replacements as $replacement) {
$sqls = str_replace($replacement, $replacement . $table_prefix, $sqls);
}
}
$sqls = str_replace('CREATE TABLE ', 'CREATE TABLE IF NOT EXISTS ' . $table_prefix, $sqls);
$sqls = str_replace('DROP TABLE ', 'DROP TABLE IF EXISTS ' . $table_prefix, $sqls);
$sqls = str_replace('<%TABLE_PREFIX%>', $table_prefix, $sqls);
$primary_language = is_object($this->Application) ? $this->Application->GetDefaultLanguageId() : 1;
$sqls = str_replace('<%PRIMARY_LANGUAGE%>', $primary_language, $sqls);
if (isset($replace_from) && isset($replace_to)) {
// replace something additionally, e.g. module root category
$sqls = str_replace($replace_from, $replace_to, $sqls);
}
$sqls = str_replace("\r\n", "\n", $sqls); // convert to linux line endings
$no_comment_sqls = preg_replace("/#\s([^;]*?)\n/is", '', $sqls); // remove all comments "#" on new lines
if ($no_comment_sqls === null) {
// "ini.pcre.backtrack-limit" reached and error happened
$sqls = explode(";\n", $sqls . "\n"); // ensures that last sql won't have ";" in it
$sqls = array_map('trim', $sqls);
// remove all comments "#" on new lines (takes about 2 seconds for 53000 sqls)
$sqls = preg_replace("/#\s([^;]*?)/", '', $sqls);
}
else {
$sqls = explode(";\n", $no_comment_sqls . "\n"); // ensures that last sql won't have ";" in it
$sqls = array_map('trim', $sqls);
}
$sql_count = count($sqls);
$db_collation = $this->getSystemConfig('Database', 'DBCollation');
for ($i = $start_from; $i < $sql_count; $i++) {
$sql = $sqls[$i];
if (!$sql || (substr($sql, 0, 1) == '#')) {
continue; // usually last line
}
if (substr($sql, 0, 13) == 'CREATE TABLE ' && $db_collation) {
// it is CREATE TABLE statement -> add collation
$sql .= ' COLLATE \'' . $db_collation . '\'';
}
$this->Conn->Query($sql);
if ($this->Conn->getErrorCode() != 0) {
if (is_object($this->_installator)) {
$this->_installator->errorMessage = 'Error: ('.$this->Conn->getErrorCode().') '.$this->Conn->getErrorMsg().'<br /><br />Last Database Query:<br /><textarea cols="70" rows="10" readonly>'.htmlspecialchars($sql).'</textarea>';
$this->_installator->LastQueryNum = $i + 1;
}
return false;
}
}
return true;
}
/**
* Performs clean language import from given xml file
*
* @param string $lang_file
* @param bool $upgrade
* @todo Import for "core/install/english.lang" (322KB) takes 18 seconds to work on Windows
*/
function ImportLanguage($lang_file, $upgrade = false)
{
$lang_file = FULL_PATH.$lang_file.'.lang';
if (!file_exists($lang_file)) {
return ;
}
$language_import_helper =& $this->Application->recallObject('LanguageImportHelper');
/* @var $language_import_helper LanguageImportHelper */
$language_import_helper->performImport($lang_file, '|0|1|2|', '', $upgrade ? LANG_SKIP_EXISTING : LANG_OVERWRITE_EXISTING);
}
/**
* Converts module version in format X.Y.Z[-BN/-RCM] to signle integer
*
* @param string $version
* @return int
*/
function ConvertModuleVersion($version)
{
if (preg_match('/(.*)-(B|RC)([\d]+)/', $version, $regs)) {
// -B<M> or RC-<N>
$parts = explode('.', $regs[1]);
$parts[] = $regs[2] == 'B' ? 1 : 2; // B reliases goes before RC releases
$parts[] = $regs[3];
}
else {
// releases without B/RC marks go after any B/RC releases
$parts = explode('.', $version . '.3.100');
}
$bin = '';
foreach ($parts as $part_index => $part) {
if ($part_index == 3) {
// version type only can be 1/2/3 (11 in binary form), so don't use padding at all
$pad_count = 2;
}
else {
$pad_count = 8;
}
$bin .= str_pad(decbin($part), $pad_count, '0', STR_PAD_LEFT);
}
return bindec($bin);
}
/**
* Returns themes, found in system
*
* @param bool $rebuild
* @return int
*/
function getThemes($rebuild = false)
{
if ($rebuild) {
$this->rebuildThemes();
}
$id_field = $this->Application->getUnitOption('theme', 'IDField');
$table_name = $this->Application->getUnitOption('theme', 'TableName');
$sql = 'SELECT Name, ' . $id_field . '
FROM ' . $table_name . '
ORDER BY Name ASC';
return $this->Conn->GetCol($sql, $id_field);
}
function ParseConfig($parse_section = false)
{
if (!file_exists($this->INIFile)) {
return Array ();
}
if (file_exists($this->INIFile) && !is_readable($this->INIFile)) {
die('Could Not Open Ini File');
}
$contents = file($this->INIFile);
if ($contents && $contents[0] == '<' . '?' . 'php die() ?' . ">\n") {
// format of "config.php" file before 5.1.0 version
array_shift($contents);
return $this->parseIniString(implode('', $contents), $parse_section);
}
$_CONFIG = Array ();
require($this->INIFile);
if ($parse_section) {
return $_CONFIG;
}
$ret = Array ();
foreach ($_CONFIG as $section => $section_variables) {
$ret = array_merge($ret, $section_variables);
}
return $ret;
}
/**
* Equivalent for "parse_ini_string" function available since PHP 5.3.0
*
* @param string $ini
* @param bool $process_sections
* @param int $scanner_mode
* @return Array
*/
function parseIniString($ini, $process_sections = false, $scanner_mode = null)
{
# Generate a temporary file.
$tempname = tempnam('/tmp', 'ini');
$fp = fopen($tempname, 'w');
fwrite($fp, $ini);
$ini = parse_ini_file($tempname, !empty($process_sections));
fclose($fp);
@unlink($tempname);
return $ini;
}
function SaveConfig($silent = false)
{
if (!is_writable($this->INIFile) && !is_writable(dirname($this->INIFile))) {
$error_msg = 'Cannot write to "' . $this->INIFile . '" file';
if ($silent) {
trigger_error($error_msg, E_USER_WARNING);
}
else {
throw new Exception($error_msg);
}
return ;
}
$fp = fopen($this->INIFile, 'w');
fwrite($fp, '<' . '?' . 'php' . "\n\n");
foreach ($this->systemConfig as $section_name => $section_data) {
foreach ($section_data as $key => $value) {
fwrite($fp, '$_CONFIG[\'' . $section_name . '\'][\'' . $key . '\'] = \'' . addslashes($value) . '\';' . "\n");
}
fwrite($fp, "\n");
}
fclose($fp);
$this->systemConfigChanged = false;
}
/**
* Sets value to system config (yet SaveConfig must be called to write it to file)
*
* @param string $section
* @param string $key
* @param string $value
*/
function setSystemConfig($section, $key, $value = null)
{
$this->systemConfigChanged = true;
if (isset($value)) {
if (!array_key_exists($section, $this->systemConfig)) {
// create section, when missing
$this->systemConfig[$section] = Array ();
}
// create key in section
$this->systemConfig[$section][$key] = $value;
return ;
}
unset($this->systemConfig[$section][$key]);
}
/**
* Returns information from system config
*
* @param string $section
* @param string $key
* @param mixed $default
* @return string|bool
*/
function getSystemConfig($section, $key, $default = false)
{
if ( !array_key_exists($section, $this->systemConfig) ) {
return $default;
}
if ( !array_key_exists($key, $this->systemConfig[$section]) ) {
return $default;
}
return $this->systemConfig[$section][$key] ? $this->systemConfig[$section][$key] : $default;
}
/**
* Checks if system config is present and is not empty
*
* @return bool
*/
function systemConfigFound()
{
return file_exists($this->INIFile) && $this->systemConfig;
}
/**
* Checks if given section is present in config
*
* @param string $section
* @return bool
*/
function sectionFound($section)
{
return array_key_exists($section, $this->systemConfig);
}
/**
* Returns formatted module name based on it's root folder
*
* @param string $module_folder
* @return string
*/
function getModuleName($module_folder)
{
return implode('-', array_map('ucfirst', explode('-', $module_folder)));
}
/**
* Returns information about module (based on "install/module_info.xml" file)
*
* @param string $module_name
* @return Array
*/
function getModuleInfo($module_name)
{
if ($module_name == 'core') {
$info_file = FULL_PATH . '/' . $module_name . '/install/module_info.xml';
}
else {
$info_file = MODULES_PATH . '/' . $module_name . '/install/module_info.xml';
}
if (!file_exists($info_file)) {
return Array ();
}
$xml_helper =& $this->Application->recallObject('kXMLHelper');
/* @var $xml_helper kXMLHelper */
$root_node =& $xml_helper->Parse( file_get_contents($info_file) );
if (!is_object($root_node) || !preg_match('/^kxmlnode/i', get_class($root_node)) || ($root_node->Name == 'ERROR')) {
// non-valid xml file
return Array ();
}
$ret = Array ();
$current_node =& $root_node->firstChild;
do {
$ret[ strtolower($current_node->Name) ] = trim($current_node->Data);
} while (($current_node =& $current_node->NextSibling()));
return $ret;
}
/**
* Returns nice module string to be used on install/upgrade screens
*
* @param string $module_name
* @param string $version_string
* @return string
*/
function getModuleString($module_name, $version_string)
{
// image (if exists) <description> (<name> <version>)
$ret = Array ();
$module_info = $this->getModuleInfo($module_name);
if (array_key_exists('name', $module_info) && $module_info['name']) {
$module_name = $module_info['name'];
}
else {
$module_name = $this->getModuleName($module_name);
}
if (array_key_exists('image', $module_info) && $module_info['image']) {
$image_src = $module_info['image'];
if (!preg_match('/^(http|https):\/\//', $image_src)) {
// local image -> make absolute url
$image_src = $this->Application->BaseURL() . $image_src;
}
$ret[] = '<img src="' . $image_src . '" alt="' . htmlspecialchars($module_name) . '" title="' . htmlspecialchars($module_name) . '" style="vertical-align:middle; margin: 3px 0 3px 5px"/>';
}
if (array_key_exists('description', $module_info) && $module_info['description']) {
$ret[] = $module_info['description'];
}
else {
$ret[] = $module_name;
}
$ret[] = '(' . $module_name . ' ' . $version_string . ')';
return implode(' ', $ret);
}
/**
* Creates module root category in "Home" category using given data and returns it
*
* @param string $name
* @param string $description
* @param string $category_template
* @param string $category_icon
* @return kDBItem
*/
function &createModuleCategory($name, $description, $category_template = null, $category_icon = null)
{
static $fields = null;
if ( !isset($fields) ) {
$ml_formatter =& $this->Application->recallObject('kMultiLanguage');
/* @var $ml_formatter kMultiLanguage */
$fields['name'] = $ml_formatter->LangFieldName('Name');
$fields['description'] = $ml_formatter->LangFieldName('Description');
}
$category =& $this->Application->recallObject('c', null, Array ('skip_autoload' => true));
/* @var $category kDBItem */
$category_fields = Array (
$fields['name'] => $name, 'Filename' => $name, 'AutomaticFilename' => 1,
$fields['description'] => $description, 'Status' => STATUS_ACTIVE, 'Priority' => -9999,
// prevents empty link to module category on spearate module install
'NamedParentPath' => 'Content/' . $name,
);
$category_fields['ParentId'] = $this->Application->getBaseCategory();
if ( isset($category_template) ) {
$category_fields['Template'] = $category_template;
$category_fields['CachedTemplate'] = $category_template;
}
if ( isset($category_icon) ) {
$category_fields['UseMenuIconUrl'] = 1;
$category_fields['MenuIconUrl'] = $category_icon;
}
$category->Clear();
$category->SetDBFieldsFromHash($category_fields);
$category->Create();
$priority_helper =& $this->Application->recallObject('PriorityHelper');
/* @var $priority_helper kPriorityHelper */
$event = new kEvent('c:OnListBuild');
// ensure, that newly created category has proper value in Priority field
$priority_helper->recalculatePriorities($event, 'ParentId = ' . $category_fields['ParentId']);
// update Priority field in object, becase "CategoriesItem::Update" method will be called
// from "kInstallToolkit::setModuleItemTemplate" and otherwise will set 0 to Priority field
$sql = 'SELECT Priority
FROM ' . $category->TableName . '
WHERE ' . $category->IDField . ' = ' . $category->GetID();
$category->SetDBField('Priority', $this->Conn->GetOne($sql));
return $category;
}
/**
* Sets category item template into custom field for given prefix
*
* @param kDBItem $category
* @param string $prefix
* @param string $item_template
*/
function setModuleItemTemplate(&$category, $prefix, $item_template)
{
$this->Application->removeObject('c-cdata');
// recreate all fields, because custom fields are added during install script
$category->Configure();
$category->SetDBField('cust_' . $prefix .'_ItemTemplate', $item_template);
$category->Update();
}
/**
* Link custom field records with search config records + create custom field columns
*
* @param string $module_folder
* @param string $prefix
* @param int $item_type
*/
function linkCustomFields($module_folder, $prefix, $item_type)
{
$module_folder = strtolower($module_folder);
$module_name = $module_folder;
if ( $module_folder == 'kernel' ) {
$module_name = 'in-portal';
$module_folder = 'core';
}
$db =& $this->Application->GetADODBConnection();
$sql = 'SELECT FieldName, CustomFieldId
FROM ' . TABLE_PREFIX . 'CustomFields
WHERE Type = ' . $item_type . ' AND IsSystem = 0'; // config is not read here yet :( $this->Application->getUnitOption('p', 'ItemType');
$custom_fields = $db->GetCol($sql, 'CustomFieldId');
foreach ($custom_fields as $cf_id => $cf_name) {
$sql = 'UPDATE ' . TABLE_PREFIX . 'SearchConfig
SET CustomFieldId = ' . $cf_id . '
WHERE (TableName = "CustomFields") AND (LOWER(ModuleName) = "' . $module_name . '") AND (FieldName = ' . $db->qstr($cf_name) . ')';
$db->Query($sql);
}
$this->Application->refreshModuleInfo(); // this module configs are now processed
// because of configs was read only from installed before modules (in-portal), then reread configs
$this->Application->UnitConfigReader->scanModules(MODULES_PATH . DIRECTORY_SEPARATOR . $module_folder);
// create correct columns in CustomData table
$ml_helper =& $this->Application->recallObject('kMultiLanguageHelper');
/* @var $ml_helper kMultiLanguageHelper */
$ml_helper->createFields($prefix . '-cdata', true);
}
/**
* Deletes cache, useful after separate module install and installator last step
*
* @param bool $refresh_permissions
* @return void
*/
function deleteCache($refresh_permissions = false)
{
$this->Application->HandleEvent($event, 'adm:OnResetConfigsCache');
$this->Application->HandleEvent($event, 'adm:OnResetSections');
$this->Application->HandleEvent($event, 'c:OnResetCMSMenuCache');
$this->Conn->Query('DELETE FROM ' . TABLE_PREFIX . 'CachedUrls');
if ($refresh_permissions) {
if ($this->Application->ConfigValue('QuickCategoryPermissionRebuild')) {
// refresh permission without progress bar
$updater =& $this->Application->makeClass('kPermCacheUpdater');
/* @var $updater kPermCacheUpdater */
$updater->OneStepRun();
}
else {
// refresh permissions with ajax progress bar (when available)
$this->Application->setDBCache('ForcePermCacheUpdate', 1);
}
}
}
/**
* Deletes all temp tables (from active sessions too)
*
*/
function deleteEditTables()
{
$table_prefix = $this->getSystemConfig('Database', 'TablePrefix');
$tables = $this->Conn->GetCol('SHOW TABLES');
$mask_edit_table = '/' . $table_prefix . 'ses_(.*)_edit_(.*)/';
$mask_search_table = '/' . $table_prefix . 'ses_(.*?)_(.*)/';
foreach ($tables as $table) {
if ( preg_match($mask_edit_table, $table, $rets) || preg_match($mask_search_table, $table, $rets) ) {
$this->Conn->Query('DROP TABLE IF EXISTS ' . $table);
}
}
}
/**
* Perform redirect after separate module install
*
* @param string $module_folder
* @param bool $refresh_permissions
*/
function finalizeModuleInstall($module_folder, $refresh_permissions = false)
{
$this->SetModuleVersion(basename($module_folder), $module_folder);
if (!$this->Application->GetVar('redirect')) {
return ;
}
$themes_helper =& $this->Application->recallObject('ThemesHelper');
/* @var $themes_helper kThemesHelper */
// use direct query, since module isn't yet in kApplication::ModuleInfo array
$sql = 'SELECT Name
FROM ' . TABLE_PREFIX . 'Modules
WHERE Path = ' . $this->Conn->qstr(rtrim($module_folder, '/') . '/');
$module_name = $this->Conn->GetOne($sql);
$themes_helper->synchronizeModule($module_name);
+ $ml_helper =& $this->Application->recallObject('kMultiLanguageHelper');
+ /* @var $ml_helper kMultiLanguageHelper */
+
+ $ml_helper->massCreateFields();
+
$this->deleteCache($refresh_permissions);
$url_params = Array (
'pass' => 'm', 'admin' => 1,
'RefreshTree' => 1, 'index_file' => 'index.php',
);
$this->Application->Redirect('modules/modules_list', $url_params);
}
/**
* Performs rebuild of themes
*
*/
function rebuildThemes()
{
$this->Application->HandleEvent($themes_event, 'adm:OnRebuildThemes');
}
/**
* Checks that file is writable by group or others
*
* @param string $file
* @return boolean
*/
function checkWritePermissions($file)
{
if (DIRECTORY_SEPARATOR == '\\') {
// windows doen't allow to check permissions (always returns null)
return null;
}
$permissions = fileperms($file);
return $permissions & 0x0010 || $permissions & 0x0002;
}
/**
* Upgrades primary skin to the latest version
*
* @param Array $module_info
* @return string|bool
*/
function upgradeSkin($module_info)
{
$upgrades_file = sprintf(UPGRADES_FILE, $module_info['Path'], 'css');
$data = file_get_contents($upgrades_file);
// get all versions with their positions in file
$versions = Array ();
preg_match_all('/(' . VERSION_MARK . ')/s', $data, $matches, PREG_SET_ORDER + PREG_OFFSET_CAPTURE);
$from_version_int = $this->ConvertModuleVersion($module_info['FromVersion']);
foreach ($matches as $index => $match) {
$version_int = $this->ConvertModuleVersion($match[2][0]);
if ( $version_int < $from_version_int ) {
// only process versions, that were released after currently used version
continue;
}
$start_pos = $match[0][1] + strlen($match[0][0]);
$end_pos = array_key_exists($index + 1, $matches) ? $matches[$index + 1][0][1] : mb_strlen($data);
$patch_data = str_replace("\r\n", "\n", substr($data, $start_pos, $end_pos - $start_pos));
$versions[] = Array (
'Version' => $match[2][0],
// fixes trimmed leading spaces by modern text editor
'Data' => ltrim( str_replace("\n\n", "\n \n", $patch_data) ),
);
}
if ( !$versions ) {
// not skin changes -> quit
return true;
}
$primary_skin =& $this->Application->recallObject('skin.primary', null, Array ('skip_autoload' => true));
/* @var $primary_skin kDBItem */
$primary_skin->Load(1, 'IsPrimary');
if ( !$primary_skin->isLoaded() ) {
// we always got primary skin, but just in case
return false;
}
$temp_handler =& $this->Application->recallObject('skin_TempHandler', 'kTempTablesHandler');
/* @var $temp_handler kTempTablesHandler */
// clone current skin
$cloned_ids = $temp_handler->CloneItems('skin', '', Array ($primary_skin->GetID()));
if ( !$cloned_ids ) {
// can't clone
return false;
}
$skin =& $this->Application->recallObject('skin.tmp', null, Array ('skip_autoload' => true));
/* @var $skin kDBItem */
$skin->Load($cloned_ids[0]);
// save css to temp file (for patching)
$skin_file = tempnam('/tmp', 'skin_css_');
$fp = fopen($skin_file, 'w');
fwrite($fp, str_replace("\r\n", "\n", $skin->GetDBField('CSS')));
fclose($fp);
$output = Array ();
$patch_file = tempnam('/tmp', 'skin_patch_');
foreach ($versions as $version_info) {
// for each left version get it's patch and apply to temp file
$fp = fopen($patch_file, 'w');
fwrite($fp, $version_info['Data']);
fclose($fp);
$output[ $version_info['Version'] ] = shell_exec('patch ' . $skin_file . ' ' . $patch_file . ' 2>&1') . "\n";
}
// place temp file content into cloned skin
$skin->SetDBField('Name', 'Upgraded to ' . $module_info['ToVersion']);
$skin->SetDBField('CSS', file_get_contents($skin_file));
$skin->Update();
unlink($skin_file);
unlink($patch_file);
$has_errors = false;
foreach ($output as $version => $version_output) {
$version_errors = trim(preg_replace("/(^|\n)(patching file .*?|Hunk #.*?\.)(\n|$)/m", '', $version_output));
if ( $version_errors ) {
$has_errors = true;
$output[$version] = trim(preg_replace("/(^|\n)(patching file .*?)(\n|$)/m", '', $output[$version]));
}
else {
unset($output[$version]);
}
}
if ( !$has_errors ) {
// copy patched css back to primary skin
$primary_skin->SetDBField('CSS', $skin->GetDBField('CSS'));
$primary_skin->Update();
// delete temporary skin record
$temp_handler->DeleteItems('skin', '', Array ($skin->GetID()));
return true;
}
// put clean skin from new version
$skin->SetDBField('CSS', file_get_contents(FULL_PATH . '/core/admin_templates/incs/style_template.css'));
$skin->Update();
// return output in case of errors
return $output;
}
/**
* Returns cache handlers, that are working
*
* @param string $current
* @return Array
*/
public function getWorkingCacheHandlers($current = null)
{
if ( !isset($current) ) {
$current = $this->getSystemConfig('Misc', 'CacheHandler');
}
$cache_handlers = Array (
'Fake' => 'None', 'Memcache' => 'Memcached', 'XCache' => 'XCache', 'Apc' => 'Alternative PHP Cache'
);
foreach ($cache_handlers AS $class_prefix => $title) {
$handler_class = $class_prefix . 'CacheHandler';
if ( !class_exists($handler_class) ) {
unset($cache_handlers[$class_prefix]);
}
else {
$handler = new $handler_class('localhost:11211');
/* @var $handler FakeCacheHandler */
if ( !$handler->isWorking() ) {
if ( $current == $class_prefix ) {
$cache_handlers[$class_prefix] .= ' (offline)';
}
else {
unset($cache_handlers[$class_prefix]);
}
}
}
}
return $cache_handlers;
}
/**
* Returns compression engines, that are working
*
* @param string $current
* @return Array
*/
public function getWorkingCompressionEngines($current = null)
{
if ( !isset($current) ) {
$current = $this->getSystemConfig('Misc', 'CompressionEngine');
}
$output = shell_exec('java -version 2>&1');
$compression_engines = Array ('' => 'None', 'yui' => 'YUICompressor (Java)', 'php' => 'PHP-based');
if ( stripos($output, 'java version') === false ) {
if ( $current == 'yui' ) {
$compression_engines['yui'] .= ' (offline)';
}
else {
unset($compression_engines['yui']);
}
}
return $compression_engines;
}
}
\ No newline at end of file
Event Timeline
Log In to Comment