Page MenuHomeIn-Portal Phabricator

in-portal
No OneTemporary

File Metadata

Created
Fri, Sep 19, 4:42 PM

in-portal

Index: branches/unlabeled/unlabeled-1.20.2/kernel/units/languages/import_xml.php
===================================================================
--- branches/unlabeled/unlabeled-1.20.2/kernel/units/languages/import_xml.php (nonexistent)
+++ branches/unlabeled/unlabeled-1.20.2/kernel/units/languages/import_xml.php (revision 5538)
@@ -0,0 +1,403 @@
+<?php
+
+ define('LANG_OVERWRITE_EXISTING', 1);
+ define('LANG_SKIP_EXISTING', 2);
+
+ class LangXML_Parser extends kBase {
+
+ /**
+ * Path to current node beeing processed
+ *
+ * @var Array
+ */
+ var $path = Array();
+
+ /**
+ * Connection to database
+ *
+ * @var kDBConnection
+ */
+ var $Conn = null;
+
+ /**
+ * Fields of language currently beeing processed
+ *
+ * @var Array
+ */
+ var $current_language = Array();
+
+ /**
+ * Fields of phrase currently beeing processed
+ *
+ * @var Array
+ */
+ var $current_phrase = Array();
+
+ /**
+ * Fields of event currently beeing processed
+ *
+ * @var Array
+ */
+ var $current_event = Array();
+
+ /**
+ * Event type + name mapping to id (from system)
+ *
+ * @var Array
+ */
+ var $events_hash = Array();
+
+
+ /**
+ * Phrase types allowed for import/export operations
+ *
+ * @var Array
+ */
+ var $phrase_types_allowed = Array();
+
+ /**
+ * Modules allowed for export (import in development)
+ *
+ * @var Array
+ */
+ var $modules_allowed = Array();
+
+ var $lang_object = null;
+
+ var $tables = Array();
+
+ var $ip_address = '';
+
+ var $import_mode = LANG_SKIP_EXISTING;
+
+ var $Encoding = 'base64';
+
+ function LangXML_Parser()
+ {
+ parent::kBase();
+ $this->Conn =& $this->Application->GetADODBConnection();
+
+ $this->Application->SetVar('lang_mode', 't');
+
+ $this->tables['lang'] = $this->prepareTempTable('lang');
+ $this->lang_object =& $this->Application->recallObject('lang.imp', null, Array('skip_autoload' => true));
+
+ $this->tables['phrases'] = $this->prepareTempTable('phrases');
+ $this->tables['emailmessages'] = $this->prepareTempTable('emailmessages');
+
+ $sql = 'SELECT EventId, CONCAT(Event,"_",Type) AS EventMix FROM '.TABLE_PREFIX.'Events';
+ $this->events_hash = $this->Conn->GetCol($sql, 'EventMix');
+
+ $this->ip_address = getenv('HTTP_X_FORWARDED_FOR') ? getenv('HTTP_X_FORWARDED_FOR') : getenv('REMOTE_ADDR');
+ }
+
+ function SetEncoding($enc)
+ {
+ $this->Encoding = $enc;
+ }
+
+ function renameTable($table_prefix, $new_name)
+ {
+ $this->Conn->Query('ALTER TABLE '.$this->tables[$table_prefix].' RENAME '.$new_name);
+ $this->tables[$table_prefix] = $new_name;
+ }
+
+ /**
+ * Create temp table for prefix, if table already exists, then delete it and create again
+ *
+ * @param string $prefix
+ */
+ function prepareTempTable($prefix)
+ {
+ $idfield = $this->Application->getUnitOption($prefix, 'IDField');
+ $table = $this->Application->getUnitOption($prefix,'TableName');
+ $temp_table = $this->Application->GetTempName($table);
+
+ $sql = 'DROP TABLE IF EXISTS %s';
+ $this->Conn->Query( sprintf($sql, $temp_table) );
+
+ $sql = 'CREATE TABLE %s SELECT * FROM %s WHERE 0';
+ $this->Conn->Query( sprintf($sql, $temp_table, $table) );
+
+ $sql = 'ALTER TABLE %1$s CHANGE %2$s %2$s INT(11) NOT NULL';
+ $this->Conn->Query( sprintf($sql, $temp_table, $idfield) );
+
+ return $temp_table;
+ }
+
+ function Parse($filename, $phrase_types, $module_ids, $import_mode = LANG_SKIP_EXISTING)
+ {
+ // define the XML parsing routines/functions to call based on the handler path
+ if( !file_exists($filename) || !$phrase_types /*|| !$module_ids*/ ) return false;
+
+ $phrase_types = explode('|', substr($phrase_types, 1, -1) );
+// $module_ids = explode('|', substr($module_ids, 1, -1) );
+
+ $this->phrase_types_allowed = array_flip($phrase_types);
+ $this->import_mode = $import_mode;
+
+ //if (in_array('In-Portal',)
+
+ $xml_parser = xml_parser_create();
+ xml_set_element_handler( $xml_parser, Array(&$this, 'startElement'), Array(&$this, 'endElement') );
+ xml_set_character_data_handler( $xml_parser, Array(&$this, 'characterData') );
+
+ $fdata = file_get_contents($filename);
+
+ $ret = xml_parse($xml_parser, $fdata);
+ xml_parser_free($xml_parser); // clean up the parser object
+
+ $this->Application->SetVar('lang_mode', '');
+ return $ret;
+ }
+
+ function startElement(&$parser, $element, $attributes)
+ {
+ array_push($this->path, $element);
+ $path = implode(' ',$this->path);
+ //check what path we are in
+
+ switch($path)
+ {
+ case 'LANGUAGES LANGUAGE':
+ $this->current_language = Array('PackName' => $attributes['PACKNAME'], 'LocalName' => $attributes['PACKNAME'], 'Encoding' => $attributes['ENCODING']);
+
+ $sql = 'SELECT %s FROM %s WHERE PackName = %s';
+ $sql = sprintf( $sql,
+ $this->lang_object->IDField,
+ $this->Application->GetLiveName($this->lang_object->TableName),
+ $this->Conn->qstr($this->current_language['PackName']) );
+ $language_id = $this->Conn->GetOne($sql);
+ if($language_id)
+ {
+ $this->current_language['LanguageId'] = $language_id;
+ $this->lang_object->SwitchToLive();
+ $this->lang_object->Load($language_id);
+ }
+ break;
+
+ case 'LANGUAGES LANGUAGE PHRASES':
+ case 'LANGUAGES LANGUAGE EVENTS':
+ if( !getArrayValue($this->current_language,'Charset') ) $this->current_language['Charset'] = 'iso-8859-1';
+ $this->lang_object->SetFieldsFromHash($this->current_language);
+
+ if( !getArrayValue($this->current_language,'LanguageId') )
+ {
+ if( $this->lang_object->Create() ) $this->current_language['LanguageId'] = $this->lang_object->GetID();
+ }
+ elseif($this->import_mode == LANG_OVERWRITE_EXISTING)
+ {
+ $this->lang_object->TableName = $this->Application->getUnitOption($this->lang_object->Prefix, 'TableName');
+ $this->lang_object->Update();
+ }
+ break;
+
+ case 'LANGUAGES LANGUAGE PHRASES PHRASE':
+ $phrase_module = getArrayValue($attributes,'MODULE');
+ if(!$phrase_module) $phrase_module = 'In-Portal';
+
+ $this->current_phrase = Array( 'LanguageId' => $this->current_language['LanguageId'],
+ 'Phrase' => $attributes['LABEL'],
+ 'PhraseType' => $attributes['TYPE'],
+ 'Module' => $phrase_module,
+ 'LastChanged' => adodb_mktime(),
+ 'LastChangeIP' => $this->ip_address,
+ 'Translation' => '');
+ break;
+
+ case 'LANGUAGES LANGUAGE EVENTS EVENT':
+ $this->current_event = Array( 'LanguageId' => $this->current_language['LanguageId'],
+ 'EventId' => $this->events_hash[ $attributes['EVENT'].'_'.$attributes['TYPE'] ],
+ 'MessageType' => $attributes['MESSAGETYPE'],
+ 'Template' => '');
+ break;
+
+
+ }
+
+ // if($path == 'SHIPMENT PACKAGE')
+ }
+
+ function characterData(&$parser, $line)
+ {
+ $line = trim($line);
+ if(!$line) return ;
+
+ $path = join (' ',$this->path);
+
+ $language_nodes = Array('DATEFORMAT','TIMEFORMAT','INPUTDATEFORMAT','INPUTTIMEFORMAT','DECIMAL','THOUSANDS','CHARSET','UNITSYSTEM');
+
+
+ $node_field_map = Array('LANGUAGES LANGUAGE DATEFORMAT' => 'DateFormat',
+ 'LANGUAGES LANGUAGE TIMEFORMAT' => 'TimeFormat',
+
+ 'LANGUAGES LANGUAGE INPUTDATEFORMAT'=> 'InputDateFormat',
+ 'LANGUAGES LANGUAGE INPUTTIMEFORMAT'=> 'InputTimeFormat',
+
+ 'LANGUAGES LANGUAGE DECIMAL' => 'DecimalPoint',
+ 'LANGUAGES LANGUAGE THOUSANDS' => 'ThousandSep',
+ 'LANGUAGES LANGUAGE CHARSET' => 'Charset',
+ 'LANGUAGES LANGUAGE UNITSYSTEM' => 'UnitSystem');
+
+ if( in_array( end($this->path), $language_nodes) )
+ {
+ $this->current_language[ $node_field_map[$path] ] = $line;
+ }
+ else
+ {
+ switch($path)
+ {
+ case 'LANGUAGES LANGUAGE PHRASES PHRASE':
+ if( isset($this->phrase_types_allowed[ $this->current_phrase['PhraseType'] ]) )
+ {
+ $this->current_phrase['Translation'] .= $line;
+ }
+ break;
+
+ case 'LANGUAGES LANGUAGE EVENTS EVENT':
+ $this->current_event['Template'] .= $line;
+ break;
+ }
+ }
+ }
+
+ function endElement(&$parser, $element)
+ {
+ $path = implode(' ',$this->path);
+
+ switch($path)
+ {
+ case 'LANGUAGES LANGUAGE PHRASES PHRASE':
+ if( isset($this->phrase_types_allowed[ $this->current_phrase['PhraseType'] ]) )
+ {
+ if ($this->current_language['Encoding'] == 'plain') {
+ // nothing to decode!
+ }
+ else {
+ $this->current_phrase['Translation'] = base64_decode($this->current_phrase['Translation']);
+ }
+ $this->insertRecord($this->tables['phrases'], $this->current_phrase);
+ }
+ break;
+
+ case 'LANGUAGES LANGUAGE EVENTS EVENT':
+ if ($this->current_language['Encoding'] == 'plain') {
+ // nothing to decode!
+ }
+ else {
+ $this->current_event['Template'] = base64_decode($this->current_event['Template']);
+ }
+ $this->insertRecord($this->tables['emailmessages'],$this->current_event);
+ break;
+ }
+
+ array_pop($this->path);
+ }
+
+ function insertRecord($table, $fields_hash)
+ {
+ $fields = '';
+ $values = '';
+
+ foreach($fields_hash as $field_name => $field_value)
+ {
+ $fields .= '`'.$field_name.'`,';
+ $values .= $this->Conn->qstr($field_value).',';
+ }
+
+ $fields = preg_replace('/(.*),$/', '\\1', $fields);
+ $values = preg_replace('/(.*),$/', '\\1', $values);
+
+ $sql = 'INSERT INTO `'.$table.'` ('.$fields.') VALUES ('.$values.')';
+ $this->Conn->Query($sql);
+
+// return $this->Conn->getInsertID(); // no need because of temp table without auto_increment column at all
+ }
+
+ /**
+ * Creates XML file with exported language data
+ *
+ * @param string $filename filename to export into
+ * @param Array $phrase_types phrases types to export from modules passed in $module_ids
+ * @param Array $language_ids IDs of languages to export
+ * @param Array $module_ids IDs of modules to export phrases from
+ */
+ function Create($filename, $phrase_types, $language_ids, $module_ids)
+ {
+ $fp = fopen($filename,'w');
+ if(!$fp || !$phrase_types || !$module_ids || !$language_ids) return false;
+
+ $phrase_types = explode('|', substr($phrase_types, 1, -1) );
+ $module_ids = explode('|', substr($module_ids, 1, -1) );
+
+ $this->events_hash = array_flip($this->events_hash);
+
+ $lang_table = $this->Application->getUnitOption('lang','TableName');
+ $phrases_table = $this->Application->getUnitOption('phrases','TableName');
+ $emailevents_table = $this->Application->getUnitOption('emailmessages','TableName');
+ $mainevents_table = $this->Application->getUnitOption('emailevents','TableName');
+
+ $phrase_tpl = "\t\t\t".'<PHRASE Label="%s" Module="%s" Type="%s">%s</PHRASE>'."\n";
+ $event_tpl = "\t\t\t".'<EVENT MessageType="%s" Event="%s" Type="%s">%s</EVENT>'."\n";
+ $sql = 'SELECT * FROM %s WHERE LanguageId = %s';
+ $ret = '<LANGUAGES>'."\n";
+ foreach($language_ids as $language_id)
+ {
+ // languages
+ $row = $this->Conn->GetRow( sprintf($sql, $lang_table, $language_id) );
+ $ret .= "\t".'<LANGUAGE PackName="'.$row['PackName'].'" Encoding="'.$this->Encoding.'"><DATEFORMAT>'.$row['DateFormat'].'</DATEFORMAT>';
+ $ret .= '<TIMEFORMAT>'.$row['TimeFormat'].'</TIMEFORMAT><INPUTDATEFORMAT>'.$row['InputDateFormat'].'</INPUTDATEFORMAT>';
+ $ret .= '<INPUTTIMEFORMAT>'.$row['InputTimeFormat'].'</INPUTTIMEFORMAT><DECIMAL>'.$row['DecimalPoint'].'</DECIMAL>';
+ $ret .= '<THOUSANDS>'.$row['ThousandSep'].'</THOUSANDS><CHARSET>'.$row['Charset'].'</CHARSET>';
+ $ret .= '<UNITSYSTEM>'.$row['UnitSystem'].'</UNITSYSTEM>'."\n";
+
+ // phrases
+ $phrases_sql = 'SELECT * FROM '.$phrases_table.' WHERE LanguageId = %s AND PhraseType IN (%s) AND Module IN (%s) ORDER BY Phrase';
+ if( in_array('In-Portal',$module_ids) ) array_push($module_ids, ''); // for old language packs
+ $rows = $this->Conn->Query( sprintf($phrases_sql,$language_id, implode(',',$phrase_types), '\''.implode('\',\'',$module_ids).'\'' ) );
+ if($rows)
+ {
+ $ret .= "\t\t".'<PHRASES>'."\n";
+ foreach($rows as $row)
+ {
+ $data = $this->Encoding == 'base64' ? base64_encode($row['Translation']) : '<![CDATA['.$row['Translation'].']]>';
+ $ret .= sprintf($phrase_tpl, $row['Phrase'], $row['Module'], $row['PhraseType'], $data );
+ }
+ $ret .= "\t\t".'</PHRASES>'."\n";
+ }
+
+ // email events
+ if( in_array('In-Portal',$module_ids) ) unset( $module_ids[array_search('',$module_ids)] ); // for old language packs
+ $module_sql = preg_replace('/(.*) OR $/', '\\1', preg_replace('/(.*),/U', 'INSTR(Module,\'\\1\') OR ', implode(',', $module_ids).',' ) );
+
+ $sql = 'SELECT EventId FROM '.$mainevents_table.' WHERE '.$module_sql;
+ $event_ids = $this->Conn->GetCol($sql);
+
+ if($event_ids)
+ {
+ $ret .= "\t\t".'<EVENTS>'."\n";
+ $event_sql = ' SELECT em.*
+ FROM '.$emailevents_table.' em
+ LEFT JOIN '.$mainevents_table.' e ON e.EventId = em.EventId
+ WHERE em.LanguageId = %s AND em.EventId IN (%s)
+ ORDER BY e.Event, e.Type';
+ $rows = $this->Conn->Query( sprintf($event_sql,$language_id, $event_ids ? implode(',',$event_ids) : '' ) );
+ foreach($rows as $row)
+ {
+ list($event_name, $event_type) = explode('_', $this->events_hash[ $row['EventId'] ] );
+ $data = $this->Encoding == 'base64' ? base64_encode($row['Template']) : '<![CDATA['.$row['Template'].']]>';
+ $ret .= sprintf($event_tpl, $row['MessageType'], $event_name, $event_type, $data );
+ }
+ $ret .= "\t\t".'</EVENTS>'."\n";
+ }
+ $ret .= "\t".'</LANGUAGE>'."\n";
+ }
+
+ $ret .= '</LANGUAGES>';
+ fwrite($fp, $ret);
+ fclose($fp);
+ return true;
+ }
+ }
+
+?>
\ No newline at end of file
Property changes on: branches/unlabeled/unlabeled-1.20.2/kernel/units/languages/import_xml.php
___________________________________________________________________
Added: cvs2svn:cvs-rev
## -0,0 +1 ##
+1.20
\ No newline at end of property
Added: svn:executable
## -0,0 +1 ##
+*
\ No newline at end of property
Index: branches/unlabeled/unlabeled-1.20.2/kernel/units/general/cat_dbitem_export.php
===================================================================
--- branches/unlabeled/unlabeled-1.20.2/kernel/units/general/cat_dbitem_export.php (nonexistent)
+++ branches/unlabeled/unlabeled-1.20.2/kernel/units/general/cat_dbitem_export.php (revision 5538)
@@ -0,0 +1,1073 @@
+<?php
+
+ define('EXPORT_STEP', 200); // export by 200 items (e.g. links)
+ define('IMPORT_CHUNK', 10240); // 10240); //30720); //50120); // 5 KB
+
+ define('IMPORT_TEMP', 1);
+ define('IMPORT_LIVE', 2);
+
+ class kCatDBItemExportHelper extends kHelper {
+
+ var $false = false;
+
+ var $cache = Array();
+
+ /**
+ * Allows to find out what items are new in cache
+ *
+ * @var Array
+ */
+ var $cacheStatus = Array();
+
+ var $cacheTable = '';
+
+ var $exportFields = Array();
+
+ /**
+ * Export options
+ *
+ * @var Array
+ */
+ var $exportOptions = Array();
+
+ /**
+ * Item beeing currenly exported
+ *
+ * @var kCatDBItem
+ */
+ var $curItem = null;
+
+ /**
+ * Dummy category object
+ *
+ * @var CategoriesItem
+ */
+ var $dummyCategory = null;
+
+ /**
+ * Pointer to opened file
+ *
+ * @var resource
+ */
+ var $filePointer = null;
+
+ /**
+ * Custom fields definition of current item
+ *
+ * @var Array
+ */
+ var $customFields = Array();
+
+ function kCatDBItemExportHelper()
+ {
+ parent::kHelper();
+ $this->cacheTable = TABLE_PREFIX.'ImportCache';
+ }
+
+ /**
+ * Returns value from cache if found or false otherwise
+ *
+ * @param string $type
+ * @param int $key
+ * @return mixed
+ */
+ function getFromCache($type, $key)
+ {
+ return getArrayValue($this->cache, $type, $key);
+ }
+
+ /**
+ * Adds value to be cached
+ *
+ * @param string $type
+ * @param int $key
+ * @param mixed $value
+ */
+ function addToCache($type, $key, $value, $is_new = true)
+ {
+// if (!isset($this->cache[$type])) $this->cache[$type] = Array();
+ $this->cache[$type][$key] = $value;
+ if ($is_new) {
+ $this->cacheStatus[$type][$key] = true;
+ }
+ }
+
+ function storeCache($cache_types)
+ {
+ $cache_types = explode(',', $cache_types);
+
+ $values_sql = '';
+ foreach ($cache_types as $cache_type) {
+ $sql_mask = '('.$this->Conn->qstr($cache_type).',%s,%s),';
+ $cache = getArrayValue($this->cacheStatus, $cache_type);
+ if (!$cache) $cache = Array();
+ foreach ($cache as $var_name => $cache_status) {
+ $var_value = $this->cache[$cache_type][$var_name];
+ $values_sql .= sprintf($sql_mask, $this->Conn->qstr($var_name), $this->Conn->qstr($var_value) );
+ }
+ }
+ $values_sql = preg_replace('/(.*),$/', '\\1', $values_sql);
+ if ($values_sql) {
+ $sql = 'INSERT INTO '.$this->cacheTable.'(`CacheName`,`VarName`,`VarValue`) VALUES '.$values_sql;
+ $this->Conn->Query($sql);
+ }
+
+ }
+
+ function loadCache()
+ {
+ $sql = 'SELECT * FROM '.$this->cacheTable;
+ $records = $this->Conn->Query($sql);
+
+ $this->cache = Array();
+ foreach ($records as $record) {
+ $this->addToCache($record['CacheName'], $record['VarName'], $record['VarValue'], false);
+ }
+ }
+
+ /**
+ * Fill required fields with dummy values
+ *
+ * @param kEvent $event
+ */
+ function fillRequiredFields(&$event, &$object, $set_status = false)
+ {
+ if ($object == $this->false) {
+ $object =& $event->getObject();
+ }
+
+ $has_empty = false;
+ $fields = array_keys($object->Fields);
+ foreach ($fields as $field_name)
+ {
+ $field_options =& $object->Fields[$field_name];
+ if (isset($object->VirtualFields[$field_name]) || !getArrayValue($field_options, 'required') ) continue;
+ if ( $object->GetDBField($field_name) ) continue;
+
+ $formatter_class = getArrayValue($field_options, 'formatter');
+ if ($formatter_class) // not tested
+ {
+ $formatter =& $this->Application->recallObject($formatter_class);
+ $sample_value = $formatter->GetSample($field_name, $field_options, $object);
+ }
+
+ $has_empty = true;
+ $object->SetDBField($field_name, isset($sample_value) && $sample_value ? $sample_value : 'no value');
+ }
+
+ if ($set_status && $has_empty) {
+ $object->SetDBField('Status', 0);
+ }
+ }
+
+ /**
+ * Verifies that all user entered export params are correct
+ *
+ * @param kEvent $event
+ */
+ function verifyOptions(&$event)
+ {
+ if ($this->Application->RecallVar($event->getPrefixSpecial().'_ForceNotValid'))
+ {
+ $this->Application->StoreVar($event->getPrefixSpecial().'_ForceNotValid', 0);
+ return false;
+ }
+
+ $this->fillRequiredFields($event, $this->false);
+
+ $object =& $event->getObject();
+ $cross_unique_fields = Array('FieldsSeparatedBy', 'FieldsEnclosedBy');
+ if (($object->GetDBField('CategoryFormat') == 1) || ($event->Special == 'import')) // in one field
+ {
+ $object->setRequired('CategorySeparator', true);
+ $cross_unique_fields[] = 'CategorySeparator';
+ }
+
+ $ret = $object->Validate();
+
+ // check if cross unique fields has no same values
+ foreach ($cross_unique_fields as $field_index => $field_name)
+ {
+ if (getArrayValue($object->FieldErrors, $field_name, 'pseudo') == 'required') continue;
+
+ $check_fields = $cross_unique_fields;
+ unset($check_fields[$field_index]);
+
+ foreach ($check_fields as $check_field)
+ {
+ if ($object->GetDBField($field_name) == $object->GetDBField($check_field))
+ {
+ $object->SetError($check_field, 'unique');
+ }
+ }
+ }
+
+ if ($event->Special == 'import')
+ {
+ $this->exportOptions = $this->loadOptions($event);
+
+ $automatic_fields = ($object->GetDBField('FieldTitles') == 1);
+ $object->setRequired('ExportColumns', !$automatic_fields);
+ $category_prefix = '__CATEGORY__';
+ if ( $automatic_fields && ($this->exportOptions['SkipFirstRow']) ) {
+ $this->openFile($event);
+ $this->exportOptions['ExportColumns'] = $this->readRecord();
+ $this->closeFile();
+
+ // remove additional (non-parseble columns)
+ foreach ($this->exportOptions['ExportColumns'] as $field_index => $field_name) {
+ if (!$this->validateField($field_name, $object)) {
+ unset($this->exportOptions['ExportColumns'][$field_index]);
+ }
+ }
+ $category_prefix = '';
+ }
+
+ // 1. check, that we have column definitions
+ if (!$this->exportOptions['ExportColumns']) {
+ $object->setError('ExportColumns', 'required');
+ $ret = false;
+ }
+ else {
+ // 1.1. check that all required fields are present in imported file
+ $missing_columns = Array();
+ foreach ($object->Fields as $field_name => $field_options) {
+ if ($object->SkipField($field_name)) continue;
+ if (getArrayValue($field_options, 'required') && !in_array($field_name, $this->exportOptions['ExportColumns']) ) {
+ $missing_columns[] = $field_name;
+ $object->setError('ExportColumns', 'required_fields_missing', 'la_error_RequiredColumnsMissing');
+ $ret = false;
+ }
+ }
+
+ if (!$ret && $this->Application->isDebugMode()) {
+ $this->Application->Debugger->appendHTML('Missing required for import/export:');
+ $this->Application->Debugger->dumpVars($missing_columns);
+ }
+ }
+
+
+ // 2. check, that we have only mixed category field or only separated category fields
+ $category_found['mixed'] = false;
+ $category_found['separated'] = false;
+
+ foreach ($this->exportOptions['ExportColumns'] as $import_field) {
+ if (preg_match('/^'.$category_prefix.'Category(Path|[0-9]+)/', $import_field, $rets)) {
+ $category_found[$rets[1] == 'Path' ? 'mixed' : 'separated'] = true;
+ }
+ }
+ if ($category_found['mixed'] && $category_found['separated']) {
+ $object->SetError('ExportColumns', 'unique_category', 'la_error_unique_category_field');
+ $ret = false;
+ }
+
+ // 3. check, that duplicates check fields are selected & present in imported fields
+ if ($this->exportOptions['ReplaceDuplicates']) {
+ if ($this->exportOptions['CheckDuplicatesMethod'] == 1) {
+ $check_fields = Array($object->IDField);
+ }
+ else {
+ $check_fields = $this->exportOptions['DuplicateCheckFields'] ? explode('|', substr($this->exportOptions['DuplicateCheckFields'], 1, -1)) : Array();
+ $object =& $event->getObject();
+
+ $language_id = $this->Application->GetDefaultLanguageId();
+ foreach ($check_fields as $index => $check_field) {
+ foreach ($object->Fields as $field_name => $field_options) {
+ if ($field_name == 'l'.$language_id.'_'.$check_field) {
+ $check_fields[$index] = 'l'.$language_id.'_'.$check_field;
+ break;
+ }
+ }
+ }
+ }
+ $this->exportOptions['DuplicateCheckFields'] = $check_fields;
+
+ if (!$check_fields) {
+ $object->setError('CheckDuplicatesMethod', 'required');
+ $ret = false;
+ }
+ else {
+ foreach ($check_fields as $check_field) {
+ $check_field = preg_replace('/^cust_(.*)/', 'Custom_\\1', $check_field);
+ if (!in_array($check_field, $this->exportOptions['ExportColumns'])) {
+ $object->setError('ExportColumns', 'required');
+ $ret = false;
+ break;
+ }
+ }
+ }
+ }
+ $this->saveOptions($event);
+ }
+
+ return $ret;
+ }
+
+ /**
+ * Returns filename to read import data from
+ *
+ * @return string
+ */
+ function getImportFilename()
+ {
+ if ($this->exportOptions['ImportSource'] == 1)
+ {
+ $ret = $this->exportOptions['ImportFilename']; // ['name']; commented by Kostja
+ }
+ else {
+ $ret = $this->exportOptions['ImportLocalFilename'];
+ }
+ return EXPORT_PATH.'/'.$ret;
+ }
+
+ /**
+ * Returns filename to write export data to
+ *
+ * @return string
+ */
+ function getExportFilename()
+ {
+ return EXPORT_PATH.'/'.$this->exportOptions['ExportFilename'].'.'.$this->getFileExtension();
+ }
+
+ /**
+ * Opens file required for export/import operations
+ *
+ * @param kEvent $event
+ */
+ function openFile(&$event)
+ {
+ if ($event->Special == 'export') {
+ $write_mode = ($this->exportOptions['start_from'] == 0) ? 'w' : 'a';
+ $this->filePointer = fopen($this->getExportFilename(), $write_mode);
+ }
+ else {
+ $this->filePointer = fopen($this->getImportFilename(), 'r');
+ }
+
+ // skip UTF-8 BOM Modifier
+ $first_chars = fread($this->filePointer, 3);
+ if (bin2hex($first_chars) != 'efbbbf') {
+ fseek($this->filePointer, 0);
+ }
+ }
+
+ /**
+ * Closes opened file
+ *
+ */
+ function closeFile()
+ {
+ fclose($this->filePointer);
+ }
+
+ function getCustomSQL()
+ {
+ $ml_formatter =& $this->Application->recallObject('kMultiLanguage');
+
+ $custom_sql = '';
+ foreach ($this->customFields as $custom_id => $custom_name) {
+ $custom_sql .= 'custom_data.'.$ml_formatter->LangFieldName('cust_'.$custom_id).' AS cust_'.$custom_name.', ';
+ }
+
+ return preg_replace('/(.*), /', '\\1', $custom_sql);
+ }
+
+ function getExportSQL($count_only = false)
+ {
+ if ($this->exportOptions['export_ids'] === false)
+ {
+ // get links from current category & all it's subcategories
+ $join_clauses = Array();
+
+ $custom_sql = $this->getCustomSQL();
+ if ($custom_sql) {
+ $custom_table = $this->Application->getUnitOption($this->curItem->Prefix.'-cdata', 'TableName');
+ $join_clauses[$custom_table.' custom_data'] = 'custom_data.ResourceId = item_table.ResourceId';
+ }
+
+ $join_clauses[TABLE_PREFIX.'CategoryItems ci'] = 'ci.ItemResourceId = item_table.ResourceId';
+ $join_clauses[TABLE_PREFIX.'Category c'] = 'c.CategoryId = ci.CategoryId';
+
+ $sql = 'SELECT item_table.*, ci.CategoryId'.($custom_sql ? ', '.$custom_sql : '').'
+ FROM '.$this->curItem->TableName.' item_table';
+
+ foreach ($join_clauses as $table_name => $join_expression) {
+ $sql .= ' LEFT JOIN '.$table_name.' ON '.$join_expression;
+ }
+ $sql .= ' WHERE ';
+
+ if ($this->exportOptions['export_cats_ids'][0] == 0)
+ {
+ $sql .= '1';
+ }
+ else {
+ foreach ($this->exportOptions['export_cats_ids'] as $category_id) {
+ $sql .= '(c.ParentPath LIKE "%|'.$category_id.'|%") OR ';
+ }
+ $sql = preg_replace('/(.*) OR $/', '\\1', $sql);
+ }
+
+ $sql .= ' ORDER BY ci.PrimaryCat DESC'; // NEW
+ }
+ else {
+ // get only selected links
+ $sql = 'SELECT item_table.*, '.$this->exportOptions['export_cats_ids'][0].' AS CategoryId
+ FROM '.$this->curItem->TableName.' item_table
+ WHERE '.$this->curItem->IDField.' IN ('.implode(',', $this->exportOptions['export_ids']).')';
+ }
+
+ if (!$count_only)
+ {
+ $sql .= ' LIMIT '.$this->exportOptions['start_from'].','.EXPORT_STEP;
+ }
+ else {
+ $sql = preg_replace("/^.*SELECT(.*?)FROM(?!_)/is", "SELECT COUNT(*) AS count FROM ", $sql);
+ }
+
+ return $sql;
+ }
+
+ /**
+ * Enter description here...
+ *
+ * @param kEvent $event
+ */
+ function performExport(&$event)
+ {
+ $this->exportOptions = $this->loadOptions($event);
+ $this->exportFields = $this->exportOptions['ExportColumns'];
+ $this->curItem =& $event->getObject( Array('skip_autoload' => true) );
+ $this->customFields = $this->Application->getUnitOption($event->Prefix, 'CustomFields');
+ $this->openFile($event);
+
+ if ($this->exportOptions['start_from'] == 0) // first export step
+ {
+ if (!getArrayValue($this->exportOptions, 'IsBaseCategory')) {
+ $this->exportOptions['IsBaseCategory'] = 0;
+ }
+
+ if ($this->exportOptions['IsBaseCategory'] ) {
+ $sql = 'SELECT CachedNavbar
+ FROM '.TABLE_PREFIX.'Category
+ WHERE CategoryId = '.$this->Application->GetVar('m_cat_id');
+ $this->exportOptions['BaseLevel'] = substr_count($this->Conn->GetOne($sql), '>') + 1; // level to cut from other categories
+ }
+
+ // 1. export field titles if required
+ if ($this->exportOptions['IncludeFieldTitles'])
+ {
+ $data_array = Array();
+ foreach ($this->exportFields as $export_field)
+ {
+ $data_array = array_merge($data_array, $this->getFieldCaption($export_field));
+ }
+ $this->writeRecord($data_array);
+ }
+ $this->exportOptions['total_records'] = $this->Conn->GetOne( $this->getExportSQL(true) );
+ }
+
+ // 2. export data
+ $records = $this->Conn->Query( $this->getExportSQL() );
+ $records_exported = 0;
+ foreach ($records as $record_info) {
+ $this->curItem->Clear();
+ $this->curItem->SetDBFieldsFromHash($record_info);
+ $this->setCurrentID();
+ $this->curItem->raiseEvent('OnAfterItemLoad', $this->curItem->GetID() );
+
+ $data_array = Array();
+ foreach ($this->exportFields as $export_field)
+ {
+ $data_array = array_merge($data_array, $this->getFieldValue($export_field) );
+ }
+ $this->writeRecord($data_array);
+ $records_exported++;
+ }
+ $this->closeFile();
+
+ $this->exportOptions['start_from'] += $records_exported;
+ $this->saveOptions($event);
+
+ return $this->exportOptions;
+ }
+
+ function getItemFields()
+ {
+ // just in case dummy user selected automtic mode & moved columns too :(
+ return array_merge($this->curItem->Fields['AvailableColumns']['options'], $this->curItem->Fields['ExportColumns']['options']);
+ }
+
+ /**
+ * Checks if field really belongs to importable field list
+ *
+ * @param string $field_name
+ * @param kCatDBItem $object
+ * @return bool
+ */
+ function validateField($field_name, &$object)
+ {
+ // 1. convert custom field
+ $field_name = preg_replace('/^Custom_(.*)/', '__CUSTOM__\\1', $field_name);
+
+ // 2. convert category field (mixed version & serparated version)
+ $field_name = preg_replace('/^Category(Path|[0-9]+)/', '__CATEGORY__Category\\1', $field_name);
+
+ $valid_fields = $object->getPossibleExportColumns();
+ return isset($valid_fields[$field_name]) || isset($valid_fields['__VIRTUAL__'.$field_name]);
+ }
+
+ /**
+ * Enter description here...
+ *
+ * @param kEvent $event
+ */
+ function performImport(&$event)
+ {
+ if (!$this->exportOptions) {
+ // load import options in case if not previously loaded in verification function
+ $this->exportOptions = $this->loadOptions($event);
+ }
+
+ $backup_category_id = $this->Application->GetVar('m_cat_id');
+ $this->Application->SetVar('m_cat_id', (int)$this->Application->RecallVar('ImportCategory') );
+
+ $this->openFile($event);
+
+ $bytes_imported = 0;
+ if ($this->exportOptions['start_from'] == 0) // first export step
+ {
+ // 1st time run
+ if ($this->exportOptions['SkipFirstRow']) {
+ $this->readRecord();
+ $this->exportOptions['start_from'] = ftell($this->filePointer);
+ $bytes_imported = ftell($this->filePointer);
+ }
+
+ $current_category_id = $this->Application->GetVar('m_cat_id');
+ if ($current_category_id > 0) {
+ $sql = 'SELECT ParentPath FROM '.TABLE_PREFIX.'Category WHERE CategoryId = '.$current_category_id;
+ $this->exportOptions['ImportCategoryPath'] = $this->Conn->GetOne($sql);
+ }
+ else {
+ $this->exportOptions['ImportCategoryPath'] = '';
+ }
+ $this->exportOptions['total_records'] = filesize($this->getImportFilename());
+ }
+ else {
+ $this->loadCache();
+ }
+
+ $this->exportFields = $this->exportOptions['ExportColumns'];
+ $this->addToCache('category_parent_path', $this->Application->GetVar('m_cat_id'), $this->exportOptions['ImportCategoryPath']);
+
+ // 2. import data
+ $this->dummyCategory =& $this->Application->recallObject('c.-tmpitem', 'c', Array('skip_autoload' => true));
+ fseek($this->filePointer, $this->exportOptions['start_from']);
+
+ while (($bytes_imported < IMPORT_CHUNK) && !feof($this->filePointer)) {
+ $data = $this->readRecord();
+ if ($data) {
+ if ($this->exportOptions['ReplaceDuplicates']) {
+ // set fields used as keys for replace duplicates code
+ $this->resetImportObject($event, IMPORT_TEMP, $data);
+ }
+
+ $this->processCurrentItem($event, $data);
+ }
+ $bytes_imported = ftell($this->filePointer) - $this->exportOptions['start_from'];
+ }
+
+ $this->closeFile();
+ $this->Application->SetVar('m_cat_id', $backup_category_id);
+
+ $this->exportOptions['start_from'] += $bytes_imported;
+ $this->storeCache('new_ids');
+
+ $this->saveOptions($event);
+
+ if ($this->exportOptions['start_from'] == $this->exportOptions['total_records']) {
+ $this->Conn->Query('TRUNCATE TABLE '.$this->cacheTable);
+ }
+
+ return $this->exportOptions;
+ }
+
+ function setCurrentID()
+ {
+ $this->curItem->setID( $this->curItem->GetDBField($this->curItem->IDField) );
+ }
+
+ function setFieldValue($field_index, $value)
+ {
+ if (empty($value)) {
+ $value = null;
+ }
+
+ $field_name = getArrayValue($this->exportFields, $field_index);
+ if ($field_name == 'ResourceId') {
+ return false;
+ }
+
+ if (substr($field_name, 0, 7) == 'Custom_') {
+ $field_name = 'cust_'.substr($field_name, 7);
+ $this->curItem->SetField($field_name, $value);
+ }
+ elseif ($field_name == 'CategoryPath' || $field_name == '__CATEGORY__CategoryPath') {
+ $this->curItem->CategoryPath = $value ? explode($this->exportOptions['CategorySeparator'], $value) : Array();
+ }
+ elseif (substr($field_name, 0, 8) == 'Category') {
+ $this->curItem->CategoryPath[ (int)substr($field_name, 8) - 1 ] = $value;
+ }
+ elseif (substr($field_name, 0, 20) == '__CATEGORY__Category') {
+ $this->curItem->CategoryPath[ (int)substr($field_name, 20) ] = $value;
+ }
+ elseif (substr($field_name, 0, 11) == '__VIRTUAL__') {
+ $field_name = substr($field_name, 11);
+ $this->curItem->SetField($field_name, $value);
+ }
+ else {
+ $this->curItem->SetField($field_name, $value);
+ }
+
+ $pseudo_error = getArrayValue($this->curItem->FieldErrors, $field_name, 'pseudo');
+ if ($pseudo_error) {
+ $this->curItem->SetDBField($field_name, null);
+ unset($this->curItem->FieldErrors[$field_name]);
+ }
+ }
+
+ function resetImportObject(&$event, $object_type, $record_data = null)
+ {
+ switch ($object_type) {
+ case IMPORT_TEMP:
+ $this->curItem =& $event->getObject( Array('skip_autoload' => true) );
+ break;
+
+ case IMPORT_LIVE:
+ $this->curItem =& $this->Application->recallObject($event->Prefix.'.-tmpitem'.$event->Special, $event->Prefix, Array('skip_autoload' => true));
+ break;
+ }
+ $this->curItem->Clear();
+ $this->customFields = $this->Application->getUnitOption($event->Prefix, 'CustomFields');
+
+ if (isset($record_data)) {
+ $this->setImportData($record_data);
+ }
+ }
+
+ function setImportData($record_data)
+ {
+ foreach ($record_data as $field_index => $field_value) {
+ $this->setFieldValue($field_index, $field_value);
+ }
+ $this->setCurrentID();
+ }
+
+
+ function getItemCategory()
+ {
+ static $lang_prefix = null;
+ $backup_category_id = $this->Application->GetVar('m_cat_id');
+
+ $category_id = $this->getFromCache('category_names', implode(':', $this->curItem->CategoryPath));
+ if ($category_id) {
+ $this->Application->SetVar('m_cat_id', $category_id);
+ return $category_id;
+ }
+
+ if (is_null($lang_prefix)) {
+ $lang_prefix = 'l'.$this->Application->GetVar('m_lang').'_';
+ }
+
+ foreach ($this->curItem->CategoryPath as $category_index => $category_name) {
+ if (!$category_name) continue;
+ $category_key = crc32( implode(':', array_slice($this->curItem->CategoryPath, 0, $category_index + 1) ) );
+
+ $category_id = $this->getFromCache('category_names', $category_key);
+ if ($category_id === false) {
+ // get parent category path to search only in it
+ $current_category_id = $this->Application->GetVar('m_cat_id');
+// $parent_path = $this->getParentPath($current_category_id);
+
+ // get category id from database by name
+ $sql = 'SELECT CategoryId
+ FROM '.TABLE_PREFIX.'Category
+ WHERE ('.$lang_prefix.'Name = '.$this->Conn->qstr($category_name).') AND (ParentId = '.$current_category_id.')';
+ $category_id = $this->Conn->GetOne($sql);
+
+ if ($category_id === false) {
+ // category not in db -> create
+ $category_fields = Array( $lang_prefix.'Name' => $category_name, $lang_prefix.'Description' => $category_name,
+ 'Status' => STATUS_ACTIVE, 'ParentId' => $current_category_id, 'AutomaticFilename' => 1
+ );
+ $this->dummyCategory->SetDBFieldsFromHash($category_fields);
+ if ($this->dummyCategory->Create()) {
+ $category_id = $this->dummyCategory->GetID();
+ $this->addToCache('category_parent_path', $category_id, $this->dummyCategory->GetDBField('ParentPath'));
+ $this->addToCache('category_names', $category_key, $category_id);
+ }
+ }
+ else {
+ $this->addToCache('category_names', $category_key, $category_id);
+ }
+ }
+
+ if ($category_id) {
+ $this->Application->SetVar('m_cat_id', $category_id);
+ }
+ }
+ if (!$this->curItem->CategoryPath) {
+ $category_id = $backup_category_id;
+ }
+
+ return $category_id;
+ }
+
+ /**
+ * Enter description here...
+ *
+ * @param kEvent $event
+ */
+ function processCurrentItem(&$event, $record_data)
+ {
+ $save_method = 'Create';
+ $load_keys = Array();
+
+ // create/update categories
+ $backup_category_id = $this->Application->GetVar('m_cat_id');
+
+ // perform replace duplicates code
+ if ($this->exportOptions['ReplaceDuplicates']) {
+ // get replace keys first, then reset current item to empty one
+ $category_id = $this->getItemCategory();
+ if ($this->exportOptions['CheckDuplicatesMethod'] == 1) {
+ if ($this->curItem->GetID()) {
+ $load_keys = Array($this->curItem->IDField => $this->curItem->GetID());
+ }
+ }
+ else {
+ $key_fields = $this->exportOptions['DuplicateCheckFields'];
+ foreach ($key_fields as $key_field) {
+ $load_keys[$key_field] = $this->curItem->GetDBField($key_field);
+ }
+ }
+
+ $this->resetImportObject($event, IMPORT_LIVE);
+
+ if (count($load_keys)) {
+ $where_clause = '';
+ foreach ($load_keys as $field_name => $field_value) {
+ if (preg_match('/^cust_(.*)/', $field_name, $regs)) {
+ $custom_id = array_search($regs[1], $this->customFields);
+ $field_name = 'l'.$this->Application->GetVar('m_lang').'_cust_'.$custom_id;
+ $where_clause .= '(custom_data.`'.$field_name.'` = '.$this->Conn->qstr($field_value).') AND ';
+ }
+ else {
+ $where_clause .= '(item_table.`'.$field_name.'` = '.$this->Conn->qstr($field_value).') AND ';
+ }
+
+ }
+ $where_clause = preg_replace('/(.*) AND $/', '\\1', $where_clause);
+
+ $item_id = $this->getFromCache('new_ids', crc32($where_clause));
+ if (!$item_id) {
+ if ($this->exportOptions['CheckDuplicatesMethod'] == 2) {
+ // by other fields
+ $parent_path = $this->getParentPath($category_id);
+ $where_clause = '(c.ParentPath LIKE "'.$parent_path.'%") AND '.$where_clause;
+ }
+
+ $cdata_table = $this->Application->getUnitOption($event->Prefix.'-cdata', 'TableName');
+ $sql = 'SELECT '.$this->curItem->IDField.'
+ FROM '.$this->curItem->TableName.' item_table
+ LEFT JOIN '.$cdata_table.' custom_data ON custom_data.ResourceId = item_table.ResourceId
+ LEFT JOIN '.TABLE_PREFIX.'CategoryItems ci ON ci.ItemResourceId = item_table.ResourceId
+ LEFT JOIN '.TABLE_PREFIX.'Category c ON c.CategoryId = ci.CategoryId
+ WHERE '.$where_clause;
+ $item_id = $this->Conn->GetOne($sql);
+ }
+ $save_method = $item_id && $this->curItem->Load($item_id) ? 'Update' : 'Create';
+ if ($save_method == 'Update') {
+ // replace id from csv file with found id
+ $record_data[ array_search($this->curItem->IDField, $this->exportFields) ] = $item_id;
+ }
+ }
+
+ $this->setImportData($record_data);
+ }
+ else {
+ $this->resetImportObject($event, IMPORT_LIVE, $record_data);
+ $category_id = $this->getItemCategory();
+ }
+
+ // create main record
+ if ($save_method == 'Create') {
+ $this->fillRequiredFields($this->false, $this->curItem, true);
+ }
+
+// $sql_start = getmicrotime();
+ if (!$this->curItem->$save_method()) {
+ return false;
+ }
+// $sql_end = getmicrotime();
+// $this->saveLog('SQL ['.$save_method.'] Time: '.($sql_end - $sql_start).'s');
+
+ if ($load_keys && ($save_method == 'Create') && $this->exportOptions['ReplaceDuplicates']) {
+ // map new id to old id
+ $this->addToCache('new_ids', crc32($where_clause), $this->curItem->GetID() );
+ }
+
+ // assign item to categories
+ $this->curItem->assignToCategory($category_id, false);
+
+ $this->Application->SetVar('m_cat_id', $backup_category_id);
+ return true;
+ }
+
+ /*function saveLog($msg)
+ {
+ static $first_time = true;
+
+ $fp = fopen(FULL_PATH.'/sqls.log', $first_time ? 'w' : 'a');
+ fwrite($fp, $msg."\n");
+ fclose($fp);
+
+ $first_time = false;
+ }*/
+
+ /**
+ * Returns category parent path, if possible, then from cache
+ *
+ * @param int $category_id
+ * @return string
+ */
+ function getParentPath($category_id)
+ {
+ $parent_path = $this->getFromCache('category_parent_path', $category_id);
+ if ($parent_path === false) {
+ $sql = 'SELECT ParentPath
+ FROM '.TABLE_PREFIX.'Category
+ WHERE CategoryId = '.$category_id;
+ $parent_path = $this->Conn->GetOne($sql);
+ $this->addToCache('category_parent_path', $category_id, $parent_path);
+ }
+ return $parent_path;
+ }
+
+ function getFileExtension()
+ {
+ return $this->exportOptions['ExportFormat'] == 1 ? 'csv' : 'xml';
+ }
+
+ function getLineSeparator($option = 'LineEndings')
+ {
+ return $this->exportOptions[$option] == 1 ? "\r\n" : "\n";
+ }
+
+ /**
+ * Returns field caption for any exported field
+ *
+ * @param string $field
+ * @return string
+ */
+ function getFieldCaption($field)
+ {
+ if (substr($field, 0, 10) == '__CUSTOM__')
+ {
+ $ret = 'Custom_'.substr($field, 10, strlen($field) );
+ }
+ elseif (substr($field, 0, 12) == '__CATEGORY__')
+ {
+ return $this->getCategoryTitle();
+ }
+ elseif (substr($field, 0, 11) == '__VIRTUAL__') {
+ $ret = substr($field, 11);
+ }
+ else
+ {
+ $ret = $field;
+ }
+
+ return Array($ret);
+ }
+
+ /**
+ * Returns requested field value (including custom fields and category fields)
+ *
+ * @param string $field
+ * @return string
+ */
+ function getFieldValue($field)
+ {
+ if (substr($field, 0, 10) == '__CUSTOM__') {
+ $field = 'cust_'.substr($field, 10, strlen($field));
+ $ret = $this->curItem->GetField($field);
+ }
+ elseif (substr($field, 0, 12) == '__CATEGORY__') {
+ return $this->getCategoryPath();
+ }
+ elseif (substr($field, 0, 11) == '__VIRTUAL__') {
+ $field = substr($field, 11);
+ return $this->curItem->GetField($field);
+ }
+ else
+ {
+ $ret = $this->curItem->GetField($field);
+ }
+
+ $ret = str_replace("\r\n", $this->getLineSeparator('LineEndingsInside'), $ret);
+ return Array($ret);
+ }
+
+ /**
+ * Returns category field(-s) caption based on export mode
+ *
+ * @return string
+ */
+ function getCategoryTitle()
+ {
+ // category path in separated fields
+ $category_count = $this->getMaxCategoryLevel();
+ if ($this->exportOptions['CategoryFormat'] == 1)
+ {
+ // category path in one field
+ return $category_count ? Array('CategoryPath') : Array();
+ }
+ else
+ {
+ $i = 0;
+ $ret = Array();
+ while ($i < $category_count) {
+ $ret[] = 'Category'.($i + 1);
+ $i++;
+ }
+ return $ret;
+ }
+ }
+
+ /**
+ * Returns category path in required format for current link
+ *
+ * @return string
+ */
+ function getCategoryPath()
+ {
+ $category_id = $this->curItem->GetDBField('CategoryId');
+ $category_path = $this->getFromCache('category_path', $category_id);
+ if (!$category_path)
+ {
+ $sql = 'SELECT CachedNavbar
+ FROM '.TABLE_PREFIX.'Category
+ WHERE CategoryId = '.$category_id;
+ $category_path = $this->Conn->GetOne($sql);
+ $category_path = $category_path ? explode('>', $category_path) : Array();
+
+ if ($this->exportOptions['IsBaseCategory']) {
+ $i = $this->exportOptions['BaseLevel'];
+ while ($i > 0) {
+ array_shift($category_path);
+ $i--;
+ }
+ }
+
+ $category_count = $this->getMaxCategoryLevel();
+ if ($this->exportOptions['CategoryFormat'] == 1) {
+ // category path in single field
+ $category_path = $category_count ? Array( implode($this->exportOptions['CategorySeparator'], $category_path) ) : Array();
+ }
+ else {
+ // category path in separated fields
+ $levels_used = count($category_path);
+ if ($levels_used < $category_count)
+ {
+ $i = 0;
+ while ($i < $category_count - $levels_used) {
+ $category_path[] = '';
+ $i++;
+ }
+ }
+ }
+ $this->addToCache('category_path', $category_id, $category_path);
+ }
+
+ return $category_path;
+ }
+
+ /**
+ * Get maximal category deep level from links beeing exported
+ *
+ * @return int
+ */
+ function getMaxCategoryLevel()
+ {
+ static $max_level = -1;
+
+ if ($max_level != -1)
+ {
+ return $max_level;
+ }
+
+ $sql = 'SELECT IF(c.CategoryId IS NULL, 0, MAX( LENGTH(c.ParentPath) - LENGTH( REPLACE(c.ParentPath, "|", "") ) - 1 ))
+ FROM '.$this->curItem->TableName.' item_table
+ LEFT JOIN '.TABLE_PREFIX.'CategoryItems ci ON item_table.ResourceId = ci.ItemResourceId
+ LEFT JOIN '.TABLE_PREFIX.'Category c ON c.CategoryId = ci.CategoryId
+ WHERE (ci.PrimaryCat = 1) AND ';
+
+ $where_clause = '';
+ if ($this->exportOptions['export_ids'] === false) {
+ // get links from current category & all it's subcategories
+ if ($this->exportOptions['export_cats_ids'][0] == 0) {
+ $where_clause = 1;
+ }
+ else {
+ foreach ($this->exportOptions['export_cats_ids'] as $category_id) {
+ $where_clause .= '(c.ParentPath LIKE "%|'.$category_id.'|%") OR ';
+ }
+ $where_clause = preg_replace('/(.*) OR $/', '\\1', $where_clause);
+ }
+ }
+ else {
+ // get only selected links
+ $where_clause = $this->curItem->IDField.' IN ('.implode(',', $this->exportOptions['export_ids']).')';
+ }
+
+ $max_level = $this->Conn->GetOne($sql.'('.$where_clause.')');
+
+ if ($this->exportOptions['IsBaseCategory'] ) {
+ $max_level -= $this->exportOptions['BaseLevel'];
+ }
+
+ return $max_level;
+ }
+
+ /**
+ * Saves one record to export file
+ *
+ * @param Array $fields_hash
+ */
+ function writeRecord($fields_hash)
+ {
+ fputcsv2($this->filePointer, $fields_hash, $this->exportOptions['FieldsSeparatedBy'], $this->exportOptions['FieldsEnclosedBy'], $this->getLineSeparator() );
+ }
+
+ function readRecord()
+ {
+ return fgetcsv($this->filePointer, 10000, $this->exportOptions['FieldsSeparatedBy'], $this->exportOptions['FieldsEnclosedBy']);
+ }
+
+ function saveOptions(&$event, $options = null)
+ {
+ if (!isset($options)) {
+ $options = $this->exportOptions;
+ }
+ $this->Application->StoreVar($event->getPrefixSpecial().'_options', serialize($options) );
+ }
+
+ function loadOptions(&$event)
+ {
+ return unserialize($this->Application->RecallVar($event->getPrefixSpecial().'_options'));
+ }
+ }
+
+?>
Property changes on: branches/unlabeled/unlabeled-1.20.2/kernel/units/general/cat_dbitem_export.php
___________________________________________________________________
Added: cvs2svn:cvs-rev
## -0,0 +1 ##
+1.20
\ No newline at end of property
Added: svn:executable
## -0,0 +1 ##
+*
\ No newline at end of property
Index: branches/unlabeled/unlabeled-1.20.2/kernel/units/general/inp_ses_storage.php
===================================================================
--- branches/unlabeled/unlabeled-1.20.2/kernel/units/general/inp_ses_storage.php (nonexistent)
+++ branches/unlabeled/unlabeled-1.20.2/kernel/units/general/inp_ses_storage.php (revision 5538)
@@ -0,0 +1,118 @@
+<?php
+
+ class InpSession extends Session
+ {
+ function Init($prefix,$special)
+ {
+ $this->SessionTimeout = $this->Application->ConfigValue('SessionTimeout');
+
+ $path = (BASE_PATH == '') ? '/' : BASE_PATH;
+ if ( $this->Application->IsAdmin() ) $path = rtrim($path, '/').'/admin';
+ $this->SetCookiePath($path);
+
+ $cookie_name = $this->Application->ConfigValue('SessionCookieName');
+ $this->SetCookieName($cookie_name ? $cookie_name : 'sid');
+
+ $this->SetCookieDomain(SERVER_NAME);
+
+ if( $this->Application->IsAdmin() )
+ {
+ $mode = constOn('IS_INSTALL') ? smCOOKIES_ONLY : smAUTO;
+ }
+ else
+ {
+ $ses_mode = $this->Application->ConfigValue('CookieSessions');
+ if ($ses_mode == 2) $mode = smAUTO;
+ if ($ses_mode == 1) $mode = smCOOKIES_ONLY;
+ if ($ses_mode == 0) $mode = smGET_ONLY;
+ }
+ $this->SetMode($mode);
+
+ parent::Init($prefix,$special);
+
+ if( !$this->Application->IsAdmin() && $this->GetField('PortalUserId') <= 0 )
+ {
+ $group_list = $this->Application->ConfigValue('User_GuestGroup').','.$this->Application->ConfigValue('User_LoggedInGroup');
+ $this->SetField('GroupId', $this->Application->ConfigValue('User_GuestGroup'));
+ $this->SetField('GroupList', $group_list);
+ }
+ }
+ }
+
+class InpSessionStorage extends SessionStorage {
+
+ function Init($prefix,$special)
+ {
+ parent::Init($prefix,$special);
+ $this->setTableName(TABLE_PREFIX.'UserSession');
+ $this->SessionDataTable = TABLE_PREFIX.'SessionData';
+ $this->setIDField('SessionKey');
+ $this->TimestampField = 'LastAccessed';
+ $this->DataValueField = 'VariableValue';
+ $this->DataVarField = 'VariableName';
+ }
+
+ function LocateSession($sid)
+ {
+ $res = parent::LocateSession($sid);
+ if ($res) {
+ $this->Expiration += $this->SessionTimeout;
+ }
+ return $res;
+ }
+
+ function UpdateSession(&$session)
+ {
+ $time = adodb_mktime();
+ // Update LastAccessed only if it's newer than 1/10 of session timeout - perfomance optimization to eliminate needless updates on every click
+ if ($time - $this->DirectVars['LastAccessed'] > $this->SessionTimeout/10) {
+ $this->SetField($session, $this->TimestampField, $time);
+ }
+ }
+
+
+ function StoreSession(&$session, $additional_fields = Array())
+ {
+ $fields_hash = Array( 'PortalUserId' => $this->Application->IsAdmin() ? 0 : -2, // Guest
+ 'Language' => $this->Application->GetDefaultLanguageId(),
+ 'Theme' => $this->Application->GetDefaultThemeId(),
+ 'IpAddress' => $_SERVER['REMOTE_ADDR'],
+ 'GroupList' => $this->Application->ConfigValue('User_GuestGroup'),
+ 'CurrentTempKey'=> $session->SID,
+
+ );
+
+ parent::StoreSession($session, $fields_hash);
+ }
+
+ function GetExpiredSIDs()
+ {
+ $query = ' SELECT '.$this->IDField.' FROM '.$this->TableName.' WHERE '.$this->TimestampField.' < '.(adodb_mktime()-$this->SessionTimeout);
+ $ret = $this->Conn->GetCol($query);
+ if($ret) {
+ $this->DeleteEditTables();
+ }
+ return $ret;
+
+ }
+
+ function DeleteEditTables()
+ {
+ $tables = $this->Conn->GetCol('SHOW TABLES');
+ $mask_edit_table = '/'.TABLE_PREFIX.'ses_(.*)_edit_(.*)/';
+ $mask_search_table = '/'.TABLE_PREFIX.'ses_(.*?)_(.*)/';
+
+ $sql='SELECT COUNT(*) FROM '.$this->TableName.' WHERE '.$this->IDField.' = \'%s\'';
+ foreach($tables as $table)
+ {
+ if( preg_match($mask_edit_table,$table,$rets) || preg_match($mask_search_table,$table,$rets) )
+ {
+ $sid=$rets[1];
+ $is_alive = $this->Conn->GetOne( sprintf($sql,$sid) );
+ if(!$is_alive) $this->Conn->Query('DROP TABLE IF EXISTS '.$table);
+ }
+ }
+ }
+}
+
+?>
\ No newline at end of file
Property changes on: branches/unlabeled/unlabeled-1.20.2/kernel/units/general/inp_ses_storage.php
___________________________________________________________________
Added: cvs2svn:cvs-rev
## -0,0 +1 ##
+1.20
\ No newline at end of property
Added: svn:executable
## -0,0 +1 ##
+*
\ No newline at end of property
Index: branches/unlabeled/unlabeled-1.20.2/kernel/include/image.php
===================================================================
--- branches/unlabeled/unlabeled-1.20.2/kernel/include/image.php (nonexistent)
+++ branches/unlabeled/unlabeled-1.20.2/kernel/include/image.php (revision 5538)
@@ -0,0 +1,1255 @@
+<?php
+
+class clsImage extends clsParsedItem
+{
+ var $Pending;
+
+ function clsImage($id=NULL)
+ {
+ global $objSession;
+
+ $this->clsParsedItem();
+ $this->tablename = GetTablePrefix()."Images";
+ $this->Pending = FALSE;
+ $this->id_field = "ImageId";
+ $this->type=-30;
+ $this->TagPrefix = "image";
+ $this->NoResourceId=1;
+ if($id)
+ $this->LoadFromDatabase($id);
+ //$this->SetDebugLevel(0);
+ }
+
+ function DetectChanges($name, $value)
+ {
+ global $objSession;
+ //print_pre($_POST);
+ if (!isset($this->Data[$name]) ) return false;
+
+ if ($this->Data[$name] != $value) {
+ //echo "$name Modified tt ".$this->Data[$name]." tt $value<br>";
+ if (!stristr($name, 'Resource') && !stristr($name, 'ImageId')) {
+ if ($objSession->GetVariable("HasChanges") != 1) {
+ $objSession->SetVariable("HasChanges", 2);
+ }
+ }
+ }
+ }
+
+ function GetFileName($thumb = 0)
+ {
+ global $pathtoroot;
+
+ if($thumb)
+ {
+ $p = $this->Get("ThumbPath");
+ }
+ else
+ {
+ $p = $this->Get("LocalPath");
+ if(!strlen($p) && $this->Get("SameImages"))
+ {
+ $p = $this->Get("ThumbPath");
+ }
+ }
+
+ if(strlen($p))
+ {
+ $parts = pathinfo($pathtoroot.$p);
+ $filename = $parts["basename"];
+ }
+ else
+ $filename = "";
+
+ return $filename;
+ }
+
+ function GetImageDir()
+ {
+ global $pathtoroot;
+
+ $p = $this->Get("ThumbPath");
+ $localp = $this->Get("LocalPath");
+ if(strlen($p))
+ {
+ $parts = pathinfo($pathtoroot.$p);
+ $d = $parts["dirname"]."/";
+ }
+ elseif (strlen($localp))
+ {
+ $parts = pathinfo($pathtoroot.$localp);
+ $d = $parts["dirname"]."/";
+ }
+
+ if($this->Pending)
+ $d .= "pending/";
+
+ return $d;
+ }
+
+
+ function Delete()
+ {
+ $this->DeleteLocalImage();
+ parent::Delete();
+ }
+
+ function Update($UpdatedBy=NULL,$modificationDate = null)
+ {
+ global $Errors, $objSession;
+
+ if(count($this->m_dirtyFieldsMap) == 0)
+ return true;
+
+ $this->SetModified($UpdatedBy,$modificationDate);
+ $sql = "UPDATE ".$this->tablename ." SET ";
+ $first = 1;
+
+ foreach ($this->m_dirtyFieldsMap as $key => $value)
+ {
+ if(!is_numeric($key) && $key != $this->IdField())
+ {
+ if($first)
+ {
+ if(isset($GLOBALS['_CopyFromEditTable']))
+ $sql = sprintf("%s %s=%s",$sql,$key,$this->adodbConnection->qstr(($value)));
+ else
+ $sql = sprintf("%s %s=%s",$sql,$key,$this->adodbConnection->qstr(stripslashes($value)));
+ $first = 0;
+ }
+ else
+ {
+ if(isset($GLOBALS['_CopyFromEditTable']))
+ $sql = sprintf("%s, %s=%s",$sql,$key,$this->adodbConnection->qstr(($value)));
+ else
+ $sql = sprintf("%s, %s=%s",$sql,$key,$this->adodbConnection->qstr(stripslashes($value)));
+ }
+ }
+ }
+
+ $sql = sprintf("%s WHERE %s = '%s'",$sql, $this->IdField(), $this->UniqueId());
+
+ if($this->debuglevel>0)
+ echo $sql."<br>";
+ if ($this->adodbConnection->Execute($sql) === false)
+ {
+ $Errors->AddError("error.DatabaseError",NULL,$this->adodbConnection->ErrorMsg(),"",get_class($this),"Update");
+ return false;
+ }
+
+ if ($objSession->GetVariable("HasChanges") == 2) {
+ $objSession->SetVariable("HasChanges", 1);
+ }
+
+ /* if ($this->adodbConnection->Affected_Rows() > 0) {
+ $objSession->SetVariable("HasChanges", 1);
+ }*/
+
+ return true;
+ }
+
+ function LoadFromDatabase($Id)
+ {
+ global $Errors;
+
+ if(!isset($Id))
+ {
+ $Errors->AddError("error.AppError",NULL,'Internal error: LoadFromDatabase id',"",get_class($this),"LoadFromDatabase");
+ return false;
+ }
+
+ $sql = sprintf("SELECT * FROM ".$this->tablename." WHERE ImageId = '%s'",$Id);
+
+ $result = $this->adodbConnection->Execute($sql);
+ if ($result === false || $result->EOF)
+ {
+ $Errors->AddError("error.DatabaseError",NULL,$this->adodbConnection->ErrorMsg(),"",get_class($this),"LoadFromDatabase");
+ return false;
+ }
+
+ $data = $result->fields;
+
+ $this->SetFromArray($data);
+ $this->Clean();
+ return true;
+ }
+
+ function LoadFromResource($Id,$ImageIndex)
+ {
+ global $Errors;
+
+ if(!isset($Id) || !isset($ImageIndex))
+ {
+ $Errors->AddError("error.AppError",NULL,'Internal error: LoadFromDatabase id',"",get_class($this),"LoadFromResource");
+ return false;
+ }
+
+ $sql = sprintf("SELECT * FROM ".$this->tablename." WHERE ResourceId = '%s'AND ImageIndex = '%s'",$Id,$ImageIndex);
+
+ $result = $this->adodbConnection->Execute($sql);
+ if ($result === false || $result->EOF)
+ {
+ // $Errors->AddError("error.DatabaseError",NULL,$this->adodbConnection->ErrorMsg(),"",get_class($this),"LoadFromResource");
+ return false;
+ }
+
+ $data = $result->fields;
+
+ $this->SetFromArray($data);
+
+ return true;
+ }
+
+ function LocalImageExists()
+ {
+ global $objConfig, $pathtoroot;
+ $result=FALSE;
+ if($this->Get("LocalImage")==1 && $this->Get("SameImages")==0)
+ {
+ $imagepath = $pathtoroot.$this->Get("LocalPath");
+ // $imagepath = $this->GetImageDir().$this->GetFileName();
+
+ // echo "PATH: ".$this->GetImageDir()."; FILE: ".$this->GetFileName()."<BR>";
+
+ if(strlen($imagepath)>0)
+ {
+ $result = file_exists($imagepath);
+ }
+ }
+ return $result;
+ }
+
+ function LocalThumbExists()
+ {
+ $result=FALSE;
+ global $objConfig, $pathtoroot;
+
+ if($this->Get("LocalThumb")==1)
+ {
+ //$imagepath = $pathtoroot.$this->Get("ThumbPath");
+ $imagepath = $this->GetImageDir().$this->GetFileName(1);
+ if(strlen($imagepath)>0)
+ {
+ $result = file_exists($imagepath);
+ }
+ }
+ return $result;
+ }
+
+
+ function DeleteLocalImage($Thumb=TRUE,$Full=TRUE)
+ {
+ global $pathtoroot;
+
+ if($Full)
+ {
+ if($this->LocalImageExists())
+ {
+ // $filename = $this->GetImageDir().$this->GetFileName();
+ $filename = $pathtoroot.$this->Get("LocalPath");
+ // echo "FULL: $filename<BR>\n";
+ @unlink($filename);
+ }
+ }
+
+ if($Thumb)
+ {
+ if($this->LocalThumbExists())
+ {
+ $filename = $this->GetImageDir().$this->GetFileName(1);
+ // echo "THUMB: $filename<BR>\n";
+ @unlink($filename);
+ }
+ }
+ }
+
+ function StoreUploadedImage($file, $rewrite_name=1,$DestDir,$IsThumb=0,$IsUpload=TRUE)
+ {
+ /* move the uploaded image to its final location and update the LocalPath property */
+ /* returns the destination filename on success */
+ global $objConfig,$pathtoroot;
+
+ $Dest_Dir = $DestDir;
+ if($this->Pending)
+ $Dest_Dir .= "pending/";
+
+ if(((int)$file["error"]==0) && (substr($file["type"],0,6)=="image/") && @getimagesize($file["tmp_name"]) )
+ {
+ $parts = pathinfo($file["name"]);
+ $ext = strtolower($parts["extension"]);
+
+ if( $GLOBALS['debuglevel'] ) echo "Processing ".$file["tmp_name"]."<br>\n";
+
+ if($rewrite_name==1)
+ {
+
+ if($IsThumb)
+ $filename = "th_";
+ $filename .= $this->Get("ResourceId")."_".$this->Get("ImageIndex").".".$ext;
+ }
+ else
+ {
+ $filename = $file["name"];
+ }
+ $destination = $pathtoroot.$Dest_Dir.$filename;
+ if( $GLOBALS['debuglevel'] ) echo $file["tmp_name"]."=>".$destination."<br>\n";
+ if($IsUpload==TRUE)
+ {
+ $result = @move_uploaded_file($file["tmp_name"],$destination);
+ }
+ else
+ $result = copy($file["tmp_name"],$destination);
+ if($result)
+ {
+ @chmod($destination, 0666);
+ return $Dest_Dir.$filename;
+ }
+ else
+ return "";
+ }
+ else
+ return "";
+ }
+
+ function CopyToPending()
+ {
+ global $pathtoroot;
+
+ $ThumbPath = (strlen($this->Get("ThumbPath"))>0) ? $pathtoroot.$this->Get("ThumbPath") : '';
+ $FullPath = strlen($this->Get("LocalPath")) ? $pathtoroot.$this->Get("LocalPath") : '';
+
+ $dest = $this->GetImageDir()."pending/";
+
+
+ // echo "DESTIN DIR: $dest<BR>";
+ // echo "THUMB PATH: $ThumbPath <BR>";
+
+ if(strlen($ThumbPath))
+ {
+ if(file_exists($ThumbPath))
+ {
+ $p = pathinfo($ThumbPath);
+ $d = $dest.$p["basename"];
+ if(file_exists($d))
+ unlink($d);
+ copy($ThumbPath,$d);
+ @chmod($ThumbPath.$d, 0666);
+ }
+ }
+
+
+ if(strlen($FullPath))
+ {
+ if(file_exists($FullPath))
+ {
+ $p = pathinfo($FullPath);
+ $d = $dest.$p["basename"];
+ if(file_exists($d))
+ unlink($d);
+ copy($FullPath,$d);
+ @chmod($FullPath.$d, 0666);
+ }
+ }
+ }
+
+ function CopyFromPending()
+ {
+ global $pathtoroot,$pathchar;
+
+ $ThumbPath = $this->Get("ThumbPath");
+ $FullPath = $this->Get("LocalPath");
+
+ // $src = $this->GetImageDir()."pending/";
+ $src = $this->GetImageDir();
+
+ if(strlen($ThumbPath))
+ {
+ if(strpos($ThumbPath,"pending/"))
+ {
+ if(file_exists($pathtoroot.$ThumbPath))
+ {
+ $path = pathinfo($pathtoroot.$ThumbPath);
+ $p = explode("/",$ThumbPath);
+ unset($p[count($p)-2]);
+
+ $d = $pathtoroot.implode("/",$p);
+
+ if(file_exists($d))
+ unlink($d);
+
+ copy($pathtoroot.$ThumbPath,$d);
+ @chmod($pathtoroot.$ThumbPath.$d, 0666);
+ unlink($pathtoroot.$ThumbPath);
+ }
+
+ }
+ }
+ if(strlen($FullPath))
+ {
+ if(file_exists($pathtoroot.$FullPath))
+ {
+ if(strpos($FullPath,"pending/"))
+ {
+ $path = pathinfo($pathtoroot.$FullPath);
+ $p = explode("/",$FullPath);
+ unset($p[count($p)-2]);
+
+ $d = $pathtoroot.implode("/",$p);
+
+ if(file_exists($d))
+ unlink($d);
+ copy($pathtoroot.$FullPath,$d);
+ @chmod($pathtoroot.$FullPath.$d, 0666);
+ unlink($pathtoroot.$FullPath);
+ }
+ }
+ }
+ }
+
+ function DeleteFromPending()
+ {
+ global $pathtoroot;
+ $ThumbPath = $pathtoroot.$this->Get("ThumbPath");
+ $FullPath = $pathtoroot.$this->Get("LocalPath");
+
+ $src = $this->GetImageDir()."pending/";
+ $p = pathinfo($ThumbPath);
+ $d = $src.$p["basename"];
+ if(file_exists($d))
+ @unlink($d);
+
+ $p = pathinfo($FullPath);
+ $d = $src.$p["basename"];
+ if(file_exists($d))
+ @unlink($d);
+ }
+
+ function RenameFiles($OldResId,$NewResId)
+ {
+ global $pathtoroot;
+
+ if($this->Pending)
+ {
+ $ThumbPath = $this->GetImageDir().$this->GetFileName(TRUE);
+ }
+ else
+ $ThumbPath = $pathtoroot.$this->Get("ThumbPath");
+ $parts = pathinfo($ThumbPath);
+ $ext = $parts["extension"];
+ $pending="";
+ if($this->Pending)
+ {
+ $pending="pending/";
+ $FullPath = $this->GetImageDir().$this->GetFileName(FALSE);
+ }
+ else
+ $FullPath = $pathtoroot.$this->Get("LocalPath");
+
+ $NewThumb = $pathtoroot."kernel/images/".$pending."th_$NewResId_".$this->Get("ImageIndex").".$ext";
+ $NewFull = $pathtoroot."kernel/images/".$pending."$NewResId_".$this->Get("ImageIndex").".$ext";
+ if(file_exists($ThumbPath))
+ {
+ @rename($ThumbPath,$NewThumb);
+ }
+
+ if(file_exists($FullPath))
+ {
+ @rename($FullPath,$NewFull);
+ }
+
+ }
+
+ function ReplaceImageFile($file)
+ {
+ global $objConfig;
+
+ if($file["error"]==0)
+ {
+ $this->DeleteLocalImage();
+ move_uploaded_file($file,$this->Get("LocalPath"));
+ @chmod($this->Get("LocalPath"), 0666);
+ }
+ }
+
+ function FullURL($ForceNoThumb=FALSE,$Default="kernel/images/noimage.gif")
+ {
+ global $rootURL, $objConfig,$pathtoroot;
+
+ if($this->Get('SameImages') && !$ForceNoThumb)
+ if (!(($this->Get('LocalImage') && strlen($this->Get('LocalPath'))) ||
+ ($this->Get('LocalImage') == 0 && strlen($this->Get('Url')))))
+ {
+ return $this->ThumbURL();
+ }
+
+ if(strlen($this->Get("Url")))
+ return $this->Get("Url");
+ if($this->Get("LocalImage")=="1")
+ {
+ $url = $this->Get("LocalPath");
+ //$url = $this->GetImageDir().$this->GetFileName();
+ if(file_exists($pathtoroot.$url))
+ {
+ if(strlen($url))
+ {
+ $url = $rootURL.$url;
+ return $url;
+ }
+ else
+ {
+ if(strlen($Default))
+ $url = $rootURL.$Default;
+ return $url;
+ }
+ }
+ else
+ {
+ if(strlen($Default))
+ {
+ return $rootURL.$Default;
+ }
+ else
+ return "";
+ }
+ }
+ else
+ {
+ if(strlen($Default))
+ {
+ return $rootURL.$Default;
+ }
+ else
+ return "";
+ }
+ }
+
+ function ThumbURL()
+ {
+ global $rootURL, $pathtoroot, $objConfig;
+
+ if(strlen($this->Get("ThumbUrl")))
+ {
+ return $this->Get("ThumbUrl");
+ }
+
+ if($this->Get("LocalThumb")=="1")
+ {
+ $url = $this->Get("ThumbPath");
+ //$url = $this->GetImageDir().$this->GetFileName();
+ if(file_exists($pathtoroot.$url))
+ {
+ if(strlen($url))
+ {
+ $url = $rootURL.$url;
+ }
+ else
+ $url = $rootURL."kernel/images/noimage.gif";
+ return $url;
+ }
+ else
+ return $rootURL."kernel/images/noimage.gif";
+ }
+ else
+ {
+ return $rootURL."kernel/images/noimage.gif";
+ }
+ }
+
+ function ParseObject($element)
+ {
+ $extra_attribs = ExtraAttributes($element->attributes);
+ if(strtolower($element->name)==$this->TagPrefix)
+ {
+ $field = strtolower($element->attributes["_field"]);
+ switch($field)
+ {
+ case "name":
+ $ret = $this->Get("Name");
+ break;
+ case "alt":
+ $ret = $this->Get("AltName");
+ break;
+ case "full_url":
+ $ret = $this->FullURL();
+ break;
+ case "thumb_url":
+ $ret = $this->ThumbURL();
+ break;
+ }
+ }
+ else
+ $ret = $element->Execute();
+ return $ret;
+ }
+
+ function parsetag($tag)
+ {
+ if(is_object($tag))
+ {
+ $tagname = $tag->name;
+ }
+ else
+ $tagname = $tag;
+ switch($tagname)
+ {
+ case "image_name":
+ $ret = $this->Get("Name");
+ break;
+ case "image_alt":
+ $ret = $this->Get("AltName");
+ break;
+ case "image_url":
+ $ret = $this->FullURL();
+ break;
+ case "thumb_url":
+ $ret = $this->ThumbURL();
+ break;
+ }
+ return $ret;
+ }
+
+ //Changes priority
+ function MoveUp()
+ {
+ $this->Increment("Priority");
+ }
+
+ function MoveDown()
+ {
+ $this->Decrement("Priority");
+ }
+
+ function GetMaxPriority()
+ {
+ $SourceId = $this->Get("ResourceId");
+ $sql = "SELECT MAX(Priority) as p from ".$this->tablename."WHERE ResourceId=$SourceId";
+ $result = $this->adodbConnection->Execute($sql);
+ return $result->fields["p"];
+ }
+
+ function GetMinPriority()
+ {
+ $SourceId = $this->Get("ResourceId");
+ $sql = "SELECT MIN(Priority) as p from ".$this->tablename."WHERE ResourceId=$SourceId";
+ $result = $this->adodbConnection->Execute($sql);
+ return $result->fields["p"];
+ }
+
+ function UpdatePriority()
+ {
+ $SourceId = $this->Get("ResourceId");
+ $sql = "SELECT MAX(Priority) as p from ".$this->tablename."WHERE ReourceId=$SourceId";
+ $result = $this->adodbConnection->Execute($sql);
+ $this->Set("Priority", $result->fields["p"]+1);
+ }
+
+ function MakeThumbnail () {
+
+ }
+}
+
+class clsImageList extends clsItemCollection
+{
+ var $Page;
+ var $PerPageVar;
+
+ function clsImageList()
+ {
+ global $objConfig;
+ $this->clsItemCollection();
+ $this->PerPageVar = "Perpage_Images";
+ $this->PerPage = $objConfig->Get($this->PerPageVar);
+ $this->SourceTable = GetTablePrefix()."Images";
+ $this->classname = "clsImage";
+ }
+
+ function LoadImages($where="",$orderBy = "")
+ {
+ global $objConfig;
+
+ $this->Clear();
+ if($this->Page<1)
+ $this->Page=1;
+
+ if(is_numeric($objConfig->Get("Perpage_Images")))
+ {
+ $Start = ($this->Page-1)*$objConfig->Get("Perpage_Images");
+ $limit = "LIMIT ".$Start.",".$objConfig->Get("Perpage_Images");
+ }
+ else
+ $limit = NULL;
+
+
+ $this->QueryItemCount=TableCount("Images",$where,0);
+ //echo $this->QueryItemCount."<br>\n";
+ if(strlen(trim($orderBy))>0)
+ {
+ $orderBy = "Priority DESC, ".$orderBy;
+ }
+ else
+ $orderBy = "Priority DESC";
+
+ return $this->Query_Images($where,$orderBy,$limit);
+ }
+
+ function Query_Images($whereClause,$orderByClause=NULL,$limit=NULL)
+ {
+ global $objSession, $Errors;
+
+ $sql = "SELECT * FROM ".$this->SourceTable;
+
+ if(isset($whereClause))
+ $sql = sprintf('%s WHERE %s',$sql,$whereClause);
+ if(isset($orderByClause) && strlen(trim($orderByClause))>0)
+ $sql = sprintf('%s ORDER BY %s',$sql,$orderByClause);
+ if(isset($limit) && strlen(trim($limit)))
+ $sql .= " ".$limit;
+ //echo $sql;
+ return $this->Query_Item($sql);
+ }
+
+ function &Add($Name, $Alt, $ResourceId, $LocalImage, $LocalThumb,
+ $Url, $ThumbUrl, $Enabled=1, $Priority=0, $DefaultImg=0, $ImageIndex=0,
+ $SameImages=0, $ImageId=-999)
+ {
+ if($DefaultImg==1)
+ {
+ $sql = "UPDATE ".$this->SourceTable." SET DefaultImg=0 WHERE ResourceId=$ResourceId";
+ $this->adodbConnection->Execute($sql);
+ }
+
+ $img = new clsImage();
+ $img->tablename = $this->SourceTable;
+ $img->Set(array("Name","AltName","ResourceId","LocalImage","LocalThumb",
+ "Url","ThumbUrl","Enabled","Priority","DefaultImg","ImageIndex","SameImages"),
+ array($Name,$Alt,$ResourceId,$LocalImage,$LocalThumb,
+ $Url,$ThumbUrl,$Enabled,$Priority,$DefaultImg,$ImageIndex,$SameImages));
+
+ if ($ImageId != -999)
+ {
+ $img->Set("ImageId", $ImageId);
+ }
+
+ if((int)$ImageIndex==0)
+ $img->Set("ImageIndex",$this->GetNextImageIndex($ResourceId));
+ $img->Create();
+ array_push($this->Items,$img);
+ return $img;
+ }
+
+
+ function Edit($ImageId,$Name, $Alt, $ResourceId, $LocalImage, $LocalThumb,
+ $Url, $ThumbUrl, $Enabled=1, $Priority=0, $DefaultImg=0, $ImageIndex=0,
+ $SameImages=0)
+ {
+ $img = $this->GetItem($ImageId);
+
+ if((int)$ImageIndex==0)
+ $ImageIndex = $img->Get("ImageIndex");
+
+ if(!strlen($ThumbUrl) && !$LocalThumb)
+ $ThumbUrl = $img->Get("ThumbUrl");
+
+ $img->Set(array("Name","AltName","ResourceId","LocalImage","LocalThumb",
+ "Url","ThumbUrl","Enabled","Priority","DefaultImg","ImageIndex","SameImages"),
+ array($Name, $Alt, $ResourceId, $LocalImage, $LocalThumb,
+ $Url, $ThumbUrl, $Enabled, $Priority, $DefaultImg, $ImageIndex,$SameImages));
+
+ if((int)$ImageIndex==0)
+ $img->Set("ImageIndex",$this->GetNextImageIndex($ResourceId));
+
+ $img->Update();
+
+ if($DefaultImg==1)
+ {
+ $sql = "UPDATE ".$this->SourceTable." SET DefaultImg=0 WHERE ResourceId=".$ResourceId." AND ImageId !=$ImageId";
+ $this->adodbConnection->Execute($sql);
+ }
+ array_push($this->Items,$img);
+
+ return $img;
+ }
+
+ function Delete_Image($ImageId)
+ {
+ $i = $this->GetItem($ImageId);
+ $i->Delete();
+ }
+
+ function DeleteResource($ResourceId)
+ {
+ $this->Clear();
+ $images = $this->Query_Images("ResourceId=".$ResourceId);
+ if(is_array($images))
+ {
+ foreach($images as $i)
+ {
+ $i->Delete();
+ }
+ }
+ }
+
+ function LoadResource($ResourceId)
+ {
+ $sql = "SELECT * FROM ".$this->SourceTable." WHERE ResourceId=$ResourceId";
+ $this->Query_Item($sql);
+ }
+
+ function CopyResource($SourceId, $DestId, $main_prefix)
+ {
+ global $pathtoroot;
+
+ $this->Clear();
+ $this->LoadResource($SourceId);
+ foreach($this->Items as $i)
+ {
+ if($i->Get("LocalThumb"))
+ {
+ $f = $pathtoroot.$i->Get("ThumbPath");
+ if(file_exists($f))
+ {
+ $p = pathinfo($f);
+ $dir = $p["dirname"];
+ $ext = $p["extension"];
+ $newfile = $dir."/th_".$DestId."_".$i->Get("ImageIndex").".".$ext;
+ if(file_exists($newfile))
+ @unlink($newfile);
+ // echo $f." -> ".$newfile;
+ copy($f,$newfile);
+ }
+ }
+ if($i->Get("LocalImage"))
+ {
+ $f = $pathtoroot.$i->Get("LocalPath");
+ if(file_exists($f))
+ {
+ $p = pathinfo($f);
+ $dir = $p["dirname"];
+ $ext = $p["extension"];
+ $newfile = $dir."/".$DestId."_".$i->Get("ImageIndex").".".$ext;
+ if(file_exists($newfile))
+ @unlink($newfile);
+
+ // echo $f." -> ".$newfile;
+ copy($f,$newfile);
+ }
+ }
+ }
+ parent::CopyResource($SourceId, $DestId, $main_prefix);
+ $this->Clear();
+ $this->LoadResource($DestId);
+ foreach($this->Items as $img)
+ {
+ if($img->Get("LocalThumb"))
+ {
+ $f = str_replace("th_$SourceId","th_$DestId",$img->Get("ThumbPath"));
+ $img->Set("ThumbPath",$f);
+ }
+ if($img->Get("LocalImage"))
+ {
+ $f = str_replace("/".$SourceId."_","/".$DestId."_",$img->Get("LocalPath"));
+ $img->Set("LocalPath",$f);
+ }
+ $img->Update();
+ }
+ }
+
+ function GetImageByResource($ResourceId,$Index)
+ {
+ $found=FALSE;
+ if($this->NumItems()>0)
+ {
+ foreach($this->Items as $i)
+ {
+ if($i->Get("ResourceID")==$ResourceId and ($i->Get("ImageIndex")==$Index))
+ {
+ $found=TRUE;
+ break;
+ }
+ }
+ }
+ if(!$found)
+ {
+ $i = NULL;
+ $i = new clsImage();
+ if($i->LoadFromResource($ResourceId,$Index))
+ {
+ array_push($this->Items, $i);
+ }
+ else
+ unset($i);
+ }
+ if(is_object($i))
+ {
+ return $i;
+ }
+ else
+ return FALSE;
+ }
+
+ function &GetDefaultImage($ResourceId)
+ {
+ $sql = "SELECT * FROM ".$this->SourceTable." WHERE ResourceId=$ResourceId AND DefaultImg=1";
+ $rs = $this->adodbConnection->Execute($sql);
+ if($rs && ! $rs->EOF)
+ {
+ $data = $rs->fields;
+ $img= new clsImage();
+ $img->SetFromArray($data);
+ $img->Clean();
+ return $img;
+ }
+ else
+ return FALSE;
+ }
+
+ function &GetAvatarImage($ResourceId)
+ {
+ $sql = 'SELECT * FROM '.$this->SourceTable.
+ ' WHERE ResourceId='.$ResourceId.' AND Name="avatar" AND Enabled=1
+ LIMIT 1';
+ $rs = $this->adodbConnection->Execute($sql);
+ if($rs && ! $rs->EOF)
+ {
+ $data = $rs->fields;
+ $img= new clsImage();
+ $img->SetFromArray($data);
+ $img->Clean();
+ return $img;
+ }
+ else
+ return FALSE;
+ }
+
+ function HandleImageUpload($FILE,$ResourceId,$RelatedTo,$DestDir, $Name="",$AltName="",$IsThumb=0)
+ {
+ global $objConfig;
+
+ $img = $this->GetImageByResource($ResourceId,$RelatedTo);
+
+ if(is_object($img) && $RelatedTo>0)
+ {
+ $img->Set("LocalImage",1);
+ $img->Set("Name",$Name);
+ $img->Set("AltName",$AltName);
+ $img->Set("IsThumbnail",$IsThumb);
+ $dest = $img->StoreUploadedImage($FILE,1,$DestDir);
+ if(strlen($dest))
+ {
+ $img->Set("Url", $objConfig->Get("Site_Path").$dest);
+ $img->Update();
+ }
+ }
+ else
+ {
+ $img=$this->NewLocalImage($ResourceId,$RelatedTo,$Name,$AltName,$IsThumb,$FILE,$DestDir);
+ }
+ return $img;
+ }
+
+ function GetResourceImages($ResourceId)
+ {
+ $sql = "SELECT * FROM ".$this->SourceTable." WHERE ResourceId=".$ResourceId;
+ $rs = $this->adodbConnection->Execute($sql);
+ while($rs && !$rs->EOF)
+ {
+ $img = new clsImage();
+ $img->LoadFromResource($ResourceId,$rs->fields["RelatedTo"]);
+ array_push($this->Images,$img);
+ $rs->MoveNext();
+ }
+ }
+
+ function GetResourceThumbnail($ResourceId)
+ {
+ $found=FALSE;
+ foreach($this->Images as $img)
+ {
+ if($img->Get("ResourceId")==$ResourceId && $img->Get("IsThumbnail")==1)
+ {
+ $found=TRUE;
+ break;
+ }
+ }
+ if($found)
+ {
+ return $img;
+ }
+ else
+ return FALSE;
+ }
+
+ function &GetImageByName($ResourceId, $name, $enabled=0)
+ {
+ $found = FALSE;
+ foreach($this->Items as $img)
+ {
+ $search_condition = ($img->Get("ResourceId")==$ResourceId && $img->Get("Name")==$name);
+ if ($enabled)
+ {
+ $search_condition = $search_condition && $img->Get("Enabled");
+ }
+ if($search_condition)
+ {
+ $found=TRUE;
+ break;
+ }
+ }
+ if($found)
+ {
+ return $img;
+ }
+ else
+ {
+ $sql = "SELECT * FROM ".$this->SourceTable." WHERE ResourceId=$ResourceId AND Name LIKE '$name'";
+ if ($enabled)
+ {
+ $sql = $sql.' AND Enabled=1';
+ }
+ //echo $sql;
+ $rs = $this->adodbConnection->Execute($sql);
+ if($rs && !$rs->EOF)
+ {
+ $img = $this->AddItemFromArray($rs->fields);
+ return $img;
+ }
+ else
+ return FALSE;
+ }
+ }
+
+ function CopyToPendingFiles()
+ {
+ $sql = "SELECT * FROM ".$this->SourceTable;
+ $this->Clear();
+ $this->Query_Item($sql);
+ foreach($this->Items as $i)
+ {
+ if(strlen($i->Get("LocalImage")) || strlen($i->Get("LocalThumb")))
+ {
+ $i->CopyToPending();
+ }
+ }
+ }
+
+ function CopyFromPendingFiles($edit_table)
+ {
+ $sql = "SELECT * FROM ".$edit_table;
+ $this->Clear();
+ $this->Query_Item($sql);
+ foreach($this->Items as $i)
+ {
+
+ ## Delete original Images
+ $OrgImage = new clsImage($i->Get("ImageId"));
+ $OrgImage->DeleteLocalImage();
+
+ if($i->Get("LocalImage") || $i->Get("LocalThumb"))
+ {
+ $i->CopyFromPending();
+
+ $t = $i->Get("LocalPath");
+
+ $p = pathinfo($t);
+ $p_arr = explode("/", $p['dirname']);
+ if (eregi("pending", $p_arr[count($p_arr)-1]))
+ {
+ unset($p_arr[count($p_arr)-1]);
+ $p['dirname'] = implode("/", $p_arr);
+ $LocalPath = $p['dirname']."/".$p['basename'];
+ $i->Set("LocalPath", $LocalPath);
+ }
+
+ $t = $i->Get("ThumbPath");
+ $p = pathinfo($t);
+
+ $p_arr = explode("/", $p['dirname']);
+ if (eregi("pending", $p_arr[count($p_arr)-1]))
+ {
+ unset($p_arr[count($p_arr)-1]);
+ $p['dirname'] = implode("/", $p_arr);
+ $ThumbPath = $p['dirname']."/".$p['basename'];
+ $i->Set("ThumbPath", $ThumbPath);
+ }
+
+ $i->tablename = $edit_table;
+
+ $update = 1;
+ }
+
+ ## Empty the fields if are not used
+ if (!$i->Get("LocalImage"))
+ {
+ $i->Set("LocalPath", "");
+ $update = 1;
+ }
+
+ if (!$i->Get("LocalThumb"))
+ {
+ $i->Set("ThumbPath", "");
+ $update = 1;
+ }
+
+ if ($update)
+ $i->Update();
+
+ }
+ }
+
+ function DeletePendingFiles($edit_table)
+ {
+ $sql = "SELECT * FROM ".$edit_table;
+ $this->Clear();
+ $this->Query_Item($sql);
+ foreach($this->Items as $i)
+ {
+ $i->DeleteFromPending();
+ }
+ }
+
+ function CopyToEditTable($idfield, $idlist)
+ {
+ global $objSession;
+
+ $edit_table = $objSession->GetEditTable($this->SourceTable);
+ @$this->adodbConnection->Execute("DROP TABLE IF EXISTS $edit_table");
+ if(is_array($idlist))
+ {
+ $list = implode(",",$idlist);
+ }
+ else
+ $list = $idlist;
+ $query = "SELECT * FROM ".$this->SourceTable." WHERE $idfield IN ($list)";
+ $insert = "CREATE TABLE ".$edit_table." ".$query;
+ if($objSession->HasSystemPermission("DEBUG.LIST"))
+ echo htmlentities($insert,ENT_NOQUOTES)."<br>\n";
+ $this->adodbConnection->Execute($insert);
+ $this->SourceTable = $edit_table;
+ $this->CopyToPendingFiles();
+
+ $this->UpdateFilenamesToPendings();
+ }
+
+ function UpdateFilenamesToPendings()
+ {
+ global $objSession;
+
+ $edit_table = $this->SourceTable;
+
+ $sql = "SELECT * FROM ".$edit_table." WHERE (LocalPath!='' AND LocalPath IS NOT NULL) OR (ThumbPath!='' AND ThumbPath IS NOT NULL)";
+ $this->Clear();
+ $this->Query_Item($sql);
+
+ foreach($this->Items as $i)
+ {
+ $set = "";
+ $ImageId = $i->Get("ImageId");
+
+ ## Update Local Image Path -> add "pending/" to PATH
+ if (strlen($i->Get("LocalPath")))
+ {
+ $p = pathinfo($i->Get("LocalPath"));
+ if (!eregi("/pending $", $p['dirname']))
+ {
+ $LocalPath = $p['dirname']."/pending/".$p['basename'];
+ $set = "SET LocalPath='$LocalPath'";
+ }
+ }
+
+ // echo "LocalImage: ".$i->Get("LocalImage").", PATH: ".$i->Get("LocalPath")."<BR>";
+
+ ## Update Local Thumb Path -> add "pending/" to PATH
+ if (strlen($i->Get("ThumbPath")))
+ {
+ $p = pathinfo($i->Get("ThumbPath"));
+ if (!eregi("/pending $", $p['dirname']))
+ {
+ $LocalThumb = $p['dirname']."/pending/".$p['basename'];
+ if (strlen($set))
+ $set.= ", ThumbPath='$LocalThumb'";
+ else
+ $set = "SET ThumbPath='$LocalThumb'";
+ }
+ }
+
+ // echo "LocalThumb: ".$i->Get("LocalThumb").", PATH: ".$i->Get("ThumbPath")."<BR>";
+
+ if (strlen($set))
+ {
+ $sql = "UPDATE $edit_table $set WHERE ImageId=$ImageId";
+ if($objSession->HasSystemPermission("DEBUG.LIST"))
+ echo htmlentities($sql,ENT_NOQUOTES)."<br>\n";
+ $this->adodbConnection->Execute($sql);
+ }
+ }
+ }
+
+ function CopyFromEditTable($idfield)
+ {
+ global $objSession;
+ $GLOBALS['_CopyFromEditTable']=1;
+
+ $edit_table = $objSession->GetEditTable($this->SourceTable);
+ $dummy =& $this->GetDummy();
+ if( !$dummy->TableExists($edit_table) )
+ {
+ echo 'ERROR: Table "<b>'.$edit_table.'</b>" missing (class: <b>'.get_class($this).'</b>)<br>';
+ //exit;
+ return;
+ }
+
+ $rs = $this->adodbConnection->Execute("SELECT * FROM $edit_table WHERE ResourceId=0");
+ while($rs && !$rs->EOF)
+ {
+ $id = $rs->fields["ImageId"];
+ if($id>0)
+ {
+ $img = $this->GetItem($id);
+ $img->Delete();
+ }
+ $rs->MoveNext();
+ }
+ $this->adodbConnection->Execute("DELETE FROM $edit_table WHERE ResourceId=0");
+ $this->CopyFromPendingFiles($edit_table);
+ parent::CopyFromEditTable($idfield);
+ unset($GLOBALS['_CopyFromEditTable']);
+ }
+
+ function PurgeEditTable($idfield)
+ {
+ global $objSession;
+
+ $edit_table = $objSession->GetEditTable($this->SourceTable);
+ $this->DeletePendingFiles($edit_table);
+ @$this->adodbConnection->Execute("DROP TABLE IF EXISTS $edit_table");
+ }
+
+ function GetNextImageIndex($ResourceId)
+ {
+ $sql = "SELECT MAX(ImageIndex) as MaxVal FROM ".$this->SourceTable." WHERE ResourceId=".$ResourceId;
+ $rs = $this->adodbConnection->Execute($sql);
+ if($rs)
+ {
+ $val = (int)$rs->fields["MaxVal"];
+ $val++;
+ }
+ return $val;
+ }
+
+ function GetMaxPriority($ResourceId)
+ {
+ $sql = "SELECT MAX(Priority) as p from ".$this->SourceTable."WHERE ResourceId=$ResourceId";
+ $result = $this->adodbConnection->Execute($sql);
+ return $result->fields["p"];
+ }
+
+ function GetMinPriority($ResourceId)
+ {
+ $sql = "SELECT MIN(Priority) as p from ".$this->SourceTable."WHERE ResourceId=$ResourceId";
+ $result = $this->adodbConnection->Execute($sql);
+ return $result->fields["p"];
+ }
+
+} /*clsImageList*/
+
+?>
Property changes on: branches/unlabeled/unlabeled-1.20.2/kernel/include/image.php
___________________________________________________________________
Added: cvs2svn:cvs-rev
## -0,0 +1 ##
+1.20
\ No newline at end of property
Added: svn:executable
## -0,0 +1 ##
+*
\ No newline at end of property
Index: branches/unlabeled/unlabeled-1.20.2/admin/category/addcategory.php
===================================================================
--- branches/unlabeled/unlabeled-1.20.2/admin/category/addcategory.php (nonexistent)
+++ branches/unlabeled/unlabeled-1.20.2/admin/category/addcategory.php (revision 5538)
@@ -0,0 +1,351 @@
+<?php
+
+// new startup: begin
+define('REL_PATH', 'admin/category');
+$relation_level = count( explode('/', REL_PATH) );
+define('FULL_PATH', realpath(dirname(__FILE__) . str_repeat('/..', $relation_level) ) );
+require_once FULL_PATH.'/kernel/startup.php';
+// new startup: end
+
+$objSession->SetVariable('IsHomeCategory', 0);
+
+require_once ($pathtoroot.$admin."/include/elements.php");
+require_once ($pathtoroot."kernel/admin/include/navmenu.php");
+//require_once ($pathtolocal."admin/include/navmenu.php");
+require_once($pathtoroot.$admin."/toolbar.php");
+
+unset($objEditItems);
+
+if($_REQUEST['item'])
+{
+ // smulate like normal edit button pressed
+ $tmp_cat =& $objCatList->GetItemByField('ResourceId', $_REQUEST['item']);
+ $_POST['catlist'][] = $tmp_cat->UniqueId();
+}
+
+$objEditItems = new clsCatList();
+$objEditItems->SourceTable = $objSession->GetEditTable("Category");
+$objCustomFields = new clsCustomFieldList(1);
+$application->SetVar('c_mode', 't');
+$objCustomDataList = new clsCustomDataList();
+$objRelList = new clsRelationshipList();
+$objImages = new clsImageList();
+
+//Multiedit init
+if ($_GET["new"] == 1)
+{
+ $c = new clsCategory(NULL);
+ $c->Set("CreatedOn", adodb_mktime());
+ $c->Set("EndOn", adodb_mktime());
+ $c->Set("ParentId",$objCatList->CurrentCategoryID());
+ $c->Set("NewItem",2); //auto
+ $c->Set("Status",2); //pending
+ $c->Set('AutomaticFilename', 1);
+ $en = 0;
+ $action = "m_add_category";
+ $objCatList->CreateEmptyEditTable("CategoryId");
+ $objRelList->CreateEmptyEditTable("RelationshipId");
+ $objCustomDataList->CreateEmptyEditTable('c');
+ $objImages->CreateEmptyEditTable("ResourceId");
+
+ $TitleVerb = prompt_language("la_Text_Adding");
+}
+else
+{
+ if(isset($_POST["catlist"]))
+ {
+ $cats = $_POST["catlist"];
+ $objCatList->CopyToEditTable("CategoryId",$cats);
+ $objEditItems->Query_Item("SELECT * FROM ".$objEditItems->SourceTable);
+ /* make a copy of the relationship records */
+ $ids = $objEditItems->GetResourceIDList();
+ $objRelList->CopyToEditTable("SourceId", $ids);
+ $objCustomDataList->CopyToEditTable('c', $ids);
+ $objImages->CopyToEditTable("ResourceId", $ids);
+ $c = $objEditItems->GetItemByIndex(0);
+ $itemcount=$objEditItems->NumItems();
+ $en = 0;
+ }
+ else
+ {
+ if($_GET["item"])
+ {
+ /*shortcut to edit link */
+ $objCatList->CopyToEditTable("ResourceId",$_GET["item"]);
+ $backurl = $_GET["return"];
+ }
+
+ //Multiedit init
+ $en = (int)$_GET["en"];
+ $objEditItems->Query_Item("SELECT * FROM ".$objEditItems->SourceTable);
+
+ //$ids = $objEditItems->GetResourceIDList();
+ //$objRelList->CopyToEditTable("SourceId", $ids);
+ //$objCustomDataList->CopyToEditTable("ResourceId",$ids);
+ //$objImages->CopyToEditTable("ResourceId", $ids);
+
+ $itemcount=$objEditItems->NumItems();
+ $c = $objEditItems->GetItemByIndex($en);
+ }
+
+ if($itemcount>1)
+ {
+ if ($en+1 == $itemcount)
+ $en_next = -1;
+ else
+ $en_next = $en+1;
+
+ if ($en == 0)
+ $en_prev = -1;
+ else
+ $en_prev = $en-1;
+ }
+
+ $action = "m_edit_category";
+ $TitleVerb = prompt_language("la_Text_Editing");
+}
+
+$envar = "env=" . BuildEnv() . "&en=$en";
+$section = 'in-portal:editcategory_general';
+
+if (strlen($c->Get("Name")))
+ $editing_category_title = "'".$c->Get("Name")."' ";
+else
+ $editing_category_title = "";
+
+$title = $TitleVerb." ".prompt_language("la_Text_Category")." $editing_category_title- ".prompt_language("la_tab_General");
+
+//$saveURL = $admin."/browse.php";
+$saveURL = $admin."/category/category_maint.php";
+$cancelURL = $admin."/".$objSession->GetVariable('ReturnScript');
+
+//Display header
+$sec = $objSections->GetSection($section);
+
+$objCatToolBar = new clsToolBar();
+$objCatToolBar->Add("img_save", "la_Save","#","swap('img_save','toolbar/tool_select_f2.gif');", "swap('img_save', 'toolbar/tool_select.gif');","edit_submit('category','CatEditStatus','$saveURL',1,'');","tool_select.gif");
+$objCatToolBar->Add("img_cancel", "la_Cancel","#","swap('img_cancel','toolbar/tool_cancel_f2.gif');", "swap('img_cancel', 'toolbar/tool_cancel.gif');","edit_submit('category','CatEditStatus','$cancelURL',2,'');","tool_cancel.gif");
+
+if ( isset($en_prev) || isset($en_next) )
+{
+ $url = $RootUrl.$admin."/category/addcategory.php";
+ $StatusField = "CatEditStatus";
+ $form = "category";
+ MultiEditButtons($objCatToolBar,$en_next,$en_prev,$form,$StatusField,$url,$sec->Get("OnClick"),'','la_PrevCategory','la_NextCategory');
+}
+
+int_header($objCatToolBar,NULL,$title);
+$c->Data=inp_htmlize($c->Data);
+if ($objSession->GetVariable("HasChanges") == 1) {
+?>
+<table width="100%" border="0" cellspacing="0" cellpadding="0" class="toolbar">
+ <tr>
+ <td valign="top">
+ <?php int_hint_red(admin_language("la_Warning_Save_Item")); ?>
+ </td>
+ </tr>
+</table>
+<?php } ?>
+<table width="100%" border="0" cellspacing="0" cellpadding="4" class="tableborder">
+<form ID="category" name="category" action="" method=POST>
+ <tr <?php int_table_color(1); ?>>
+ <td valign="top" colspan="3"><?php echo prompt_language("la_prompt_Enable_HTML"); ?>
+ <input type="checkbox" name="html_enable" value="1" checked>
+ <br>
+ <?php int_hint(prompt_language("la_Warning_Enable_HTML")); ?>
+ </td>
+ </tr>
+ <?php int_subsection_title(prompt_language("la_Text_Category")); ?>
+ <?php if( $c->Get("CategoryId") > 0 ) { ?>
+ <tr <?php int_table_color(); ?>>
+ <td valign="top"><span class="text"><?php echo prompt_language("la_prompt_CategoryId"); ?></span></td>
+ <td valign="top"><span class="text"><?php echo $c->Get("CategoryId"); ?></span></td>
+ <td class="text">
+ <?php
+ if (IsDebugMode()) {
+ echo '<b>DBG:</b> ResourceId = '.$c->Get('ResourceId');
+ }
+ else {
+ echo '&nbsp;';
+ }
+ ?>
+ </td>
+ </tr>
+ <?php } ?>
+ <tr <?php int_table_color(); ?>>
+ <td valign="top"><span ID="prompt_cat_name" class="text"><?php echo prompt_language("la_prompt_Name"); ?></span></td>
+ <td>
+ <input type="text" name="cat_name" ValidationType="exists" tabindex="1" class="text" size="30" value="<?php echo $c->parsetag("cat_name"); ?>">
+ </td>
+ <td></td>
+ </tr>
+ <tr <?php int_table_color(); ?>>
+ <td valign="top"><span ID="prompt_cat_desc" class="text"><?php echo prompt_language("la_prompt_Description"); ?></span>
+ <br />
+ <a href="#">
+ <img src="<?php echo $rootURL; ?>admin/icons/icon24_link_editor.gif" style="cursor:hand" border="0"
+ ONCLICK="document.forms[0].elements[0].checked=true; OpenEditor('&section=<?php echo $section; ?>','category','cat_desc');">
+ </a>
+ </td>
+ <td>
+ <textarea name="cat_desc" id="cat_desc" tabindex="2" ValidationType="exists" cols="60" rows="5" class="text"><?php echo inp_textarea_unescape($c->parsetag("cat_desc")); ?></textarea>
+ </td>
+ <td></td>
+ </tr>
+
+ <tr <?php int_table_color(); ?>>
+ <td valign="top"><span id="prompt_auto_filename" class="text"><?php echo prompt_language('la_prompt_AutomaticDirectoryName'); ?></span></td>
+ <td>
+ <input type="checkbox" tabindex="3" name="auto_filename" id="auto_filename" class="text" value="1"<?php if( $c->Get('AutomaticFilename') == 1) echo ' checked'; ?> onchange="reflect_filename();">
+ </td>
+ <td class="text">&nbsp;</td>
+ </tr>
+ <tr <?php int_table_color(); ?>>
+ <td valign="top"><span ID="prompt_filename" class="text"><?php echo prompt_language('la_prompt_DirectoryName'); ?></span></td>
+ <td>
+ <input type="text" name="filename" id="filename" tabindex="4" class="text" size="63" value="<?php echo $c->Get('Filename'); ?>">
+ </td>
+ <td>&nbsp;</td>
+ </tr>
+
+ <tr <?php int_table_color(); ?>>
+ <td valign="top"><span ID="prompt_category_template" class="text"><?php echo prompt_language('la_fld_CategoryTemplate'); ?></span></td>
+ <td>
+ <input type="text" name="category_template" tabindex="5" class="text" size="40" value="<?php echo $c->Get('CategoryTemplate'); ?>">
+ </td>
+ <td>&nbsp;</td>
+ </tr>
+ <tr <?php int_table_color(); ?>>
+ <td valign="top"><span ID="prompt_item_template" class="text"><?php echo prompt_language('la_fld_ItemTemplate'); ?></span></td>
+ <td>
+ <input type="text" name="item_template" tabindex="6" class="text" size="40" value="<?php echo $c->Get('ItemTemplate'); ?>">
+ </td>
+ <td>&nbsp;</td>
+ </tr>
+
+ <?php int_subsection_title(prompt_language("la_tab_Properties")); ?>
+ <tr <?php int_table_color(); ?>>
+ <td valign="top"><span id="prompt_status" class="text"><?php echo prompt_language("la_prompt_Status"); ?></span></td>
+ <td>
+ <input type="radio" tabindex="7" name="status" class="text" value="1" <?php if($c->Get("Status") == 1) echo "checked"; ?>><?php echo prompt_language("la_val_Active"); ?>
+ <input type="radio" tabindex="7" name="status" class="text" value="2" <?php if($c->Get("Status") == 2) echo "checked"; ?>><?php echo prompt_language("la_val_Pending"); ?>
+ <input type="radio" tabindex="7" name="status" class="text" value="0" <?php if($c->Get("Status") == 0) echo "checked"; ?>><?php echo prompt_language("la_val_Disabled"); ?>
+ </td>
+ <td class="text">&nbsp;</td>
+ </tr>
+ <tr <?php int_table_color(); ?>>
+ <td valign="top"><span id="prompt_itemnew" class="text"><?php echo prompt_language("la_prompt_New"); ?></span></td>
+ <td>
+ <input type="radio" tabindex="8" name="itemnew" class="text" value="2" <?php if($c->Get("NewItem") == 2) echo "checked"; ?>><?php echo prompt_language("la_val_Auto"); ?>
+ <input type="radio" tabindex="8" name="itemnew" class="text" value="1" <?php if($c->Get("NewItem") == 1) echo "checked"; ?>><?php echo prompt_language("la_val_Always"); ?>
+ <input type="radio" tabindex="8" name="itemnew" class="text" value="0" <?php if($c->Get("NewItem") == 0) echo "checked"; ?>><?php echo prompt_language("la_val_Never"); ?>
+
+ </td>
+ <td class="text">&nbsp;</td>
+ </tr>
+ <tr <?php int_table_color(); ?>>
+ <td valign="top"><span id="prompt_cat_pick" class="text"><?php echo prompt_language("la_prompt_EditorsPick"); ?></span></td>
+ <td>
+ <input type="checkbox" tabindex="9" name="cat_pick" class="text" value="1" <?php if($c->Get("EditorsPick") == 1) echo "checked"; ?>>
+ </td>
+ <td class="text">&nbsp;</td>
+ </tr>
+ <TR <?php int_table_color(); ?> >
+ <TD><span id="prompt_Priority" class="text"><?php echo prompt_language("la_prompt_Priority"); ?></span></TD>
+ <TD><input type=text SIZE="5" tabindex="10" NAME="Priority" VALUE="<?php echo $c->Get("Priority"); ?>"></TD>
+ <TD>&nbsp;</TD>
+ </TR>
+ <tr <?php int_table_color(); ?>>
+ <td valign="top" ID="prompt_cat_date" class="text"> <?php echo prompt_language("la_prompt_CreatedOn"); ?> </td>
+ <td>
+ <input type="text" ValidationType="date,exists" tabindex="11" name="cat_date" id="cat_date_selector" datepickerIcon="../images/ddarrow.gif" class="text" size="20" value="<?php echo $c->parsetag("cat_date"); ?>">
+ <span class="small"><?php echo prompt_language("la_prompt_DateFormat"); ?></span>
+ </td>
+ <td>
+ <?php if( IsDebugMode() ) echo '<b>DBG:</b> '.adodb_date('M d. Y H:i:s', $c->get('Modified') ); ?>
+ </td>
+ </tr>
+ <?php int_subsection_title(prompt_language("la_Sectionheader_MetaInformation")); ?>
+ <tr <?php int_table_color(); ?>>
+ <td valign="top"><span id="prompt_meta_keywords" class="text"><?php echo prompt_language("la_prompt_MetaKeywords"); ?></span></td>
+ <td>
+ <input type="text" name="meta_keywords" tabindex="12" class="text" size="30" value="<?php echo $c->parsetag("cat_metakeywords"); ?>">
+ </td>
+ <td class="text">&nbsp;</td>
+ </tr>
+ <tr <?php int_table_color(); ?>>
+ <td valign="top"><span id="prompt_meta_desc" class="text"><?php echo prompt_language("la_prompt_MetaDescription"); ?></span></td>
+ <td>
+ <textarea name="meta_desc" tabindex="13" cols="60" rows="2" class="text"><?php echo inp_textarea_unescape($c->parsetag("cat_metadesc")); ?></textarea>
+ </td>
+ <td class="text">&nbsp;</td>
+ </tr>
+<?php
+
+$CustomFieldUI = $objCustomFields->GetFieldUIList(TRUE);
+if($CustomFieldUI->NumItems()>0)
+{
+ $objCustomDataList->SourceTable = $objSession->GetEditTable("CustomMetaData");
+ if((int)$c->Get("ResourceId")>0)
+ {
+ $objCustomDataList->LoadResource($c->Get("ResourceId"));
+ }
+ $headings = $CustomFieldUI->GetHeadingList();
+ //echo "<PRE>";print_r($objCustomFields); echo "</PRE>";
+ $tab_index = 14;
+ for($i=0;$i<=count($headings);$i++)
+ {
+ $h = $headings[$i];
+ if(strlen($h))
+ {
+ int_subsection_title(prompt_language($h));
+ $Items = $CustomFieldUI->GetHeadingItems($h);
+ foreach($Items as $f)
+ {
+ $n = substr($f->name,1);
+
+ $cfield = $objCustomFields->GetItemByField("FieldName",$n,FALSE);
+ if (is_object($cfield)) {
+ $f->default_value = $c->GetCustomFieldValue($n, '', 0, true);
+ }
+ print "<tr ".int_table_color_ret().">\n";
+ print " <td valign=\"top\" class=\"text\">".$f->GetPrompt()."</td>\n";
+ print " <td nowrap>".$f->ItemFormElement($tab_index++)."</TD>";
+ if(is_object($f->NextItem))
+ {
+ $n = $f->NextItem;
+ print " <td>".$n->ItemFormElement($tab_index++)."</TD>";
+ }
+ else
+ print " <td><span class=\"text\">&nbsp;</span></td>\n";
+ print "</tr>\n";
+ }
+ }
+ }
+}
+?>
+ <input type="hidden" name="ParentId" value="<?php echo $c->Get("ParentId"); ?>">
+ <input type="hidden" name="CategoryId" value="<?php echo $c->parsetag("cat_id"); ?>">
+ <input type="hidden" name="Action" value="<?php echo $action; ?>">
+ <input type="hidden" name="CatEditStatus" VALUE="0">
+</FORM>
+
+</table>
+<script src="<?php echo $adminURL; ?>/include/calendar.js"></script>
+
+<SCRIPT language="JavaScript">
+ initCalendar("cat_date_selector", CalDateFormat);
+ function reflect_filename()
+ {
+ var $checked = document.getElementById('auto_filename').checked;
+ document.getElementById('filename').readOnly = $checked;
+ }
+ reflect_filename();
+</SCRIPT>
+<FORM method="POST" NAME="save_edit" ID="save_edit">
+ <input type="hidden" name="CatEditStatus" VALUE="0">
+</FORM>
+<?php
+ MarkFields('category');
+ int_footer();
+?>
\ No newline at end of file
Property changes on: branches/unlabeled/unlabeled-1.20.2/admin/category/addcategory.php
___________________________________________________________________
Added: cvs2svn:cvs-rev
## -0,0 +1 ##
+1.20
\ No newline at end of property
Added: svn:executable
## -0,0 +1 ##
+*
\ No newline at end of property
Index: branches/unlabeled/unlabeled-1.20.2/core/units/languages/import_xml.php
===================================================================
--- branches/unlabeled/unlabeled-1.20.2/core/units/languages/import_xml.php (nonexistent)
+++ branches/unlabeled/unlabeled-1.20.2/core/units/languages/import_xml.php (revision 5538)
@@ -0,0 +1,403 @@
+<?php
+
+ define('LANG_OVERWRITE_EXISTING', 1);
+ define('LANG_SKIP_EXISTING', 2);
+
+ class LangXML_Parser extends kBase {
+
+ /**
+ * Path to current node beeing processed
+ *
+ * @var Array
+ */
+ var $path = Array();
+
+ /**
+ * Connection to database
+ *
+ * @var kDBConnection
+ */
+ var $Conn = null;
+
+ /**
+ * Fields of language currently beeing processed
+ *
+ * @var Array
+ */
+ var $current_language = Array();
+
+ /**
+ * Fields of phrase currently beeing processed
+ *
+ * @var Array
+ */
+ var $current_phrase = Array();
+
+ /**
+ * Fields of event currently beeing processed
+ *
+ * @var Array
+ */
+ var $current_event = Array();
+
+ /**
+ * Event type + name mapping to id (from system)
+ *
+ * @var Array
+ */
+ var $events_hash = Array();
+
+
+ /**
+ * Phrase types allowed for import/export operations
+ *
+ * @var Array
+ */
+ var $phrase_types_allowed = Array();
+
+ /**
+ * Modules allowed for export (import in development)
+ *
+ * @var Array
+ */
+ var $modules_allowed = Array();
+
+ var $lang_object = null;
+
+ var $tables = Array();
+
+ var $ip_address = '';
+
+ var $import_mode = LANG_SKIP_EXISTING;
+
+ var $Encoding = 'base64';
+
+ function LangXML_Parser()
+ {
+ parent::kBase();
+ $this->Conn =& $this->Application->GetADODBConnection();
+
+ $this->Application->SetVar('lang_mode', 't');
+
+ $this->tables['lang'] = $this->prepareTempTable('lang');
+ $this->lang_object =& $this->Application->recallObject('lang.imp', null, Array('skip_autoload' => true));
+
+ $this->tables['phrases'] = $this->prepareTempTable('phrases');
+ $this->tables['emailmessages'] = $this->prepareTempTable('emailmessages');
+
+ $sql = 'SELECT EventId, CONCAT(Event,"_",Type) AS EventMix FROM '.TABLE_PREFIX.'Events';
+ $this->events_hash = $this->Conn->GetCol($sql, 'EventMix');
+
+ $this->ip_address = getenv('HTTP_X_FORWARDED_FOR') ? getenv('HTTP_X_FORWARDED_FOR') : getenv('REMOTE_ADDR');
+ }
+
+ function SetEncoding($enc)
+ {
+ $this->Encoding = $enc;
+ }
+
+ function renameTable($table_prefix, $new_name)
+ {
+ $this->Conn->Query('ALTER TABLE '.$this->tables[$table_prefix].' RENAME '.$new_name);
+ $this->tables[$table_prefix] = $new_name;
+ }
+
+ /**
+ * Create temp table for prefix, if table already exists, then delete it and create again
+ *
+ * @param string $prefix
+ */
+ function prepareTempTable($prefix)
+ {
+ $idfield = $this->Application->getUnitOption($prefix, 'IDField');
+ $table = $this->Application->getUnitOption($prefix,'TableName');
+ $temp_table = $this->Application->GetTempName($table);
+
+ $sql = 'DROP TABLE IF EXISTS %s';
+ $this->Conn->Query( sprintf($sql, $temp_table) );
+
+ $sql = 'CREATE TABLE %s SELECT * FROM %s WHERE 0';
+ $this->Conn->Query( sprintf($sql, $temp_table, $table) );
+
+ $sql = 'ALTER TABLE %1$s CHANGE %2$s %2$s INT(11) NOT NULL';
+ $this->Conn->Query( sprintf($sql, $temp_table, $idfield) );
+
+ return $temp_table;
+ }
+
+ function Parse($filename, $phrase_types, $module_ids, $import_mode = LANG_SKIP_EXISTING)
+ {
+ // define the XML parsing routines/functions to call based on the handler path
+ if( !file_exists($filename) || !$phrase_types /*|| !$module_ids*/ ) return false;
+
+ $phrase_types = explode('|', substr($phrase_types, 1, -1) );
+// $module_ids = explode('|', substr($module_ids, 1, -1) );
+
+ $this->phrase_types_allowed = array_flip($phrase_types);
+ $this->import_mode = $import_mode;
+
+ //if (in_array('In-Portal',)
+
+ $xml_parser = xml_parser_create();
+ xml_set_element_handler( $xml_parser, Array(&$this, 'startElement'), Array(&$this, 'endElement') );
+ xml_set_character_data_handler( $xml_parser, Array(&$this, 'characterData') );
+
+ $fdata = file_get_contents($filename);
+
+ $ret = xml_parse($xml_parser, $fdata);
+ xml_parser_free($xml_parser); // clean up the parser object
+
+ $this->Application->SetVar('lang_mode', '');
+ return $ret;
+ }
+
+ function startElement(&$parser, $element, $attributes)
+ {
+ array_push($this->path, $element);
+ $path = implode(' ',$this->path);
+ //check what path we are in
+
+ switch($path)
+ {
+ case 'LANGUAGES LANGUAGE':
+ $this->current_language = Array('PackName' => $attributes['PACKNAME'], 'LocalName' => $attributes['PACKNAME'], 'Encoding' => $attributes['ENCODING']);
+
+ $sql = 'SELECT %s FROM %s WHERE PackName = %s';
+ $sql = sprintf( $sql,
+ $this->lang_object->IDField,
+ $this->Application->GetLiveName($this->lang_object->TableName),
+ $this->Conn->qstr($this->current_language['PackName']) );
+ $language_id = $this->Conn->GetOne($sql);
+ if($language_id)
+ {
+ $this->current_language['LanguageId'] = $language_id;
+ $this->lang_object->SwitchToLive();
+ $this->lang_object->Load($language_id);
+ }
+ break;
+
+ case 'LANGUAGES LANGUAGE PHRASES':
+ case 'LANGUAGES LANGUAGE EVENTS':
+ if( !getArrayValue($this->current_language,'Charset') ) $this->current_language['Charset'] = 'iso-8859-1';
+ $this->lang_object->SetFieldsFromHash($this->current_language);
+
+ if( !getArrayValue($this->current_language,'LanguageId') )
+ {
+ if( $this->lang_object->Create() ) $this->current_language['LanguageId'] = $this->lang_object->GetID();
+ }
+ elseif($this->import_mode == LANG_OVERWRITE_EXISTING)
+ {
+ $this->lang_object->TableName = $this->Application->getUnitOption($this->lang_object->Prefix, 'TableName');
+ $this->lang_object->Update();
+ }
+ break;
+
+ case 'LANGUAGES LANGUAGE PHRASES PHRASE':
+ $phrase_module = getArrayValue($attributes,'MODULE');
+ if(!$phrase_module) $phrase_module = 'In-Portal';
+
+ $this->current_phrase = Array( 'LanguageId' => $this->current_language['LanguageId'],
+ 'Phrase' => $attributes['LABEL'],
+ 'PhraseType' => $attributes['TYPE'],
+ 'Module' => $phrase_module,
+ 'LastChanged' => adodb_mktime(),
+ 'LastChangeIP' => $this->ip_address,
+ 'Translation' => '');
+ break;
+
+ case 'LANGUAGES LANGUAGE EVENTS EVENT':
+ $this->current_event = Array( 'LanguageId' => $this->current_language['LanguageId'],
+ 'EventId' => $this->events_hash[ $attributes['EVENT'].'_'.$attributes['TYPE'] ],
+ 'MessageType' => $attributes['MESSAGETYPE'],
+ 'Template' => '');
+ break;
+
+
+ }
+
+ // if($path == 'SHIPMENT PACKAGE')
+ }
+
+ function characterData(&$parser, $line)
+ {
+ $line = trim($line);
+ if(!$line) return ;
+
+ $path = join (' ',$this->path);
+
+ $language_nodes = Array('DATEFORMAT','TIMEFORMAT','INPUTDATEFORMAT','INPUTTIMEFORMAT','DECIMAL','THOUSANDS','CHARSET','UNITSYSTEM');
+
+
+ $node_field_map = Array('LANGUAGES LANGUAGE DATEFORMAT' => 'DateFormat',
+ 'LANGUAGES LANGUAGE TIMEFORMAT' => 'TimeFormat',
+
+ 'LANGUAGES LANGUAGE INPUTDATEFORMAT'=> 'InputDateFormat',
+ 'LANGUAGES LANGUAGE INPUTTIMEFORMAT'=> 'InputTimeFormat',
+
+ 'LANGUAGES LANGUAGE DECIMAL' => 'DecimalPoint',
+ 'LANGUAGES LANGUAGE THOUSANDS' => 'ThousandSep',
+ 'LANGUAGES LANGUAGE CHARSET' => 'Charset',
+ 'LANGUAGES LANGUAGE UNITSYSTEM' => 'UnitSystem');
+
+ if( in_array( end($this->path), $language_nodes) )
+ {
+ $this->current_language[ $node_field_map[$path] ] = $line;
+ }
+ else
+ {
+ switch($path)
+ {
+ case 'LANGUAGES LANGUAGE PHRASES PHRASE':
+ if( isset($this->phrase_types_allowed[ $this->current_phrase['PhraseType'] ]) )
+ {
+ $this->current_phrase['Translation'] .= $line;
+ }
+ break;
+
+ case 'LANGUAGES LANGUAGE EVENTS EVENT':
+ $this->current_event['Template'] .= $line;
+ break;
+ }
+ }
+ }
+
+ function endElement(&$parser, $element)
+ {
+ $path = implode(' ',$this->path);
+
+ switch($path)
+ {
+ case 'LANGUAGES LANGUAGE PHRASES PHRASE':
+ if( isset($this->phrase_types_allowed[ $this->current_phrase['PhraseType'] ]) )
+ {
+ if ($this->current_language['Encoding'] == 'plain') {
+ // nothing to decode!
+ }
+ else {
+ $this->current_phrase['Translation'] = base64_decode($this->current_phrase['Translation']);
+ }
+ $this->insertRecord($this->tables['phrases'], $this->current_phrase);
+ }
+ break;
+
+ case 'LANGUAGES LANGUAGE EVENTS EVENT':
+ if ($this->current_language['Encoding'] == 'plain') {
+ // nothing to decode!
+ }
+ else {
+ $this->current_event['Template'] = base64_decode($this->current_event['Template']);
+ }
+ $this->insertRecord($this->tables['emailmessages'],$this->current_event);
+ break;
+ }
+
+ array_pop($this->path);
+ }
+
+ function insertRecord($table, $fields_hash)
+ {
+ $fields = '';
+ $values = '';
+
+ foreach($fields_hash as $field_name => $field_value)
+ {
+ $fields .= '`'.$field_name.'`,';
+ $values .= $this->Conn->qstr($field_value).',';
+ }
+
+ $fields = preg_replace('/(.*),$/', '\\1', $fields);
+ $values = preg_replace('/(.*),$/', '\\1', $values);
+
+ $sql = 'INSERT INTO `'.$table.'` ('.$fields.') VALUES ('.$values.')';
+ $this->Conn->Query($sql);
+
+// return $this->Conn->getInsertID(); // no need because of temp table without auto_increment column at all
+ }
+
+ /**
+ * Creates XML file with exported language data
+ *
+ * @param string $filename filename to export into
+ * @param Array $phrase_types phrases types to export from modules passed in $module_ids
+ * @param Array $language_ids IDs of languages to export
+ * @param Array $module_ids IDs of modules to export phrases from
+ */
+ function Create($filename, $phrase_types, $language_ids, $module_ids)
+ {
+ $fp = fopen($filename,'w');
+ if(!$fp || !$phrase_types || !$module_ids || !$language_ids) return false;
+
+ $phrase_types = explode('|', substr($phrase_types, 1, -1) );
+ $module_ids = explode('|', substr($module_ids, 1, -1) );
+
+ $this->events_hash = array_flip($this->events_hash);
+
+ $lang_table = $this->Application->getUnitOption('lang','TableName');
+ $phrases_table = $this->Application->getUnitOption('phrases','TableName');
+ $emailevents_table = $this->Application->getUnitOption('emailmessages','TableName');
+ $mainevents_table = $this->Application->getUnitOption('emailevents','TableName');
+
+ $phrase_tpl = "\t\t\t".'<PHRASE Label="%s" Module="%s" Type="%s">%s</PHRASE>'."\n";
+ $event_tpl = "\t\t\t".'<EVENT MessageType="%s" Event="%s" Type="%s">%s</EVENT>'."\n";
+ $sql = 'SELECT * FROM %s WHERE LanguageId = %s';
+ $ret = '<LANGUAGES>'."\n";
+ foreach($language_ids as $language_id)
+ {
+ // languages
+ $row = $this->Conn->GetRow( sprintf($sql, $lang_table, $language_id) );
+ $ret .= "\t".'<LANGUAGE PackName="'.$row['PackName'].'" Encoding="'.$this->Encoding.'"><DATEFORMAT>'.$row['DateFormat'].'</DATEFORMAT>';
+ $ret .= '<TIMEFORMAT>'.$row['TimeFormat'].'</TIMEFORMAT><INPUTDATEFORMAT>'.$row['InputDateFormat'].'</INPUTDATEFORMAT>';
+ $ret .= '<INPUTTIMEFORMAT>'.$row['InputTimeFormat'].'</INPUTTIMEFORMAT><DECIMAL>'.$row['DecimalPoint'].'</DECIMAL>';
+ $ret .= '<THOUSANDS>'.$row['ThousandSep'].'</THOUSANDS><CHARSET>'.$row['Charset'].'</CHARSET>';
+ $ret .= '<UNITSYSTEM>'.$row['UnitSystem'].'</UNITSYSTEM>'."\n";
+
+ // phrases
+ $phrases_sql = 'SELECT * FROM '.$phrases_table.' WHERE LanguageId = %s AND PhraseType IN (%s) AND Module IN (%s) ORDER BY Phrase';
+ if( in_array('In-Portal',$module_ids) ) array_push($module_ids, ''); // for old language packs
+ $rows = $this->Conn->Query( sprintf($phrases_sql,$language_id, implode(',',$phrase_types), '\''.implode('\',\'',$module_ids).'\'' ) );
+ if($rows)
+ {
+ $ret .= "\t\t".'<PHRASES>'."\n";
+ foreach($rows as $row)
+ {
+ $data = $this->Encoding == 'base64' ? base64_encode($row['Translation']) : '<![CDATA['.$row['Translation'].']]>';
+ $ret .= sprintf($phrase_tpl, $row['Phrase'], $row['Module'], $row['PhraseType'], $data );
+ }
+ $ret .= "\t\t".'</PHRASES>'."\n";
+ }
+
+ // email events
+ if( in_array('In-Portal',$module_ids) ) unset( $module_ids[array_search('',$module_ids)] ); // for old language packs
+ $module_sql = preg_replace('/(.*) OR $/', '\\1', preg_replace('/(.*),/U', 'INSTR(Module,\'\\1\') OR ', implode(',', $module_ids).',' ) );
+
+ $sql = 'SELECT EventId FROM '.$mainevents_table.' WHERE '.$module_sql;
+ $event_ids = $this->Conn->GetCol($sql);
+
+ if($event_ids)
+ {
+ $ret .= "\t\t".'<EVENTS>'."\n";
+ $event_sql = ' SELECT em.*
+ FROM '.$emailevents_table.' em
+ LEFT JOIN '.$mainevents_table.' e ON e.EventId = em.EventId
+ WHERE em.LanguageId = %s AND em.EventId IN (%s)
+ ORDER BY e.Event, e.Type';
+ $rows = $this->Conn->Query( sprintf($event_sql,$language_id, $event_ids ? implode(',',$event_ids) : '' ) );
+ foreach($rows as $row)
+ {
+ list($event_name, $event_type) = explode('_', $this->events_hash[ $row['EventId'] ] );
+ $data = $this->Encoding == 'base64' ? base64_encode($row['Template']) : '<![CDATA['.$row['Template'].']]>';
+ $ret .= sprintf($event_tpl, $row['MessageType'], $event_name, $event_type, $data );
+ }
+ $ret .= "\t\t".'</EVENTS>'."\n";
+ }
+ $ret .= "\t".'</LANGUAGE>'."\n";
+ }
+
+ $ret .= '</LANGUAGES>';
+ fwrite($fp, $ret);
+ fclose($fp);
+ return true;
+ }
+ }
+
+?>
\ No newline at end of file
Property changes on: branches/unlabeled/unlabeled-1.20.2/core/units/languages/import_xml.php
___________________________________________________________________
Added: cvs2svn:cvs-rev
## -0,0 +1 ##
+1.20
\ No newline at end of property
Added: svn:executable
## -0,0 +1 ##
+*
\ No newline at end of property
Index: branches/unlabeled/unlabeled-1.20.2/core/units/general/cat_dbitem_export.php
===================================================================
--- branches/unlabeled/unlabeled-1.20.2/core/units/general/cat_dbitem_export.php (nonexistent)
+++ branches/unlabeled/unlabeled-1.20.2/core/units/general/cat_dbitem_export.php (revision 5538)
@@ -0,0 +1,1073 @@
+<?php
+
+ define('EXPORT_STEP', 200); // export by 200 items (e.g. links)
+ define('IMPORT_CHUNK', 10240); // 10240); //30720); //50120); // 5 KB
+
+ define('IMPORT_TEMP', 1);
+ define('IMPORT_LIVE', 2);
+
+ class kCatDBItemExportHelper extends kHelper {
+
+ var $false = false;
+
+ var $cache = Array();
+
+ /**
+ * Allows to find out what items are new in cache
+ *
+ * @var Array
+ */
+ var $cacheStatus = Array();
+
+ var $cacheTable = '';
+
+ var $exportFields = Array();
+
+ /**
+ * Export options
+ *
+ * @var Array
+ */
+ var $exportOptions = Array();
+
+ /**
+ * Item beeing currenly exported
+ *
+ * @var kCatDBItem
+ */
+ var $curItem = null;
+
+ /**
+ * Dummy category object
+ *
+ * @var CategoriesItem
+ */
+ var $dummyCategory = null;
+
+ /**
+ * Pointer to opened file
+ *
+ * @var resource
+ */
+ var $filePointer = null;
+
+ /**
+ * Custom fields definition of current item
+ *
+ * @var Array
+ */
+ var $customFields = Array();
+
+ function kCatDBItemExportHelper()
+ {
+ parent::kHelper();
+ $this->cacheTable = TABLE_PREFIX.'ImportCache';
+ }
+
+ /**
+ * Returns value from cache if found or false otherwise
+ *
+ * @param string $type
+ * @param int $key
+ * @return mixed
+ */
+ function getFromCache($type, $key)
+ {
+ return getArrayValue($this->cache, $type, $key);
+ }
+
+ /**
+ * Adds value to be cached
+ *
+ * @param string $type
+ * @param int $key
+ * @param mixed $value
+ */
+ function addToCache($type, $key, $value, $is_new = true)
+ {
+// if (!isset($this->cache[$type])) $this->cache[$type] = Array();
+ $this->cache[$type][$key] = $value;
+ if ($is_new) {
+ $this->cacheStatus[$type][$key] = true;
+ }
+ }
+
+ function storeCache($cache_types)
+ {
+ $cache_types = explode(',', $cache_types);
+
+ $values_sql = '';
+ foreach ($cache_types as $cache_type) {
+ $sql_mask = '('.$this->Conn->qstr($cache_type).',%s,%s),';
+ $cache = getArrayValue($this->cacheStatus, $cache_type);
+ if (!$cache) $cache = Array();
+ foreach ($cache as $var_name => $cache_status) {
+ $var_value = $this->cache[$cache_type][$var_name];
+ $values_sql .= sprintf($sql_mask, $this->Conn->qstr($var_name), $this->Conn->qstr($var_value) );
+ }
+ }
+ $values_sql = preg_replace('/(.*),$/', '\\1', $values_sql);
+ if ($values_sql) {
+ $sql = 'INSERT INTO '.$this->cacheTable.'(`CacheName`,`VarName`,`VarValue`) VALUES '.$values_sql;
+ $this->Conn->Query($sql);
+ }
+
+ }
+
+ function loadCache()
+ {
+ $sql = 'SELECT * FROM '.$this->cacheTable;
+ $records = $this->Conn->Query($sql);
+
+ $this->cache = Array();
+ foreach ($records as $record) {
+ $this->addToCache($record['CacheName'], $record['VarName'], $record['VarValue'], false);
+ }
+ }
+
+ /**
+ * Fill required fields with dummy values
+ *
+ * @param kEvent $event
+ */
+ function fillRequiredFields(&$event, &$object, $set_status = false)
+ {
+ if ($object == $this->false) {
+ $object =& $event->getObject();
+ }
+
+ $has_empty = false;
+ $fields = array_keys($object->Fields);
+ foreach ($fields as $field_name)
+ {
+ $field_options =& $object->Fields[$field_name];
+ if (isset($object->VirtualFields[$field_name]) || !getArrayValue($field_options, 'required') ) continue;
+ if ( $object->GetDBField($field_name) ) continue;
+
+ $formatter_class = getArrayValue($field_options, 'formatter');
+ if ($formatter_class) // not tested
+ {
+ $formatter =& $this->Application->recallObject($formatter_class);
+ $sample_value = $formatter->GetSample($field_name, $field_options, $object);
+ }
+
+ $has_empty = true;
+ $object->SetDBField($field_name, isset($sample_value) && $sample_value ? $sample_value : 'no value');
+ }
+
+ if ($set_status && $has_empty) {
+ $object->SetDBField('Status', 0);
+ }
+ }
+
+ /**
+ * Verifies that all user entered export params are correct
+ *
+ * @param kEvent $event
+ */
+ function verifyOptions(&$event)
+ {
+ if ($this->Application->RecallVar($event->getPrefixSpecial().'_ForceNotValid'))
+ {
+ $this->Application->StoreVar($event->getPrefixSpecial().'_ForceNotValid', 0);
+ return false;
+ }
+
+ $this->fillRequiredFields($event, $this->false);
+
+ $object =& $event->getObject();
+ $cross_unique_fields = Array('FieldsSeparatedBy', 'FieldsEnclosedBy');
+ if (($object->GetDBField('CategoryFormat') == 1) || ($event->Special == 'import')) // in one field
+ {
+ $object->setRequired('CategorySeparator', true);
+ $cross_unique_fields[] = 'CategorySeparator';
+ }
+
+ $ret = $object->Validate();
+
+ // check if cross unique fields has no same values
+ foreach ($cross_unique_fields as $field_index => $field_name)
+ {
+ if (getArrayValue($object->FieldErrors, $field_name, 'pseudo') == 'required') continue;
+
+ $check_fields = $cross_unique_fields;
+ unset($check_fields[$field_index]);
+
+ foreach ($check_fields as $check_field)
+ {
+ if ($object->GetDBField($field_name) == $object->GetDBField($check_field))
+ {
+ $object->SetError($check_field, 'unique');
+ }
+ }
+ }
+
+ if ($event->Special == 'import')
+ {
+ $this->exportOptions = $this->loadOptions($event);
+
+ $automatic_fields = ($object->GetDBField('FieldTitles') == 1);
+ $object->setRequired('ExportColumns', !$automatic_fields);
+ $category_prefix = '__CATEGORY__';
+ if ( $automatic_fields && ($this->exportOptions['SkipFirstRow']) ) {
+ $this->openFile($event);
+ $this->exportOptions['ExportColumns'] = $this->readRecord();
+ $this->closeFile();
+
+ // remove additional (non-parseble columns)
+ foreach ($this->exportOptions['ExportColumns'] as $field_index => $field_name) {
+ if (!$this->validateField($field_name, $object)) {
+ unset($this->exportOptions['ExportColumns'][$field_index]);
+ }
+ }
+ $category_prefix = '';
+ }
+
+ // 1. check, that we have column definitions
+ if (!$this->exportOptions['ExportColumns']) {
+ $object->setError('ExportColumns', 'required');
+ $ret = false;
+ }
+ else {
+ // 1.1. check that all required fields are present in imported file
+ $missing_columns = Array();
+ foreach ($object->Fields as $field_name => $field_options) {
+ if ($object->SkipField($field_name)) continue;
+ if (getArrayValue($field_options, 'required') && !in_array($field_name, $this->exportOptions['ExportColumns']) ) {
+ $missing_columns[] = $field_name;
+ $object->setError('ExportColumns', 'required_fields_missing', 'la_error_RequiredColumnsMissing');
+ $ret = false;
+ }
+ }
+
+ if (!$ret && $this->Application->isDebugMode()) {
+ $this->Application->Debugger->appendHTML('Missing required for import/export:');
+ $this->Application->Debugger->dumpVars($missing_columns);
+ }
+ }
+
+
+ // 2. check, that we have only mixed category field or only separated category fields
+ $category_found['mixed'] = false;
+ $category_found['separated'] = false;
+
+ foreach ($this->exportOptions['ExportColumns'] as $import_field) {
+ if (preg_match('/^'.$category_prefix.'Category(Path|[0-9]+)/', $import_field, $rets)) {
+ $category_found[$rets[1] == 'Path' ? 'mixed' : 'separated'] = true;
+ }
+ }
+ if ($category_found['mixed'] && $category_found['separated']) {
+ $object->SetError('ExportColumns', 'unique_category', 'la_error_unique_category_field');
+ $ret = false;
+ }
+
+ // 3. check, that duplicates check fields are selected & present in imported fields
+ if ($this->exportOptions['ReplaceDuplicates']) {
+ if ($this->exportOptions['CheckDuplicatesMethod'] == 1) {
+ $check_fields = Array($object->IDField);
+ }
+ else {
+ $check_fields = $this->exportOptions['DuplicateCheckFields'] ? explode('|', substr($this->exportOptions['DuplicateCheckFields'], 1, -1)) : Array();
+ $object =& $event->getObject();
+
+ $language_id = $this->Application->GetDefaultLanguageId();
+ foreach ($check_fields as $index => $check_field) {
+ foreach ($object->Fields as $field_name => $field_options) {
+ if ($field_name == 'l'.$language_id.'_'.$check_field) {
+ $check_fields[$index] = 'l'.$language_id.'_'.$check_field;
+ break;
+ }
+ }
+ }
+ }
+ $this->exportOptions['DuplicateCheckFields'] = $check_fields;
+
+ if (!$check_fields) {
+ $object->setError('CheckDuplicatesMethod', 'required');
+ $ret = false;
+ }
+ else {
+ foreach ($check_fields as $check_field) {
+ $check_field = preg_replace('/^cust_(.*)/', 'Custom_\\1', $check_field);
+ if (!in_array($check_field, $this->exportOptions['ExportColumns'])) {
+ $object->setError('ExportColumns', 'required');
+ $ret = false;
+ break;
+ }
+ }
+ }
+ }
+ $this->saveOptions($event);
+ }
+
+ return $ret;
+ }
+
+ /**
+ * Returns filename to read import data from
+ *
+ * @return string
+ */
+ function getImportFilename()
+ {
+ if ($this->exportOptions['ImportSource'] == 1)
+ {
+ $ret = $this->exportOptions['ImportFilename']; // ['name']; commented by Kostja
+ }
+ else {
+ $ret = $this->exportOptions['ImportLocalFilename'];
+ }
+ return EXPORT_PATH.'/'.$ret;
+ }
+
+ /**
+ * Returns filename to write export data to
+ *
+ * @return string
+ */
+ function getExportFilename()
+ {
+ return EXPORT_PATH.'/'.$this->exportOptions['ExportFilename'].'.'.$this->getFileExtension();
+ }
+
+ /**
+ * Opens file required for export/import operations
+ *
+ * @param kEvent $event
+ */
+ function openFile(&$event)
+ {
+ if ($event->Special == 'export') {
+ $write_mode = ($this->exportOptions['start_from'] == 0) ? 'w' : 'a';
+ $this->filePointer = fopen($this->getExportFilename(), $write_mode);
+ }
+ else {
+ $this->filePointer = fopen($this->getImportFilename(), 'r');
+ }
+
+ // skip UTF-8 BOM Modifier
+ $first_chars = fread($this->filePointer, 3);
+ if (bin2hex($first_chars) != 'efbbbf') {
+ fseek($this->filePointer, 0);
+ }
+ }
+
+ /**
+ * Closes opened file
+ *
+ */
+ function closeFile()
+ {
+ fclose($this->filePointer);
+ }
+
+ function getCustomSQL()
+ {
+ $ml_formatter =& $this->Application->recallObject('kMultiLanguage');
+
+ $custom_sql = '';
+ foreach ($this->customFields as $custom_id => $custom_name) {
+ $custom_sql .= 'custom_data.'.$ml_formatter->LangFieldName('cust_'.$custom_id).' AS cust_'.$custom_name.', ';
+ }
+
+ return preg_replace('/(.*), /', '\\1', $custom_sql);
+ }
+
+ function getExportSQL($count_only = false)
+ {
+ if ($this->exportOptions['export_ids'] === false)
+ {
+ // get links from current category & all it's subcategories
+ $join_clauses = Array();
+
+ $custom_sql = $this->getCustomSQL();
+ if ($custom_sql) {
+ $custom_table = $this->Application->getUnitOption($this->curItem->Prefix.'-cdata', 'TableName');
+ $join_clauses[$custom_table.' custom_data'] = 'custom_data.ResourceId = item_table.ResourceId';
+ }
+
+ $join_clauses[TABLE_PREFIX.'CategoryItems ci'] = 'ci.ItemResourceId = item_table.ResourceId';
+ $join_clauses[TABLE_PREFIX.'Category c'] = 'c.CategoryId = ci.CategoryId';
+
+ $sql = 'SELECT item_table.*, ci.CategoryId'.($custom_sql ? ', '.$custom_sql : '').'
+ FROM '.$this->curItem->TableName.' item_table';
+
+ foreach ($join_clauses as $table_name => $join_expression) {
+ $sql .= ' LEFT JOIN '.$table_name.' ON '.$join_expression;
+ }
+ $sql .= ' WHERE ';
+
+ if ($this->exportOptions['export_cats_ids'][0] == 0)
+ {
+ $sql .= '1';
+ }
+ else {
+ foreach ($this->exportOptions['export_cats_ids'] as $category_id) {
+ $sql .= '(c.ParentPath LIKE "%|'.$category_id.'|%") OR ';
+ }
+ $sql = preg_replace('/(.*) OR $/', '\\1', $sql);
+ }
+
+ $sql .= ' ORDER BY ci.PrimaryCat DESC'; // NEW
+ }
+ else {
+ // get only selected links
+ $sql = 'SELECT item_table.*, '.$this->exportOptions['export_cats_ids'][0].' AS CategoryId
+ FROM '.$this->curItem->TableName.' item_table
+ WHERE '.$this->curItem->IDField.' IN ('.implode(',', $this->exportOptions['export_ids']).')';
+ }
+
+ if (!$count_only)
+ {
+ $sql .= ' LIMIT '.$this->exportOptions['start_from'].','.EXPORT_STEP;
+ }
+ else {
+ $sql = preg_replace("/^.*SELECT(.*?)FROM(?!_)/is", "SELECT COUNT(*) AS count FROM ", $sql);
+ }
+
+ return $sql;
+ }
+
+ /**
+ * Enter description here...
+ *
+ * @param kEvent $event
+ */
+ function performExport(&$event)
+ {
+ $this->exportOptions = $this->loadOptions($event);
+ $this->exportFields = $this->exportOptions['ExportColumns'];
+ $this->curItem =& $event->getObject( Array('skip_autoload' => true) );
+ $this->customFields = $this->Application->getUnitOption($event->Prefix, 'CustomFields');
+ $this->openFile($event);
+
+ if ($this->exportOptions['start_from'] == 0) // first export step
+ {
+ if (!getArrayValue($this->exportOptions, 'IsBaseCategory')) {
+ $this->exportOptions['IsBaseCategory'] = 0;
+ }
+
+ if ($this->exportOptions['IsBaseCategory'] ) {
+ $sql = 'SELECT CachedNavbar
+ FROM '.TABLE_PREFIX.'Category
+ WHERE CategoryId = '.$this->Application->GetVar('m_cat_id');
+ $this->exportOptions['BaseLevel'] = substr_count($this->Conn->GetOne($sql), '>') + 1; // level to cut from other categories
+ }
+
+ // 1. export field titles if required
+ if ($this->exportOptions['IncludeFieldTitles'])
+ {
+ $data_array = Array();
+ foreach ($this->exportFields as $export_field)
+ {
+ $data_array = array_merge($data_array, $this->getFieldCaption($export_field));
+ }
+ $this->writeRecord($data_array);
+ }
+ $this->exportOptions['total_records'] = $this->Conn->GetOne( $this->getExportSQL(true) );
+ }
+
+ // 2. export data
+ $records = $this->Conn->Query( $this->getExportSQL() );
+ $records_exported = 0;
+ foreach ($records as $record_info) {
+ $this->curItem->Clear();
+ $this->curItem->SetDBFieldsFromHash($record_info);
+ $this->setCurrentID();
+ $this->curItem->raiseEvent('OnAfterItemLoad', $this->curItem->GetID() );
+
+ $data_array = Array();
+ foreach ($this->exportFields as $export_field)
+ {
+ $data_array = array_merge($data_array, $this->getFieldValue($export_field) );
+ }
+ $this->writeRecord($data_array);
+ $records_exported++;
+ }
+ $this->closeFile();
+
+ $this->exportOptions['start_from'] += $records_exported;
+ $this->saveOptions($event);
+
+ return $this->exportOptions;
+ }
+
+ function getItemFields()
+ {
+ // just in case dummy user selected automtic mode & moved columns too :(
+ return array_merge($this->curItem->Fields['AvailableColumns']['options'], $this->curItem->Fields['ExportColumns']['options']);
+ }
+
+ /**
+ * Checks if field really belongs to importable field list
+ *
+ * @param string $field_name
+ * @param kCatDBItem $object
+ * @return bool
+ */
+ function validateField($field_name, &$object)
+ {
+ // 1. convert custom field
+ $field_name = preg_replace('/^Custom_(.*)/', '__CUSTOM__\\1', $field_name);
+
+ // 2. convert category field (mixed version & serparated version)
+ $field_name = preg_replace('/^Category(Path|[0-9]+)/', '__CATEGORY__Category\\1', $field_name);
+
+ $valid_fields = $object->getPossibleExportColumns();
+ return isset($valid_fields[$field_name]) || isset($valid_fields['__VIRTUAL__'.$field_name]);
+ }
+
+ /**
+ * Enter description here...
+ *
+ * @param kEvent $event
+ */
+ function performImport(&$event)
+ {
+ if (!$this->exportOptions) {
+ // load import options in case if not previously loaded in verification function
+ $this->exportOptions = $this->loadOptions($event);
+ }
+
+ $backup_category_id = $this->Application->GetVar('m_cat_id');
+ $this->Application->SetVar('m_cat_id', (int)$this->Application->RecallVar('ImportCategory') );
+
+ $this->openFile($event);
+
+ $bytes_imported = 0;
+ if ($this->exportOptions['start_from'] == 0) // first export step
+ {
+ // 1st time run
+ if ($this->exportOptions['SkipFirstRow']) {
+ $this->readRecord();
+ $this->exportOptions['start_from'] = ftell($this->filePointer);
+ $bytes_imported = ftell($this->filePointer);
+ }
+
+ $current_category_id = $this->Application->GetVar('m_cat_id');
+ if ($current_category_id > 0) {
+ $sql = 'SELECT ParentPath FROM '.TABLE_PREFIX.'Category WHERE CategoryId = '.$current_category_id;
+ $this->exportOptions['ImportCategoryPath'] = $this->Conn->GetOne($sql);
+ }
+ else {
+ $this->exportOptions['ImportCategoryPath'] = '';
+ }
+ $this->exportOptions['total_records'] = filesize($this->getImportFilename());
+ }
+ else {
+ $this->loadCache();
+ }
+
+ $this->exportFields = $this->exportOptions['ExportColumns'];
+ $this->addToCache('category_parent_path', $this->Application->GetVar('m_cat_id'), $this->exportOptions['ImportCategoryPath']);
+
+ // 2. import data
+ $this->dummyCategory =& $this->Application->recallObject('c.-tmpitem', 'c', Array('skip_autoload' => true));
+ fseek($this->filePointer, $this->exportOptions['start_from']);
+
+ while (($bytes_imported < IMPORT_CHUNK) && !feof($this->filePointer)) {
+ $data = $this->readRecord();
+ if ($data) {
+ if ($this->exportOptions['ReplaceDuplicates']) {
+ // set fields used as keys for replace duplicates code
+ $this->resetImportObject($event, IMPORT_TEMP, $data);
+ }
+
+ $this->processCurrentItem($event, $data);
+ }
+ $bytes_imported = ftell($this->filePointer) - $this->exportOptions['start_from'];
+ }
+
+ $this->closeFile();
+ $this->Application->SetVar('m_cat_id', $backup_category_id);
+
+ $this->exportOptions['start_from'] += $bytes_imported;
+ $this->storeCache('new_ids');
+
+ $this->saveOptions($event);
+
+ if ($this->exportOptions['start_from'] == $this->exportOptions['total_records']) {
+ $this->Conn->Query('TRUNCATE TABLE '.$this->cacheTable);
+ }
+
+ return $this->exportOptions;
+ }
+
+ function setCurrentID()
+ {
+ $this->curItem->setID( $this->curItem->GetDBField($this->curItem->IDField) );
+ }
+
+ function setFieldValue($field_index, $value)
+ {
+ if (empty($value)) {
+ $value = null;
+ }
+
+ $field_name = getArrayValue($this->exportFields, $field_index);
+ if ($field_name == 'ResourceId') {
+ return false;
+ }
+
+ if (substr($field_name, 0, 7) == 'Custom_') {
+ $field_name = 'cust_'.substr($field_name, 7);
+ $this->curItem->SetField($field_name, $value);
+ }
+ elseif ($field_name == 'CategoryPath' || $field_name == '__CATEGORY__CategoryPath') {
+ $this->curItem->CategoryPath = $value ? explode($this->exportOptions['CategorySeparator'], $value) : Array();
+ }
+ elseif (substr($field_name, 0, 8) == 'Category') {
+ $this->curItem->CategoryPath[ (int)substr($field_name, 8) - 1 ] = $value;
+ }
+ elseif (substr($field_name, 0, 20) == '__CATEGORY__Category') {
+ $this->curItem->CategoryPath[ (int)substr($field_name, 20) ] = $value;
+ }
+ elseif (substr($field_name, 0, 11) == '__VIRTUAL__') {
+ $field_name = substr($field_name, 11);
+ $this->curItem->SetField($field_name, $value);
+ }
+ else {
+ $this->curItem->SetField($field_name, $value);
+ }
+
+ $pseudo_error = getArrayValue($this->curItem->FieldErrors, $field_name, 'pseudo');
+ if ($pseudo_error) {
+ $this->curItem->SetDBField($field_name, null);
+ unset($this->curItem->FieldErrors[$field_name]);
+ }
+ }
+
+ function resetImportObject(&$event, $object_type, $record_data = null)
+ {
+ switch ($object_type) {
+ case IMPORT_TEMP:
+ $this->curItem =& $event->getObject( Array('skip_autoload' => true) );
+ break;
+
+ case IMPORT_LIVE:
+ $this->curItem =& $this->Application->recallObject($event->Prefix.'.-tmpitem'.$event->Special, $event->Prefix, Array('skip_autoload' => true));
+ break;
+ }
+ $this->curItem->Clear();
+ $this->customFields = $this->Application->getUnitOption($event->Prefix, 'CustomFields');
+
+ if (isset($record_data)) {
+ $this->setImportData($record_data);
+ }
+ }
+
+ function setImportData($record_data)
+ {
+ foreach ($record_data as $field_index => $field_value) {
+ $this->setFieldValue($field_index, $field_value);
+ }
+ $this->setCurrentID();
+ }
+
+
+ function getItemCategory()
+ {
+ static $lang_prefix = null;
+ $backup_category_id = $this->Application->GetVar('m_cat_id');
+
+ $category_id = $this->getFromCache('category_names', implode(':', $this->curItem->CategoryPath));
+ if ($category_id) {
+ $this->Application->SetVar('m_cat_id', $category_id);
+ return $category_id;
+ }
+
+ if (is_null($lang_prefix)) {
+ $lang_prefix = 'l'.$this->Application->GetVar('m_lang').'_';
+ }
+
+ foreach ($this->curItem->CategoryPath as $category_index => $category_name) {
+ if (!$category_name) continue;
+ $category_key = crc32( implode(':', array_slice($this->curItem->CategoryPath, 0, $category_index + 1) ) );
+
+ $category_id = $this->getFromCache('category_names', $category_key);
+ if ($category_id === false) {
+ // get parent category path to search only in it
+ $current_category_id = $this->Application->GetVar('m_cat_id');
+// $parent_path = $this->getParentPath($current_category_id);
+
+ // get category id from database by name
+ $sql = 'SELECT CategoryId
+ FROM '.TABLE_PREFIX.'Category
+ WHERE ('.$lang_prefix.'Name = '.$this->Conn->qstr($category_name).') AND (ParentId = '.$current_category_id.')';
+ $category_id = $this->Conn->GetOne($sql);
+
+ if ($category_id === false) {
+ // category not in db -> create
+ $category_fields = Array( $lang_prefix.'Name' => $category_name, $lang_prefix.'Description' => $category_name,
+ 'Status' => STATUS_ACTIVE, 'ParentId' => $current_category_id, 'AutomaticFilename' => 1
+ );
+ $this->dummyCategory->SetDBFieldsFromHash($category_fields);
+ if ($this->dummyCategory->Create()) {
+ $category_id = $this->dummyCategory->GetID();
+ $this->addToCache('category_parent_path', $category_id, $this->dummyCategory->GetDBField('ParentPath'));
+ $this->addToCache('category_names', $category_key, $category_id);
+ }
+ }
+ else {
+ $this->addToCache('category_names', $category_key, $category_id);
+ }
+ }
+
+ if ($category_id) {
+ $this->Application->SetVar('m_cat_id', $category_id);
+ }
+ }
+ if (!$this->curItem->CategoryPath) {
+ $category_id = $backup_category_id;
+ }
+
+ return $category_id;
+ }
+
+ /**
+ * Enter description here...
+ *
+ * @param kEvent $event
+ */
+ function processCurrentItem(&$event, $record_data)
+ {
+ $save_method = 'Create';
+ $load_keys = Array();
+
+ // create/update categories
+ $backup_category_id = $this->Application->GetVar('m_cat_id');
+
+ // perform replace duplicates code
+ if ($this->exportOptions['ReplaceDuplicates']) {
+ // get replace keys first, then reset current item to empty one
+ $category_id = $this->getItemCategory();
+ if ($this->exportOptions['CheckDuplicatesMethod'] == 1) {
+ if ($this->curItem->GetID()) {
+ $load_keys = Array($this->curItem->IDField => $this->curItem->GetID());
+ }
+ }
+ else {
+ $key_fields = $this->exportOptions['DuplicateCheckFields'];
+ foreach ($key_fields as $key_field) {
+ $load_keys[$key_field] = $this->curItem->GetDBField($key_field);
+ }
+ }
+
+ $this->resetImportObject($event, IMPORT_LIVE);
+
+ if (count($load_keys)) {
+ $where_clause = '';
+ foreach ($load_keys as $field_name => $field_value) {
+ if (preg_match('/^cust_(.*)/', $field_name, $regs)) {
+ $custom_id = array_search($regs[1], $this->customFields);
+ $field_name = 'l'.$this->Application->GetVar('m_lang').'_cust_'.$custom_id;
+ $where_clause .= '(custom_data.`'.$field_name.'` = '.$this->Conn->qstr($field_value).') AND ';
+ }
+ else {
+ $where_clause .= '(item_table.`'.$field_name.'` = '.$this->Conn->qstr($field_value).') AND ';
+ }
+
+ }
+ $where_clause = preg_replace('/(.*) AND $/', '\\1', $where_clause);
+
+ $item_id = $this->getFromCache('new_ids', crc32($where_clause));
+ if (!$item_id) {
+ if ($this->exportOptions['CheckDuplicatesMethod'] == 2) {
+ // by other fields
+ $parent_path = $this->getParentPath($category_id);
+ $where_clause = '(c.ParentPath LIKE "'.$parent_path.'%") AND '.$where_clause;
+ }
+
+ $cdata_table = $this->Application->getUnitOption($event->Prefix.'-cdata', 'TableName');
+ $sql = 'SELECT '.$this->curItem->IDField.'
+ FROM '.$this->curItem->TableName.' item_table
+ LEFT JOIN '.$cdata_table.' custom_data ON custom_data.ResourceId = item_table.ResourceId
+ LEFT JOIN '.TABLE_PREFIX.'CategoryItems ci ON ci.ItemResourceId = item_table.ResourceId
+ LEFT JOIN '.TABLE_PREFIX.'Category c ON c.CategoryId = ci.CategoryId
+ WHERE '.$where_clause;
+ $item_id = $this->Conn->GetOne($sql);
+ }
+ $save_method = $item_id && $this->curItem->Load($item_id) ? 'Update' : 'Create';
+ if ($save_method == 'Update') {
+ // replace id from csv file with found id
+ $record_data[ array_search($this->curItem->IDField, $this->exportFields) ] = $item_id;
+ }
+ }
+
+ $this->setImportData($record_data);
+ }
+ else {
+ $this->resetImportObject($event, IMPORT_LIVE, $record_data);
+ $category_id = $this->getItemCategory();
+ }
+
+ // create main record
+ if ($save_method == 'Create') {
+ $this->fillRequiredFields($this->false, $this->curItem, true);
+ }
+
+// $sql_start = getmicrotime();
+ if (!$this->curItem->$save_method()) {
+ return false;
+ }
+// $sql_end = getmicrotime();
+// $this->saveLog('SQL ['.$save_method.'] Time: '.($sql_end - $sql_start).'s');
+
+ if ($load_keys && ($save_method == 'Create') && $this->exportOptions['ReplaceDuplicates']) {
+ // map new id to old id
+ $this->addToCache('new_ids', crc32($where_clause), $this->curItem->GetID() );
+ }
+
+ // assign item to categories
+ $this->curItem->assignToCategory($category_id, false);
+
+ $this->Application->SetVar('m_cat_id', $backup_category_id);
+ return true;
+ }
+
+ /*function saveLog($msg)
+ {
+ static $first_time = true;
+
+ $fp = fopen(FULL_PATH.'/sqls.log', $first_time ? 'w' : 'a');
+ fwrite($fp, $msg."\n");
+ fclose($fp);
+
+ $first_time = false;
+ }*/
+
+ /**
+ * Returns category parent path, if possible, then from cache
+ *
+ * @param int $category_id
+ * @return string
+ */
+ function getParentPath($category_id)
+ {
+ $parent_path = $this->getFromCache('category_parent_path', $category_id);
+ if ($parent_path === false) {
+ $sql = 'SELECT ParentPath
+ FROM '.TABLE_PREFIX.'Category
+ WHERE CategoryId = '.$category_id;
+ $parent_path = $this->Conn->GetOne($sql);
+ $this->addToCache('category_parent_path', $category_id, $parent_path);
+ }
+ return $parent_path;
+ }
+
+ function getFileExtension()
+ {
+ return $this->exportOptions['ExportFormat'] == 1 ? 'csv' : 'xml';
+ }
+
+ function getLineSeparator($option = 'LineEndings')
+ {
+ return $this->exportOptions[$option] == 1 ? "\r\n" : "\n";
+ }
+
+ /**
+ * Returns field caption for any exported field
+ *
+ * @param string $field
+ * @return string
+ */
+ function getFieldCaption($field)
+ {
+ if (substr($field, 0, 10) == '__CUSTOM__')
+ {
+ $ret = 'Custom_'.substr($field, 10, strlen($field) );
+ }
+ elseif (substr($field, 0, 12) == '__CATEGORY__')
+ {
+ return $this->getCategoryTitle();
+ }
+ elseif (substr($field, 0, 11) == '__VIRTUAL__') {
+ $ret = substr($field, 11);
+ }
+ else
+ {
+ $ret = $field;
+ }
+
+ return Array($ret);
+ }
+
+ /**
+ * Returns requested field value (including custom fields and category fields)
+ *
+ * @param string $field
+ * @return string
+ */
+ function getFieldValue($field)
+ {
+ if (substr($field, 0, 10) == '__CUSTOM__') {
+ $field = 'cust_'.substr($field, 10, strlen($field));
+ $ret = $this->curItem->GetField($field);
+ }
+ elseif (substr($field, 0, 12) == '__CATEGORY__') {
+ return $this->getCategoryPath();
+ }
+ elseif (substr($field, 0, 11) == '__VIRTUAL__') {
+ $field = substr($field, 11);
+ return $this->curItem->GetField($field);
+ }
+ else
+ {
+ $ret = $this->curItem->GetField($field);
+ }
+
+ $ret = str_replace("\r\n", $this->getLineSeparator('LineEndingsInside'), $ret);
+ return Array($ret);
+ }
+
+ /**
+ * Returns category field(-s) caption based on export mode
+ *
+ * @return string
+ */
+ function getCategoryTitle()
+ {
+ // category path in separated fields
+ $category_count = $this->getMaxCategoryLevel();
+ if ($this->exportOptions['CategoryFormat'] == 1)
+ {
+ // category path in one field
+ return $category_count ? Array('CategoryPath') : Array();
+ }
+ else
+ {
+ $i = 0;
+ $ret = Array();
+ while ($i < $category_count) {
+ $ret[] = 'Category'.($i + 1);
+ $i++;
+ }
+ return $ret;
+ }
+ }
+
+ /**
+ * Returns category path in required format for current link
+ *
+ * @return string
+ */
+ function getCategoryPath()
+ {
+ $category_id = $this->curItem->GetDBField('CategoryId');
+ $category_path = $this->getFromCache('category_path', $category_id);
+ if (!$category_path)
+ {
+ $sql = 'SELECT CachedNavbar
+ FROM '.TABLE_PREFIX.'Category
+ WHERE CategoryId = '.$category_id;
+ $category_path = $this->Conn->GetOne($sql);
+ $category_path = $category_path ? explode('>', $category_path) : Array();
+
+ if ($this->exportOptions['IsBaseCategory']) {
+ $i = $this->exportOptions['BaseLevel'];
+ while ($i > 0) {
+ array_shift($category_path);
+ $i--;
+ }
+ }
+
+ $category_count = $this->getMaxCategoryLevel();
+ if ($this->exportOptions['CategoryFormat'] == 1) {
+ // category path in single field
+ $category_path = $category_count ? Array( implode($this->exportOptions['CategorySeparator'], $category_path) ) : Array();
+ }
+ else {
+ // category path in separated fields
+ $levels_used = count($category_path);
+ if ($levels_used < $category_count)
+ {
+ $i = 0;
+ while ($i < $category_count - $levels_used) {
+ $category_path[] = '';
+ $i++;
+ }
+ }
+ }
+ $this->addToCache('category_path', $category_id, $category_path);
+ }
+
+ return $category_path;
+ }
+
+ /**
+ * Get maximal category deep level from links beeing exported
+ *
+ * @return int
+ */
+ function getMaxCategoryLevel()
+ {
+ static $max_level = -1;
+
+ if ($max_level != -1)
+ {
+ return $max_level;
+ }
+
+ $sql = 'SELECT IF(c.CategoryId IS NULL, 0, MAX( LENGTH(c.ParentPath) - LENGTH( REPLACE(c.ParentPath, "|", "") ) - 1 ))
+ FROM '.$this->curItem->TableName.' item_table
+ LEFT JOIN '.TABLE_PREFIX.'CategoryItems ci ON item_table.ResourceId = ci.ItemResourceId
+ LEFT JOIN '.TABLE_PREFIX.'Category c ON c.CategoryId = ci.CategoryId
+ WHERE (ci.PrimaryCat = 1) AND ';
+
+ $where_clause = '';
+ if ($this->exportOptions['export_ids'] === false) {
+ // get links from current category & all it's subcategories
+ if ($this->exportOptions['export_cats_ids'][0] == 0) {
+ $where_clause = 1;
+ }
+ else {
+ foreach ($this->exportOptions['export_cats_ids'] as $category_id) {
+ $where_clause .= '(c.ParentPath LIKE "%|'.$category_id.'|%") OR ';
+ }
+ $where_clause = preg_replace('/(.*) OR $/', '\\1', $where_clause);
+ }
+ }
+ else {
+ // get only selected links
+ $where_clause = $this->curItem->IDField.' IN ('.implode(',', $this->exportOptions['export_ids']).')';
+ }
+
+ $max_level = $this->Conn->GetOne($sql.'('.$where_clause.')');
+
+ if ($this->exportOptions['IsBaseCategory'] ) {
+ $max_level -= $this->exportOptions['BaseLevel'];
+ }
+
+ return $max_level;
+ }
+
+ /**
+ * Saves one record to export file
+ *
+ * @param Array $fields_hash
+ */
+ function writeRecord($fields_hash)
+ {
+ fputcsv2($this->filePointer, $fields_hash, $this->exportOptions['FieldsSeparatedBy'], $this->exportOptions['FieldsEnclosedBy'], $this->getLineSeparator() );
+ }
+
+ function readRecord()
+ {
+ return fgetcsv($this->filePointer, 10000, $this->exportOptions['FieldsSeparatedBy'], $this->exportOptions['FieldsEnclosedBy']);
+ }
+
+ function saveOptions(&$event, $options = null)
+ {
+ if (!isset($options)) {
+ $options = $this->exportOptions;
+ }
+ $this->Application->StoreVar($event->getPrefixSpecial().'_options', serialize($options) );
+ }
+
+ function loadOptions(&$event)
+ {
+ return unserialize($this->Application->RecallVar($event->getPrefixSpecial().'_options'));
+ }
+ }
+
+?>
Property changes on: branches/unlabeled/unlabeled-1.20.2/core/units/general/cat_dbitem_export.php
___________________________________________________________________
Added: cvs2svn:cvs-rev
## -0,0 +1 ##
+1.20
\ No newline at end of property
Added: svn:executable
## -0,0 +1 ##
+*
\ No newline at end of property
Index: branches/unlabeled/unlabeled-1.20.2/core/units/general/inp_ses_storage.php
===================================================================
--- branches/unlabeled/unlabeled-1.20.2/core/units/general/inp_ses_storage.php (nonexistent)
+++ branches/unlabeled/unlabeled-1.20.2/core/units/general/inp_ses_storage.php (revision 5538)
@@ -0,0 +1,118 @@
+<?php
+
+ class InpSession extends Session
+ {
+ function Init($prefix,$special)
+ {
+ $this->SessionTimeout = $this->Application->ConfigValue('SessionTimeout');
+
+ $path = (BASE_PATH == '') ? '/' : BASE_PATH;
+ if ( $this->Application->IsAdmin() ) $path = rtrim($path, '/').'/admin';
+ $this->SetCookiePath($path);
+
+ $cookie_name = $this->Application->ConfigValue('SessionCookieName');
+ $this->SetCookieName($cookie_name ? $cookie_name : 'sid');
+
+ $this->SetCookieDomain(SERVER_NAME);
+
+ if( $this->Application->IsAdmin() )
+ {
+ $mode = constOn('IS_INSTALL') ? smCOOKIES_ONLY : smAUTO;
+ }
+ else
+ {
+ $ses_mode = $this->Application->ConfigValue('CookieSessions');
+ if ($ses_mode == 2) $mode = smAUTO;
+ if ($ses_mode == 1) $mode = smCOOKIES_ONLY;
+ if ($ses_mode == 0) $mode = smGET_ONLY;
+ }
+ $this->SetMode($mode);
+
+ parent::Init($prefix,$special);
+
+ if( !$this->Application->IsAdmin() && $this->GetField('PortalUserId') <= 0 )
+ {
+ $group_list = $this->Application->ConfigValue('User_GuestGroup').','.$this->Application->ConfigValue('User_LoggedInGroup');
+ $this->SetField('GroupId', $this->Application->ConfigValue('User_GuestGroup'));
+ $this->SetField('GroupList', $group_list);
+ }
+ }
+ }
+
+class InpSessionStorage extends SessionStorage {
+
+ function Init($prefix,$special)
+ {
+ parent::Init($prefix,$special);
+ $this->setTableName(TABLE_PREFIX.'UserSession');
+ $this->SessionDataTable = TABLE_PREFIX.'SessionData';
+ $this->setIDField('SessionKey');
+ $this->TimestampField = 'LastAccessed';
+ $this->DataValueField = 'VariableValue';
+ $this->DataVarField = 'VariableName';
+ }
+
+ function LocateSession($sid)
+ {
+ $res = parent::LocateSession($sid);
+ if ($res) {
+ $this->Expiration += $this->SessionTimeout;
+ }
+ return $res;
+ }
+
+ function UpdateSession(&$session)
+ {
+ $time = adodb_mktime();
+ // Update LastAccessed only if it's newer than 1/10 of session timeout - perfomance optimization to eliminate needless updates on every click
+ if ($time - $this->DirectVars['LastAccessed'] > $this->SessionTimeout/10) {
+ $this->SetField($session, $this->TimestampField, $time);
+ }
+ }
+
+
+ function StoreSession(&$session, $additional_fields = Array())
+ {
+ $fields_hash = Array( 'PortalUserId' => $this->Application->IsAdmin() ? 0 : -2, // Guest
+ 'Language' => $this->Application->GetDefaultLanguageId(),
+ 'Theme' => $this->Application->GetDefaultThemeId(),
+ 'IpAddress' => $_SERVER['REMOTE_ADDR'],
+ 'GroupList' => $this->Application->ConfigValue('User_GuestGroup'),
+ 'CurrentTempKey'=> $session->SID,
+
+ );
+
+ parent::StoreSession($session, $fields_hash);
+ }
+
+ function GetExpiredSIDs()
+ {
+ $query = ' SELECT '.$this->IDField.' FROM '.$this->TableName.' WHERE '.$this->TimestampField.' < '.(adodb_mktime()-$this->SessionTimeout);
+ $ret = $this->Conn->GetCol($query);
+ if($ret) {
+ $this->DeleteEditTables();
+ }
+ return $ret;
+
+ }
+
+ function DeleteEditTables()
+ {
+ $tables = $this->Conn->GetCol('SHOW TABLES');
+ $mask_edit_table = '/'.TABLE_PREFIX.'ses_(.*)_edit_(.*)/';
+ $mask_search_table = '/'.TABLE_PREFIX.'ses_(.*?)_(.*)/';
+
+ $sql='SELECT COUNT(*) FROM '.$this->TableName.' WHERE '.$this->IDField.' = \'%s\'';
+ foreach($tables as $table)
+ {
+ if( preg_match($mask_edit_table,$table,$rets) || preg_match($mask_search_table,$table,$rets) )
+ {
+ $sid=$rets[1];
+ $is_alive = $this->Conn->GetOne( sprintf($sql,$sid) );
+ if(!$is_alive) $this->Conn->Query('DROP TABLE IF EXISTS '.$table);
+ }
+ }
+ }
+}
+
+?>
\ No newline at end of file
Property changes on: branches/unlabeled/unlabeled-1.20.2/core/units/general/inp_ses_storage.php
___________________________________________________________________
Added: cvs2svn:cvs-rev
## -0,0 +1 ##
+1.20
\ No newline at end of property
Added: svn:executable
## -0,0 +1 ##
+*
\ No newline at end of property

Event Timeline