Page MenuHomeIn-Portal Phabricator

in-portal
No OneTemporary

File Metadata

Created
Tue, Feb 11, 6:29 PM

in-portal

Index: branches/5.0.x/core/kernel/utility/email_send.php
===================================================================
--- branches/5.0.x/core/kernel/utility/email_send.php (revision 12705)
+++ branches/5.0.x/core/kernel/utility/email_send.php (revision 12706)
@@ -1,2020 +1,2018 @@
<?php
/**
* @version $Id$
* @package In-Portal
* @copyright Copyright (C) 1997 - 2009 Intechnic. All rights reserved.
* @license GNU/GPL
* In-Portal is Open Source software.
* This means that this software may have been modified pursuant
* the GNU General Public License, and as distributed it includes
* or is derivative of works licensed under the GNU General Public License
* or other free or open source software licenses.
* See http://www.in-portal.net/license/ for copyright notices and details.
*/
defined('FULL_PATH') or die('restricted access!');
/**
* Class used to compose email message (using MIME standarts) and send it via mail function or via SMTP server
*
*/
class kEmailSendingHelper extends kHelper {
/**
* headers of main header part
*
* @var Array
*/
var $headers = Array ();
/**
* Tells if all message parts were combined together
*
* @var int
*/
var $bodyPartNumber = false;
/**
* Composed message parts
*
* @var Array
*/
var $parts = Array();
/**
* Lines separator by MIME standart
*
* @var string
*/
var $line_break = "\n";
/**
* Charset used for message composing
*
* @var string
*/
var $charset = 'utf-8';
/**
* Name of mailer program (X-Mailer header)
*
* @var string
*/
var $mailerName = '';
/**
* Options used for message content-type & structure guessing
*
* @var Array
*/
var $guessOptions = Array ();
/**
* Send messages using selected method
*
* @var string
*/
var $sendMethod = 'Mail';
/**
* Parameters used to initiate SMTP server connection
*
* @var Array
*/
var $smtpParams = Array ();
/**
* List of supported authentication methods, in preferential order.
* @var array
* @access public
*/
var $smtpAuthMethods = Array('CRAM-MD5', 'LOGIN', 'PLAIN');
/**
* The socket resource being used to connect to the SMTP server.
* @var kSocket
* @access private
*/
var $smtpSocket = null;
/**
* The most recent server response code.
* @var int
* @access private
*/
var $smtpResponceCode = -1;
/**
* The most recent server response arguments.
* @var array
* @access private
*/
var $smtpRespoceArguments = Array();
/**
* Stores detected features of the SMTP server.
* @var array
* @access private
*/
var $smtpFeatures = Array();
function kEmailSendingHelper()
{
parent::kHelper();
// set default guess options
$this->guessOptions = Array (
'attachments' => Array (),
'inline_attachments' => Array (),
'text_part' => false,
'html_part' => false,
);
// read SMTP server connection params from config
$smtp_mapping = Array ('server' => 'Smtp_Server', 'port' => 'Smtp_Port');
if ($this->Application->ConfigValue('Smtp_Authenticate')) {
$smtp_mapping['username'] = 'Smtp_User';
$smtp_mapping['password'] = 'Smtp_Pass';
}
foreach ($smtp_mapping as $smtp_name => $config_name) {
$this->smtpParams[$smtp_name] = $this->Application->ConfigValue($config_name);
}
$this->smtpParams['use_auth'] = isset($this->smtpParams['username']) ? true : false;
$this->smtpParams['localhost'] = 'localhost'; // The value to give when sending EHLO or HELO.
$this->sendMethod = $this->smtpParams['server'] && $this->smtpParams['port'] ? 'SMTP' : 'Mail';
if ($this->sendMethod == 'SMTP') {
// create connection object if we will use SMTP
$this->smtpSocket =& $this->Application->makeClass('Socket');
}
$this->SetCharset(null, true);
}
/**
* Returns new message id header by sender's email address
*
* @param string $email_address email address
* @return string
*/
function GenerateMessageID($email_address)
{
list ($micros, $seconds) = explode(' ', microtime());
list ($user, $domain) = explode('@', $email_address, 2);
$message_id = strftime('%Y%m%d%H%M%S', $seconds).substr($micros, 1, 5).'.'.preg_replace('/[^A-Za-z]+/', '-', $user).'@'.$domain;
$this->SetHeader('Message-ID', '<'.$message_id.'>');
}
/**
* Returns extension of given filename
*
* @param string $filename
* @return string
*/
function GetFilenameExtension($filename)
{
$last_dot = mb_strrpos($filename, '.');
return $last_dot !== false ? mb_substr($filename, $last_dot + 1) : '';
}
/**
* Creates boundary for part by number (only if it's missing)
*
* @param int $part_number
*
*/
function CreatePartBoundary($part_number)
{
$part =& $this->parts[$part_number];
if (!isset($part['BOUNDARY'])) {
$part['BOUNDARY'] = md5(uniqid($part_number.time()));
}
}
/**
* Returns ready to use headers associative array of any message part by it's number
*
* @param int $part_number
* @return Array
*/
function GetPartHeaders($part_number)
{
$part =& $this->parts[$part_number];
if (!isset($part['Content-Type'])) {
return $this->SetError('MISSING_CONTENT_TYPE');
}
$full_type = strtolower($part['Content-Type']);
list ($type, $sub_type) = explode('/', $full_type);
$headers['Content-Type'] = $full_type;
switch ($type) {
case 'text':
case 'image':
case 'audio':
case 'video':
case 'application':
case 'message':
// 1. update content-type header
if (isset($part['CHARSET'])) {
$headers['Content-Type'] .= '; charset='.$part['CHARSET'];
}
if (isset($part['NAME'])) {
$headers['Content-Type'] .= '; name="'.$part['NAME'].'"';
}
// 2. set content-transfer-encoding header
if (isset($part['Content-Transfer-Encoding'])) {
$headers['Content-Transfer-Encoding'] = $part['Content-Transfer-Encoding'];
}
// 3. set content-disposition header
if (isset($part['DISPOSITION']) && $part['DISPOSITION']) {
$headers['Content-Disposition'] = $part['DISPOSITION'];
if (isset($part['NAME'])) {
$headers['Content-Disposition'] .= '; filename="'.$part['NAME'].'"';
}
}
break;
case 'multipart':
switch ($sub_type) {
case 'alternative':
case 'related':
case 'mixed':
case 'parallel':
$this->CreatePartBoundary($part_number);
$headers['Content-Type'] .= '; boundary="'.$part['BOUNDARY'].'"';
break;
default:
return $this->SetError('INVALID_MULTIPART_SUBTYPE', Array($sub_type));
}
break;
default:
return $this->SetError('INVALID_CONTENT_TYPE', Array($full_type));
}
// set content-id if any
if (isset($part['Content-ID'])) {
$headers['Content-ID'] = '<'.$part['Content-ID'].'>';
}
return $headers;
}
function GetPartBody($part_number)
{
$part =& $this->parts[$part_number];
if (!isset($part['Content-Type'])) {
return $this->SetError('MISSING_CONTENT_TYPE');
}
$full_type = strtolower($part['Content-Type']);
list ($type, $sub_type) = explode('/', $full_type);
$body = '';
switch ($type) {
// compose text/binary content
case 'text':
case 'image':
case 'audio':
case 'video':
case 'application':
case 'message':
// 1. get content of part
if (isset($part['FILENAME'])) {
// content provided via absolute path to content containing file
$filename = $part['FILENAME'];
$file_size = filesize($filename);
$body = file_get_contents($filename);
if ($body === false) {
return $this->SetError('FILE_PART_OPEN_ERROR', Array($filename));
}
$actual_size = strlen($body);
if (($file_size === false || $actual_size > $file_size) && get_magic_quotes_runtime()) {
$body = stripslashes($body);
}
if ($file_size !== false && $actual_size != $file_size) {
return $this->SetError('FILE_PART_DATA_ERROR', Array($filename));
}
}
else {
// content provided directly as one of part keys
if (!isset($part['DATA'])) {
return $this->SetError('FILE_PART_DATA_MISSING');
}
$body =& $part['DATA'];
}
// 2. get part transfer encoding
$encoding = isset($part['Content-Transfer-Encoding']) ? strtolower($part['Content-Transfer-Encoding']) : '';
if (!in_array($encoding, Array ('', 'base64', 'quoted-printable', '7bit'))) {
return $this->SetError('INVALID_ENCODING', Array($encoding));
}
if ($encoding == 'base64') {
// split base64 encoded text by 76 symbols at line (MIME requirement)
$body = chunk_split( base64_encode($body) );
}
break;
case 'multipart':
// compose multipart message
switch ($sub_type) {
case 'alternative':
case 'related':
case 'mixed':
case 'parallel':
$this->CreatePartBoundary($part_number);
$boundary = $this->line_break.'--'.$part['BOUNDARY'];
foreach ($part['PARTS'] as $multipart_number) {
$body .= $boundary.$this->line_break;
$part_headers = $this->GetPartHeaders($multipart_number);
if ($part_headers === false) {
// some of sub-part headers were invalid
return false;
}
foreach ($part_headers as $header_name => $header_value) {
$body .= $header_name.': '.$header_value.$this->line_break;
}
$part_body = $this->GetPartBody($multipart_number);
if ($part_body === false) {
// part body was invalid
return false;
}
$body .= $this->line_break.$part_body;
}
$body .= $boundary.'--'.$this->line_break;
break;
default:
return $this->SetError('INVALID_MULTIPART_SUBTYPE', Array($sub_type));
}
break;
default:
return $this->SetError('INVALID_CONTENT_TYPE', Array($full_type));
}
return $body;
}
/**
* Applies quoted-printable encoding to specified text
*
* @param string $text
* @param string $header_charset
* @param int $break_lines
* @return unknown
*/
function QuotedPrintableEncode($text, $header_charset = '', $break_lines = 1)
{
$ln = strlen($text);
$h = strlen($header_charset) > 0;
if ($h) {
$s = Array (
'=' => 1,
'?' => 1,
'_' => 1,
'(' => 1,
')' => 1,
'<' => 1,
'>' => 1,
'@' => 1,
',' => 1,
';' => 1,
'"' => 1,
'\\' => 1,
/*
'/' => 1,
'[' => 1,
']' => 1,
':' => 1,
'.' => 1,
*/
);
$b = $space = $break_lines = 0;
for ($i = 0; $i < $ln; $i++) {
if (isset($s[$text[$i]])) {
$b = 1;
break;
}
switch ($o = ord($text[$i])) {
case 9:
case 32:
$space = $i + 1;
$b = 1;
break 2;
case 10:
case 13:
break 2;
default:
if ($o < 32 || $o > 127) {
$b = 1;
break 2;
}
}
}
if($i == $ln) {
return $text;
}
if ($space > 0) {
return substr($text, 0, $space).($space < $ln ? $this->QuotedPrintableEncode(substr($text, $space), $header_charset, 0) : '');
}
}
for ($w = $e = '', $n = 0, $l = 0, $i = 0; $i < $ln; $i++) {
$c = $text[$i];
$o = ord($c);
$en = 0;
switch ($o) {
case 9:
case 32:
if (!$h) {
$w = $c;
$c = '';
}
else {
if ($b) {
if ($o == 32) {
$c = '_';
}
else {
$en = 1;
}
}
}
break;
case 10:
case 13:
if (strlen($w)) {
if ($break_lines && $l + 3 > 75) {
$e .= '='.$this->line_break;
$l = 0;
}
$e .= sprintf('=%02X', ord($w));
$l += 3;
$w = '';
}
$e .= $c;
if ($h) {
$e .= "\t";
}
$l = 0;
continue 2;
case 46:
case 70:
case 102:
$en = (!$h && ($l == 0 || $l + 1 > 75));
break;
default:
if ($o > 127 || $o < 32 || !strcmp($c, '=')) {
$en = 1;
}
elseif ($h && isset($s[$c])) {
$en = 1;
}
break;
}
if (strlen($w)) {
if ($break_lines && $l + 1 > 75) {
$e .= '='.$this->line_break;
$l = 0;
}
$e .= $w;
$l++;
$w = '';
}
if (strlen($c)) {
if ($en) {
$c = sprintf('=%02X', $o);
$el = 3;
$n = 1;
$b = 1;
}
else {
$el = 1;
}
if ($break_lines && $l + $el > 75) {
$e .= '='.$this->line_break;
$l = 0;
}
$e .= $c;
$l += $el;
}
}
if (strlen($w)) {
if ($break_lines && $l + 3 > 75) {
$e .= '='.$this->line_break;
}
$e .= sprintf('=%02X', ord($w));
}
return $h && $n ? '=?'.$header_charset.'?q?'.$e.'?=' : $e;
}
/**
* Sets message header + encodes is by quoted-printable using charset specified
*
* @param string $name
* @param string $value
* @param string $encoding_charset
*/
function SetHeader($name, $value, $encoding_charset = '')
{
if ($encoding_charset) {
// actually for headers base64 method may give shorter result
$value = $this->QuotedPrintableEncode($value, $encoding_charset);
}
$this->headers[$name] = $value;
}
/**
* Sets header + automatically encodes it using default charset
*
* @param string $name
* @param string $value
*/
function SetEncodedHeader($name, $value)
{
$this->SetHeader($name, $value, $this->charset);
}
/**
* Sets header which value is email and username +autoencode
*
* @param string $header
* @param string $address
* @param string $name
*/
function SetEncodedEmailHeader($header, $address, $name)
{
$this->SetHeader($header, $this->QuotedPrintableEncode($name, $this->charset).' <'.$address.'>');
}
function SetMultipleEncodedEmailHeader($header, $addresses)
{
$value = '';
foreach ($addresses as $name => $address) {
$value .= $this->QuotedPrintableEncode($name, $this->charset).' <'.$address.'>, ';
}
- $value = preg_replace('/(.*),$/', '\\1', $value);
- $this->SetHeader($header, $value);
+ $this->SetHeader($header, substr($value, 0, -2));
}
/**
* Adds new part to message and returns it's number
*
* @param Array $part_definition
* @param int $part_number number of new part
* @return int
*/
function AddPart(&$part_definition, $part_number = false)
{
$part_number = $part_number !== false ? $part_number : count($this->parts);
$this->parts[$part_number] =& $part_definition;
return $part_number;
}
/**
* Returns text version of HTML document
*
* @param string $html
* @return string
*/
function ConvertToText($html)
{
$search = Array (
"'(<\/td>.*)[\r\n]+(.*<td)'i",//formating text in tables
"'(<br[ ]?[\/]?>[\r\n]{0,2})|(<\/p>)|(<\/div>)|(<\/tr>)'i",
"'<head>(.*?)</head>'si",
"'<style(.*?)</style>'si",
"'<title>(.*?)</title>'si",
"'<script(.*?)</script>'si",
// "'^[\s\n\r\t]+'", //strip all spacers & newlines in the begin of document
// "'[\s\n\r\t]+$'", //strip all spacers & newlines in the end of document
"'&(quot|#34);'i",
"'&(amp|#38);'i",
"'&(lt|#60);'i",
"'&(gt|#62);'i",
"'&(nbsp|#160);'i",
"'&(iexcl|#161);'i",
"'&(cent|#162);'i",
"'&(pound|#163);'i",
"'&(copy|#169);'i",
"'&#(\d+);'e"
);
$replace = Array (
"\\1\t\\2",
"\n",
"",
"",
"",
"",
// "",
// "",
"\"",
"&",
"<",
">",
" ",
chr(161),
chr(162),
chr(163),
chr(169),
"chr(\\1)"
);
return strip_tags( preg_replace ($search, $replace, $html) );
}
/**
* Add text OR html part to message (optionally encoded)
*
* @param string $text part's text
* @param bool $is_html this html part or not
* @param bool $encode encode message using quoted-printable encoding
*
* @return int number of created part
*/
function CreateTextHtmlPart($text, $is_html = false, $encode = true)
{
if ($is_html) {
// if adding HTML part, then create plain-text part too
$this->CreateTextHtmlPart($this->ConvertToText($text));
}
// in case if text is from $_REQUEST, then line endings are "\r\n", but we need "\n" here
$text = str_replace("\r\n", "\n", $text); // possible case
$text = str_replace("\r", "\n", $text); // impossible case, but just in case replace this too
$definition = Array (
'Content-Type' => $is_html ? 'text/html' : 'text/plain',
'CHARSET' => $this->charset,
'DATA' => $encode ? $this->QuotedPrintableEncode($text) : $text,
);
if ($encode) {
$definition['Content-Transfer-Encoding'] = 'quoted-printable';
}
$guess_name = $is_html ? 'html_part' : 'text_part';
$part_number = $this->guessOptions[$guess_name] !== false ? $this->guessOptions[$guess_name] : false;
$part_number = $this->AddPart($definition, $part_number);
$this->guessOptions[$guess_name] = $part_number;
return $part_number;
}
/**
* Adds attachment part to message
*
* @param string $file name of the file with attachment body
* @param string $attach_name name for attachment (name of file is used, when not specified)
* @param string $content_type content type for attachment
* @param string $content body of file to be attached
* @param bool $inline is attachment inline or not
*
* @return int number of created part
*/
function AddAttachment($file = '', $attach_name = '', $content_type = '', $content = '', $inline = false)
{
$definition = Array (
'Disposition' => $inline ? 'inline' : 'attachment',
'Content-Type' => $content_type ? $content_type : 'automatic/name',
);
if ($file) {
// filename of attachment given
$definition['FileName'] = $file;
}
if ($attach_name) {
// name of attachment given
$definition['Name'] = $attach_name;
}
if ($content) {
// attachment data is given
$definition['Data'] = $content;
}
$definition =& $this->GetFileDefinition($definition);
$part_number = $this->AddPart($definition);
if ($inline) {
// it's inline attachment and needs content-id to be addressed by in message
$this->parts[$part_number]['Content-ID'] = md5(uniqid($part_number.time())).'.'.$this->GetFilenameExtension($attach_name ? $attach_name : $file);
}
$this->guessOptions[$inline ? 'inline_attachments' : 'attachments'][] = $part_number;
return $part_number;
}
/**
* Adds another MIME message as attachment to message being composed
*
* @param string $file name of the file with attachment body
* @param string $attach_name name for attachment (name of file is used, when not specified)
* @param string $content body of file to be attached
*
* @return int number of created part
*/
function AddMessageAttachment($file = '', $attach_name = '', $content = '')
{
$part_number = $this->AddAttachment($file, $attach_name, 'message/rfc822', $content, true);
unset($this->parts[$part_number]['Content-ID']); // messages don't have content-id, but have inline disposition
return $part_number;
}
/**
* Creates multipart of specified type and returns it's number
*
* @param Array $part_numbers
* @param string $multipart_type = {alternative,related,mixed,paralell}
* @return int
*/
function CreateMultipart($part_numbers, $multipart_type)
{
$types = Array ('alternative', 'related' , 'mixed', 'paralell');
if (!in_array($multipart_type, $types)) {
return $this->SetError('INVALID_MULTIPART_SUBTYPE', Array($multipart_type));
}
$definition = Array (
'Content-Type' => 'multipart/'.$multipart_type,
'PARTS' => $part_numbers,
);
return $this->AddPart($definition);
}
/**
* Creates missing content-id header for inline attachments
*
* @param int $part_number
*/
function CreateContentID($part_number)
{
$part =& $this->parts[$part_number];
if (!isset($part['Content-ID']) && $part['DISPOSITION'] == 'inline') {
$part['Content-ID'] = md5(uniqid($part_number.time())).'.'.$this->GetFilenameExtension($part['NAME']);
}
}
/**
* Returns attachment part based on file used in attachment
*
* @param Array $file
* @return Array
*/
function &GetFileDefinition ($file)
{
$name = '';
if (isset($file['Name'])) {
// if name is given directly, then use it
$name = $file['Name'];
}
else {
// auto-guess attachment name based on source filename
$name = isset($file['FileName']) ? basename($file['FileName']) : '';
}
if (!$name || (!isset($file['FileName']) && !isset($file['Data']))) {
// filename not specified || no filename + no direct file content
return $this->SetError('MISSING_FILE_DATA');
}
$encoding = 'base64';
if (isset($file['Content-Type'])) {
$content_type = $file['Content-Type'];
list ($type, $sub_type) = explode('/', $content_type);
switch ($type) {
case 'text':
case 'image':
case 'audio':
case 'video':
case 'application':
break;
case 'message':
$encoding = '7bit';
break;
case 'automatic':
if (!$name) {
return $this->SetError('MISSING_FILE_NAME');
}
$this->guessContentType($name, $content_type, $encoding);
break;
default:
return $this->SetError('INVALID_CONTENT_TYPE', Array($content_type));
}
}
else {
// encoding not passed in file part, then assume, that it's binary
$content_type = 'application/octet-stream';
}
$definition = Array (
'Content-Type' => $content_type,
'Content-Transfer-Encoding' => $encoding,
'NAME' => $name, // attachment name
);
if (isset($file['Disposition'])) {
$disposition = strtolower($file['Disposition']);
if ($disposition == 'inline' || $disposition == 'attachment') {
// valid disposition header value
$definition['DISPOSITION'] = $file['Disposition'];
}
else {
return $this->SetError('INVALID_DISPOSITION', Array($file['Disposition']));
}
}
if (isset($file['FileName'])) {
$definition['FILENAME'] = $file['FileName'];
}
elseif (isset($file['Data'])) {
$definition['DATA'] =& $file['Data'];
}
return $definition;
}
/**
* Returns content-type based on filename extension
*
* @param string $filename
* @param string $content_type
* @param string $encoding
*
* @todo Regular expression used is not completely finished, that's why if extension used for
* comparing in some other extension (from list) part, that partial match extension will be returned.
* Because of two extension that begins with same 2 letters always belong to same content type
* this unfinished regular expression still gives correct result in any case.
*/
function guessContentType($filename, &$content_type, &$encoding)
{
$file_extension = mb_strtolower( $this->GetFilenameExtension($filename) );
$mapping = '(xls:application/excel)(hqx:application/macbinhex40)(doc,dot,wrd:application/msword)(pdf:application/pdf)
(pgp:application/pgp)(ps,eps,ai:application/postscript)(ppt:application/powerpoint)(rtf:application/rtf)
(tgz,gtar:application/x-gtar)(gz:application/x-gzip)(php,php3:application/x-httpd-php)(js:application/x-javascript)
(ppd,psd:application/x-photoshop)(swf,swc,rf:application/x-shockwave-flash)(tar:application/x-tar)(zip:application/zip)
(mid,midi,kar:audio/midi)(mp2,mp3,mpga:audio/mpeg)(ra:audio/x-realaudio)(wav:audio/wav)(bmp:image/bitmap)(bmp:image/bitmap)
(gif:image/gif)(iff:image/iff)(jb2:image/jb2)(jpg,jpe,jpeg:image/jpeg)(jpx:image/jpx)(png:image/png)(tif,tiff:image/tiff)
(wbmp:image/vnd.wap.wbmp)(xbm:image/xbm)(css:text/css)(txt:text/plain)(htm,html:text/html)(xml:text/xml)
(mpg,mpe,mpeg:video/mpeg)(qt,mov:video/quicktime)(avi:video/x-ms-video)(eml:message/rfc822)';
if (preg_match('/[\(,]'.$file_extension.'[,]{0,1}.*?:(.*?)\)/s', $mapping, $regs)) {
if ($file_extension == 'eml') {
$encoding = '7bit';
}
$content_type = $regs[1];
}
else {
$content_type = 'application/octet-stream';
}
}
/**
* Using guess options combines all added parts together and returns combined part number
*
* @return int
*/
function PrepareMessageBody()
{
if ($this->bodyPartNumber === false) {
$part_number = false; // number of generated body part
// 1. set text content of message
if ($this->guessOptions['text_part'] !== false && $this->guessOptions['html_part'] !== false) {
// text & html parts present -> compose into alternative part
$parts = Array (
$this->guessOptions['text_part'],
$this->guessOptions['html_part'],
);
$part_number = $this->CreateMultipart($parts, 'alternative');
}
elseif ($this->guessOptions['text_part'] !== false) {
// only text part is defined, then leave as is
$part_number = $this->guessOptions['text_part'];
}
if ($part_number === false) {
return $this->SetError('MESSAGE_TEXT_MISSING');
}
// 2. if inline attachments found, then create related multipart from text & inline attachments
if ($this->guessOptions['inline_attachments']) {
$parts = array_merge(Array($part_number), $this->guessOptions['inline_attachments']);
$part_number = $this->CreateMultipart($parts, 'related');
}
// 3. if normal attachments found, then create mixed multipart from text & attachments
if ($this->guessOptions['attachments']) {
$parts = array_merge(Array($part_number), $this->guessOptions['attachments']);
$part_number = $this->CreateMultipart($parts, 'mixed');
}
$this->bodyPartNumber = $part_number;
}
return $this->bodyPartNumber;
}
/**
* Returns message headers and body part (by reference in parameters)
*
* @param Array $message_headers
* @param string $message_body
* @return bool
*/
function GetHeadersAndBody(&$message_headers, &$message_body)
{
$part_number = $this->PrepareMessageBody();
if ($part_number === false) {
return $this->SetError('MESSAGE_COMPOSE_ERROR');
}
$message_headers = $this->GetPartHeaders($part_number);
// join message headers and body headers
$message_headers = array_merge_recursive2($this->headers, $message_headers);
$message_headers['MIME-Version'] = '1.0';
if ($this->mailerName) {
$message_headers['X-Mailer'] = $this->mailerName;
}
$this->GenerateMessageID($message_headers['From']);
$valid_headers = $this->ValidateHeaders($message_headers);
if ($valid_headers) {
// set missing headers from existing
$from_headers = Array ('Reply-To', 'Errors-To');
foreach ($from_headers as $header_name) {
if (!isset($message_headers[$header_name])) {
$message_headers[$header_name] = $message_headers['From'];
}
}
$message_body = $this->GetPartBody($part_number);
return true;
}
return false;
}
/**
* Checks that all required headers are set and not empty
*
* @param Array $message_headers
* @return bool
*/
function ValidateHeaders($message_headers)
{
$from = isset($message_headers['From']) ? $message_headers['From'] : '';
if (!$from) {
return $this->SetError('HEADER_MISSING', Array('From'));
}
if (!isset($message_headers['To'])) {
return $this->SetError('HEADER_MISSING', Array('To'));
}
if (!isset($message_headers['Subject'])) {
return $this->SetError('HEADER_MISSING', Array('Subject'));
}
return true;
}
/**
* Returns full message source (headers + body) for sending to SMTP server
*
* @return string
*/
function GetMessage()
{
$composed = $this->GetHeadersAndBody($message_headers, $message_body);
if ($composed) {
// add headers to resulting message
$message = '';
foreach ($message_headers as $header_name => $header_value) {
$message .= $header_name.': '.$header_value.$this->line_break;
}
// add message body
$message .= $this->line_break.$message_body;
return $message;
}
return false;
}
/**
* Sets just happened error code
*
* @param string $code
* @param Array $params additional error params
* @return bool
*/
function SetError($code, $params = null, $fatal = true)
{
$error_msgs = Array (
'MAIL_NOT_FOUND' => 'the mail() function is not available in this PHP installation',
'MISSING_CONTENT_TYPE' => 'it was added a part without Content-Type: defined',
'INVALID_CONTENT_TYPE' => 'Content-Type: %s not yet supported',
'INVALID_MULTIPART_SUBTYPE' => 'multipart Content-Type sub_type %s not yet supported',
'FILE_PART_OPEN_ERROR' => 'could not open part file %s',
'FILE_PART_DATA_ERROR' => 'the length of the file that was read does not match the size of the part file %s due to possible data corruption',
'FILE_PART_DATA_MISSING' => 'it was added a part without a body PART',
'INVALID_ENCODING' => '%s is not yet a supported encoding type',
'MISSING_FILE_DATA' => 'file part data is missing',
'MISSING_FILE_NAME' => 'it is not possible to determine content type from the name',
'INVALID_DISPOSITION' => '%s is not a supported message part content disposition',
'MESSAGE_TEXT_MISSING' => 'text part of message was not defined',
'MESSAGE_COMPOSE_ERROR' => 'unknown message composing error',
'HEADER_MISSING' => 'header %s is required',
// SMTP errors
'INVALID_COMMAND' => 'Commands cannot contain newlines',
'CONNECTION_TERMINATED' => 'Connection was unexpectedly closed',
'HELO_ERROR' => 'HELO was not accepted: %s',
'AUTH_METHOD_NOT_SUPPORTED' => '%s is not a supported authentication method',
'AUTH_METHOD_NOT_IMPLEMENTED' => '%s is not a implemented authentication method',
);
if (!is_array($params)) {
$params = Array ();
}
trigger_error('mail error: '.vsprintf($error_msgs[$code], $params), $fatal ? E_USER_ERROR : E_USER_WARNING);
return false;
}
/**
* Simple method of message sending
*
* @param string $from_email
* @param string $to_email
* @param string $subject
* @param string $from_name
* @param string $to_name
*/
function Send($from_email, $to_email, $subject, $from_name = '', $to_name = '')
{
$this->SetSubject($subject);
$this->SetFrom($from_email, trim($from_name) ? trim($from_name) : $from_email);
if (!isset($this->headers['Return-Path'])) {
$this->SetReturnPath($from_email);
}
$this->SetTo($to_email, $to_name ? $to_name : $to_email);
return $this->Deliver();
}
/**
* Prepares class for sending another message
*
*/
function Clear()
{
$this->headers = Array ();
$this->bodyPartNumber = false;
$this->parts = Array();
$this->guessOptions = Array (
'attachments' => Array(),
'inline_attachments' => Array (),
'text_part' => false,
'html_part' => false,
);
$this->SetCharset(null, true);
}
/**
* Sends message via php mail function
*
* @param Array $message_headers
* @param string $body
*
* @return bool
*/
function SendMail($message_headers, &$body)
{
if (!function_exists('mail')) {
return $this->SetError('MAIL_NOT_FOUND');
}
$to = $message_headers['To'];
$subject = $message_headers['Subject'];
$return_path = $message_headers['Return-Path'];
unset($message_headers['To'], $message_headers['Subject']);
$headers = '';
$header_separator = $this->Application->ConfigValue('MailFunctionHeaderSeparator') == 1 ? "\n" : "\r\n";
foreach ($message_headers as $header_name => $header_value) {
$headers .= $header_name.': '.$header_value.$header_separator;
}
if ($return_path) {
if (constOn('SAFE_MODE') || (defined('PHP_OS') && substr(PHP_OS, 0, 3) == 'WIN')) {
// safe mode restriction OR is windows
$return_path = '';
}
}
return mail($to, $subject, $body, $headers, $return_path ? '-f'.$return_path : null);
}
/**
* Sends message via SMTP server
*
* @param Array $message_headers
* @param string $body
*
* @return bool
*/
function SendSMTP($message_headers, &$message_body)
{
if (!$this->SmtpConnect()) {
return false;
}
$from = $this->ExtractRecipientEmail($message_headers['From']);
if (!$this->SmtpSetFrom($from)) {
return false;
}
$recipients = '';
$recipient_headers = Array ('To', 'Cc', 'Bcc');
foreach ($recipient_headers as $recipient_header) {
if (isset($message_headers[$recipient_header])) {
$recipients .= ' '.$message_headers[$recipient_header];
}
}
$recipients_accepted = 0;
$recipients = $this->ExtractRecipientEmail($recipients, true);
foreach ($recipients as $recipient) {
if ($this->SmtpAddTo($recipient)) {
$recipients_accepted++;
}
}
if ($recipients_accepted == 0) {
// none of recipients were accepted
return false;
}
$headers = '';
foreach ($message_headers as $header_name => $header_value) {
$headers .= $header_name.': '.$header_value.$this->line_break;
}
if (!$this->SmtpSendMessage($headers . "\r\n" . $message_body)) {
return false;
}
$this->SmtpDisconnect();
return true;
}
/**
* Send a command to the server with an optional string of
* arguments. A carriage return / linefeed (CRLF) sequence will
* be appended to each command string before it is sent to the
* SMTP server.
*
* @param string $command The SMTP command to send to the server.
* @param string $args A string of optional arguments to append to the command.
*
* @return bool
*
*/
function SmtpSendCommand($command, $args = '')
{
if (!empty($args)) {
$command .= ' ' . $args;
}
if (strcspn($command, "\r\n") !== strlen($command)) {
return $this->SetError('INVALID_COMMAND');
}
return $this->smtpSocket->write($command . "\r\n") === false ? false : true;
}
/**
* Read a reply from the SMTP server. The reply consists of a response code and a response message.
*
* @param mixed $valid The set of valid response codes. These may be specified as an array of integer values or as a single integer value.
*
* @return bool
*
*/
function SmtpParseResponse($valid)
{
$this->smtpResponceCode = -1;
$this->smtpRespoceArguments = array();
while ($line = $this->smtpSocket->readLine()) {
// If we receive an empty line, the connection has been closed.
if (empty($line)) {
$this->SmtpDisconnect();
return $this->SetError('CONNECTION_TERMINATED', null, false);
}
// Read the code and store the rest in the arguments array.
$code = substr($line, 0, 3);
$this->smtpRespoceArguments[] = trim(substr($line, 4));
// Check the syntax of the response code.
if (is_numeric($code)) {
$this->smtpResponceCode = (int)$code;
} else {
$this->smtpResponceCode = -1;
break;
}
// If this is not a multiline response, we're done.
if (substr($line, 3, 1) != '-') {
break;
}
}
// Compare the server's response code with the valid code.
if (is_int($valid) && ($this->smtpResponceCode === $valid)) {
return true;
}
// If we were given an array of valid response codes, check each one.
if (is_array($valid)) {
foreach ($valid as $valid_code) {
if ($this->smtpResponceCode === $valid_code) {
return true;
}
}
}
return false;
}
/**
* Attempt to connect to the SMTP server.
*
* @param int $timeout The timeout value (in seconds) for the socket connection.
* @param bool $persistent Should a persistent socket connection be used ?
*
* @return bool
*
*/
function SmtpConnect($timeout = null, $persistent = false)
{
$result = $this->smtpSocket->connect($this->smtpParams['server'], $this->smtpParams['port'], $persistent, $timeout);
if (!$result) {
return false;
}
if ($this->SmtpParseResponse(220) === false) {
return false;
}
elseif ($this->SmtpNegotiate() === false) {
return false;
}
if ($this->smtpParams['use_auth']) {
$result = $this->SmtpAuthentificate($this->smtpParams['username'], $this->smtpParams['password']);
if (!$result) {
// authentification failed
return false;
}
}
return true;
}
/**
* Attempt to disconnect from the SMTP server.
*
* @return bool
*/
function SmtpDisconnect()
{
if ($this->SmtpSendCommand('QUIT') === false) {
return false;
}
elseif ($this->SmtpParseResponse(221) === false) {
return false;
}
return $this->smtpSocket->disconnect();
}
/**
* Attempt to send the EHLO command and obtain a list of ESMTP
* extensions available, and failing that just send HELO.
*
* @return bool
*/
function SmtpNegotiate()
{
if (!$this->SmtpSendCommand('EHLO', $this->smtpParams['localhost'])) {
return false;
}
if (!$this->SmtpParseResponse(250)) {
// If we receive a 503 response, we're already authenticated.
if ($this->smtpResponceCode === 503) {
return true;
}
// If the EHLO failed, try the simpler HELO command.
if (!$this->SmtpSendCommand('HELO', $this->smtpParams['localhost'])) {
return false;
}
if (!$this->SmtpParseResponse(250)) {
return $this->SetError('HELO_ERROR', Array($this->smtpResponceCode), false);
}
return true;
}
foreach ($this->smtpRespoceArguments as $argument) {
$verb = strtok($argument, ' ');
$arguments = substr($argument, strlen($verb) + 1, strlen($argument) - strlen($verb) - 1);
$this->smtpFeatures[$verb] = $arguments;
}
return true;
}
/**
* Attempt to do SMTP authentication.
*
* @param string The userid to authenticate as.
* @param string The password to authenticate with.
* @param string The requested authentication method. If none is specified, the best supported method will be used.
*
* @return bool
*/
function SmtpAuthentificate($uid, $pwd , $method = '')
{
if (empty($this->smtpFeatures['AUTH'])) {
// server doesn't understand AUTH command, then don't authentificate
return true;
}
$available_methods = explode(' ', $this->smtpFeatures['AUTH']); // methods supported by SMTP server
if (empty($method)) {
foreach ($this->smtpAuthMethods as $supported_method) {
// check if server supports methods, that we have implemented
if (in_array($supported_method, $available_methods)) {
$method = $supported_method;
break;
}
}
} else {
$method = strtoupper($method);
}
if (!in_array($method, $available_methods)) {
// coosen method is not supported by server
return $this->SetError('AUTH_METHOD_NOT_SUPPORTED', Array($method));
}
switch ($method) {
case 'CRAM-MD5':
$result = $this->_authCRAM_MD5($uid, $pwd);
break;
case 'LOGIN':
$result = $this->_authLogin($uid, $pwd);
break;
case 'PLAIN':
$result = $this->_authPlain($uid, $pwd);
break;
default:
return $this->SetError('AUTH_METHOD_NOT_IMPLEMENTED', Array($method));
break;
}
return $result;
}
/**
* Function which implements HMAC MD5 digest
*
* @param string $key The secret key
* @param string $data The data to protect
* @return string The HMAC MD5 digest
*/
function _HMAC_MD5($key, $data)
{
if (strlen($key) > 64) {
$key = pack('H32', md5($key));
}
if (strlen($key) < 64) {
$key = str_pad($key, 64, chr(0));
}
$k_ipad = substr($key, 0, 64) ^ str_repeat(chr(0x36), 64);
$k_opad = substr($key, 0, 64) ^ str_repeat(chr(0x5C), 64);
$inner = pack('H32', md5($k_ipad . $data));
$digest = md5($k_opad . $inner);
return $digest;
}
/**
* Authenticates the user using the CRAM-MD5 method.
*
* @param string The userid to authenticate as.
* @param string The password to authenticate with.
*
* @return bool
*/
function _authCRAM_MD5($uid, $pwd)
{
if (!$this->SmtpSendCommand('AUTH', 'CRAM-MD5')) {
return false;
}
// 334: Continue authentication request
if (!$this->SmtpParseResponse(334)) {
// 503: Error: already authenticated
return $this->smtpResponceCode === 503 ? true : false;
}
$challenge = base64_decode($this->smtpRespoceArguments[0]);
$auth_str = base64_encode($uid . ' ' . $this->_HMAC_MD5($pwd, $challenge));
if (!$this->SmtpSendCommand($auth_str)) {
return false;
}
// 235: Authentication successful
if (!$this->SmtpParseResponse(235)) {
return false;
}
return true;
}
/**
* Authenticates the user using the LOGIN method.
*
* @param string The userid to authenticate as.
* @param string The password to authenticate with.
*
* @return bool
*/
function _authLogin($uid, $pwd)
{
if (!$this->SmtpSendCommand('AUTH', 'LOGIN')) {
return false;
}
// 334: Continue authentication request
if (!$this->SmtpParseResponse(334)) {
// 503: Error: already authenticated
return $this->smtpResponceCode === 503 ? true : false;
}
if (!$this->SmtpSendCommand(base64_encode($uid))) {
return false;
}
// 334: Continue authentication request
if (!$this->SmtpParseResponse(334)) {
return false;
}
if (!$this->SmtpSendCommand(base64_encode($pwd))) {
return false;
}
// 235: Authentication successful
if (!$this->SmtpParseResponse(235)) {
return false;
}
return true;
}
/**
* Authenticates the user using the PLAIN method.
*
* @param string The userid to authenticate as.
* @param string The password to authenticate with.
*
* @return bool
*/
function _authPlain($uid, $pwd)
{
if (!$this->SmtpSendCommand('AUTH', 'PLAIN')) {
return false;
}
// 334: Continue authentication request
if (!$this->SmtpParseResponse(334)) {
// 503: Error: already authenticated
return $this->smtpResponceCode === 503 ? true : false;
}
$auth_str = base64_encode(chr(0) . $uid . chr(0) . $pwd);
if (!$this->SmtpSendCommand($auth_str)) {
return false;
}
// 235: Authentication successful
if (!$this->SmtpParseResponse(235)) {
return false;
}
return true;
}
/**
* Send the MAIL FROM: command.
*
* @param string $sender The sender (reverse path) to set.
* @param string $params String containing additional MAIL parameters, such as the NOTIFY flags defined by RFC 1891 or the VERP protocol.
*
* @return bool
*/
function SmtpSetFrom($sender, $params = null)
{
$args = "FROM:<$sender>";
if (is_string($params)) {
$args .= ' ' . $params;
}
if (!$this->SmtpSendCommand('MAIL', $args)) {
return false;
}
if (!$this->SmtpParseResponse(250)) {
return false;
}
return true;
}
/**
* Send the RCPT TO: command.
*
* @param string $recipient The recipient (forward path) to add.
* @param string $params String containing additional RCPT parameters, such as the NOTIFY flags defined by RFC 1891.
*
* @return bool
*/
function SmtpAddTo($recipient, $params = null)
{
$args = "TO:<$recipient>";
if (is_string($params)) {
$args .= ' ' . $params;
}
if (!$this->SmtpSendCommand('RCPT', $args)) {
return false;
}
if (!$this->SmtpParseResponse(array(250, 251))) {
return false;
}
return true;
}
/**
* Send the DATA command.
*
* @param string $data The message body to send.
*
* @return bool
*/
function SmtpSendMessage($data)
{
/* RFC 1870, section 3, subsection 3 states "a value of zero
* indicates that no fixed maximum message size is in force".
* Furthermore, it says that if "the parameter is omitted no
* information is conveyed about the server's fixed maximum
* message size". */
if (isset($this->smtpFeatures['SIZE']) && ($this->smtpFeatures['SIZE'] > 0)) {
if (strlen($data) >= $this->smtpFeatures['SIZE']) {
$this->SmtpDisconnect();
return $this->SetError('Message size excedes the server limit', null, false);
}
}
// Quote the data based on the SMTP standards
// Change Unix (\n) and Mac (\r) linefeeds into Internet-standard CRLF (\r\n) linefeeds.
$data = preg_replace(Array('/(?<!\r)\n/','/\r(?!\n)/'), "\r\n", $data);
// Because a single leading period (.) signifies an end to the data,
// legitimate leading periods need to be "doubled" (e.g. '..')
$data = str_replace("\n.", "\n..", $data);
if (!$this->SmtpSendCommand('DATA')) {
return false;
}
if (!$this->SmtpParseResponse(354)) {
return false;
}
if ($this->smtpSocket->write($data . "\r\n.\r\n") === false) {
return false;
}
if (!$this->SmtpParseResponse(250)) {
return false;
}
return true;
}
/**
* Sets global charset for every message part
*
* @param string $charset
* @param bool set charset to default for current langauge
*/
function SetCharset($charset, $is_system = false)
{
if ($is_system) {
$language =& $this->Application->recallObject('lang.current');
/* @var $language LanguagesItem */
$charset = $language->GetDBField('Charset') ? $language->GetDBField('Charset') : 'ISO-8859-1';
}
$this->charset = $charset;
}
/**
* Allows to extract recipient's name from text by specifying it's email
*
* @param string $text
* @param string $email
* @return string
*/
function ExtractRecipientName($text, $email = '')
{
$lastspace = mb_strrpos($text, ' ');
$name = trim(mb_substr($text, 0, $lastspace - mb_strlen($text)), " \r\n\t\0\x0b\"'");
if (empty($name)) {
$name = $email;
}
return $name;
}
/**
* Takes $text and returns an email address from it
* Set $multiple to true to retrieve all found addresses
* Returns false if no addresses were found
*
* @param string $text
* @param bool $multiple
* @param bool $allowOnlyDomain
* @return string
*/
function ExtractRecipientEmail($text, $multiple = false, $allowOnlyDomain = false) {
if ($allowOnlyDomain) {
$pattern = '/(('.REGEX_EMAIL_USER.'@)?'.REGEX_EMAIL_DOMAIN.')/i';
} else {
$pattern = '/('.REGEX_EMAIL_USER.'@'.REGEX_EMAIL_DOMAIN.')/i';
}
if ($multiple) {
if (preg_match_all($pattern, $text, $findemail) >= 1) {
return $findemail[1];
} else {
return false;
}
} else {
if (preg_match($pattern, $text, $findemail) == 1) {
return $findemail[1];
} else {
return false;
}
}
}
/**
* Returns array of recipient names and emails
*
* @param string $list
* @param string $separator
* @return Array
*/
function GetRecipients($list, $separator = ';')
{
// by MIME specs recipients should be separated using "," symbol,
// but users can write ";" too (like in OutLook)
if (!trim($list)) {
return false;
}
$list = explode(',', str_replace($separator, ',', $list));
$ret = Array ();
foreach ($list as $recipient) {
$email = $this->ExtractRecipientEmail($recipient);
if (!$email) {
// invalid email format -> error
return false;
}
$name = $this->ExtractRecipientName($recipient, $email);
$ret[] = Array('Name' => $name, 'Email' => $email);
}
return $ret;
}
/* methods for nice header setting */
/**
* Sets "From" header.
*
* @param string $email
* @param string $first_last_name FirstName and LastName or just FirstName
* @param string $last_name LastName (if not specified in previous parameter)
*/
function SetFrom($email, $first_last_name, $last_name = '')
{
$name = rtrim($first_last_name.' '.$last_name, ' ');
$this->SetEncodedEmailHeader('From', $email, $name ? $name : $email);
if (!isset($this->headers['Return-Path'])) {
$this->SetReturnPath($email);
}
}
/**
* Sets "To" header.
*
* @param string $email
* @param string $first_last_name FirstName and LastName or just FirstName
* @param string $last_name LastName (if not specified in previous parameter)
*/
function SetTo($email, $first_last_name, $last_name = '')
{
$name = rtrim($first_last_name.' '.$last_name, ' ');
$email = $this->_replaceRecipientEmail($email);
$this->SetEncodedEmailHeader('To', $email, $name ? $name : $email);
}
/**
* Sets "Return-Path" header (useful for spammers)
*
* @param string $email
*/
function SetReturnPath($email)
{
$this->SetHeader('Return-Path', $email);
}
/**
* Adds one more recipient into "To" header
*
* @param string $email
* @param string $first_last_name FirstName and LastName or just FirstName
* @param string $last_name LastName (if not specified in previous parameter)
*/
function AddTo($email, $first_last_name = '', $last_name = '')
{
$name = rtrim($first_last_name.' '.$last_name, ' ');
$this->AddRecipient('To', $email, $name);
}
/**
* Allows to replace recipient in all sent emails (used for debugging)
*
* @param string $email
* @return string
*/
function _replaceRecipientEmail($email)
{
if (defined('DBG_EMAIL') && DBG_EMAIL) {
if (substr(DBG_EMAIL, 0, 1) == '@') {
// domain
$email = str_replace('@', '_at_', $email) . DBG_EMAIL;
}
else {
$email = DBG_EMAIL;
}
}
return $email;
}
/**
* Adds one more recipient into "Cc" header
*
* @param string $email
* @param string $first_last_name FirstName and LastName or just FirstName
* @param string $last_name LastName (if not specified in previous parameter)
*/
function AddCc($email, $first_last_name = '', $last_name = '')
{
$name = rtrim($first_last_name.' '.$last_name, ' ');
$this->AddRecipient('Cc', $email, $name);
}
/**
* Adds one more recipient into "Bcc" header
*
* @param string $email
* @param string $first_last_name FirstName and LastName or just FirstName
* @param string $last_name LastName (if not specified in previous parameter)
*/
function AddBcc($email, $first_last_name = '', $last_name = '')
{
$name = rtrim($first_last_name.' '.$last_name, ' ');
$this->AddRecipient('Bcc', $email, $name);
}
/**
* Adds one more recipient to specified header
*
* @param string $header_name
* @param string $email
* @param string $name
*/
function AddRecipient($header_name, $email, $name = '')
{
$email = $this->_replaceRecipientEmail($email);
if (!$name) {
$name = $email;
}
$value = isset($this->headers[$header_name]) ? $this->headers[$header_name] : '';
- $value .= ', '.$this->QuotedPrintableEncode($name, $this->charset).' <'.$email.'>';
+ $value .= ', ' . $this->QuotedPrintableEncode($name, $this->charset) . ' <' . $email . '>';
- $value = preg_replace('/^,(.*)/', '\\1', $value); // remove first comma
- $this->SetHeader($header_name, $value);
+ $this->SetHeader($header_name, substr($value, 2));
}
/**
* Sets "Subject" header.
*
* @param string $subject message subject
*/
function SetSubject($subject)
{
$this->setEncodedHeader('Subject', $subject);
}
/**
* Sets HTML part of message
*
* @param string $html
*/
function SetHTML($html)
{
$this->CreateTextHtmlPart($html, true);
}
/**
* Sets Plain-Text part of message
*
* @param string $plain_text
*/
function SetPlain($plain_text)
{
$this->CreateTextHtmlPart($plain_text);
}
/**
* Sets HTML and optionally plain part of the message
*
* @param string $html
* @param string $plain_text
*/
function SetBody($html, $plain_text = '')
{
$this->SetHTML($html);
if ($plain_text) {
$this->SetPlain($plain_text);
}
}
/**
* Performs mail delivery (supports delayed delivery)
*
* @param string $mesasge message, if not given, then use composed one
* @param bool $immediate_send send message now or MailingId
* @param bool $immediate_clear clear message parts after message is sent
*
*/
function Deliver($message = null, $immediate_send = true, $immediate_clear = true)
{
if (isset($message)) {
// if message is given directly, then use it
if (is_array($message)) {
$message_headers =& $message[0];
$message_body =& $message[1];
}
else {
$message_headers = Array ();
list ($headers, $message_body) = explode("\n\n", $message, 2);
$headers = explode("\n", $headers);
foreach ($headers as $header) {
$header = explode(':', $header, 2);
$message_headers[ trim($header[0]) ] = trim($header[1]);
}
}
$composed = true;
} else {
// direct message not given, then assemble message from available parts
$composed = $this->GetHeadersAndBody($message_headers, $message_body);
}
if ($composed) {
if ($immediate_send === true) {
$send_method = 'Send'.$this->sendMethod;
$result = $this->$send_method($message_headers, $message_body);
if ($immediate_clear) {
$this->Clear();
}
return $result;
}
else {
$fields_hash = Array (
'ToEmail' => $message_headers['To'],
'Subject' => $message_headers['Subject'],
'Queued' => adodb_mktime(),
'SendRetries' => 0,
'LastSendRetry' => 0,
'MailingId' => (int)$immediate_send,
);
$fields_hash['MessageHeaders'] = serialize($message_headers);
$fields_hash['MessageBody'] =& $message_body;
$this->Conn->doInsert($fields_hash, TABLE_PREFIX.'EmailQueue');
if ($immediate_clear) {
$this->Clear();
}
}
}
// if not immediate send, then send result is positive :)
return $immediate_send !== true ? true : false;
}
}
\ No newline at end of file
Index: branches/5.0.x/core/kernel/db/dbitem.php
===================================================================
--- branches/5.0.x/core/kernel/db/dbitem.php (revision 12705)
+++ branches/5.0.x/core/kernel/db/dbitem.php (revision 12706)
@@ -1,1300 +1,1302 @@
<?php
/**
* @version $Id$
* @package In-Portal
* @copyright Copyright (C) 1997 - 2009 Intechnic. All rights reserved.
* @license GNU/GPL
* In-Portal is Open Source software.
* This means that this software may have been modified pursuant
* the GNU General Public License, and as distributed it includes
* or is derivative of works licensed under the GNU General Public License
* or other free or open source software licenses.
* See http://www.in-portal.net/license/ for copyright notices and details.
*/
defined('FULL_PATH') or die('restricted access!');
/**
* DBItem
*
* Desciption
* @package kernel4
*/
class kDBItem extends kDBBase {
/**
* Description
*
* @var array Associative array of current item' field values
* @access public
*/
var $FieldValues;
/**
* Unformatted field values, before parse
*
* @var Array
* @access private
*/
var $DirtyFieldValues = Array();
/**
* Holds item values after loading (not affected by submit)
*
* @var Array
* @access private
*/
var $OriginalFieldValues = Array ();
var $FieldErrors;
var $ErrorMsgs = Array();
/**
* If set to true, Update will skip Validation before running
*
* @var array Associative array of current item' field values
* @access public
*/
var $IgnoreValidation = false;
var $Loaded = false;
/**
* Holds item' primary key value
*
* @var int Value of primary key field for current item
* @access public
*/
var $ID;
function kDBItem()
{
parent::kDBBase();
$this->ErrorMsgs['required'] = '!la_err_required!'; //'Field is required';
$this->ErrorMsgs['unique'] = '!la_err_unique!'; //'Field value must be unique';
$this->ErrorMsgs['value_out_of_range'] = '!la_err_value_out_of_range!'; //'Field is out of range, possible values from %s to %s';
$this->ErrorMsgs['length_out_of_range'] = '!la_err_length_out_of_range!'; //'Field is out of range';
$this->ErrorMsgs['bad_type'] = '!la_err_bad_type!'; //'Incorrect data format, please use %s';
$this->ErrorMsgs['invalid_format'] = '!la_err_invalid_format!'; //'Incorrect data format, please use %s';
$this->ErrorMsgs['bad_date_format'] = '!la_err_bad_date_format!'; //'Incorrect date format, please use (%s) ex. (%s)';
$this->ErrorMsgs['primary_lang_required'] = '!la_err_primary_lang_required!';
}
function SetDirtyField($field_name, $field_value)
{
$this->DirtyFieldValues[$field_name] = $field_value;
}
function GetDirtyField($field_name)
{
return $this->DirtyFieldValues[$field_name];
}
function GetOriginalField($field_name, $formatted = false, $format=null)
{
if (array_key_exists($field_name, $this->OriginalFieldValues)) {
// item was loaded before
$value = $this->OriginalFieldValues[$field_name];
}
else {
// no original fields -> use default field value
$value = $this->Fields[$field_name]['default'];
}
if (!$formatted) {
return $value;
}
$options = $this->GetFieldOptions($field_name);
$res = $value;
if (array_key_exists('formatter', $options)) {
$formatter =& $this->Application->recallObject($options['formatter']);
/* @var $formatter kFormatter */
$res = $formatter->Format($value, $field_name, $this, $format);
}
return $res;
}
/**
* Sets original field value (useful for custom virtual fields)
*
* @param string $field_name
*/
function SetOriginalField($field_name, $field_value)
{
$this->OriginalFieldValues[$field_name] = $field_value;
}
/**
* Set's default values for all fields
*
* @param bool $populate_ml_fields create all ml fields from db in config or not
*
* @access public
*/
function SetDefaultValues($populate_ml_fields = false)
{
parent::SetDefaultValues($populate_ml_fields);
if ($populate_ml_fields) {
$this->PopulateMultiLangFields();
}
foreach ($this->Fields as $field => $params) {
if ( isset($params['default']) ) {
$this->SetDBField($field, $params['default']);
}
else {
$this->SetDBField($field, NULL);
}
}
}
/**
* Sets current item field value
* (applies formatting)
*
* @access public
* @param string $name Name of the field
* @param mixed $value Value to set the field to
* @return void
*/
function SetField($name,$value)
{
$options = $this->GetFieldOptions($name);
$parsed = $value;
if ($value == '') {
$parsed = NULL;
}
// kFormatter is always used, to make sure, that numeric value is converted to normal representation
// according to regional format, even when formatter is not set (try seting format to 1.234,56 to understand why)
$formatter =& $this->Application->recallObject(isset($options['formatter']) ? $options['formatter'] : 'kFormatter');
$parsed = $formatter->Parse($value, $name, $this);
$this->SetDBField($name,$parsed);
}
/**
* Sets current item field value
* (doesn't apply formatting)
*
* @access public
* @param string $name Name of the field
* @param mixed $value Value to set the field to
* @return void
*/
function SetDBField($name,$value)
{
$this->FieldValues[$name] = $value;
/*if (isset($this->Fields[$name]['formatter'])) {
$formatter =& $this->Application->recallObject($this->Fields[$name]['formatter']);
$formatter->UpdateSubFields($name, $value, $this->Fields[$name], $this);
}*/
}
/**
* Set's field error, if pseudo passed not found then create it with message text supplied.
* Don't owerrite existing pseudo translation.
*
* @param string $field
* @param string $pseudo
* @param string $error_label
*
* @return bool
*/
function SetError($field, $pseudo, $error_label = null, $error_params = null)
{
$error_field = isset($this->Fields[$field]['error_field']) ? $this->Fields[$field]['error_field'] : $field;
if (isset($this->FieldErrors[$error_field]['pseudo'])) {
// don't set more then one error on field
return false;
}
$this->FieldErrors[$error_field]['pseudo'] = $pseudo;
if (isset($error_params)) {
// additional params, that helps to determine error sources
$this->FieldErrors[$error_field]['params'] = $error_params;
}
if (isset($error_label) && !isset($this->ErrorMsgs[$pseudo])) {
// label for error (only when not already set)
$this->ErrorMsgs[$pseudo] = (substr($error_label, 0, 1) == '+') ? substr($error_label, 1) : '!'.$error_label.'!';
}
return true;
}
/**
* Return current item' field value by field name
* (doesn't apply formatter)
*
* @access public
* @param string $name field name to return
* @return mixed
*/
function GetDBField($name)
{
/*if (!array_key_exists($name, $this->FieldValues) && defined('DEBUG_MODE') && DEBUG_MODE) {
$this->Application->Debugger->appendTrace();
}*/
return $this->FieldValues[$name];
}
function HasField($name)
{
return isset($this->FieldValues[$name]);
}
function GetFieldValues()
{
return $this->FieldValues;
}
/**
* Sets item' fields corresponding to elements in passed $hash values.
*
* The function sets current item fields to values passed in $hash, by matching $hash keys with field names
* of current item. If current item' fields are unknown {@link kDBItem::PrepareFields()} is called before acutally setting the fields
*
* @access public
* @param Array $hash
* @param Array $set_fields Optional param, field names in target object to set, other fields will be skipped
* @return void
*/
function SetFieldsFromHash($hash, $set_fields = null)
{
// used in formatter which work with multiple fields together
foreach($hash as $field_name => $field_value) {
if (is_numeric($field_name) || !array_key_exists($field_name, $this->Fields)) {
continue;
}
if (is_array($set_fields) && !in_array($field_name, $set_fields)) {
continue;
}
$this->SetDirtyField($field_name, $field_value);
}
// formats all fields using associated formatters
foreach ($hash as $field_name => $field_value)
{
if (is_numeric($field_name) || !array_key_exists($field_name, $this->Fields)) {
continue;
}
if (is_array($set_fields) && !in_array($field_name, $set_fields)) {
continue;
}
$this->SetField($field_name,$field_value);
}
}
function SetDBFieldsFromHash($hash, $set_fields = null)
{
foreach ($hash as $field_name => $field_value) {
if (is_numeric($field_name) || !array_key_exists($field_name, $this->Fields)) {
continue;
}
if (is_array($set_fields) && !in_array($field_name, $set_fields)) {
continue;
}
$this->SetDBField($field_name, $field_value);
}
}
/**
* Returns part of SQL WHERE clause identifing the record, ex. id = 25
*
* @access public
* @param string $method Child class may want to know who called GetKeyClause, Load(), Update(), Delete() send its names as method
* @param Array $keys_hash alternative, then item id, keys hash to load item by
* @return void
* @see kDBItem::Load()
* @see kDBItem::Update()
* @see kDBItem::Delete()
*/
function GetKeyClause($method=null, $keys_hash = null)
{
- if( !isset($keys_hash) ) $keys_hash = Array($this->IDField => $this->ID);
+ if (!isset($keys_hash)) {
+ $keys_hash = Array ($this->IDField => $this->ID);
+ }
$ret = '';
- foreach($keys_hash as $field => $value)
- {
+
+ foreach ($keys_hash as $field => $value) {
if (!preg_match('/\./', $field)) {
- $ret .= '(`'.$this->TableName.'`.'.$field.' = '.$this->Conn->qstr($value).') AND ';
+ $ret .= '(`' . $this->TableName . '`.' . $field . ' = ' . $this->Conn->qstr($value) . ') AND ';
}
else {
- $ret .= '('.$field.' = '.$this->Conn->qstr($value).') AND ';
+ $ret .= '(' . $field . ' = ' . $this->Conn->qstr($value) . ') AND ';
}
}
- return preg_replace('/(.*) AND $/', '\\1', $ret);
+ return substr($ret, 0, -5);
}
/**
* Loads item from the database by given id
*
* @access public
* @param mixed $id item id of keys->values hash to load item by
* @param string $id_field_name Optional parameter to load item by given Id field
* @return bool True if item has been loaded, false otherwise
*/
function Load($id, $id_field_name = null)
{
if ( isset($id_field_name) ) {
$this->SetIDField($id_field_name); // set new IDField
}
$keys_sql = '';
if (is_array($id)) {
$keys_sql = $this->GetKeyClause('load', $id);
}
else {
$this->setID($id);
$keys_sql = $this->GetKeyClause('load');
}
if ( isset($id_field_name) ) {
// restore original IDField from unit config
$this->setIDField( $this->Application->getUnitOption($this->Prefix, 'IDField') );
}
if (($id === false) || !$keys_sql) {
return $this->Clear();
}
if (!$this->raiseEvent('OnBeforeItemLoad', $id)) {
return false;
}
$q = $this->GetSelectSQL() . ' WHERE ' . $keys_sql;
$field_values = $this->Conn->GetRow($q);
if ($field_values) {
$this->FieldValues = array_merge_recursive2($this->FieldValues, $field_values);
$this->OriginalFieldValues = $this->FieldValues;
}
else {
return $this->Clear();
}
if (is_array($id) || isset($id_field_name)) {
$this->setID($this->FieldValues[$this->IDField]);
}
$this->UpdateFormattersSubFields(); // used for updating separate virtual date/time fields from DB timestamp (for example)
$this->raiseEvent('OnAfterItemLoad', $this->GetID());
$this->Loaded = true;
return true;
}
/**
* Builds select sql, SELECT ... FROM parts only
*
* @access public
* @return string
*/
function GetSelectSQL()
{
$sql = $this->addCalculatedFields($this->SelectClause);
return parent::GetSelectSQL($sql);
}
function UpdateFormattersMasterFields()
{
foreach ($this->Fields as $field => $options) {
if (isset($options['formatter'])) {
$formatter =& $this->Application->recallObject($options['formatter']);
$formatter->UpdateMasterFields($field, $this->GetDBField($field), $options, $this);
}
}
}
/**
* Allows to skip certain fields from getting into sql queries
*
* @param string $field_name
* @param mixed $force_id
* @return bool
*/
function skipField($field_name, $force_id = false)
{
$skip = false;
// 1. skipping 'virtual' field
$skip = $skip || array_key_exists($field_name, $this->VirtualFields);
// 2. don't write empty field value to db, when "skip_empty" option is set
$field_value = array_key_exists($field_name, $this->FieldValues) ? $this->FieldValues[$field_name] : false;
$skip_empty = array_key_exists('skip_empty', $this->Fields[$field_name]) ? $this->Fields[$field_name]['skip_empty'] : false;
$skip = $skip || (!$field_value && $skip_empty);
// 3. skipping field not in Fields (nor virtual, nor real)
$skip = $skip || !array_key_exists($field_name, $this->Fields);
return $skip;
}
/**
* Updates previously loaded record with current item' values
*
* @access public
* @param int Primery Key Id to update
* @return bool
*/
function Update($id = null, $system_update = false)
{
if (isset($id)) {
$this->setID($id);
}
if (!$this->raiseEvent('OnBeforeItemUpdate')) {
return false;
}
if (!isset($this->ID)) {
// ID could be set inside OnBeforeItemUpdate event, so don't combine this check with previous one
return false;
}
// validate before updating
if (!$this->Validate()) {
return false;
}
if (!$this->raiseEvent('OnAfterItemValidate')) {
return false;
}
if (!$this->FieldValues) {
// nothing to update
return true;
}
$sql = '';
foreach ($this->FieldValues as $field_name => $field_value) {
if ($this->skipField($field_name)) {
continue;
}
if ( is_null($field_value) ) {
if (array_key_exists('not_null', $this->Fields[$field_name]) && $this->Fields[$field_name]['not_null']) {
// "kFormatter::Parse" methods converts empty values to NULL and for
// not-null fields they are replaced with default value here
$field_value = $this->Fields[$field_name]['default'];
}
}
$sql .= '`' . $field_name . '` = ' . $this->Conn->qstr($field_value) . ', ';
}
$sql = 'UPDATE ' . $this->TableName . '
SET ' . substr($sql, 0, -2) . '
WHERE ' . $this->GetKeyClause('update');
if ($this->Conn->ChangeQuery($sql) === false) {
// there was and sql error
return false;
}
$affected = $this->Conn->getAffectedRows();
if (!$system_update && $affected == 1) {
$this->setModifiedFlag(clUPDATE);
}
$this->saveCustomFields();
$this->raiseEvent('OnAfterItemUpdate');
$this->Loaded = true;
if ($this->mode != 't') {
$this->Application->resetCounters($this->TableName);
}
return true;
}
function ValidateField($field)
{
$options = $this->Fields[$field];
/*if (isset($options['formatter'])) {
$formatter =& $this->Application->recallObject($options['formatter']);
$formatter->UpdateMasterFields($field, $this->GetDBField($field), $options, $this);
}*/
$error_field = isset($options['error_field']) ? $options['error_field'] : $field;
$res = !isset($this->FieldErrors[$error_field]['pseudo']) || !$this->FieldErrors[$error_field]['pseudo'];
$res = $res && $this->ValidateRequired($field, $options);
$res = $res && $this->ValidateType($field, $options);
$res = $res && $this->ValidateRange($field, $options);
$res = $res && $this->ValidateUnique($field, $options);
$res = $res && $this->CustomValidation($field, $options);
return $res;
}
/**
* Validate all item fields based on
* constraints set in each field options
* in config
*
* @return bool
* @access private
*/
function Validate()
{
$this->UpdateFormattersMasterFields(); //order is critical - should be called BEFORE checking errors
if ($this->IgnoreValidation) {
return true;
}
$global_res = true;
foreach ($this->Fields as $field => $params) {
$res = $this->ValidateField($field);
$global_res = $global_res && $res;
}
if (!$global_res && $this->Application->isDebugMode()) {
$error_msg = ' Validation failed in prefix <strong>'.$this->Prefix.'</strong>,
FieldErrors follow (look at items with <strong>"pseudo"</strong> key set)<br />
You may ignore this notice if submitted data really has a validation error';
trigger_error(trim($error_msg), E_USER_NOTICE);
$this->Application->Debugger->dumpVars($this->FieldErrors);
}
return $global_res;
}
/**
* Check field value by user-defined alghoritm
*
* @param string $field field name
* @param Array $params field options from config
* @return bool
*/
function CustomValidation($field, $params)
{
return true;
}
/**
* Check if item has errors
*
* @param Array $skip_fields fields to skip during error checking
* @return bool
*/
function HasErrors($skip_fields)
{
$global_res = false;
foreach ($this->Fields as $field => $field_params) {
// If Formatter has set some error messages during values parsing
if ( !( in_array($field, $skip_fields) ) &&
isset($this->FieldErrors[$field]['pseudo']) && $this->FieldErrors[$field] != '') {
$global_res = true;
}
}
return $global_res;
}
/**
* Check if value in field matches field type specified in config
*
* @param string $field field name
* @param Array $params field options from config
* @return bool
*/
function ValidateType($field, $params)
{
$res = true;
$val = $this->FieldValues[$field];
if ( $val != '' &&
isset($params['type']) &&
preg_match("#int|integer|double|float|real|numeric|string#", $params['type'])
) {
if ($params['type'] == 'numeric') {
trigger_error('Invalid field type <strong>'.$params['type'].'</strong> (in ValidateType method), please use <strong>float</strong> instead', E_USER_NOTICE);
$params['type'] = 'float';
}
$res = is_numeric($val);
if ($params['type']=='string' || $res) {
$f = 'is_'.$params['type'];
settype($val, $params['type']);
$res = $f($val) && ($val == $this->FieldValues[$field]);
}
if (!$res) {
$this->SetError($field, 'bad_type', null, $params['type']);
}
}
return $res;
}
/**
* Check if value is set for required field
*
* @param string $field field name
* @param Array $params field options from config
* @return bool
* @access private
*/
function ValidateRequired($field, $params)
{
$res = true;
if (isset($params['required']) && $params['required']) {
$check_value = $this->FieldValues[$field];
if ($this->Application->ConfigValue('TrimRequiredFields')) {
$check_value = trim($check_value);
}
$res = ((string)$check_value != '');
}
if (!$res) {
$this->SetError($field, 'required');
}
return $res;
}
/**
* Validates that current record has unique field combination among other table records
*
* @param string $field field name
* @param Array $params field options from config
* @return bool
* @access private
*/
function ValidateUnique($field, $params)
{
$res = true;
$unique_fields = getArrayValue($params,'unique');
if($unique_fields !== false)
{
$where = Array();
array_push($unique_fields,$field);
foreach($unique_fields as $unique_field)
{
// if field is not empty or if it is required - we add where condition
if ((string)$this->GetDBField($unique_field) != '' || (isset($this->Fields[$unique_field]['required']) && $this->Fields[$unique_field]['required'])) {
$where[] = '`'.$unique_field.'` = '.$this->Conn->qstr( $this->GetDBField($unique_field) );
}
else {
// not good if we check by less fields than indicated
return true;
}
}
// This can ONLY happen if all unique fields are empty and not required.
// In such case we return true, because if unique field is not required there may be numerous empty values
// if (!$where) return true;
$sql = 'SELECT COUNT(*) FROM %s WHERE ('.implode(') AND (',$where).') AND ('.$this->IDField.' <> '.(int)$this->ID.')';
$res_temp = $this->Conn->GetOne( str_replace('%s', $this->TableName, $sql) );
$current_table_only = getArrayValue($params, 'current_table_only'); // check unique record only in current table
$res_live = $current_table_only ? 0 : $this->Conn->GetOne( str_replace('%s', $this->Application->GetLiveName($this->TableName), $sql) );
$res = ($res_temp == 0) && ($res_live == 0);
if (!$res) {
$this->SetError($field, 'unique');
}
}
return $res;
}
/**
* Check if field value is in range specified in config
*
* @param string $field field name
* @param Array $params field options from config
* @return bool
* @access private
*/
function ValidateRange($field, $params)
{
$res = true;
$val = $this->FieldValues[$field];
if ( isset($params['type']) && preg_match("#int|integer|double|float|real#", $params['type']) && strlen($val) > 0 ) {
if ( isset($params['max_value_inc'])) {
$res = $res && $val <= $params['max_value_inc'];
$max_val = $params['max_value_inc'].' (inclusive)';
}
if ( isset($params['min_value_inc'])) {
$res = $res && $val >= $params['min_value_inc'];
$min_val = $params['min_value_inc'].' (inclusive)';
}
if ( isset($params['max_value_exc'])) {
$res = $res && $val < $params['max_value_exc'];
$max_val = $params['max_value_exc'].' (exclusive)';
}
if ( isset($params['min_value_exc'])) {
$res = $res && $val > $params['min_value_exc'];
$min_val = $params['min_value_exc'].' (exclusive)';
}
}
if (!$res) {
if ( !isset($min_val) ) $min_val = '-&infin;';
if ( !isset($max_val) ) $max_val = '&infin;';
$this->SetError($field, 'value_out_of_range', null, Array ($min_val, $max_val));
return $res;
}
if ( isset($params['max_len'])) {
$res = $res && mb_strlen($val) <= $params['max_len'];
}
if ( isset($params['min_len'])) {
$res = $res && mb_strlen($val) >= $params['min_len'];
}
if (!$res) {
$error_params = Array (getArrayValue($params, 'min_len'), getArrayValue($params, 'max_len'));
$this->SetError($field, 'length_out_of_range', null, $error_params);
return $res;
}
return $res;
}
/**
* Return error message for field
*
* @param string $field
* @return string
* @access public
*/
function GetErrorMsg($field, $force_escape = null)
{
if( !isset($this->FieldErrors[$field]) ) return '';
$err = getArrayValue($this->FieldErrors[$field], 'pseudo');
if (!$err) return '';
// if special error msg defined in config
if( isset($this->Fields[$field]['error_msgs'][$err]) )
{
$msg = $this->Fields[$field]['error_msgs'][$err];
}
else //fall back to defaults
{
if( !isset($this->ErrorMsgs[$err]) ) {
trigger_error('No user message is defined for pseudo error <b>'.$err.'</b><br>', E_USER_WARNING);
return $err; //return the pseudo itself
}
$msg = $this->ErrorMsgs[$err];
}
$msg = $this->Application->ReplaceLanguageTags($msg, $force_escape);
if ( isset($this->FieldErrors[$field]['params']) )
{
return vsprintf($msg, $this->FieldErrors[$field]['params']);
}
return $msg;
}
/**
* Creates a record in the database table with current item' values
*
* @param mixed $force_id Set to TRUE to force creating of item's own ID or to value to force creating of passed id. Do not pass 1 for true, pass exactly TRUE!
* @access public
* @return bool
*/
function Create($force_id = false, $system_create = false)
{
if (!$this->raiseEvent('OnBeforeItemCreate')) {
return false;
}
// Validating fields before attempting to create record
if (!$this->Validate()) {
return false;
}
if (!$this->raiseEvent('OnAfterItemValidate')) {
return false;
}
if (is_int($force_id)) {
$this->FieldValues[$this->IDField] = $force_id;
}
elseif (!$force_id || !is_bool($force_id)) {
$this->FieldValues[$this->IDField] = $this->generateID();
}
$fields_sql = '';
$values_sql = '';
foreach ($this->FieldValues as $field_name => $field_value) {
if ($this->skipField($field_name, $force_id)) {
continue;
}
if (is_null($field_value)) {
if (array_key_exists('not_null', $this->Fields[$field_name]) && $this->Fields[$field_name]['not_null']) {
// "kFormatter::Parse" methods converts empty values to NULL and for
// not-null fields they are replaced with default value here
$values_sql .= $this->Conn->qstr($this->Fields[$field_name]['default']);
}
else {
$values_sql .= $this->Conn->qstr($field_value);
}
}
else {
if (($field_name == $this->IDField) && ($field_value == 0)) {
// don't skip IDField in INSERT statement, just use DEFAULT keyword as it's value
$values_sql .= 'DEFAULT';
}
else {
$values_sql .= $this->Conn->qstr($field_value);
}
}
$fields_sql .= '`' . $field_name . '`, '; //Adding field name to fields block of Insert statement
$values_sql .= ', ';
}
$sql = 'INSERT INTO ' . $this->TableName . ' (' . substr($fields_sql, 0, -2) . ')
VALUES (' . substr($values_sql, 0, -2) . ')';
//Executing the query and checking the result
if ($this->Conn->ChangeQuery($sql) === false) {
return false;
}
$insert_id = $this->Conn->getInsertID();
if ($insert_id == 0) {
// insert into temp table (id is not auto-increment field)
$insert_id = $this->FieldValues[$this->IDField];
}
$this->setID($insert_id);
if (!$system_create){
$this->setModifiedFlag(clCREATE);
}
$this->saveCustomFields();
if ($this->mode != 't') {
$this->Application->resetCounters($this->TableName);
}
$this->raiseEvent('OnAfterItemCreate');
$this->Loaded = true;
return true;
}
/**
* Deletes the record from databse
*
* @access public
* @return bool
*/
function Delete($id = null)
{
if (isset($id)) {
$this->setID($id);
}
if (!$this->raiseEvent('OnBeforeItemDelete')) {
return false;
}
$sql = 'DELETE FROM ' . $this->TableName . '
WHERE ' . $this->GetKeyClause('Delete');
$ret = $this->Conn->ChangeQuery($sql);
$affected_rows = $this->Conn->getAffectedRows();
$this->setModifiedFlag(clDELETE); // will change affected rows, so get it before this line
if ($affected_rows > 0) {
// something was actually deleted
$this->raiseEvent('OnAfterItemDelete');
}
if ($this->mode != 't') {
$this->Application->resetCounters($this->TableName);
}
return $ret;
}
function PopulateMultiLangFields()
{
$ml_helper =& $this->Application->recallObject('kMultiLanguageHelper');
/* @var $ml_helper kMultiLanguageHelper */
$lang_count = $ml_helper->getLanguageCount();
foreach ($this->Fields as $field => $options)
{
// master field is set only for CURRENT language
if (isset($options['formatter']) && $options['formatter'] == 'kMultiLanguage' && isset($options['master_field'])) {
if (preg_match('/^l([0-9]+)_(.*)/', $field, $regs)) {
$l = $regs[1];
$name = $regs[2];
// MuliLanguage formatter sets error_field to master_field, but in PopulateMlFields mode, we display ML fields directly
// so we set it back to itself, otherwise error will not be displayed
$this->Fields['l' . $l . '_' . $name]['error_field'] = 'l' . $l . '_' . $name;
for ($i = 1; $i <= $lang_count; $i++) {
if ($i == $l || !$ml_helper->LanguageFound($i)) continue;
$f_options = $options;
$f_options['error_field'] = 'l' . $i . '_' . $name; // set error field back to itself - see comment above
if ($i != $this->Application->GetDefaultLanguageId()) {
unset($f_options['required']); // all non-primary language field set to non-required
}
$this->Fields['l' . $i . '_' . $name] = $f_options;
}
}
}
}
}
/**
* Sets new name for item in case if it is beeing copied
* in same table
*
* @param array $master Table data from TempHandler
* @param int $foreign_key ForeignKey value to filter name check query by
* @param string $title_field FieldName to alter, by default - TitleField of the prefix
* @param string $format sprintf-style format of renaming pattern, by default Copy %1$s of %2$s which makes it Copy [Number] of Original Name
* @access private
*/
function NameCopy($master=null, $foreign_key=null, $title_field=null, $format='Copy %1$s of %2$s')
{
if (!isset($title_field)) {
$title_field = $this->Application->getUnitOption($this->Prefix, 'TitleField');
if (!$title_field || isset($this->CalculatedFields[$title_field]) ) return;
}
$new_name = $this->GetDBField($title_field);
$original_checked = false;
do {
if ( preg_match('/'.sprintf($format, '([0-9]*) *', '(.*)').'/', $new_name, $regs) ) {
$new_name = sprintf($format, ($regs[1]+1), $regs[2]);
}
elseif ($original_checked) {
$new_name = sprintf($format, '', $new_name);
}
// if we are cloning in temp table this will look for names in temp table,
// since object' TableName contains correct TableName (for temp also!)
// if we are cloning live - look in live
$query = 'SELECT '.$title_field.' FROM '.$this->TableName.'
WHERE '.$title_field.' = '.$this->Conn->qstr($new_name);
$foreign_key_field = getArrayValue($master, 'ForeignKey');
$foreign_key_field = is_array($foreign_key_field) ? $foreign_key_field[ $master['ParentPrefix'] ] : $foreign_key_field;
if ($foreign_key_field && isset($foreign_key)) {
$query .= ' AND '.$foreign_key_field.' = '.$foreign_key;
}
$res = $this->Conn->GetOne($query);
/*// if not found in live table, check in temp table if applicable
if ($res === false && $object->Special == 'temp') {
$query = 'SELECT '.$name_field.' FROM '.$this->GetTempName($master['TableName']).'
WHERE '.$name_field.' = '.$this->Conn->qstr($new_name);
$res = $this->Conn->GetOne($query);
}*/
$original_checked = true;
} while ($res !== false);
$this->SetDBField($title_field, $new_name);
}
function raiseEvent($name, $id = null, $additional_params = Array())
{
if( !isset($id) ) $id = $this->GetID();
$event = new kEvent( Array('name'=>$name,'prefix'=>$this->Prefix,'special'=>$this->Special) );
$event->setEventParam('id', $id);
if ($additional_params) {
foreach ($additional_params as $ap_name => $ap_value) {
$event->setEventParam($ap_name, $ap_value);
}
}
$this->Application->HandleEvent($event);
return $event->status == erSUCCESS ? true : false;
}
/**
* Set's new ID for item
*
* @param int $new_id
* @access public
*/
function setID($new_id)
{
$this->ID = $new_id;
$this->SetDBField($this->IDField, $new_id);
}
/**
* Generate and set new temporary id
*
* @access private
*/
function setTempID()
{
$new_id = (int)$this->Conn->GetOne('SELECT MIN('.$this->IDField.') FROM '.$this->TableName);
if($new_id > 0) $new_id = 0;
--$new_id;
$this->Conn->Query('UPDATE '.$this->TableName.' SET `'.$this->IDField.'` = '.$new_id.' WHERE `'.$this->IDField.'` = '.$this->GetID());
if ($this->ShouldLogChanges()) {
// Updating TempId in ChangesLog, if changes are disabled
$ses_var_name = $this->Application->GetTopmostPrefix($this->Prefix).'_changes_'.$this->Application->GetTopmostWid($this->Prefix);
$changes = $this->Application->RecallVar($ses_var_name);
$changes = $changes ? unserialize($changes) : Array ();
if ($changes) {
foreach ($changes as $key => $rec) {
if ($rec['Prefix'] == $this->Prefix && $rec['ItemId'] == $this->GetID()) {
$changes[$key]['ItemId'] = $new_id;
}
}
}
$this->Application->StoreVar($ses_var_name, serialize($changes));
}
$this->SetID($new_id);
}
/**
* Set's modification flag for main prefix of current prefix to true
*
* @access private
* @author Alexey
*/
function setModifiedFlag($mode = null)
{
$main_prefix = $this->Application->GetTopmostPrefix($this->Prefix);
$this->Application->StoreVar($main_prefix.'_modified', '1', !$this->Application->IsAdmin());
if ($this->ShouldLogChanges()) {
$this->LogChanges($main_prefix, $mode);
if (!$this->IsTempTable()) {
$handler =& $this->Application->recallObject($this->Prefix.'_EventHandler');
$ses_var_name = $main_prefix.'_changes_'.$this->Application->GetTopmostWid($this->Prefix);
$handler->SaveLoggedChanges($ses_var_name);
}
}
}
/**
* Determines, that changes made to this item should be written to change log
*
* @return bool
*/
function ShouldLogChanges()
{
$log_changes = $this->Application->getUnitOption($this->Prefix, 'LogChanges') || $this->Application->ConfigValue('UseChangeLog');
return $log_changes && !$this->Application->getUnitOption($this->Prefix, 'ForceDontLogChanges');
}
function LogChanges($main_prefix, $mode)
{
if (!$mode) {
return ;
}
$ses_var_name = $main_prefix.'_changes_'.$this->Application->GetTopmostWid($this->Prefix);
$changes = $this->Application->RecallVar($ses_var_name);
$changes = $changes ? unserialize($changes) : array();
$general = array(
'Prefix' => $this->Prefix,
'ItemId' => $this->GetID(),
'OccuredOn' => adodb_mktime(),
'MasterPrefix' => $main_prefix,
'MasterId' => $this->Prefix == $main_prefix ? $this->GetID() : $this->Application->GetVar($main_prefix.'_id'), // is that correct (Kostja)??
'Action' => $mode,
);
switch ($mode) {
case clUPDATE:
$changes[] = array_merge($general, Array(
'Changes' => serialize(array_merge($this->GetTitleField(), $this->GetChangedFields())),
));
break;
case clCREATE:
$changes[] = array_merge($general, Array(
'Changes' => serialize($this->GetTitleField()),
));
break;
case clDELETE:
$changes[] = array_merge($general, Array(
'Changes' => serialize(array_merge($this->GetTitleField(), $this->GetRealFields())),
));
}
$this->Application->StoreVar($ses_var_name, serialize($changes));
}
function GetTitleField()
{
$title_field = $this->Application->getUnitOption($this->Prefix, 'TitleField');
if ($title_field && $this->GetField($title_field)) {
return Array($title_field => $this->GetField($title_field));
}
}
function GetRealFields()
{
if (function_exists('array_diff_key')) {
$db_fields = array_diff_key($this->FieldValues, $this->VirtualFields, $this->CalculatedFields);
}
else {
$db_fields = array();
foreach ($this->FieldValues as $key => $value) {
if (array_key_exists($key, $this->VirtualFields) || array_key_exists($key, $this->CalculatedFields)) continue;
$db_fields[$key] = $value;
}
}
return $db_fields;
}
function GetChangedFields()
{
$changes = array();
$diff = array_diff_assoc($this->GetRealFields(), $this->OriginalFieldValues);
foreach ($diff as $field => $new_value) {
$changes[$field] = array('old' => $this->GetOriginalField($field, true), 'new' => $this->GetField($field));
}
return $changes;
}
/**
* Returns ID of currently processed record
*
* @return int
* @access public
*/
function GetID()
{
return $this->ID;
}
/**
* Generates ID for new items before inserting into database
*
* @return int
* @access private
*/
function generateID()
{
return 0;
}
/**
* Returns true if item was loaded successfully by Load method
*
* @return bool
*/
function isLoaded()
{
return $this->Loaded;
}
/**
* Checks if field is required
*
* @param string $field
* @return bool
*/
function isRequired($field)
{
return getArrayValue( $this->Fields[$field], 'required' );
}
/**
* Sets new required flag to field
*
* @param string $field
* @param bool $is_required
*/
function setRequired($field, $is_required = true)
{
$this->Fields[$field]['required'] = $is_required;
}
function Clear($new_id = null)
{
$this->Loaded = false;
$this->FieldValues = Array();
$this->OriginalFieldValues = Array ();
$this->SetDefaultValues(); // will wear off kDBItem::setID effect, so set it later
$this->FieldErrors = Array();
$this->setID($new_id);
return $this->Loaded;
}
function Query($force = false)
{
if ($this->Application->isDebugMode()) {
$this->Application->Debugger->appendTrace();
}
trigger_error('<b>Query</b> method is called in class <b>'.get_class($this).'</b> for prefix <b>'.$this->getPrefixSpecial().'</b>', E_USER_ERROR);
}
function saveCustomFields()
{
if (!$this->customFields) {
return true;
}
$cdata_key = rtrim($this->Prefix.'-cdata.'.$this->Special, '.');
$cdata =& $this->Application->recallObject($cdata_key, null, Array('skip_autoload' => true, 'populate_ml_fields' => true));
$resource_id = $this->GetDBField('ResourceId');
$cdata->Load($resource_id, 'ResourceId');
$cdata->SetDBField('ResourceId', $resource_id);
$ml_formatter =& $this->Application->recallObject('kMultiLanguage');
/* @var $ml_formatter kMultiLanguage */
foreach ($this->customFields as $custom_id => $custom_name) {
$force_primary = isset($cdata->Fields['cust_'.$custom_id]['force_primary']) && $cdata->Fields['cust_'.$custom_id]['force_primary'];
$cdata->SetDBField($ml_formatter->LangFieldName('cust_'.$custom_id, $force_primary), $this->GetDBField('cust_'.$custom_name));
}
if ($cdata->isLoaded()) {
$ret = $cdata->Update();
}
else {
$ret = $cdata->Create();
if ($cdata->mode == 't') $cdata->setTempID();
}
return $ret;
}
/**
* Returns specified field value from all selected rows.
* Don't affect current record index
*
* @param string $field
* @return Array
*/
function GetCol($field)
{
return Array (0 => $this->GetDBField($field));
}
}
\ No newline at end of file
Index: branches/5.0.x/core/units/statistics/statistics_event_handler.php
===================================================================
--- branches/5.0.x/core/units/statistics/statistics_event_handler.php (revision 12705)
+++ branches/5.0.x/core/units/statistics/statistics_event_handler.php (revision 12706)
@@ -1,40 +1,40 @@
<?php
/**
* @version $Id$
* @package In-Portal
* @copyright Copyright (C) 1997 - 2009 Intechnic. All rights reserved.
* @license GNU/GPL
* In-Portal is Open Source software.
* This means that this software may have been modified pursuant
* the GNU General Public License, and as distributed it includes
* or is derivative of works licensed under the GNU General Public License
* or other free or open source software licenses.
* See http://www.in-portal.net/license/ for copyright notices and details.
*/
defined('FULL_PATH') or die('restricted access!');
class StatisticsEventHandler extends kDBEventHandler {
/**
* Allows to show statistics only of requrested type
*
* @param kEvent $event
*/
function SetCustomQuery(&$event)
{
$object =& $event->getObject();
if ($event->Special == 'summary') {
$object->addFilter('summary_filter', '%1$s.AdminSummary = 1');
}
$module_list = '';
foreach ($this->Application->ModuleInfo as $module_name => $module_info) {
$module_list .= $this->Conn->qstr($module_name).',';
}
- $module_list = preg_replace('/(.*),$/', '\\1', $module_list);
+ $module_list = substr($module_list, 0, -1);
$object->addFilter('status_filter', '%1$s.Module IN ('.$module_list.')');
}
}
\ No newline at end of file
Index: branches/5.0.x/core/units/helpers/spam_helper.php
===================================================================
--- branches/5.0.x/core/units/helpers/spam_helper.php (revision 12705)
+++ branches/5.0.x/core/units/helpers/spam_helper.php (revision 12706)
@@ -1,144 +1,144 @@
<?php
/**
* @version $Id$
* @package In-Portal
* @copyright Copyright (C) 1997 - 2009 Intechnic. All rights reserved.
* @license GNU/GPL
* In-Portal is Open Source software.
* This means that this software may have been modified pursuant
* the GNU General Public License, and as distributed it includes
* or is derivative of works licensed under the GNU General Public License
* or other free or open source software licenses.
* See http://www.in-portal.net/license/ for copyright notices and details.
*/
defined('FULL_PATH') or die('restricted access!');
class SpamHelper extends kHelper {
/**
* Table name where spam control information is keeped
*
* @var string
*/
var $TableName;
/**
* RecourceId field of current item
*
* @var int
*/
var $ResourceId = 0;
/**
* Type of information to put into spam control
*
* @var string
*/
var $DataType = '';
/**
* Default spam control record expiration
*
* @var int
*/
var $Expiration = 0;
function SpamHelper()
{
parent::kHelper();
$this->TableName = TABLE_PREFIX.'SpamControl';
}
/**
* Initializes helper for concrete item
*
* @param int $resource_id
* @param string $data_type
* @param int $expiration
*/
function InitHelper($resource_id, $data_type, $expiration)
{
$this->ResourceId = $resource_id;
$this->DataType = $data_type;
if (preg_match('/(.*):(.*)/', $expiration, $regs)) {
$delay_value = $this->Application->ConfigValue($regs[1]);
$delay_interval = $this->Application->ConfigValue($regs[2]);
$expiration = $delay_value * $delay_interval;
}
$this->Expiration = adodb_mktime() + $expiration;
}
/**
* Returns WHERE clause that identified each spam control record
*
* @param bool $as_array return result as array, not string
*
* @return string
*/
function GetKeyClause($as_array = false)
{
$user_id = $this->Application->RecallVar('user_id');
if ($user_id == 0) {
$user_id = -2;
}
$keys = Array (
'ItemResourceId' => $this->ResourceId,
'IPaddress' => $_SERVER['REMOTE_ADDR'],
'PortalUserId' => $user_id,
'DataType' => $this->DataType,
);
if ($as_array) {
return $keys;
}
$ret = '';
foreach ($keys as $field_name => $field_value) {
$ret .= '('.$field_name.' = '.$this->Conn->qstr($field_value).') AND ';
}
- return preg_replace('/(.*) AND $/', '\\1', $ret);
+ return substr($ret, 0, -5);
}
/**
* Allows to add current item in spam control
*
*/
function AddToSpamControl()
{
$fields_hash = $this->GetKeyClause(true);
$fields_hash['Expire'] = $this->Expiration;
$this->Conn->doInsert($fields_hash, $this->TableName);
}
/**
* Allows to check if current item is in spam control
*
* @return bool
*/
function InSpamControl()
{
$key_clause = $this->GetKeyClause();
$sql = 'SELECT Expire
FROM '.$this->TableName.'
WHERE '.$key_clause;
$expires = $this->Conn->GetOne($sql);
if ($expires && $expires < adodb_mktime()) {
// spam control record is expired
$sql = 'DELETE FROM '.$this->TableName.'
WHERE '.$key_clause;
$this->Conn->Query($sql);
return false;
}
return $expires ? true : false;
}
}
\ No newline at end of file
Index: branches/5.0.x/core/units/helpers/language_import_helper.php
===================================================================
--- branches/5.0.x/core/units/helpers/language_import_helper.php (revision 12705)
+++ branches/5.0.x/core/units/helpers/language_import_helper.php (revision 12706)
@@ -1,609 +1,613 @@
<?php
/**
* @version $Id$
* @package In-Portal
* @copyright Copyright (C) 1997 - 2009 Intechnic. All rights reserved.
* @license GNU/GPL
* In-Portal is Open Source software.
* This means that this software may have been modified pursuant
* the GNU General Public License, and as distributed it includes
* or is derivative of works licensed under the GNU General Public License
* or other free or open source software licenses.
* See http://www.in-portal.net/license/ for copyright notices and details.
*/
defined('FULL_PATH') or die('restricted access!');
define('LANG_OVERWRITE_EXISTING', 1);
define('LANG_SKIP_EXISTING', 2);
class LanguageImportHelper extends kHelper {
/**
* Current Language in import
*
* @var LanguagesItem
*/
var $lang_object = null;
/**
* Current user's IP address
*
* @var string
*/
var $ip_address = '';
/**
* Event type + name mapping to id (from system)
*
* @var Array
*/
var $events_hash = Array ();
/**
* Language pack import mode
*
* @var int
*/
var $import_mode = LANG_SKIP_EXISTING;
/**
* Language IDs, that were imported
*
* @var Array
*/
var $_languages = Array ();
/**
* Temporary table names to perform import on
*
* @var Array
*/
var $_tables = Array ();
/**
* Phrase types allowed for import/export operations
*
* @var Array
*/
var $phrase_types_allowed = Array ();
/**
* Encoding, used for language pack exporting
*
* @var string
*/
var $_exportEncoding = 'base64';
/**
* Debug language pack import process
*
* @var bool
*/
var $_debugMode = false;
function LanguageImportHelper()
{
parent::kHelper();
// "core/install/english.lang", phrase count: 3318, xml parse time on windows: 10s, insert time: 0.058s
set_time_limit(0);
ini_set('memory_limit', -1);
$this->lang_object =& $this->Application->recallObject('lang.import', null, Array ('skip_autoload' => true));
if (!(defined('IS_INSTALL') && IS_INSTALL)) {
// perform only, when not in installation mode
$this->_updateEventsCache();
}
$this->ip_address = getenv('HTTP_X_FORWARDED_FOR') ? getenv('HTTP_X_FORWARDED_FOR') : getenv('REMOTE_ADDR');
// $this->_debugMode = $this->Application->isDebugMode();
}
/**
* Performs import of given language pack (former Parse method)
*
* @param string $filename
* @param string $phrase_types
* @param Array $module_ids
* @param int $import_mode
* @return bool
*/
function performImport($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;
}
if ($this->_debugMode) {
$start_time = getmicrotime();
$this->Application->Debugger->appendHTML(__CLASS__ . '::' . __FUNCTION__ . '("' . $filename . '")');
}
if (defined('IS_INSTALL') && IS_INSTALL) {
// new events could be added during module upgrade
$this->_updateEventsCache();
}
$this->_initImportTables();
$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;
$this->_parseXML($filename);
// copy data from temp tables to live
foreach ($this->_languages as $language_id) {
$this->_performUpgrade($language_id, 'phrases', 'PhraseKey');
$this->_performUpgrade($language_id, 'emailmessages', 'EventId');
}
$this->_initImportTables(true);
if ($this->_debugMode) {
$this->Application->Debugger->appendHTML(__CLASS__ . '::' . __FUNCTION__ . '("' . $filename . '"): ' . (getmicrotime() - $start_time));
}
return true;
}
/**
* Creates XML file with exported language data (former Create method)
*
* @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 performExport($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->_exportEncoding.'"><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><DOCS_URL>'.$row['UserDocsUrl'].'</DOCS_URL>';
$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->_exportEncoding == '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).',' ) );
+ if ( in_array('In-Portal',$module_ids) ) {
+ unset( $module_ids[array_search('',$module_ids)] ); // for old language packs
+ }
+
+ $module_sql = preg_replace('/(.*),/U', 'INSTR(Module,\'\\1\') OR ', implode(',', $module_ids).',');
+ $module_sql = substr($module_sql, 0, -4);
$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)
{
if (!array_key_exists($row['EventId'], $this->events_hash)) {
// don't export existing translations of missing events
continue;
}
list($event_name, $event_type) = explode('_', $this->events_hash[ $row['EventId'] ] );
$data = $this->_exportEncoding == '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;
}
/**
* Sets language pack encoding (not charset) used during export
*
* @param string $encoding
*/
function setExportEncoding($encoding)
{
$this->_exportEncoding = $encoding;
}
/**
* Performs upgrade of given language pack part
*
* @param int $language_id
* @param string $prefix
* @param string $unique_field
*/
function _performUpgrade($language_id, $prefix, $unique_field)
{
// TODO: find a way to compare (intersect,diff) phrases in non-case sensitive way, but keeping original case in result
$live_records = $this->_getTableData($language_id, $prefix, $unique_field, false);
$temp_records = $this->_getTableData($language_id, $prefix, $unique_field, true);
if ($this->import_mode == LANG_OVERWRITE_EXISTING) {
// remove existing records before copy
$common_records = array_intersect($temp_records, $live_records);
if ($common_records) {
$live_records = array_diff($live_records, $common_records); // remove overlaping records
$common_records = array_map(Array(&$this->Conn, 'qstr'), $common_records);
$sql = 'DELETE FROM ' . $this->Application->getUnitOption($prefix, 'TableName') . '
WHERE (LanguageId = ' . $language_id . ') AND (' . $unique_field . ' IN (' . implode(',', $common_records) . '))';
$this->Conn->Query($sql);
}
}
$temp_records = array_diff($temp_records, $live_records);
if (!$temp_records) {
// no new records found in temp table while comparing it to live table
return ;
}
$temp_records = array_map(Array(&$this->Conn, 'qstr'), $temp_records);
$sql = 'INSERT INTO ' . $this->Application->getUnitOption($prefix, 'TableName') . '
SELECT *
FROM ' . $this->_tables[$prefix] . '
WHERE (LanguageId = ' . $language_id . ')';
if ($live_records) {
// subsctract live records from temp table during coping
$sql .= ' AND (' . $unique_field . ' IN (' . implode(',', $temp_records) . '))';
}
$this->Conn->Query($sql);
}
/**
* Returns data from given table used for language pack upgrade
*
* @param int $language_id
* @param string $prefix
* @param string $unique_field
* @param bool $temp_mode
* @return Array
*/
function _getTableData($language_id, $prefix, $unique_field, $temp_mode = false)
{
$table_name = $this->Application->getUnitOption($prefix, 'TableName');
if ($temp_mode) {
$table_name = $this->Application->GetTempName($table_name, 'prefix:' . $prefix);
}
$sql = 'SELECT ' . $unique_field . '
FROM ' . $table_name . '
WHERE LanguageId = ' . $language_id;
return $this->Conn->GetCol($sql);
}
function _parseXML($filename)
{
if ($this->_debugMode) {
$start_time = getmicrotime();
$this->Application->Debugger->appendHTML(__CLASS__ . '::' . __FUNCTION__ . '("' . $filename . '")');
}
$fdata = file_get_contents($filename);
$xml_parser =& $this->Application->recallObject('kXMLHelper');
/* @var $xml_parser kXMLHelper */
$root_node =& $xml_parser->Parse($fdata);
if (!is_object($root_node) || !is_a($root_node, 'kXMLNode')) {
// invalid language pack contents
return false;
}
if ($root_node->Children) {
$this->_processLanguages($root_node->firstChild);
}
if ($this->_debugMode) {
$this->Application->Debugger->appendHTML(__CLASS__ . '::' . __FUNCTION__ . '("' . $filename . '"): ' . (getmicrotime() - $start_time));
}
return true;
}
/**
* Creates temporary tables, used during language import
*
* @param bool $drop_only
*/
function _initImportTables($drop_only = false)
{
$this->_tables['phrases'] = $this->_prepareTempTable('phrases', $drop_only);
$this->_tables['emailmessages'] = $this->_prepareTempTable('emailmessages', $drop_only);
}
/**
* Create temp table for prefix, if table already exists, then delete it and create again
*
* @param string $prefix
*/
function _prepareTempTable($prefix, $drop_only = false)
{
$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) );
if (!$drop_only) {
$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 DEFAULT "0"';
$this->Conn->Query( sprintf($sql, $temp_table, $idfield) );
}
return $temp_table;
}
/**
* Prepares mapping between event name+type and their ids in database
*
*/
function _updateEventsCache()
{
$sql = 'SELECT EventId, CONCAT(Event,"_",Type) AS EventMix
FROM ' . TABLE_PREFIX . 'Events';
$this->events_hash = $this->Conn->GetCol($sql, 'EventMix');
}
/**
* Processes parsed XML
*
* @param kXMLNode $language_node
*/
function _processLanguages(&$language_node)
{
$field_mapping = Array (
'DATEFORMAT' => 'DateFormat',
'TIMEFORMAT' => 'TimeFormat',
'INPUTDATEFORMAT' => 'InputDateFormat',
'INPUTTIMEFORMAT' => 'InputTimeFormat',
'DECIMAL' => 'DecimalPoint',
'THOUSANDS' => 'ThousandSep',
'CHARSET' => 'Charset',
'UNITSYSTEM' => 'UnitSystem',
'DOCS_URL' => 'UserDocsUrl',
);
do {
$language_id = false;
$fields_hash = Array (
'PackName' => $language_node->Attributes['PACKNAME'],
'LocalName' => $language_node->Attributes['PACKNAME'],
'Encoding' => $language_node->Attributes['ENCODING'],
'Charset' => 'iso-8859-1',
);
$sub_node =& $language_node->firstChild;
/* @var $sub_node kXMLNode */
do {
switch ($sub_node->Name) {
case 'PHRASES':
if ($sub_node->Children) {
if (!$language_id) {
$language_id = $this->_processLanguage($fields_hash);
}
if ($this->_debugMode) {
$start_time = getmicrotime();
}
$this->_processPhrases($sub_node->firstChild, $language_id, $fields_hash['Encoding']);
if ($this->_debugMode) {
$this->Application->Debugger->appendHTML(__CLASS__ . '::' . '_processPhrases: ' . (getmicrotime() - $start_time));
}
}
break;
case 'EVENTS':
if ($sub_node->Children) {
if (!$language_id) {
$language_id = $this->_processLanguage($fields_hash);
}
$this->_processEvents($sub_node->firstChild, $language_id, $fields_hash['Encoding']);
}
break;
default:
$fields_hash[ $field_mapping[$sub_node->Name] ] = $sub_node->Data;
break;
}
} while (($sub_node =& $sub_node->NextSibling()));
} while (($language_node =& $language_node->NextSibling()));
}
/**
* Performs phases import
*
* @param kXMLNode $phrase_node
* @param int $language_id
* @param string $language_encoding
*/
function _processPhrases(&$phrase_node, $language_id, $language_encoding)
{
do {
$fields_hash = Array (
'LanguageId' => $language_id,
'Phrase' => $phrase_node->Attributes['LABEL'],
'PhraseKey' => mb_strtoupper($phrase_node->Attributes['LABEL']),
'PhraseType' => $phrase_node->Attributes['TYPE'],
'Module' => array_key_exists('MODULE', $phrase_node->Attributes) ? $phrase_node->Attributes['MODULE'] : 'Core',
'LastChanged' => adodb_mktime(),
'LastChangeIP' => $this->ip_address,
'Translation' => $phrase_node->Data,
);
if (array_key_exists($fields_hash['PhraseType'], $this->phrase_types_allowed)) {
if ($language_encoding != 'plain') {
$fields_hash['Translation'] = base64_decode($fields_hash['Translation']);
}
$this->Conn->doInsert($fields_hash, $this->_tables['phrases'], 'INSERT', false);
}
} while (($phrase_node =& $phrase_node->NextSibling()));
$this->Conn->doInsert($fields_hash, $this->_tables['phrases'], 'INSERT');
}
/**
* Performs email event import
*
* @param kXMLNode $event_node
* @param int $language_id
* @param string $language_encoding
*/
function _processEvents(&$event_node, $language_id, $language_encoding)
{
$email_message_helper =& $this->Application->recallObject('EmailMessageHelper');
/* @var $email_message_helper EmailMessageHelper */
do {
$event_id = $this->_getEventId($event_node->Attributes['EVENT'], $event_node->Attributes['TYPE']);
if ($event_id) {
$fields_hash = Array (
'LanguageId' => $language_id,
'EventId' => $event_id,
'MessageType' => $event_node->Attributes['MESSAGETYPE'],
);
if ($language_encoding == 'plain') {
$fields_hash['Template'] = rtrim($event_node->Data);
}
else {
$fields_hash['Template'] = base64_decode($event_node->Data);
}
$parsed = $email_message_helper->parseTemplate($fields_hash['Template']);
$fields_hash['Subject'] = $parsed['Subject'];
$this->Conn->doInsert($fields_hash, $this->_tables['emailmessages'], 'INSERT', false);
}
} while (($event_node =& $event_node->NextSibling()));
if ($fields_hash) {
// at least one corresponding event declaration found by email event name+type given in translation
$this->Conn->doInsert($fields_hash, $this->_tables['emailmessages'], 'INSERT');
}
}
/**
* Creates/updates language based on given fields and returns it's id
*
* @param Array $fields_hash
* @return int
*/
function _processLanguage($fields_hash)
{
// 1. get language from database
$sql = 'SELECT ' . $this->lang_object->IDField . '
FROM ' . $this->lang_object->TableName . '
WHERE PackName = ' . $this->Conn->qstr($fields_hash['PackName']);
$language_id = $this->Conn->GetOne($sql);
if ($language_id) {
// 2. language found -> update, when allowed
$this->lang_object->Load($language_id);
if ($this->import_mode == LANG_OVERWRITE_EXISTING) {
// update live language record based on data from xml
$this->lang_object->SetFieldsFromHash($fields_hash);
$this->lang_object->Update();
}
}
else {
// 3. language not found -> create
$this->lang_object->SetFieldsFromHash($fields_hash);
$this->lang_object->SetDBField('Enabled', STATUS_ACTIVE);
if ($this->lang_object->Create()) {
$language_id = $this->lang_object->GetID();
if (defined('IS_INSTALL') && IS_INSTALL) {
// language created during install becomes admin interface language
$this->lang_object->setPrimary(true, true);
}
}
}
// 4. collect ID of every processed language
if (!in_array($language_id, $this->_languages)) {
$this->_languages[] = $language_id;
}
return $language_id;
}
/**
* Returns event id based on it's name and type
*
* @param string $event_name
* @param string $event_type
* @return int
*/
function _getEventId($event_name, $event_type)
{
$cache_key = $event_name . '_' . $event_type;
return array_key_exists($cache_key, $this->events_hash) ? $this->events_hash[$cache_key] : 0;
}
}
\ No newline at end of file
Index: branches/5.0.x/core/units/helpers/category_helper.php
===================================================================
--- branches/5.0.x/core/units/helpers/category_helper.php (revision 12705)
+++ branches/5.0.x/core/units/helpers/category_helper.php (revision 12706)
@@ -1,511 +1,512 @@
<?php
/**
* @version $Id$
* @package In-Portal
* @copyright Copyright (C) 1997 - 2009 Intechnic. All rights reserved.
* @license GNU/GPL
* In-Portal is Open Source software.
* This means that this software may have been modified pursuant
* the GNU General Public License, and as distributed it includes
* or is derivative of works licensed under the GNU General Public License
* or other free or open source software licenses.
* See http://www.in-portal.net/license/ for copyright notices and details.
*/
defined('FULL_PATH') or die('restricted access!');
class CategoryHelper extends kHelper {
/**
* Structure tree for ParentId field in category or category items
*
* @var Array
*/
var $_structureTree = null;
/**
* ID of primary language (only for caching)
*
* @var int
*/
var $_primaryLanguageId = false;
/**
* Prints category path using given blocks. Also supports used defined path elements at the end.
*
* @param Array $params
* @return string
*/
function NavigationBar($params)
{
$params['is_first'] = 1;
$main_category_id = isset($params['cat_id']) ? $params['cat_id'] : $this->Application->GetVar('m_cat_id');
if (array_key_exists('shift', $params) && $params['shift']) {
$home_element = '';
$params['shift']--;
}
else {
$home_element = $this->getHomeCategoryPath($params, $main_category_id);
unset($params['is_first']);
}
if (!getArrayValue($params, 'titles') && !getArrayValue($params, 'templates')) {
// no static templates given, show only category path
return $home_element . $this->getCategoryPath($main_category_id, $params);
}
$navigation_parts = $this->getNavigationParts($params['titles'], $params['templates']);
$ret = '';
$block_params = Array (); //$params; // sort of TagProcessor:prepareTagParams
$block_params['no_editing'] = 1;
$block_params['category'] = 0;
$block_params['separator'] = $params['separator'];
$current_template = $this->Application->GetVar('t');
$show_category = getArrayValue($params, 'show_category');
foreach ($navigation_parts as $template => $title) {
$block_params['template'] = $template;
if ($title == '__item__') {
if ($show_category) {
$ret .= $this->getCategoryPath($main_category_id, $params);
$show_category = false;
}
$category_path = $this->getCategoryParentPath($main_category_id);
$module_info = $this->getCategoryModule($params, array_keys($category_path));
if (!$module_info) {
continue;
}
$module_prefix = $module_info['Var'];
$object =& $this->Application->recallObject($module_prefix);
/* @var $object kCatDBItem */
$title_field = $this->Application->getUnitOption($module_prefix, 'TitleField');
$block_params['title'] = $object->GetField($title_field);
$block_params['prefix'] = $module_prefix;
$block_params['current'] = 0;
$block_params['name'] = $this->SelectParam($params, 'module_item_render_as,render_as');
}
else {
$block_params['current'] = ($template == $current_template);
$block_params['title'] = $this->Application->Phrase($title);
$block_params['name'] = $template == $current_template ? $params['current_render_as'] : $params['render_as'];
}
$ret .= $this->Application->ParseBlock($block_params);
}
if ($show_category) {
$params['no_current'] = true;
return $home_element . ($show_category ? $this->getCategoryPath($main_category_id, $params) : '') . $ret;
}
return $home_element . $ret;
}
/**
* Get navigation parts
*
* @param Array $titles
* @param Array $templates
* @return Array
*/
function getNavigationParts($titles, $templates)
{
$titles = explode(',', $titles);
$templates = explode(',', $templates);
$ret = Array ();
foreach ($templates as $template_pos => $template) {
$ret[$template] = $titles[$template_pos];
}
return $ret;
}
/**
* Renders path to given category using given blocks.
*
* @param int $main_category_id
* @param Array $params
* @return string
*/
function getCategoryPath($main_category_id, $params)
{
$category_path = $this->getCategoryParentPath($main_category_id);
if (!$category_path) {
// in "Home" category
return '';
}
if (array_key_exists('shift', $params) && $params['shift']) {
array_splice($category_path, 0, $params['shift']);
}
$module_info = $this->getCategoryModule($params, array_keys($category_path));
$module_category_id = $module_info['RootCat'];
$module_item_id = $this->Application->GetVar($module_info['Var'].'_id');
$ret = '';
$block_params['category'] = 1;
$block_params['no_editing'] = 1;
if (array_key_exists('is_first', $params)) {
$block_params['is_first'] = $params['is_first'];
}
$block_params['separator'] = $params['separator'];
$no_current = isset($params['no_current']) && $params['no_current'];
$backup_category_id = $this->Application->GetVar('c_id');
foreach ($category_path as $category_id => $category_name) {
$block_params['cat_id'] = $category_id;
$block_params['cat_name'] = $block_params['title'] = $category_name;
if ($no_current) {
$block_params['current'] = 0;
}
else {
$block_params['current'] = ($main_category_id == $category_id) && !$module_item_id ? 1 : 0;
}
$block_params['is_module_root'] = $category_id == $module_category_id ? 1 : 0;
$block_params['name'] = $this->SelectParam($params, 'render_as,block');
// which block to parse as current ?
if ($block_params['is_module_root']) {
$block_params['name'] = $this->SelectParam($params, 'module_root_render_as,render_as');
$block_params['module_index'] = $module_info['TemplatePath'].'index';
}
if ($block_params['current']) {
$block_params['name'] = $this->SelectParam($params, 'current_render_as,render_as');
}
$this->Application->SetVar('c_id', $category_id);
$ret .= $this->Application->ParseBlock($block_params);
if (array_key_exists('is_first', $block_params)) {
unset($block_params['is_first']);
}
}
$this->Application->SetVar('c_id', $backup_category_id);
return $ret;
}
/**
* Returns module information based on given module name or current category (relative to module root categories)
*
* @param Array $params
* @param Array $category_ids category parent path (already as array)
* @return Array
*/
function getCategoryModule($params, $category_ids)
{
if (isset($params['module'])) {
// get module by name specified
$module_info = $this->Application->findModule('Name', $params['module']);
}
elseif ($category_ids) {
// get module by category path
$module_root_categories = $this->getModuleRootCategories();
$common_categories = array_intersect($category_ids, $module_root_categories);
$module_category_id = array_shift($common_categories); // get 1st common category
$module_info = $this->Application->findModule('RootCat', $module_category_id);
}
return $module_info;
}
/**
* Renders path to top catalog category
*
* @param Array $params
* @param int $current_category
* @return string
*/
function getHomeCategoryPath($params, $current_category)
{
$block_params['cat_id'] = $this->Application->findModule('Name', 'Core', 'RootCat'); // 0;
$block_params['no_editing'] = 1;
$block_params['current'] = $current_category == $block_params['cat_id'] ? 1 : 0;
$block_params['separator'] = $params['separator'];
$block_params['is_first'] = $params['is_first'];
$block_params['cat_name'] = $this->Application->ProcessParsedTag('m', 'RootCategoryName', $params);
$block_params['name'] = $this->SelectParam($params, 'root_cat_render_as,render_as');
return $this->Application->ParseBlock($block_params);
}
/**
* Returns root categories from all modules
*
* @return Array
*/
function getModuleRootCategories()
{
static $root_categories = null;
if (!isset($root_categories)) {
$root_categories = Array ();
foreach ($this->Application->ModuleInfo as $module_name => $module_info) {
array_push($root_categories, $module_info['RootCat']);
}
$root_categories = array_unique($root_categories);
}
return $root_categories;
}
/**
* Returns given category's parent path as array of id=>name elements
*
* @param int $main_category_id
* @return Array
*/
function getCategoryParentPath($main_category_id)
{
static $cached_path = null;
if ($main_category_id == 0) {
// don't query path for "Home" category
return Array ();
}
if (!isset($cached_path[$main_category_id])) {
$ml_formatter =& $this->Application->recallObject('kMultiLanguage');
$navbar_field = $ml_formatter->LangFieldName('CachedNavBar');
$id_field = $this->Application->getUnitOption('c', 'IDField');
$table_name = $this->Application->getUnitOption('c', 'TableName');
$sql = 'SELECT '.$navbar_field.', ParentPath
FROM '.$table_name.'
WHERE '.$id_field.' = '.$main_category_id;
$category_data = $this->Conn->GetRow($sql);
$skip_category = $this->Application->findModule('Name', 'Core', 'RootCat');
$cached_path[$main_category_id] = Array ();
if ($category_data) {
$category_names = explode('&|&', $category_data[$navbar_field]);
$category_ids = explode('|', substr($category_data['ParentPath'], 1, -1));
foreach ($category_ids as $category_index => $category_id) {
if ($category_id == $skip_category) {
continue;
}
$cached_path[$main_category_id][$category_id] = $category_names[$category_index];
}
}
}
return $cached_path[$main_category_id];
}
/**
* Not tag, method for parameter
* selection from list in this TagProcessor
*
* @param Array $params
* @param string $possible_names
* @return string
* @access public
*/
function SelectParam($params, $possible_names)
{
if (!is_array($params)) return;
if (!is_array($possible_names))
$possible_names = explode(',', $possible_names);
foreach ($possible_names as $name)
{
if( isset($params[$name]) ) return $params[$name];
}
return false;
}
/**
* Converts multi-dimensional category structure in one-dimensional option array (category_id=>category_name)
*
* @param Array $data
* @param int $parent_category_id
* @param int_type $language_id
* @param int $theme_id
* @param int $level
* @return Array
*/
function _printChildren(&$data, $parent_category_id, $language_id, $theme_id, $level = 0)
{
if ($data['ThemeId'] != $theme_id && $data['ThemeId'] != 0) {
// don't show system templates from different themes
return Array ();
}
$category_language = $data['l' . $language_id . '_Name'] ? $language_id : $this->_primaryLanguageId;
$ret = Array($parent_category_id => str_repeat('-', $level).' '.$data['l' . $category_language . '_Name']);
if ($data['children']) {
$level++;
foreach ($data['children'] as $category_id => $category_data) {
$ret = array_merge_recursive2($ret, $this->_printChildren($data['children'][$category_id], $category_id, $language_id, $theme_id, $level));
}
}
return $ret;
}
/**
* Returns information about children under parent path (recursive)
*
* @param int $parent_category_id
* @param int $language_count
* @return Array
*/
function _getChildren($parent_category_id, $language_count)
{
$id_field = $this->Application->getUnitOption('c', 'IDField');
// get category children + parent category
$sql = 'SELECT *
FROM '.$this->Application->getUnitOption('c', 'TableName').'
WHERE ParentId = '.$parent_category_id.' OR '.$id_field.' = '.$parent_category_id.'
ORDER BY Priority DESC';
$categories = $this->Conn->Query($sql, $id_field);
$parent_data = $categories[$parent_category_id];
unset($categories[$parent_category_id]);
// no children for this category
$data = Array ('id' => $parent_data[$id_field], 'children' => false, 'ThemeId' => $parent_data['ThemeId']);
for ($i = 1; $i <= $language_count; $i++) {
$data['l'.$i.'_Name'] = $parent_data['l'.$i.'_Name'];
}
if (!$categories) {
// no children
return $data;
}
// category has children
foreach ($categories as $category_id => $category_data) {
$data['children'][$category_id] = $this->_getChildren($category_id, $language_count);
}
return $data;
}
/**
* Generates OR retrieves from cache structure tree
*
* @return Array
*/
function &_getStructureTree()
{
// get cached version of structure tree
$sql = 'SELECT Data
FROM ' . TABLE_PREFIX . 'Cache
WHERE VarName = "StructureTree"';
$data = $this->Conn->GetOne($sql);
if ($data) {
$data = unserialize($data);
return $data;
}
// generate structure tree from scratch
$ml_helper =& $this->Application->recallObject('kMultiLanguageHelper');
/* @var $ml_helper kMultiLanguageHelper */
$language_count = $ml_helper->getLanguageCount();
$root_category = $this->Application->findModule('Name', 'Core', 'RootCat');
$data = $this->_getChildren($root_category, $language_count);
$fields_hash = Array (
'VarName' => 'StructureTree',
'Data' => serialize($data),
'Cached' => adodb_mktime(),
);
$this->Conn->doInsert($fields_hash, TABLE_PREFIX.'Cache', 'REPLACE');
return $data;
}
/**
* Returns category structure as field option list
*
* @return Array
*/
function getStructureTreeAsOptions()
{
if (defined('IS_INSTALL') && IS_INSTALL) {
// no need to create category structure during install, because it's not used there
return Array ();
}
if (isset($this->_structureTree)) {
return $this->_structureTree;
}
$themes_helper =& $this->Application->recallObject('ThemesHelper');
/* @var $themes_helper kThemesHelper */
$data = $this->_getStructureTree();
$theme_id = (int)$themes_helper->getCurrentThemeId();
$root_category = $this->Application->findModule('Name', 'Core', 'RootCat');
$this->_primaryLanguageId = $this->Application->GetDefaultLanguageId();
$this->_structureTree = $this->_printChildren($data, $root_category, $this->Application->GetVar('m_lang'), $theme_id);
return $this->_structureTree;
}
/**
* Replace links like "@@ID@@" to actual template names in given text
*
* @param string $text
* @return string
*/
function replacePageIds($text)
{
if (!preg_match_all('/@@(\\d+)@@/', $text, $regs)) {
return $text;
}
$page_ids = $regs[1];
$sql = 'SELECT NamedParentPath, CategoryId
FROM ' . TABLE_PREFIX . 'Category
WHERE CategoryId IN (' . implode(',', $page_ids) . ')';
$templates = $this->Conn->GetCol($sql, 'CategoryId');
foreach ($page_ids as $page_id) {
if (!array_key_exists($page_id, $templates)) {
// internal page was deleted, but link to it was found in given content block data
continue;
}
$url_params = Array ('m_cat_id' => $page_id, 'pass' => 'm');
$page_url = $this->Application->HREF(strtolower($templates[$page_id]), '', $url_params);
/*if ($this->Application->IsAdmin()) {
$page_url = preg_replace('/&(admin|editing_mode)=[\d]/', '', $page_url);
}*/
- $text = preg_replace('/@@' . $page_id . '@@/', $page_url, $text);
+
+ $text = str_replace('@@' . $page_id . '@@', $page_url, $text);
}
return $text;
}
}
\ No newline at end of file
Index: branches/5.0.x/core/units/helpers/cat_dbitem_export_helper.php
===================================================================
--- branches/5.0.x/core/units/helpers/cat_dbitem_export_helper.php (revision 12705)
+++ branches/5.0.x/core/units/helpers/cat_dbitem_export_helper.php (revision 12706)
@@ -1,1450 +1,1452 @@
<?php
/**
* @version $Id$
* @package In-Portal
* @copyright Copyright (C) 1997 - 2009 Intechnic. All rights reserved.
* @license GNU/GPL
* In-Portal is Open Source software.
* This means that this software may have been modified pursuant
* the GNU General Public License, and as distributed it includes
* or is derivative of works licensed under the GNU General Public License
* or other free or open source software licenses.
* See http://www.in-portal.net/license/ for copyright notices and details.
*/
defined('FULL_PATH') or die('restricted access!');
define('EXPORT_STEP', 100); // export by 200 items (e.g. links)
define('IMPORT_STEP', 20); // 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);
+
+ $values_sql = substr($values_sql, 0, -1);
+
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->SetField($field_name, isset($sample_value) && $sample_value ? $sample_value : 'no value');
}
$object->UpdateFormattersSubFields();
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();
if (!$this->exportOptions['ExportColumns']) {
$this->exportOptions['ExportColumns'] = Array ();
}
$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);
+ return substr($custom_sql, 0, -2);
}
function getPlainExportSQL($count_only = false) {
if ($count_only && isset($this->exportOptions['ForceCountSQL'])) {
$sql = $this->exportOptions['ForceCountSQL'];
}
elseif (!$count_only && isset($this->exportOptions['ForceSelectSQL'])) {
$sql = $this->exportOptions['ForceSelectSQL'];
}
else {
$items_list =& $this->Application->recallObject($this->curItem->Prefix.'.export-items-list', $this->curItem->Prefix.'_List');
$items_list->SetPerPage(-1);
if ($options['export_ids'] != '') {
$items_list->AddFilter('export_ids', $items_list->TableName.'.'.$items_list->IDField.' IN ('.implode(',',$options['export_ids']).')');
}
if ($count_only) {
$sql = $items_list->getCountSQL( $items_list->GetSelectSQL(true,false) );
}
else {
$sql = $items_list->GetSelectSQL();
}
}
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;
}
function getExportSQL($count_only = false)
{
if (!$this->Application->getUnitOption($this->curItem->Prefix, 'CatalogItem')) {
return $this->GetPlainExportSQL($count_only); // in case this is not a CategoryItem
}
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 = substr($sql, 0, -4);
}
$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 ParentPath
FROM '.TABLE_PREFIX.'Category
WHERE CategoryId = ' . (int)$this->Application->GetVar('m_cat_id');
$parent_path = $this->Conn->GetOne($sql);
$parent_path = explode('|', substr($parent_path, 1, -1));
if ($parent_path && $parent_path[0] == $this->Application->findModule('Name', 'Core', 'RootCat')) {
array_shift($parent_path);
}
$this->exportOptions['BaseLevel'] = count($parent_path); // 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']);
$items_processed = 0;
while (($bytes_imported < IMPORT_CHUNK && $items_processed < IMPORT_STEP) && !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'];
$items_processed++;
}
$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 = '.(int)$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 = '';
$language_id = (int)$this->Application->GetVar('m_lang');
if (!$language_id) {
$language_id = 1;
}
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'.$language_id.'_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);
+ $where_clause = substr($where_clause, 0, -5);
$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 (only when ID is found in cvs file)
if (in_array($this->curItem->IDField, $this->exportFields)) {
$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()) {
$this->Application->SetVar('m_cat_id', $backup_category_id);
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);
$ret = $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)
{
$ml_formatter =& $this->Application->recallObject('kMultiLanguage');
$sql = 'SELECT '.$ml_formatter->LangFieldName('CachedNavbar').'
FROM '.TABLE_PREFIX.'Category
WHERE CategoryId = '.$category_id;
$category_path = $this->Conn->GetOne($sql);
$category_path = $category_path ? explode('&|&', $category_path) : Array();
if ($category_path && strtolower($category_path[0]) == 'content') {
array_shift($category_path);
}
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);
+ $where_clause = substr($where_clause, 0, -4);
}
}
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'));
}
/**
* Sets correct available & export fields
*
* @param kEvent $event
*/
function prepareExportColumns(&$event)
{
$object =& $event->getObject( Array('skip_autoload' => true) );
if (!array_key_exists('ExportColumns', $object->Fields)) {
// import/export prefix was used (see kDBEventHandler::prepareObject) but object don't plan to be imported/exported
return ;
}
$available_columns = Array();
if ($this->Application->getUnitOption($event->Prefix, 'CatalogItem')) {
// category field (mixed)
$available_columns['__CATEGORY__CategoryPath'] = 'CategoryPath';
if ($event->Special == 'import') {
// category field (separated fields)
$max_level = $this->Application->ConfigValue('MaxImportCategoryLevels');
$i = 0;
while ($i < $max_level) {
$available_columns['__CATEGORY__Category'.($i + 1)] = 'Category'.($i + 1);
$i++;
}
}
}
// db fields
foreach ($object->Fields as $field_name => $field_options)
{
if (!$object->skipField($field_name))
{
$available_columns[$field_name] = $field_name.(getArrayValue($field_options, 'required') ? '*' : '');
}
}
$handler =& $this->Application->recallObject($event->Prefix.'_EventHandler');
$available_columns = array_merge_recursive2($available_columns, $handler->getCustomExportColumns($event));
// custom fields
foreach ($object->customFields as $custom_id => $custom_name)
{
$available_columns['__CUSTOM__'.$custom_name] = $custom_name;
}
// columns already in use
$items_info = $this->Application->GetVar( $event->getPrefixSpecial(true) );
if ($items_info)
{
list($item_id, $field_values) = each($items_info);
$export_keys = $field_values['ExportColumns'];
$export_keys = $export_keys ? explode('|', substr($export_keys, 1, -1) ) : Array();
}
else {
$export_keys = Array();
}
$export_columns = Array();
foreach ($export_keys as $field_key)
{
$field_name = $this->getExportField($field_key);
$export_columns[$field_key] = $field_name;
unset($available_columns[$field_key]);
}
$options = $object->GetFieldOptions('ExportColumns');
$options['options'] = $export_columns;
$object->SetFieldOptions('ExportColumns', $options);
$options = $object->GetFieldOptions('AvailableColumns');
$options['options'] = $available_columns;
$object->SetFieldOptions('AvailableColumns', $options);
$this->updateImportFiles($event);
$this->PrepareExportPresets($event);
}
function PrepareExportPresets(&$event)
{
$object =& $event->getObject( Array('skip_autoload' => true) );
$options = $object->GetFieldOptions('ExportPresets');
$export_settings = $this->Application->RecallPersistentVar('export_settings');
if (!$export_settings) return ;
$export_settings = unserialize($export_settings);
if (!isset($export_settings[$event->Prefix])) return ;
$export_presets = array(''=>'');
foreach ($export_settings[$event->Prefix] as $key => $val) {
$export_presets[implode('|', $val['ExportColumns'])] = $key;
}
$options['options'] = $export_presets;
$object->SetFieldOptions('ExportPresets', $options);
}
function getExportField($field_key)
{
$prepends = Array('__CUSTOM__', '__CATEGORY__');
foreach ($prepends as $prepend)
{
if (substr($field_key, 0, strlen($prepend) ) == $prepend)
{
$field_key = substr($field_key, strlen($prepend), strlen($field_key) );
break;
}
}
return $field_key;
}
/**
* Updates uploaded files list
*
* @param kEvent $event
*/
function updateImportFiles(&$event)
{
if ($event->Special != 'import') {
return false;
}
$object =& $event->getObject();
$import_filenames = Array();
if ($folder_handle = opendir(EXPORT_PATH)) {
while (false !== ($file = readdir($folder_handle))) {
if (is_dir(EXPORT_PATH.'/'.$file) || substr($file, 0, 1) == '.' || strtolower($file) == 'cvs' || strtolower($file) == 'dummy' || filesize(EXPORT_PATH.'/'.$file) == 0) continue;
$file_size = formatSize( filesize(EXPORT_PATH.'/'.$file) );
$import_filenames[$file] = $file.' ('.$file_size.')';
}
closedir($folder_handle);
}
$options = $object->GetFieldOptions('ImportLocalFilename');
$options['options'] = $import_filenames;
$object->SetFieldOptions('ImportLocalFilename', $options);
}
/**
* Returns module folder
*
* @param kEvent $event
* @return string
*/
function getModuleFolder(&$event)
{
return $this->Application->getUnitOption($event->Prefix, 'ModuleFolder');
}
/**
* Export form validation & processing
*
* @param kEvent $event
*/
function OnExportBegin(&$event)
{
$items_info = $this->Application->GetVar( $event->getPrefixSpecial(true) );
if (!$items_info)
{
$items_info = unserialize( $this->Application->RecallVar($event->getPrefixSpecial().'_ItemsInfo') );
$this->Application->SetVar($event->getPrefixSpecial(true), $items_info);
}
list($item_id, $field_values) = each($items_info);
$object =& $event->getObject( Array('skip_autoload' => true) );
$object->SetFieldsFromHash($field_values);
$field_values['ImportFilename'] = $object->GetDBField('ImportFilename'); //if upload formatter has renamed the file during moving !!!
$object->setID($item_id);
$this->setRequiredFields($event);
$export_object =& $this->Application->recallObject('CatItemExportHelper');
// save export/import options
if ($event->Special == 'export')
{
$export_ids = $this->Application->RecallVar($event->Prefix.'_export_ids');
$export_cats_ids = $this->Application->RecallVar($event->Prefix.'_export_cats_ids');
// used for multistep export
$field_values['export_ids'] = $export_ids ? explode(',', $export_ids) : false;
$field_values['export_cats_ids'] = $export_cats_ids ? explode(',', $export_cats_ids) : Array( $this->Application->GetVar('m_cat_id') );
}
$field_values['ExportColumns'] = $field_values['ExportColumns'] ? explode('|', substr($field_values['ExportColumns'], 1, -1) ) : Array();
$field_values['start_from'] = 0;
$this->Application->HandleEvent($nevent, $event->Prefix.':OnBeforeExportBegin', array('options'=>$field_values));
$field_values = $nevent->getEventParam('options');
$export_object->saveOptions($event, $field_values);
if( $export_object->verifyOptions($event) )
{
if ($this->_getExportSavePreset($object)) {
$name = $object->GetDBField('ExportPresetName');
$export_settings = $this->Application->RecallPersistentVar('export_settings');
$export_settings = $export_settings ? unserialize($export_settings) : array();
$export_settings[$event->Prefix][$name] = $field_values;
$this->Application->StorePersistentVar('export_settings', serialize($export_settings));
}
$progress_t = $this->Application->RecallVar('export_progress_t');
if ($progress_t) {
$this->Application->RemoveVar('export_progress_t');
}
else {
$progress_t = $export_object->getModuleFolder($event).'/'.$event->Special.'_progress';
}
$event->redirect = $progress_t;
if ($event->Special == 'import') {
$import_category = (int)$this->Application->RecallVar('ImportCategory');
// in future could use module root category if import category will be unavailable :)
$event->SetRedirectParam('m_cat_id', $import_category); // for template permission checking
$this->Application->StoreVar('m_cat_id', $import_category); // for event permission checking
}
}
else
{
// make uploaded file local & change source selection
$filename = getArrayValue($field_values, 'ImportFilename');
if ($filename) {
$export_object->updateImportFiles($event);
$object->SetDBField('ImportSource', 2);
$field_values['ImportSource'] = 2;
$object->SetDBField('ImportLocalFilename', $filename);
$field_values['ImportLocalFilename'] = $filename;
$export_object->saveOptions($event, $field_values);
}
$event->status = erFAIL;
$event->redirect = false;
}
}
/**
* Returns export save preset name, when used at all
*
* @param kDBItem $object
* @return string
*/
function _getExportSavePreset(&$object)
{
if (!array_key_exists('ExportSavePreset', $object->Fields)) {
return '';
}
return $object->GetDBField('ExportSavePreset');
}
/**
* set required fields based on import or export params
*
* @param kEvent $event
*/
function setRequiredFields(&$event)
{
$required_fields['common'] = Array('FieldsSeparatedBy', 'LineEndings', 'CategoryFormat');
$required_fields['export'] = Array('ExportFormat', 'ExportFilename','ExportColumns');
$object =& $event->getObject();
if ($this->_getExportSavePreset($object)) {
$required_fields['export'][] = 'ExportPresetName';
}
$required_fields['import'] = Array('FieldTitles', 'ImportSource', 'CheckDuplicatesMethod'); // ImportFilename, ImportLocalFilename
if ($event->Special == 'import')
{
$import_source = Array(1 => 'ImportFilename', 2 => 'ImportLocalFilename');
$used_field = $import_source[ $object->GetDBField('ImportSource') ];
$required_fields[$event->Special][] = $used_field;
$object->Fields[$used_field]['error_field'] = 'ImportSource';
if ($object->GetDBField('FieldTitles') == 2) $required_fields[$event->Special][] = 'ExportColumns'; // manual field titles
}
$required_fields = array_merge($required_fields['common'], $required_fields[$event->Special]);
foreach ($required_fields as $required_field) {
$object->setRequired($required_field, true);
}
}
}
\ No newline at end of file
Index: branches/5.0.x/core/units/helpers/multilanguage_helper.php
===================================================================
--- branches/5.0.x/core/units/helpers/multilanguage_helper.php (revision 12705)
+++ branches/5.0.x/core/units/helpers/multilanguage_helper.php (revision 12706)
@@ -1,306 +1,307 @@
<?php
/**
* @version $Id$
* @package In-Portal
* @copyright Copyright (C) 1997 - 2009 Intechnic. All rights reserved.
* @license GNU/GPL
* In-Portal is Open Source software.
* This means that this software may have been modified pursuant
* the GNU General Public License, and as distributed it includes
* or is derivative of works licensed under the GNU General Public License
* or other free or open source software licenses.
* See http://www.in-portal.net/license/ for copyright notices and details.
*/
defined('FULL_PATH') or die('restricted access!');
/**
* Performs action on multilingual fields
*
*/
class kMultiLanguageHelper extends kHelper {
/**
* Maximal language id
*
* @var int
*/
var $languageCount = 0;
/**
* Languages created in system
*
* @var Array
*/
var $languagesIDs = Array ();
/**
* Structure of table, that is currently processed
*
* @var Array
*/
var $curStructure = Array();
/**
* Field, to get structure information from
*
* @var string
*/
var $curSourceField = false;
/**
* Indexes used in table of 32
*
* @var int
*/
var $curIndexCount = 0;
/**
* Fields from config, that are currently used
*
* @var Array
*/
var $curFields = Array();
function kMultiLanguageHelper()
{
parent::kHelper();
$this->languageCount = $this->getLanguageCount();
}
/**
* Checks if language with specified id is created
*
* @param int $language_id
* @return bool
*/
function LanguageFound($language_id)
{
return in_array($language_id, $this->languagesIDs) || $language_id <= 5;
}
/**
* Returns language count in system (always is divisible by 5)
*
*/
function getLanguageCount()
{
$id_field = $this->Application->getUnitOption('lang', 'IDField');
$table_name = $this->Application->getUnitOption('lang', 'TableName');
$this->languagesIDs = $this->Conn->GetCol('SELECT '.$id_field.' FROM '.$table_name);
$languages_count = $this->Conn->GetOne('SELECT MAX('.$id_field.') FROM '.$table_name);
return max($languages_count, 5);
}
function scanTable($mask)
{
$i = 0;
$fields_found = 0;
$fields = array_keys($this->curStructure);
foreach ($fields as $field_name) {
if (preg_match($mask, $field_name)) {
$fields_found++;
}
}
return $fields_found;
}
function readTableStructure($table_name, $refresh = false)
{
// if ($refresh || !getArrayValue($structure_status, $prefix.'.'.$table_name)) {
$this->curStructure = $this->Conn->Query('DESCRIBE '.$table_name, 'Field');
$this->curIndexCount = count($this->Conn->Query('SHOW INDEXES FROM '.$table_name));
// }
}
/**
* Creates missing multilanguage fields in table by specified prefix
*
* @param string $prefix
* @param bool $refresh Forces config field structure to be re-read from database
*/
function createFields($prefix, $refresh = false)
{
if ($refresh && preg_match('/(.*)-cdata$/', $prefix, $regs)) {
// call main item config to clone cdata table
$this->Application->UnitConfigReader->loadConfig($regs[1]);
$this->Application->HandleEvent( new kEvent($prefix.':OnAfterConfigRead') );
}
$table_name = $this->Application->getUnitOption($prefix, 'TableName');
$this->curFields = $this->Application->getUnitOption($prefix, 'Fields');
if (!($table_name && $this->curFields) || ($table_name && !$this->Conn->TableFound($table_name))) {
// invalid config found or prefix not found
return true;
}
$sqls = Array();
$this->readTableStructure($table_name, $refresh);
foreach($this->curFields as $field_name => $field_options)
{
if (getArrayValue($field_options, 'formatter') == 'kMultiLanguage') {
if (isset($field_options['master_field'])) {
unset($this->curFields[$field_name]);
continue;
}
$this->setSourceField($field_name);
if ($this->languageCount > 0) {
// `l77_Name` VARCHAR( 255 ) NULL DEFAULT '0';
$field_mask = Array();
$field_mask['name'] = 'l%s_'.$field_name;
$field_mask['null'] = getArrayValue($field_options, 'not_null') ? 'NOT NULL' : 'NULL';
if ($this->curSourceField) {
$default_value = $this->getFieldParam('Default') != 'NULL' ? $this->Conn->qstr($this->getFieldParam('Default')) : $this->getFieldParam('Default');
$field_mask['type'] = $this->getFieldParam('Type');
}
else {
$default_value = is_null($field_options['default']) ? 'NULL' : $this->Conn->qstr($field_options['default']);
$field_mask['type'] = $field_options['db_type'];
}
$field_mask['default'] = 'DEFAULT '.$default_value;
if (strtoupper($field_mask['type']) == 'TEXT') {
// text fields in mysql doesn't have default value
$field_mask = $field_mask['name'].' '.$field_mask['type'].' '.$field_mask['null'];
}
else {
$field_mask = $field_mask['name'].' '.$field_mask['type'].' '.$field_mask['null'].' '.$field_mask['default'];
}
$alter_sqls = $this->generateAlterSQL($field_mask, 1, $this->languageCount);
if ($alter_sqls) {
$sqls[] = 'ALTER TABLE '.$table_name.' '.$alter_sqls;
}
}
}
}
foreach ($sqls as $sql_query) {
$this->Conn->Query($sql_query);
}
}
function deleteField($prefix, $custom_id)
{
$table_name = $this->Application->getUnitOption($prefix, 'TableName');
$sql = 'DESCRIBE '.$table_name.' "l%_cust_'.$custom_id.'"';
$fields = $this->Conn->GetCol($sql);
$sql = 'ALTER TABLE '.$table_name.' ';
$sql_template = 'DROP COLUMN %s, ';
+
foreach ($fields as $field_name) {
$sql .= sprintf($sql_template, $field_name);
}
- $sql = preg_replace('/(.*), $/', '\\1', $sql);
- $this->Conn->Query($sql);
+
+ $this->Conn->Query( substr($sql, 0, -2) );
}
/**
* Returns parameter requested of current source field
*
* @param string $param_name
* @return string
*/
function getFieldParam($param_name)
{
return $this->curStructure[$this->curSourceField][$param_name];
}
/**
* Detects field name to create other fields from
*
* @param string $field_name
*/
function setSourceField($field_name)
{
$ret = $this->scanTable('/^l[\d]+_'.preg_quote($field_name, '/').'$/');
if (!$ret) {
// no multilingual fields at all (but we have such field without language prefix)
$original_found = $this->scanTable('/'.preg_quote($field_name, '/').'/');
$this->curSourceField = $original_found ? $field_name : false;
}
else {
$this->curSourceField = 'l1_'.$field_name;
}
}
/**
* Returns ALTER statement part for adding required fields to table
*
* @param string $field_mask sql mask for creating field with correct definition (type & size)
* @param int $start_index add new fields starting from this index
* @param int $create_count create this much new multilingual field translations
* @return string
*/
function generateAlterSQL($field_mask, $start_index, $create_count)
{
static $single_lang = null;
if (!isset($single_lang)) {
// if single language mode, then create indexes only on primary columns
$table_name = $this->Application->getUnitOption('lang', 'TableName');
$sql = 'SELECT COUNT(*)
FROM '.$table_name.'
WHERE Enabled = 1';
// if language count = 0, then assume it's multi language mode
$single_lang = $this->Conn->GetOne($sql) == 1;
}
$ret = '';
$ml_field = preg_replace('/l(.*?)_(.*?) (.*)/', '\\2', $field_mask);
$i_count = $start_index + $create_count;
while ($start_index < $i_count) {
if (isset($this->curStructure['l'.$start_index.'_'.$ml_field]) || (!$this->LanguageFound($start_index)) ) {
$start_index++;
continue;
}
$prev_index = $start_index - 1;
do {
list($prev_field,$type) = explode(' ', sprintf($field_mask, $prev_index) );
} while ($prev_index > 0 && !$this->LanguageFound($prev_index--));
if (substr($prev_field, 0, 3) == 'l0_') {
$prev_field = substr($prev_field, 3, strlen($prev_field));
if (!$this->curSourceField) {
// get field name before this one
$fields = array_keys($this->curFields);
// $prev_field = key(end($this->curStructure));
$prev_field = $fields[array_search($prev_field, $fields) - 1];
if (getArrayValue($this->curFields[$prev_field], 'formatter') == 'kMultiLanguage') {
$prev_field = 'l'.$this->languageCount.'_'.$prev_field;
}
}
}
$field_expression = sprintf($field_mask, $start_index);
$ret .= 'ADD COLUMN '.$field_expression.' AFTER `'.$prev_field.'`, ';
if ($this->curIndexCount < 32 && ($start_index == $this->Application->GetDefaultLanguageId() || !$single_lang)) {
// create index for primary language column + for all others (if multiple languages installed)
list($field_name, $field_params) = explode(' ', $field_expression, 2);
$index_type = isset($this->curFields[$ml_field]['index_type']) ? $this->curFields[$prev_field]['index_type'] : 'string';
$ret .= $index_type == 'string' ? 'ADD INDEX (`'.$field_name.'` (5) ), ' : 'ADD INDEX (`'.$field_name.'`), ';
$this->curIndexCount++;
}
$start_index++;
}
return preg_replace('/, $/', ';', $ret);
}
}
?>
\ No newline at end of file
Index: branches/5.0.x/core/units/admin/admin_events_handler.php
===================================================================
--- branches/5.0.x/core/units/admin/admin_events_handler.php (revision 12705)
+++ branches/5.0.x/core/units/admin/admin_events_handler.php (revision 12706)
@@ -1,1254 +1,1254 @@
<?php
/**
* @version $Id$
* @package In-Portal
* @copyright Copyright (C) 1997 - 2009 Intechnic. All rights reserved.
* @license GNU/GPL
* In-Portal is Open Source software.
* This means that this software may have been modified pursuant
* the GNU General Public License, and as distributed it includes
* or is derivative of works licensed under the GNU General Public License
* or other free or open source software licenses.
* See http://www.in-portal.net/license/ for copyright notices and details.
*/
defined('FULL_PATH') or die('restricted access!');
class AdminEventsHandler extends kDBEventHandler {
function mapPermissions()
{
parent::mapPermissions();
$permissions = Array(
'OnSaveColumns' => array('self' => true),
'OnClosePopup' => array('self' => true),
'OnSaveSetting' => array('self' => true),
// export/import permissions is checked within events
'OnExportCSV' => Array('self' => true),
'OnGetCSV' => Array('self' => true),
'OnCSVImportBegin' => Array('self' => true),
'OnCSVImportStep' => Array('self' => true),
'OnDropTempTablesByWID' => Array('self' => true),
);
$this->permMapping = array_merge($this->permMapping, $permissions);
}
/**
* Checks permissions of user
*
* @param kEvent $event
*/
function CheckPermission(&$event)
{
$perm_value = null;
$system_events = Array (
'OnResetModRwCache', 'OnResetCMSMenuCache', 'OnResetSections',
'OnResetConfigsCache', 'OnDeleteCompiledTemplates', 'OnCompileTemplates',
'OnGenerateTableStructure', 'OnRebuildThemes', 'OnCheckPrefixConfig',
);
if (in_array($event->Name, $system_events)) {
// events from "Tools -> System Tools" section are controlled via that section "edit" permission
$perm_value = $this->Application->CheckPermission($event->getSection() . '.edit');
}
$tools_events = Array (
'OnBackup' => 'in-portal:backup.view',
'OnBackupProgress' => 'in-portal:backup.view',
'OnDeleteBackup' => 'in-portal:backup.view',
'OnBackupCancel' => 'in-portal:backup.view',
'OnRestore' => 'in-portal:restore.view',
'OnRestoreProgress' => 'in-portal:restore.view',
'OnRestoreCancel' => 'in-portal:backup.view',
'OnSqlQuery' => 'in-portal:sql_query.view',
);
if (array_key_exists($event->Name, $tools_events)) {
$perm_value = $this->Application->CheckPermission($tools_events[$event->Name]);
}
if ($event->Name == 'OnSaveMenuFrameWidth') {
$perm_value = $this->Application->IsAdmin() && $this->Application->LoggedIn();
}
if (isset($perm_value)) {
$perm_helper =& $this->Application->recallObject('PermissionsHelper');
/* @var $perm_helper kPermissionsHelper */
return $perm_helper->finalizePermissionCheck($event, $perm_value);
}
return parent::CheckPermission($event);
}
/**
* Enter description here...
*
* @param kEvent $event
*/
function OnResetModRwCache(&$event)
{
if ($this->Application->GetVar('ajax') == 'yes') {
$event->status = erSTOP;
}
$this->Conn->Query('DELETE FROM '.TABLE_PREFIX.'Cache WHERE VarName LIKE "mod_rw%"');
}
function OnResetCMSMenuCache(&$event)
{
if ($this->Application->GetVar('ajax') == 'yes') {
$event->status = erSTOP;
}
$this->Conn->Query('DELETE FROM '.TABLE_PREFIX.'Cache WHERE VarName IN ("cms_menu", "StructureTree")');
}
function OnResetSections(&$event)
{
if ($this->Application->GetVar('ajax') == 'yes') {
$event->status = erSTOP;
}
$sql = 'DELETE FROM ' . TABLE_PREFIX . 'Cache
WHERE VarName = "sections_parsed"';
$this->Conn->Query($sql);
if (isset($this->Application->Memcached)) {
$this->Application->Memcached->delete('master:sections_parsed');
}
$event->SetRedirectParam('refresh_tree', 1);
}
function OnResetConfigsCache(&$event)
{
if ($this->Application->GetVar('ajax') == 'yes') {
$event->status = erSTOP;
}
$sql = 'DELETE FROM ' . TABLE_PREFIX . 'Cache
WHERE VarName IN("config_files", "configs_parsed", "sections_parsed")';
$this->Conn->Query($sql);
$skin_helper =& $this->Application->recallObject('SkinHelper');
/* @var $skin_helper SkinHelper */
$skin_helper->deleteCompiled();
if (isset($this->Application->Memcached)) {
$this->Application->Memcached->delete('master:config_files');
$this->Application->Memcached->delete('master:configs_parsed');
$this->Application->Memcached->delete('master:sections_parsed');
}
$event->SetRedirectParam('refresh_tree', 1);
}
function OnCompileTemplates(&$event)
{
$compiler =& $this->Application->recallObject('NParserCompiler');
/* @var $compiler NParserCompiler */
$compiler->CompileTemplatesStep();
$event->status = erSTOP;
}
/**
* Deletes all compiled templates
*
* @param kEvent $event
*/
function OnDeleteCompiledTemplates(&$event)
{
if ($this->Application->GetVar('ajax') == 'yes') {
$event->status = erSTOP;
}
$base_path = WRITEABLE . DIRECTORY_SEPARATOR . 'cache';
// delete debugger reports
$debugger_reports = glob($base_path . '/debug_@*@.txt');
foreach ($debugger_reports as $debugger_report) {
unlink($debugger_report);
}
$this->_deleteCompiledTemplates($base_path);
}
function _deleteCompiledTemplates($folder, $unlink_folder = false)
{
$sub_folders = glob($folder . '/*', GLOB_ONLYDIR);
foreach ($sub_folders as $sub_folder) {
$this->_deleteCompiledTemplates($sub_folder, true);
}
$files = glob($folder . '/*.php');
foreach ($files as $file) {
unlink($file);
}
if ($unlink_folder) {
rmdir($folder);
}
}
/**
* Generates sturcture for specified table
*
* @param kEvent $event
* @author Alex
*/
function OnGenerateTableStructure(&$event)
{
$types_hash = Array(
'string' => 'varchar|text|mediumtext|longtext|date|datetime|time|timestamp|char|year|enum|set',
'int' => 'smallint|mediumint|int|bigint|tinyint',
'float' => 'float|double|decimal',
);
$table_name = $this->Application->GetVar('table_name');
if (!$table_name) {
echo 'error: no table name specified';
return ;
}
if (TABLE_PREFIX && !preg_match('/^'.preg_quote(TABLE_PREFIX, '/').'(.*)/', $table_name) && (strtolower($table_name) != $table_name)) {
// table name without prefix, then add it (don't affect K3 tables named in lowercase)
$table_name = TABLE_PREFIX.$table_name;
}
if (!$this->Conn->TableFound($table_name)) {
// table with prefix doesn't exist, assume that just config prefix passed -> resolve table name from it
$prefix = preg_replace('/^' . preg_quote(TABLE_PREFIX, '/') . '/', '', $table_name);
if ($this->Application->prefixRegistred($prefix)) {
// when prefix is found -> use it's table (don't affect K3 tables named in lowecase)
$table_name = $this->Application->getUnitOption($prefix, 'TableName');
}
}
$table_info = $this->Conn->Query('DESCRIBE '.$table_name);
// 1. prepare config keys
$grids = Array (
'Default' => Array (
'Icons' => Array ('default' => 'icon16_item.png'),
'Fields' => Array (),
)
);
$grid_fields = Array();
$id_field = '';
$fields = Array();
$float_types = Array ('float', 'double', 'numeric');
foreach ($table_info as $field_info) {
if (preg_match('/l[\d]+_.*/', $field_info['Field'])) {
// don't put multilingual fields in config
continue;
}
$field_options = Array ();
$grid_col_options = Array(
'title' => 'la_col_' . $field_info['Field'],
'filter_block' => 'grid_like_filter',
);
// 1. get php field type by mysql field type
foreach ($types_hash as $php_type => $db_types) {
if (preg_match('/'.$db_types.'/', $field_info['Type'])) {
$field_options['type'] = $php_type;
break;
}
}
$default_value = $field_info['Default'];
if (in_array($php_type, $float_types)) {
// this is float number
if (preg_match('/'.$db_types.'\([\d]+,([\d]+)\)/i', $field_info['Type'], $regs)) {
// size is described in structure -> add formatter
$field_options['formatter'] = 'kFormatter';
$field_options['format'] = '%01.'.$regs[1].'f';
if ($field_info['Null'] != 'YES') {
// null fields, will most likely have NULL as default value
$default_value = 0;
}
}
else {
// no size information, just convert to float
if ($field_info['Null'] != 'YES') {
// null fields, will most likely have NULL as default value
$default_value = (float)$default_value;
}
}
}
if (preg_match('/varchar\(([\d]+)\)/i', $field_info['Type'], $regs)) {
$field_options['max_len'] = (int)$regs[1];
}
if ($field_info['Null'] != 'YES') {
$field_options['not_null'] = 1;
}
if ($field_info['Key'] == 'PRI') {
$default_value = 0;
$id_field = $field_info['Field'];
}
if ($php_type == 'int' && ($field_info['Null'] != 'YES' || is_numeric($default_value))) {
// is integer field AND not null
$field_options['default'] = (int)$default_value;
}
else {
$field_options['default'] = $default_value;
}
$fields[ $field_info['Field'] ] = $this->transformDump($field_options);
$grids_fields[ $field_info['Field'] ] = $this->transformDump($grid_col_options);
}
$grids['Default']['Fields'] = $grids_fields;
$ret = "'IDField' => '".$id_field."',\n'Fields' => A".substr(stripslashes(var_export($fields, true)), 1).',';
$ret .= "\n"."'Grids' => ".stripslashes(var_export($grids, true));
$ret = str_replace('array (', 'Array (', $ret);
$ret = preg_replace("/'(.*?)' => 'Array \((.*?), \)',/", "'\\1' => Array (\\2),", $ret);
$ret = preg_replace("/\n '/", "\n\t'", $ret);
$this->Application->InitParser();
ob_start();
echo $this->Application->ParseBlock(Array('name' => 'incs/header', 'body_properties' => 'style="background-color: #E7E7E7; margin: 8px;"'));
?>
<script type="text/javascript">
set_window_title('Table "<?php echo $table_name; ?>" Structure');
</script>
<a href="javascript:window_close();">Close Window</a><br /><br />
<?php echo $GLOBALS['debugger']->highlightString($ret); ?>
<br /><br /><a href="javascript:window_close();">Close Window</a><br />
<?php
echo $this->Application->ParseBlock(Array('name' => 'incs/footer'));
echo ob_get_clean();
$event->status = erSTOP;
}
function transformDump($dump)
{
if (is_array($dump)) {
$dump = var_export($dump, true);
}
$dump = preg_replace("/,\n[ ]*/", ', ', $dump);
$dump = preg_replace("/array \(\n[ ]*/", 'Array (', $dump); // replace array start
$dump = preg_replace("/,\n[ ]*\),/", "),", $dump); // replace array end
return $dump;
}
/**
* Refreshes ThemeFiles & Theme tables by actual content on HDD
*
* @param kEvent $event
*/
function OnRebuildThemes(&$event)
{
if ($this->Application->GetVar('ajax') == 'yes') {
$event->status = erSTOP;
}
$themes_helper =& $this->Application->recallObject('ThemesHelper');
/* @var $themes_helper kThemesHelper */
$themes_helper->refreshThemes();
}
function OnSaveColumns(&$event)
{
$picker_helper =& $this->Application->recallObject('ColumnPickerHelper');
/* @var $picker_helper kColumnPickerHelper */
$picker_helper->SetGridName($this->Application->GetLinkedVar('grid_name'));
$picked = trim($this->Application->GetVar('picked_str'), '|');
$hidden = trim($this->Application->GetVar('hidden_str'), '|');
$main_prefix = $this->Application->GetVar('main_prefix');
$picker_helper->SaveColumns($main_prefix, $picked, $hidden);
$this->finalizePopup($event);
}
/**
* Saves various admin settings via ajax
*
* @param kEvent $event
*/
function OnSaveSetting(&$event)
{
if ($this->Application->GetVar('ajax') != 'yes') {
return ;
}
$var_name = $this->Application->GetVar('var_name');
$var_value = $this->Application->GetVar('var_value');
$this->Application->StorePersistentVar($var_name, $var_value);
$event->status = erSTOP;
}
/**
* Just closes popup & deletes last_template & opener_stack if popup, that is closing
*
* @param kEvent $event
*/
function OnClosePopup(&$event)
{
$event->SetRedirectParam('opener', 'u');
}
/**
* Occurs right after initialization of the kernel, used mainly as hook-to event
*
* @param kEvent $event
*/
function OnStartup(&$event)
{
}
/**
* Occurs right before echoing the output, in Done method of application, used mainly as hook-to event
*
* @param kEvent $event
*/
function OnBeforeShutdown(&$event)
{
}
/**
* Is called after tree was build (when not from cache)
*
* @param kEvent $event
*/
function OnAfterBuildTree(&$event)
{
}
/**
* Called by AJAX to perform CSV export
*
* @param kEvent $event
*/
function OnExportCSV(&$event)
{
$export_helper =& $this->Application->recallObject('CSVHelper');
/* @var $export_helper kCSVHelper */
$prefix_special = $this->Application->GetVar('PrefixSpecial');
if(!$prefix_special) {
$prefix_special = $export_helper->ExportData('prefix');
}
$prefix_elems = split('\.|_', $prefix_special, 2);
$perm_sections = $this->Application->getUnitOption($prefix_elems[0], 'PermSection');
if(!$this->Application->CheckPermission($perm_sections['main'].'.view')) {
$this->Application->Redirect('no_permission');
}
$export_helper->PrefixSpecial = $prefix_special;
$export_helper->grid = $this->Application->GetVar('grid');
$export_helper->ExportStep();
$event->status = erSTOP;
}
/**
* Returning created by AJAX CSV file
*
* @param kEvent $event
*/
function OnGetCSV(&$event)
{
$export_helper =& $this->Application->recallObject('CSVHelper');
/* @var $export_helper kCSVHelper */
$prefix_special = $export_helper->ExportData('prefix');
$prefix_elems = split('\.|_', $prefix_special, 2);
$perm_sections = $this->Application->getUnitOption($prefix_elems[0], 'PermSection');
if(!$this->Application->CheckPermission($perm_sections['main'].'.view')) {
$this->Application->Redirect('no_permission');
}
$export_helper->GetCSV();
}
/**
* Enter description here...
*
* @param kEvent $event
*/
function OnCSVImportBegin(&$event)
{
$prefix_special = $this->Application->GetVar('PrefixSpecial');
$prefix_elems = split('\.|_', $prefix_special, 2);
$perm_sections = $this->Application->getUnitOption($prefix_elems[0], 'PermSection');
if(!$this->Application->CheckPermission($perm_sections['main'].'.add') && !$this->Application->CheckPermission($perm_sections['main'].'.edit')) {
$this->Application->Redirect('no_permission');
}
$object =& $event->getObject( Array('skip_autoload' => true) );
/* @var $object kDBItem */
$items_info = $this->Application->GetVar( $event->getPrefixSpecial(true) );
$field_values = array_shift($items_info);
$object->SetFieldsFromHash($field_values);
$event->redirect = false;
$result = 'required';
if($object->GetDBField('ImportFile')) {
$import_helper =& $this->Application->recallObject('CSVHelper');
/* @var $import_helper kCSVHelper */
$import_helper->PrefixSpecial = $this->Application->GetVar('PrefixSpecial');
$import_helper->grid = $this->Application->GetVar('grid');
$result = $import_helper->ImportStart( $object->GetField('ImportFile', 'file_paths') );
if($result === true) {
$event->redirect = $this->Application->GetVar('next_template');
$event->SetRedirectParam('PrefixSpecial', $this->Application->GetVar('PrefixSpecial'));
$event->SetRedirectParam('grid', $this->Application->GetVar('grid'));
}
}
if($event->redirect === false) {
$object->SetError('ImportFile', $result);
$event->status = erFAIL;
}
}
/**
* Enter description here...
*
* @param kEvent $event
*/
function OnCSVImportStep(&$event)
{
$import_helper =& $this->Application->recallObject('CSVHelper');
/* @var $export_helper kCSVHelper */
$prefix_special = $import_helper->ImportData('prefix');
$prefix_elems = split('\.|_', $prefix_special, 2);
$perm_sections = $this->Application->getUnitOption($prefix_elems[0], 'PermSection');
if(!$this->Application->CheckPermission($perm_sections['main'].'.add') && !$this->Application->CheckPermission($perm_sections['main'].'.edit')) {
$this->Application->Redirect('no_permission');
}
$import_helper->ImportStep();
$event->status = erSTOP;
}
/**
* Shows unit config filename, where requested prefix is defined
*
* @param kEvent $event
*/
function OnCheckPrefixConfig(&$event)
{
$prefix = $this->Application->GetVar('config_prefix');
$config_file = $this->Application->UnitConfigReader->prefixFiles[$prefix];
$this->Application->InitParser();
ob_start();
echo $this->Application->ParseBlock(Array('name' => 'incs/header', 'body_properties' => 'style="background-color: #E7E7E7; margin: 8px;"'));
?>
<script type="text/javascript">
set_window_title('Unit Config of "<?php echo $prefix; ?>" prefix');
</script>
<a href="javascript:window_close();">Close Window</a><br /><br />
<strong>Prefix:</strong> <?php echo $prefix; ?><br />
<strong>Unit Config:</strong> <?php echo $GLOBALS['debugger']->highlightString($config_file); ?><br />
<br /><a href="javascript:window_close();">Close Window</a><br />
<?php
echo $this->Application->ParseBlock(Array('name' => 'incs/footer'));
echo ob_get_clean();
$event->status = erSTOP;
}
function OnUploadFile(&$event)
{
// Flash uploader does NOT send correct cookies, so we need to make our own check
$cookie_name = 'adm_'.$this->Application->ConfigValue('SessionCookieName');
$this->Application->HttpQuery->Cookie['cookies_on'] = 1;
$this->Application->HttpQuery->Cookie[$cookie_name] = $this->Application->GetVar('flashsid');
$admin_ses =& $this->Application->recallObject('Session.admin');
/* @var $admin_ses Session */
$user = $admin_ses->RecallVar('user_id');
$perm_helper =& $this->Application->recallObject('PermissionsHelper');
/* @var $perm_helper kPermissionsHelper */
/*if() {
$prefix_special = $this->Application->GetVar('PrefixSpecial');
$prefix_elems = split('\.|_', $prefix_special, 2);
$perm_sections = $this->Application->getUnitOption($prefix_elems[0], 'PermSection');
$section = $perm_sections['main'];
}
else {*/
$section = $event->getSection();
/*}*/
if ($this->Application->GetVar('t') != 'import/import_start' && !$perm_helper->CheckUserPermission($user, $section.'.add') && !$perm_helper->CheckUserPermission($user, $section.'.edit')) {
$event->status = erPERM_FAIL;
header('HTTP/1.0 403 You don\'t have permissions to upload');
exit;
return;
}
if (!$cookie_name) $cookie_name = 'sid';
$value = $this->Application->GetVar('Filedata');
if (!$value) return ;
$tmp_path = WRITEABLE . '/tmp/';
$fname = $value['name'];
$id = $this->Application->GetVar('id');
if ($id) $fname = $id.'_'.$fname;
if (!is_writable($tmp_path)) {
header('HTTP/1.0 500 Write permissions not set on the server');
exit;
}
move_uploaded_file($value['tmp_name'], $tmp_path.$fname);
exit;
}
function OnDropTempTablesByWID(&$event)
{
$sid = $this->Application->GetSID();
$wid = $this->Application->GetVar('m_wid');
$tables = $this->Conn->GetCol('SHOW TABLES');
$mask_edit_table = '/'.TABLE_PREFIX.'ses_'.$sid.'_'.$wid.'_edit_(.*)$/';
foreach($tables as $table)
{
if( preg_match($mask_edit_table,$table,$rets) )
{
$this->Conn->Query('DROP TABLE IF EXISTS '.$table);
}
}
echo 'OK';
$event->status = erSTOP;
return ;
}
/**
* Backup all data
*
* @param kEvent $event
*/
function OnBackup(&$event)
{
$a_tables = $this->Conn->GetCol('SHOW TABLES'); // array_keys($tables);
$TableNames = Array();
for($x=0;$x<count($a_tables);$x++)
{
if(substr($a_tables[$x],0,strlen(TABLE_PREFIX))==TABLE_PREFIX)
{
if (!strstr($a_tables[$x], 'ses_')) {
$TableNames[] = $a_tables[$x];
}
}
}
// echo "<pre>"; print_r($TableNames); echo "</pre>";
// exit;
$backupProgress = Array (
'table_num' => 0,
'table_names' => $TableNames,
'table_count' => count($TableNames),
'record_count' => 0,
'file_name' => $this->Application->ConfigValue('Backup_Path')."/dump".adodb_mktime().".txt",
);
$this->Application->RemoveVar('adm.backupcomplete_filename');
$this->Application->RemoveVar('adm.backupcomplete_filesize');
$out = array();
for($x=0;$x<count($TableNames);$x++) {
if (!strstr($TableNames[$x], 'ses_')) {
$out[] = $this->GetTableCreate($TableNames[$x]);
}
}
$fp = fopen($backupProgress['file_name'], 'a');
$sql = "SELECT Name, Version FROM ".TABLE_PREFIX."Modules";
$r = $this->Conn->Query($sql);
foreach ($r AS $a_module) {
$version = $a_module['Version'];
fwrite($fp, "# ".$a_module['Name']." Version: $version;\n");
}
fwrite($fp, "#------------------------------------------\n\n");
fwrite($fp,implode("\n",$out));
fwrite($fp,"\n");
fclose($fp);
$this->Application->StoreVar('adm.backup_status', serialize($backupProgress));
$event->redirect = 'tools/backup2';
}
/**
* Perform next backup step
*
* @param kEvent $event
*/
function OnBackupProgress(&$event)
{
$done_percent = $this->performBackup();
if ($done_percent == 100) {
$event->redirect = 'tools/backup3';
return ;
}
echo $done_percent;
$event->status = erSTOP;
}
/**
* Stops Backup & redirect to Backup template
*
* @param kEvent $event
*/
function OnBackupCancel(&$event)
{
$event->redirect = 'tools/backup1';
}
/**
* Stops Restore & redirect to Restore template
*
* @param kEvent $event
*/
function OnRestoreCancel(&$event)
{
$event->redirect = 'tools/restore1';
}
function performBackup()
{
$backupProgress = unserialize($this->Application->RecallVar('adm.backup_status'));
// echo "<pre>"; print_r($backupProgress); echo "</pre>";
// exit;
$CurrentTable = $backupProgress['table_names'][$backupProgress['table_num']];
// get records
$a_records = $this->insert_data($CurrentTable,$backupProgress['record_count'],50,"");
// echo "<pre>"; print_r($a_records); echo "</pre>";
// exit;
if ($a_records['num'] < 50) {
$backupProgress['table_num']++;
// if ($backupProgress['table_names'][$backupProgress['table_num']] == TABLE_PREFIX.'Cache') {
// $backupProgress['table_num']++;
// }
$backupProgress['record_count'] = 0;
} else {
$backupProgress['record_count']+=50;
}
if ($a_records['sql']) {
$fp = fopen($backupProgress['file_name'], 'a');
fwrite($fp, $a_records['sql']);
fclose($fp);
}
$percent = ($backupProgress['table_num'] / $backupProgress['table_count']) * 100;
if ($percent >= 100) {
$percent = 100;
$this->Application->StoreVar('adm.backupcomplete_filename', $backupProgress['file_name']);
$this->Application->StoreVar('adm.backupcomplete_filesize', round(filesize($backupProgress['file_name'])/1024/1024, 2)); // Mbytes
} else {
$this->Application->StoreVar('adm.backup_status', serialize($backupProgress));
}
return round($percent);
}
//extracts the rows of data from tables using limits
function insert_data($table, $start, $limit, $mywhere)
{
// global $out;
if ($mywhere !="")
{
$whereclause= " WHERE ".$mywhere." ";
}
else
{
$whereclause = "";
}
$a_data = $this->Conn->Query("SELECT * from $table $whereclause LIMIT $start, $limit");
// echo "SELECT * from $table $whereclause LIMIT $start, $limit";
// echo "<pre>"; print_r($a_records); echo "</pre>";
// exit;
if (!$a_data) {
return Array(
'num' => 0,
'sql' => '',
);
}
// $prefix = GetTablePrefix();
$rowcount = 0;
$a_fields = array_keys($a_data[0]);
$fields_sql = '';
foreach ($a_fields AS $field_name) {
$fields_sql .= '`'.$field_name.'`,';
}
- $fields_sql = preg_replace('/(.*),$/', '\\1', $fields_sql);
+ $fields_sql = substr($fields_sql, 0, -1);
$temp = '';
foreach ($a_data AS $a_row)
{
$values_sql = '';
foreach ($a_row as $field_name => $field_value) {
$values_sql .= $this->Conn->qstr($field_value).',';
}
- $values_sql = preg_replace('/(.*),$/', '\\1', $values_sql);
+ $values_sql = substr($values_sql, 0, -1);
$sql = 'INSERT INTO '.$table.' ('.$fields_sql.') VALUES ('.$values_sql.');';
$sql = str_replace("\n", "\\n", $sql);
$sql = str_replace("\r", "\\r", $sql);
$temp .= $sql."\n";
}
if(strlen(TABLE_PREFIX))
{
$temp = str_replace("INSERT INTO ".TABLE_PREFIX, "INSERT INTO ", $temp);
}
return Array(
'num' => count($a_data),
'sql' => $temp,
);
}
function GetTableCreate($table, $crlf="\n")
{
$schema_create = 'DROP TABLE IF EXISTS ' . $table . ';' . $crlf;
$schema_create .="# --------------------------------------------------------".$crlf;
$this->Conn->Query("SET SQL_QUOTE_SHOW_CREATE = 0");
$tmpres = $this->Conn->Query("SHOW CREATE TABLE $table");
// echo "<pre>"; print_r($tmpres); echo "</pre>";
// exit;
if(is_array($tmpres) && isset($tmpres[0]))
{
$tmpres = $tmpres[0];
$pos = strpos($tmpres["Create Table"], ' (');
$pos2 = strpos($tmpres["Create Table"], '(');
if ($pos2 != $pos + 1)
{
$pos = $pos2;
$tmpres["Create Table"] = str_replace(",", ",\n ", $tmpres["Create Table"]);
}
$tmpres["Create Table"] = substr($tmpres["Create Table"], 0, 13)
. (($use_backquotes) ? $tmpres["Table"] : $tmpres["Table"])
. substr($tmpres["Create Table"], $pos);
$tmpres["Create Table"] = str_replace("\n", $crlf, $tmpres["Create Table"]);
if (preg_match_all('((,\r?\n[\s]*(CONSTRAINT|FOREIGN[\s]*KEY)[^\r\n,]+)+)', $tmpres["Create Table"], $regs)) {
if (!isset($sql_constraints)) {
if (isset($GLOBALS['no_constraints_comments'])) {
$sql_constraints = '';
} else {
$sql_constraints = $crlf . '#' . $crlf
. '# ' . $GLOBALS['strConstraintsForDumped'] . $crlf
. '#' . $crlf;
}
}
if (!isset($GLOBALS['no_constraints_comments'])) {
$sql_constraints .= $crlf .'#' . $crlf .'# ' . $GLOBALS['strConstraintsForTable'] . ' ' . $table . $crlf . '#' . $crlf;
}
$sql_constraints .= 'ALTER TABLE $table $crlf '
. preg_replace('/(,\r?\n|^)([\s]*)(CONSTRAINT|FOREIGN[\s]*KEY)/', '\1\2ADD \3', substr($regs[0][0], 2))
. ";\n";
$tmpres["Create Table"] = preg_replace('((,\r?\n[\s]*(CONSTRAINT|FOREIGN[\s]*KEY)[^\r\n,]+)+)', '', $tmpres["Create Table"]);
}
$schema_create .= $tmpres["Create Table"];
}
if(strlen($schema_create))
{
$schema_create = str_replace("DROP TABLE IF EXISTS ".TABLE_PREFIX,"DROP TABLE ",$schema_create);
$schema_create = str_replace("CREATE TABLE ".TABLE_PREFIX,"CREATE TABLE ",$schema_create);
while(strlen($schema_create && substr($schema_create,-1)!=")"))
{
$schema_create = substr($schema_create,0,-1);
}
}
$schema_create .= "\n# --------------------------------------------------------\n";
return $schema_create;
}
/**
* Deletes one backup file
*
* @param kEvent $event
*/
function OnDeleteBackup(&$event)
{
@unlink($this->get_backup_file());
}
function get_backup_file()
{
return $this->Application->ConfigValue('Backup_Path').'/dump'.$this->Application->GetVar('backupdate').'.txt';
}
/**
* Starts restore process
*
* @param kEvent $event
*/
function OnRestore(&$event)
{
$file = $this->get_backup_file();
$restoreProgress = Array (
'file_pos' => 0,
'file_name' => $file,
'file_size' => filesize($file),
);
$this->Application->RemoveVar('adm.restore_success');
$this->Application->StoreVar('adm.restore_status', serialize($restoreProgress));
$event->redirect = 'tools/restore3';
}
function OnRestoreProgress(&$event)
{
$done_percent = $this->performRestore();
if ($done_percent == -3) {
$event->redirect = 'tools/restore4';
return ;
}
if ($done_percent < 0) {
$this->Application->StoreVar('adm.restore_error', 'File read error'); $event->redirect = 'tools/restore4';
return ;
}
if ($done_percent == 100) {
$this->replaceRestoredFiles();
$this->Application->StoreVar('adm.restore_success', 1);
$event->redirect = 'tools/restore4';
return ;
}
echo $done_percent;
$event->status = erSTOP;
}
function replaceRestoredFiles()
{
// gather restored table names
$tables = $this->Conn->GetCol('SHOW TABLES');
$mask_restore_table = '/^restore'.TABLE_PREFIX.'(.*)$/';
foreach($tables as $table)
{
if( preg_match($mask_restore_table,$table,$rets) )
{
$old_table = substr($table, 7);
$this->Conn->Query('DROP TABLE IF EXISTS '.$old_table);
$this->Conn->Query('CREATE TABLE '.$old_table.' LIKE '.$table);
$this->Conn->Query('INSERT INTO '.$old_table.' SELECT * FROM '.$table);
$this->Conn->Query('DROP TABLE '.$table);
}
}
}
function performRestore()
{
$restoreProgress = unserialize($this->Application->RecallVar('adm.restore_status'));
$filename = $restoreProgress['file_name'];
$FileOffset = $restoreProgress['file_pos'];
$MaxLines = 200;
$size = filesize($filename);
if($FileOffset > $size) {
return -2;
}
$fp = fopen($filename,"r");
if(!$fp) {
return -1;
}
if($FileOffset>0)
{
fseek($fp,$FileOffset);
}
else
{
$EndOfSQL = FALSE;
$sql = "";
while(!feof($fp) && !$EndOfSQL)
{
$l = fgets($fp);
if(substr($l,0,11)=="INSERT INTO")
{
$EndOfSQL = TRUE;
}
else
{
$sql .= $l;
$FileOffset = ftell($fp) - strlen($l);
}
}
if(strlen($sql))
{
$error = $this->runSchemaText($sql);
if ($error != '') {
$this->Application->StoreVar('adm.restore_error', $error);
return -3;
}
}
fseek($fp,$FileOffset);
}
$LinesRead = 0;
$sql = "";
$AllSql = array();
while($LinesRead < $MaxLines && !feof($fp))
{
$sql = fgets($fp);
if(strlen($sql))
{
$AllSql[] = $sql;
$LinesRead++;
}
}
if(!feof($fp))
{
$FileOffset = ftell($fp);
}
else
{
$FileOffset = $size;
}
fclose($fp);
if(count($AllSql)>0) {
$error = $this->runSQLText($AllSql);
if ($error != '') {
$this->Application->StoreVar('adm.restore_error', $error);
return -3;
}
}
$restoreProgress['file_pos'] = $FileOffset;
$this->Application->StoreVar('adm.restore_status', serialize($restoreProgress));
return round($FileOffset/$size * 100);
// $this->Application->StoreVar('adm.restore_error', 'lalalal');
// $event->redirect = 'tools/restore4';
}
function runSchemaText($sql)
{
$table_prefix = 'restore'.TABLE_PREFIX;
// $table_prefix = TABLE_PREFIX;
if (strlen($table_prefix) > 0) {
$replacements = Array ('INSERT INTO ', 'UPDATE ', 'ALTER TABLE ', 'DELETE FROM ', 'REPLACE INTO ');
foreach ($replacements as $replacement) {
$sql = str_replace($replacement, $replacement . $table_prefix, $sql);
}
}
$sql = str_replace('CREATE TABLE ', 'CREATE TABLE IF NOT EXISTS ' . $table_prefix, $sql);
$sql = str_replace('DROP TABLE ', 'DROP TABLE IF EXISTS ' . $table_prefix, $sql);
$commands = explode("# --------------------------------------------------------",$sql);
if(count($commands)>0)
{
// $query_func = getConnectionInterface('query',$dbo_type);
// $errorno_func = getConnectionInterface('errorno',$dbo_type);
// $errormsg_func = getConnectionInterface('errormsg',$dbo_type);
for($i = 0; $i < count($commands); $i++)
{
$cmd = $commands[$i];
$cmd = trim($cmd);
if(strlen($cmd)>0)
{
$this->Conn->Query($cmd);
if($this->Conn->errorCode != 0)
{
return $this->Conn->errorMessage." COMMAND:<PRE>$cmd</PRE>";
}
}
}
}
}
function runSQLText($allsql)
{
$line = 0;
// $query_func = getConnectionInterface('query',$dbo_type);
// $errorno_func = getConnectionInterface('errorno',$dbo_type);
// $errormsg_func = getConnectionInterface('errormsg',$dbo_type);
while($line<count($allsql))
{
$sql = $allsql[$line];
if(strlen(trim($sql))>0 && substr($sql,0,1)!="#")
{
$table_prefix = 'restore'.TABLE_PREFIX;
if (strlen($table_prefix) > 0) {
$replacements = Array ('INSERT INTO ', 'UPDATE ', 'ALTER TABLE ', 'DELETE FROM ', 'REPLACE INTO ');
foreach ($replacements as $replacement) {
$sql = str_replace($replacement, $replacement . $table_prefix, $sql);
}
}
$sql = str_replace('CREATE TABLE ', 'CREATE TABLE IF NOT EXISTS ' . $table_prefix, $sql);
$sql = str_replace('DROP TABLE ', 'DROP TABLE IF EXISTS ' . $table_prefix, $sql);
$sql = trim($sql);
if(strlen($sql)>0)
{
$this->Conn->Query($sql);
if($this->Conn->errorCode != 0)
{
return $this->Conn->errorMessage." COMMAND:<PRE>$sql</PRE>";
}
}
}
$line++;
}
}
/**
* Starts restore process
*
* @param kEvent $event
*/
function OnSqlQuery(&$event)
{
$sql = $this->Application->GetVar('sql');
if ($sql) {
$start = $this->getMoment();
$result = $this->Conn->Query($sql);
$this->Application->SetVar('sql_time', round($this->getMoment() - $start, 7));
if ($result)
{
if (is_array($result))
{
$this->Application->SetVar('sql_has_rows', 1);
$this->Application->SetVar('sql_rows', serialize($result));
}
}
$check_sql = trim(strtolower($sql));
if (
(substr($check_sql, 0, 6) == 'insert')
|| (substr($check_sql, 0, 6) == 'update')
|| (substr($check_sql, 0, 7) == 'replace')
|| (substr($check_sql, 0, 6) == 'delete')
) {
$this->Application->SetVar('sql_has_affected', 1);
$this->Application->SetVar('sql_affected', $this->Conn->getAffectedRows());
}
}
$this->Application->SetVar('query_status', 1);
$event->status = erFAIL;
}
function getMoment()
{
list($usec, $sec) = explode(' ', microtime());
return ((float)$usec + (float)$sec);
}
/**
* Occurs after unit config cache was successfully rebuilt
*
* @param kEvent $event
*/
function OnAfterCacheRebuild(&$event)
{
}
/**
* Removes "Community -> Groups" section when it is not allowed
*
* @param kEvent $event
*/
function OnAfterConfigRead(&$event)
{
parent::OnAfterConfigRead($event);
if (!$this->Application->ConfigValue('AdvancedUserManagement')) {
$section_ajustments = $this->Application->getUnitOption($event->Prefix, 'SectionAdjustments');
if (!$section_ajustments) {
$section_ajustments = Array ();
}
$section_ajustments['in-portal:user_groups'] = 'remove';
$this->Application->setUnitOption($event->Prefix, 'SectionAdjustments', $section_ajustments);
}
}
/**
* Saves menu (tree) frame width
*
* @param kEvent $event
*/
function OnSaveMenuFrameWidth(&$event)
{
$event->status = erSTOP;
if (!$this->Application->ConfigValue('ResizableFrames')) {
return ;
}
$sql = 'UPDATE ' . $this->Application->getUnitOption('conf', 'TableName') . '
SET VariableValue = ' . (int)$this->Application->GetVar('width') . '
WHERE VariableName = "MenuFrameWidth"';
$this->Conn->Query($sql);
if ($this->Conn->getAffectedRows()) {
$this->Application->UnitConfigReader->ResetParsedData(false);
}
}
}
\ No newline at end of file
Index: branches/5.0.x/core/units/permissions/permissions_tag_processor.php
===================================================================
--- branches/5.0.x/core/units/permissions/permissions_tag_processor.php (revision 12705)
+++ branches/5.0.x/core/units/permissions/permissions_tag_processor.php (revision 12706)
@@ -1,211 +1,211 @@
<?php
/**
* @version $Id$
* @package In-Portal
* @copyright Copyright (C) 1997 - 2009 Intechnic. All rights reserved.
* @license GNU/GPL
* In-Portal is Open Source software.
* This means that this software may have been modified pursuant
* the GNU General Public License, and as distributed it includes
* or is derivative of works licensed under the GNU General Public License
* or other free or open source software licenses.
* See http://www.in-portal.net/license/ for copyright notices and details.
*/
defined('FULL_PATH') or die('restricted access!');
class PermissionsTagProcessor extends kDBTagProcessor {
function HasPermission($params)
{
$section_name = $params['section_name'];
$sections_helper =& $this->Application->recallObject('SectionsHelper');
$section_data =& $sections_helper->getSectionData($section_name);
return array_search($params['perm_name'], $section_data['permissions']) !== false;
}
function HasAdvancedPermissions($params)
{
$section_name = $params['section_name'];
$sections_helper =& $this->Application->recallObject('SectionsHelper');
$section_data =& $sections_helper->getSectionData($section_name);
$ret = false;
foreach ($section_data['permissions'] as $perm_name) {
if (preg_match('/^advanced:(.*)/', $perm_name)) {
$ret = true;
break;
}
}
return $ret;
}
function PermissionValue($params)
{
$section_name = $params['section_name'];
$perm_name = $params['perm_name'];
$sections_helper =& $this->Application->recallObject('SectionsHelper');
$section_data =& $sections_helper->getSectionData($section_name);
if ($section_data && isset($section_data['perm_prefix'])) {
// using permission from other prefix
$section_name = $this->Application->getUnitOption($section_data['perm_prefix'].'.main', 'PermSection');
}
$permissions_helper =& $this->Application->recallObject('PermissionsHelper');
if (!$permissions_helper->isOldPermission($section_name, $perm_name)) {
$perm_name = $section_name.'.'.$perm_name;
}
return $permissions_helper->getPermissionValue($perm_name);
}
function LoadPermissions($params)
{
$permissions_helper =& $this->Application->recallObject('PermissionsHelper');
$prefix_parts = explode('-', $this->Prefix, 2);
/* @var $permissions_helper kPermissionsHelper */
$permissions_helper->LoadPermissions($this->Application->GetVar('g_id'), 0, 1, 'g');
}
function LevelIndicator($params)
{
return $params['level'] * $params['multiply'];
}
function PrintPermissions($params)
{
$category =& $this->Application->recallObject('c');
$group_id = $this->Application->GetVar('group_id');
$prefix = $this->Application->GetVar('item_prefix');
$module = $this->Application->findModule('Var', $prefix, 'Name');
$perm_live_table = $this->Application->getUnitOption('c-perm', 'TableName');
$perm_temp_table = $this->Application->GetTempName($perm_live_table, 'prefix:'.$this->Prefix);
if ($category->GetID() == 0) {
$categories = Array(0);
}
else {
$categories = explode('|', substr($category->GetDBField('ParentPath'), 1, -1));
}
if (count($categories) == 1 || $category->GetID() == 0) {
// category located in root category ("Home") => then add it to path virtually
array_unshift($categories, 0);
}
$this_cat = array_pop($categories);
// get permission name + category position in parent path that has value set for that permission
$case = 'MAX(CASE c.CategoryId';
foreach ($categories as $pos => $cat_id) {
$case .= ' WHEN '.$cat_id.' THEN '.$pos;
}
$case .= ' END) AS InheritedPosition';
$sql = 'SELECT '.$case.', p.Permission AS Perm
FROM '.TABLE_PREFIX.'Category c
LEFT JOIN '.$perm_live_table.' p ON p.CatId = c.CategoryId
LEFT JOIN '.TABLE_PREFIX.'PermissionConfig pc ON pc.PermissionName = p.Permission
WHERE
CategoryId IN ('.implode(',', $categories).') AND
ModuleId = "'.$module.'" AND
(
(p.GroupId = '.(int)$group_id.' AND p.Type = 0)
)
GROUP BY Perm';
$perm_positions = $this->Conn->GetCol($sql, 'Perm');
$pos_sql = '';
foreach ($perm_positions as $perm_name => $category_pos) {
$pos_sql .= '(#TABLE_PREFIX#.Permission = "'.$perm_name.'" AND #TABLE_PREFIX#.CatId = '.$categories[$category_pos].') OR ';
}
- $pos_sql = $pos_sql ? preg_replace('/(.*) OR $/', '\\1', $pos_sql) : '0';
+ $pos_sql = $pos_sql ? substr($pos_sql, 0, -4) : '0';
// get all permissions list with iheritence status, inherited category id and permission value
$sql = 'SELECT pc.PermissionName,
pc.Description,
IF (tmp_p.PermissionValue IS NULL AND p.PermissionValue IS NULL,
0,
IF (tmp_p.PermissionValue IS NOT NULL, tmp_p.PermissionValue, p.PermissionValue)
) AS Value,
IF (tmp_p.CatId IS NOT NULL, tmp_p.CatId, IF(p.CatId IS NOT NULL, p.CatId, 0) ) AS InheritedFrom,
IF(tmp_p.CatId = '.$category->GetID().', 0, 1) AS Inherited,
IF(p.PermissionValue IS NOT NULL, p.PermissionValue, 0) AS InheritedValue
FROM '.TABLE_PREFIX.'PermissionConfig pc
LEFT JOIN '.$perm_live_table.' p
ON (p.Permission = pc.PermissionName) AND ('.str_replace('#TABLE_PREFIX#', 'p', $pos_sql).') AND (p.GroupId = '.(int)$group_id.')
LEFT JOIN '.$perm_temp_table.' tmp_p
ON (tmp_p.Permission = pc.PermissionName) AND (tmp_p.CatId = '.$this_cat.') AND (tmp_p.GroupId = '.$group_id.')
WHERE ModuleId = "'.$module.'"';
$permissions = $this->Conn->Query($sql);
$ret = '';
$block_params = array_merge_recursive2( $this->prepareTagParams($params), Array('name' => $params['render_as']));
foreach ($permissions as $perm_record) {
$block_params = array_merge_recursive2($block_params, $perm_record);
$ret .= $this->Application->ParseBlock($block_params);
}
return $ret;
}
/**
* Print module tab for each module
*
* @param Array $params
* @return string
*/
function PrintTabs($params)
{
$ret = '';
$block_params = $params;
foreach ($this->Application->ModuleInfo as $module_name => $module_data) {
if (!$this->Application->prefixRegistred($module_data['Var']) || !$this->Application->getUnitOption($module_data['Var'], 'CatalogItem')) continue;
$params['item_prefix'] = $module_data['Var'];
$ret .= $this->Application->IncludeTemplate($params);
}
return $ret;
}
/**
* Returns category name by ID
*
* @param Array $params
*/
function CategoryPath($params)
{
$category_id = $params['cat_id'];
$category_path = $this->Application->getCache('category_paths', $category_id);
if ($category_path === false) {
// not chached
if ($category_id > 0) {
$id_field = $this->Application->getUnitOption('c', 'IDField');
$table_name = $this->Application->getUnitOption('c', 'TableName');
$ml_formatter =& $this->Application->recallObject('kMultiLanguage');
$sql = 'SELECT '.$ml_formatter->LangFieldName('CachedNavbar').'
FROM '.$table_name.'
WHERE '.$id_field.' = '.$category_id;
$cached_navbar = preg_replace('/^Content(&\|&){0,1}/i', '', $this->Conn->GetOne($sql));
$category_path = trim($this->CategoryPath( Array('cat_id' => 0) ).' > '.str_replace('&|&', ' > ', $cached_navbar), ' > ');
}
else {
$category_path = $this->Application->Phrase( $this->Application->ConfigValue('Root_Name') );
}
$this->Application->setCache('category_paths', $category_id, $category_path);
}
return $category_path;
}
function PermInputName($params)
{
return $this->Prefix.'['.$this->Application->GetVar('group_id').']['.$this->Application->Parser->GetParam('PermissionName').']['.$params['sub_key'].']';
}
}
\ No newline at end of file

Event Timeline