Page MenuHomeIn-Portal Phabricator

in-portal
No OneTemporary

File Metadata

Created
Sun, Aug 17, 12:18 PM

in-portal

This file is larger than 256 KB, so syntax highlighting was skipped.
Index: branches/unlabeled/unlabeled-1.16.8/core/kernel/utility/email.php
===================================================================
--- branches/unlabeled/unlabeled-1.16.8/core/kernel/utility/email.php (revision 7747)
+++ branches/unlabeled/unlabeled-1.16.8/core/kernel/utility/email.php (nonexistent)
@@ -1,459 +0,0 @@
-<?php
-
-class kEmailMessage extends kBase {
-
- var $Compiled;
- var $Headers;
- var $HeadersArray;
- var $BodyText;
- var $BodyHtml;
- var $Body;
- var $Subject;
-// var $From;
-// var $To;
-// var $ReplyTo;
-// var $CC;
-// var $BCC;
- var $Charset;
- var $LineFeed;
- var $TransferEncoding;
- var $From;
- var $To;
-
-
- var $IsMultipart;
- var $Parts;
- var $Files;
-
-
- var $TextBoundary;
- var $EmailBoundary;
-
- function kEmailMessage(){
- parent::kBase();
- //$this->TextBoundary = uniqid(adodb_mktime());
- $this->EmailBoundary = uniqid(adodb_mktime());
- $this->LineFeed = "\n";
-
- $lang =& $this->Application->recallObject('lang.current');
- $this->Charset = $lang->GetDBField('Charset') ? $lang->GetDBField('Charset') : 'ISO-8859-1';
-
- $this->TransferEncoding='8bit';
- $this->Body = '';
- $this->setHeader('Subject', 'Automatically generated message');
- $this->HeadersArray=array();
-
- $this->setHeader('Mime-Version', '1.0');
- }
-
- function setHeader($header, $value){
- $this->HeadersArray[$header] = $value;
- $this->Compiled = false;
- }
-
- function fixLineBreaks($data)
- {
- $data = str_replace("\n\n","\r\n\r\n",$data);
- $data = str_replace("\r\n","\n",$data);
- $data = str_replace("\n","\r\n",$data);
- return $data;
- }
-
- function setHeaders($headers){
- $headers=$this->fixLineBreaks($headers);
- $headers_lines = explode("\r\n", $headers);
- foreach ($headers_lines as $line_num => $line){
- list($header_field, $header_value) = explode(':', $line, 2);
- $header_value = trim($header_value);
- $this->setHeader($header_field, $header_value);
- if ($header_field == 'Subject') $this->Subject = $header_value;
- }
-
- }
-
- function appendHeader($header, $value){
- $this->HeadersArray[$header][] = $value;
- $this->Compiled = false;
- }
-
-
- function setFrom($from, $name=''){
-
- $this->From = $from;
-
- if ($name!=''){
- $from = trim($name).' <'.$from.'>';
- }
- $this->setHeader('From', trim($from));
- }
-
- function setTo($to, $name=''){
-
- $this->To = $to;
-
- if ($name!=''){
- $to = trim($name).' <'.$to.'>';
- }
-
- $this->setHeader('To', trim($to));
- }
-
- function setSubject($subj){
- $this->setHeader('Subject', $subj);
- }
-
- function SetCC($to_cc){
- $this->appendHeader('CC', $to_cc);
- }
-
- function SetBCC($to_bcc){
- $this->appendHeader('BCC', $to_bcc);
- }
-
- function setReplyTo($reply_to){
- $this->setHeader('Reply-to', $reply_to);
- }
-
- function Clear()
- {
- $this->Compiled = false;
- $this->Body = '';
- $this->BodyHtml = '';
- $this->BodyText = '';
- $this->Headers = '';
- $this->Files = '';
- $this->From = '';
- $this->To = '';
- }
-
- function setTextBody($body_text){
-
- $this->BodyText = $body_text;
- $this->Compiled = false;
- }
-
- function setHTMLBody($body_html){
-
- $this->BodyHtml = $body_html;
- $this->IsMultipart = true;
- $this->Compiled = false;
- }
-
-
- function convertHTMLtoPlain($text)
- {
- $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, $text) );
- }
-
- function compileBody(){
-
- if($this->BodyHtml){
- $not_html = $this->convertHTMLtoPlain($this->BodyHtml);
-
-// $not_html = $this->removeBlankLines($not_html);
- // Fixing problem with add exclamation characters "!" into the body of the email.
- $not_html = wordwrap($not_html, 72);
- $this->BodyHtml = wordwrap($this->BodyHtml, 72);
-
- $this->Body = '';
- //$this->Body .= 'Content-Type: multipart/alternative;'.$this->LF()." ".'boundary="----='.$this->TextBoundary.'"'.$this->LF();
- //$this->Body .= $this->LF();
- $this->Body .= '------='.$this->EmailBoundary.$this->LF();
- $this->Body .= 'Content-Type: text/plain;'." ".'charset="'.$this->Charset.'"'.$this->LF();
- $this->Body .= $this->LF();
- $this->Body .= $not_html.$this->LF().$this->LF();
- $this->Body .= '------='.$this->EmailBoundary.$this->LF();
- $this->Body .= 'Content-Type: text/html;'." ".'charset="'.$this->Charset.'"'.$this->LF();
- $this->Body .= 'Content-Transfer-Encoding: '.$this->TransferEncoding.$this->LF();
- $this->Body .= 'Content-Description: HTML part'.$this->LF();
- $this->Body .= 'Content-Disposition: inline'.$this->LF();
- $this->Body .= $this->LF();
-
- $this->BodyHtml = str_replace("\r", "", $this->BodyHtml);
- $this->BodyHtml = str_replace("\n", $this->LF(), $this->BodyHtml);
-
- $this->Body .= $this->BodyHtml;
- $this->Body .= $this->LF().$this->LF();
-
-
- $this->IsMultipart = true;
-
- }else{
- $not_html = $this->convertHTMLtoPlain($this->BodyText);
-// $not_html = $this->removeBlankLines($not_html);
- // Fixing problem with add exclamation characters "!" into the body of the email.
- $not_html = wordwrap($not_html, 72);
-
-
- if ($this->IsMultipart){
- $this->Body .= '------='.$this->EmailBoundary.$this->LF();
- $this->Body .= 'Content-Type: text/plain;'.$this->LF()." ".'charset="'.$this->Charset.'"'.$this->LF();
- $this->Body .= 'Content-Disposition: inline'.$this->LF();
- $this->Body .= $this->LF();
- $this->Body .= $not_html.$this->LF().$this->LF();
- }else{
- //$this->BodyText = str_replace("\r", "", $this->BodyText);
- //$this->BodyText = str_replace("\n", $this->LF(), $this->BodyText);
- $this->Body = $not_html;
- }
-
- }
-
- }
-
- function setCharset($charset){
- $this->Charset = $charset;
- $this->Compiled = false;
- }
-
- function setLineFeed($linefeed){
- $this->LineFeed=$linefeed;
- }
-
- function attachFile($filepath, $mime="application/octet-stream"){
-
- if(is_file($filepath)){
- $file_info = array('path'=>$filepath, 'mime'=>$mime);
- $this->Files[] = $file_info;
- }else{
- $this->Application->ApplicationDie('File "'.$filepath.'" not exist...'."\n");
- }
-
- $this->IsMultipart = true;
- $this->Compiled = false;
- }
-
- function LF($str=''){
- $str = str_replace("\n", "", $str);
- $str = str_replace("\r", "", $str);
- return $str.$this->LineFeed;
- }
-
- function getContentType(){
- $content_type="";
- if ($this->IsMultipart){
- $content_type .= $this->LF('multipart/alternative; boundary="----='.$this->EmailBoundary.'"');
- }else{
- $content_type .= $this->LF('text/plain;');
- $content_type .= $this->LF(" ".'charset='.$this->Charset);
- }
-
- return $content_type;
-
- }
-
- // ========================================
-
- function compileHeaders(){
-
- $this->Headers="";
-
-// $this->Headers .= "From: ".$this->LF($this->From);
- //if ($this->ReplyTo){
-// $this->Headers .= "Reply-To: ".$this->ReplyTo.$this->LF();
- //}
- //$this->Headers .= "To: ".$this->LF($this->To);
- //$this->Headers .= "Subject: ".$this->LF($this->Subject);
- /*
- if (sizeof($this->CC)){
- $this->Headers .= "Cc: ";
- foreach ($this->Cc as $key => $addr){
- $this->Headers.=$this->LF($addr.',');
- }
- }
-
- if (sizeof($this->BCC)){
- $this->Headers .= "Bcc: ";
- foreach ($this->BCC as $key => $addr){
- $this->Headers.=$this->LF($addr.',');
- }
- }
- */
-
- foreach ($this->HeadersArray as $key => $val){
- if ($key=="To" || $key=="") continue; // avoid duplicate "To" field in headers
- if (is_array($val)){
- $val = chunk_split(implode(', ', $val),72, $this->LF().' ');
-
-
- $this->Headers .= $key.": ".$val.$this->LF();
- }else{
- $this->Headers .= $key.": ".$val.$this->LF();
- }
-
- }
-
- if ($this->IsMultipart) {
- $this->Headers .= 'MIME-Version: 1.0'.$this->LF();
- }
- $this->Headers .= "Content-Type: ".$this->getContentType();
-
- //$this->Headers .= "Content-Transfer-Encoding: ".$this->TransferEncoding.$this->LF();
-
-
- }
-
- function compileFiles(){
- if ($this->Files){
- foreach($this->Files as $key => $file_info)
- {
- $filepath = $file_info['path'];
- $mime = $file_info['mime'];
- $attachment_header = $this->LF('------='.$this->EmailBoundary);
- $attachment_header .= $this->LF('Content-Type: '.$mime.'; name="'.basename($filepath).'"');
- $attachment_header .= $this->LF('Content-Transfer-Encoding: base64');
- $attachment_header .= $this->LF('Content-Description: '.basename($filepath));
- $attachment_header .= $this->LF('Content-Disposition: attachment; filename="'.basename($filepath).'"');
- $attachment_header .= $this->LF('');
-
- $attachment_data = fread(fopen($filepath,"rb"),filesize($filepath));
- $attachment_data = base64_encode($attachment_data);
- $attachment_data = chunk_split($attachment_data,72);
-
- $this->Body .= $attachment_header.$attachment_data.$this->LF('');
- $this->IsMultipart = true;
- }
- }
- }
-
- function compile(){
-
- if ($this->Compiled) return;
-
- $this->compileBody();
-
- $this->compileFiles();
-
- $this->compileHeaders();
-
- // Compile
- if ($this->IsMultipart){
- $this->Body .= '------='.$this->EmailBoundary.'--'.$this->LF();
- }
-
- $this->Body = $this->fixLineBreaks($this->Body);
- $this->Headers = $this->fixLineBreaks($this->Headers);
-
-
- $this->Compiled = true;
- }
-
- // ========================================
-
- function getHeaders(){
-
- $this->Compile();
- return $this->Headers;
- }
-
- function getBody(){
-
- $this->Compile();
- return $this->Body;
- }
-
- function send(){
-
- return mail($this->HeadersArray['To'], $this->HeadersArray['Subject'], "", $this->getHeaders().$this->LF().$this->LF().$this->getBody());
- //return mail($this->HeadersArray['To'], $this->HeadersArray['Subject'], "", $this->getHeaders().$this->LF().$this->LF().$this->getBody(), '-f'.$this->From);
-
- }
-
- function sendSMTP(&$smtp_object, $smtp_host, $user, $pass, $auth_used = 0){
-
- $params['host'] = $smtp_host; // The smtp server host/ip
- $params['port'] = 25; // The smtp server port
- $params['helo'] = $_SERVER['HTTP_HOST']; // What to use when sending the helo command. Typically, your domain/hostname
- $params['auth'] = TRUE; // Whether to use basic authentication or not
- $params['user'] = $user; // Username for authentication
-
-
- $params['pass'] = $pass; // Password for authentication
- $params['debug'] = 1;
- if ($auth_used == 0){
- $params['authmethod'] = 'NOAUTH'; // forse disabling auth
- }
-
-
- if (strpos($this->To, ',') !== false) {
- $this->To = str_replace(' ', '', $this->To);
- $send_params['recipients'] = explode(',', $this->To);
- }
- else {
- $send_params['recipients'] = array($this->To); // The recipients (can be multiple)
- }
-
- $send_params['headers'] = explode("\r\n", $this->getHeaders());
-
- array_unshift($send_params['headers'], 'To: '.$this->HeadersArray['To']);
- $send_params['from'] = $this->From; // This is used as in the MAIL FROM: cmd
- // It should end up as the Return-Path: header
- $send_params['body']=$this->getBody();
-
-
- if($smtp_object->connect($params) && $smtp_object->send($send_params)){
- if ( $this->Application->isDebugMode() )
- {
- $this->Application->Debugger->appendHTML('<pre>'.$smtp_object->debugtext.'</pre>');
- //define('DBG_REDIRECT', 1);
- }
- return true;
- }
- else {
- if ( $this->Application->isDebugMode() )
- {
- $this->Application->Debugger->appendHTML('<pre>'.$smtp_object->debugtext.'</pre>');
- //define('DBG_REDIRECT', 1);
- }
- return false;
- }
-
- }
-
-
-}
-
-
-
-?>
Property changes on: branches/unlabeled/unlabeled-1.16.8/core/kernel/utility/email.php
___________________________________________________________________
Deleted: cvs2svn:cvs-rev
## -1 +0,0 ##
-1.16
\ No newline at end of property
Deleted: svn:executable
## -1 +0,0 ##
-*
\ No newline at end of property
Index: branches/unlabeled/unlabeled-1.3.62/core/kernel/utility/smtp_client.php
===================================================================
--- branches/unlabeled/unlabeled-1.3.62/core/kernel/utility/smtp_client.php (revision 7747)
+++ branches/unlabeled/unlabeled-1.3.62/core/kernel/utility/smtp_client.php (nonexistent)
@@ -1,829 +0,0 @@
-<?php
-
-define('SMTP_STATUS_NOT_CONNECTED', 1, TRUE);
-define('SMTP_STATUS_CONNECTED', 2, TRUE);
-
-
-
-class kSmtpClient extends kBase {
-
- var $connection;
- var $recipients;
- var $headers;
- var $timeout;
- var $errors;
- var $status;
- var $body;
- var $from;
- var $host;
- var $port;
- var $helo;
- var $auth;
- var $user;
- var $pass;
- var $debug;
- var $buffer;
-
- var $authmethod;
- var $CRLF = "\r\n";
-
- var $debugtext='';
- /**
- * List of supported authentication methods, in preferential order.
- * @var array
- * @access public
- */
- var $auth_methods = array('DIGEST-MD5','CRAM-MD5','LOGIN','PLAIN');
- /**
- * The most recent server response code.
- * @var int
- * @access private
- */
- var $_code = -1;
-
- /**
- * The most recent server response arguments.
- * @var array
- * @access private
- */
- var $_arguments = array();
- /**
- * Stores detected features of the SMTP server.
- * @var array
- * @access private
- */
- var $_esmtp = array();
-
- /***************************************
- ** Constructor function. Arguments:
- ** $params - An assoc array of parameters:
- **
- ** host - The hostname of the smtp server Default: localhost
- ** port - The port the smtp server runs on Default: 25
- ** helo - What to send as the HELO command Default: localhost
- ** (typically the hostname of the
- ** machine this script runs on)
- ** auth - Whether to use basic authentication Default: FALSE
- ** user - Username for authentication Default: <blank>
- ** pass - Password for authentication Default: <blank>
- ** timeout - The timeout in seconds for the call Default: 5
- ** to fsockopen()
- ***************************************/
-
- function kSmtpClient($params = array()){
-
- $this->timeout = 5;
- $this->status = SMTP_STATUS_NOT_CONNECTED;
- $this->host = 'localhost';
- $this->port = 25;
- $this->helo = 'localhost';
- $this->auth = FALSE;
- $this->user = '';
- $this->pass = '';
- $this->errors = array();
- $this->buffer = array();
- $this->debug=0;
- foreach($params as $key => $value){
- $this->$key = $value;
- }
- }
-
- /***************************************
- ** Connect function. This will, when called
- ** statically, create a new smtp object,
- ** call the connect function (ie this function)
- ** and return it. When not called statically,
- ** it will connect to the server and send
- ** the HELO command.
- ***************************************/
-
- function connect($params = array()){
-
- if(!isset($this->status))
- {
- $obj = new kSmtpClient($params);
- if($obj->connect()){
- $obj->status = SMTP_STATUS_CONNECTED;
- }
-
- return $obj;
-
- }
- else
- {
- foreach($params as $key => $value){
- $this->$key = $value;
- }
- $this->connection = @fsockopen($this->host, $this->port, $errno, $errstr, $this->timeout);
- if(is_resource($this->connection))
- {
- socket_set_timeout($this->connection, 0, 250000);
- socket_set_blocking($this->connection,TRUE);
- $greeting = $this->get_data();
- $this->status = SMTP_STATUS_CONNECTED;
- return $this->auth ? $this->ehlo() : $this->helo();
- }
- else
- {
- $this->errors[] = 'Failed to connect to server: '.$errstr;
- return FALSE;
- }
- }
- }
-
- function disconnect()
- {
- if(is_resource($this->connection))
- fclose($this->connection);
- unset($this->connection);
- $this->status=SMTP_STATUS_NOT_CONNECTED;
- }
- /***************************************
- ** Function which handles sending the mail.
- ** Arguments:
- ** $params - Optional assoc array of parameters.
- ** Can contain:
- ** recipients - Indexed array of recipients
- ** from - The from address. (used in MAIL FROM:),
- ** this will be the return path
- ** headers - Indexed array of headers, one header per array entry
- ** body - The body of the email
- ** It can also contain any of the parameters from the connect()
- ** function
- ***************************************/
-
- function send($params = array()){
-
- foreach($params as $key => $value){
- $this->set($key, $value);
- }
- if($this->is_connected()){
-
- // Do we auth or not? Note the distinction between the auth variable and auth() function
- if($this->auth){
- if(!$this->auth())
- return FALSE;
- }
- $this->mail($this->from);
- if(is_array($this->recipients))
- foreach($this->recipients as $value)
- $this->rcpt($value);
- else
- $this->rcpt($this->recipients);
-
- if(!$this->data())
- return FALSE;
-
- // Transparency
- $headers = str_replace($this->CRLF.'.', $this->CRLF.'..', trim(implode($this->CRLF, $this->headers)));
- $body = str_replace($this->CRLF.'.', $this->CRLF.'..', $this->body);
- $body = $body[0] == '.' ? '.'.$body : $body;
-
- $this->send_data($headers);
- $this->send_data('');
- $this->send_data($body);
- $this->send_data($this->CRLF.".");
-
- return (substr(trim($this->get_data()), 0, 3) === '250');
- }else{
- $this->errors[] = 'Not connected!';
- return FALSE;
- }
- }
-
- /***************************************
- ** Function to implement HELO cmd
- ***************************************/
-
- function helo(){
- if(is_resource($this->connection)
- AND $this->send_data('HELO '.$this->helo)
- AND substr(trim($error = $this->get_data()), 0, 3) === '250' ){
-
- return TRUE;
-
- }else{
- $this->errors[] = 'HELO command failed, output: ' . trim(substr(trim($error),3));
- return FALSE;
- }
- }
-
- /***************************************
- ** Function to implement EHLO cmd
- ***************************************/
-
- function ehlo()
- {
- $ret_status=is_resource($this->connection) AND $this->send_data('EHLO '.$this->helo);
- $success=$this->_parseResponse(250);
- if(!$ret_status && $success !== true)
- {
- $this->errors[] = 'EHLO command failed, output: ' . trim(substr(trim($error),3));
- return FALSE;
- }
-
- foreach ($this->_arguments as $argument) {
- $verb = strtok($argument, ' ');
- $arguments = substr($argument, strlen($verb) + 1,
- strlen($argument) - strlen($verb) - 1);
- $this->_esmtp[$verb] = $arguments;
- }
-
- return TRUE;
-
-
- }
-
- /***************************************
- ** Function to implement AUTH cmd
- ***************************************/
-
- function _getBestAuthMethod()
- {
- if ($this->authmethod) return $this->authmethod;
-
- if (!isset($this->_esmtp['AUTH'])) return 'NOAUTH';
-
- $available_methods = explode(' ', $this->_esmtp['AUTH']);
-
-
-
- foreach ($this->auth_methods as $method)
- {
- if (in_array($method, $available_methods)) return $method;
- }
- return false;
- }
-
-
- function auth(){
- if(is_resource($this->connection))
- {
- $method=$this->_getBestAuthMethod();
-
- if ($method == 'NOAUTH') return true;
-
- switch ($method) {
- case 'DIGEST-MD5':
- $result = $this->_authDigest_MD5($this->user, $this->pass);
- break;
- case 'CRAM-MD5':
- $result = $this->_authCRAM_MD5($this->user, $this->pass);
- break;
- case 'LOGIN':
- $result = $this->_authLogin($this->user, $this->pass);
- break;
- case 'PLAIN':
- $result = $this->_authPlain($this->user, $this->pass);
- break;
- default:
- $this->errors[] = 'AUTH command failed: no supported authentication methods';
- return false;
- break;
- }
- if($result!==true)
- {
- $this->errors[] = 'AUTH command failed: '.$result;
- return FALSE;
- }
- return true;
-
- }else{
- $this->errors[] = 'AUTH command failed: ' . trim(substr(trim($error),3));
- return FALSE;
- }
- }
-
-// ============= AUTH METHODS: BEGIN ==========================
-/**
- * Authenticates the user using the DIGEST-MD5 method.
- *
- * @param string The userid to authenticate as.
- * @param string The password to authenticate with.
- *
- * @return mixed Returns a PEAR_Error with an error message on any
- * kind of failure, or true on success.
- * @access private
- * @since 1.1.0
- */
- function _authDigest_MD5($uid, $pwd)
- {
- $this->send_data('AUTH DIGEST-MD5');
-
- /* 334: Continue authentication request */
- if(($error=$this->_parseResponse(334)) !== true)
- {
- /* 503: Error: already authenticated */
- if ($this->_code === 503) {
- return true;
- }
- return $error;
- }
-
- $challenge = base64_decode($this->_arguments[0]);
- $auth_str = base64_encode($this->get_digestMD5Auth($uid, $pwd, $challenge,
- $this->host, "smtp"));
-
-
- $this->send_data($auth_str);
-
- /* 334: Continue authentication request */
- if(($error=$this->_parseResponse(334)) !== true) return $error;
-
- /*
- * We don't use the protocol's third step because SMTP doesn't allow
- * subsequent authentication, so we just silently ignore it.
- */
- $this->send_data(' ');
-
- /* 235: Authentication successful */
- if(($error=$this->_parseResponse(235)) !== true) return $error;
- }
-
-
- /**
- * Provides the (main) client response for DIGEST-MD5
- * requires a few extra parameters than the other
- * mechanisms, which are unavoidable.
- *
- * @param string $authcid Authentication id (username)
- * @param string $pass Password
- * @param string $challenge The digest challenge sent by the server
- * @param string $hostname The hostname of the machine you're connecting to
- * @param string $service The servicename (eg. imap, pop, acap etc)
- * @param string $authzid Authorization id (username to proxy as)
- * @return string The digest response (NOT base64 encoded)
- * @access public
- */
- function get_digestMD5Auth($authcid, $pass, $challenge, $hostname, $service, $authzid = '')
- {
- $challenge = $this->_parseChallenge($challenge);
- $authzid_string = '';
- if ($authzid != '') {
- $authzid_string = ',authzid="' . $authzid . '"';
- }
-
- if (!empty($challenge)) {
- $cnonce = $this->_getCnonce();
- $digest_uri = sprintf('%s/%s', $service, $hostname);
- $response_value = $this->_getResponseValue($authcid, $pass, $challenge['realm'], $challenge['nonce'], $cnonce, $digest_uri, $authzid);
-
- return sprintf('username="%s",realm="%s"' . $authzid_string . ',nonce="%s",cnonce="%s",nc="00000001",qop=auth,digest-uri="%s",response=%s,%d', $authcid, $challenge['realm'], $challenge['nonce'], $cnonce, $digest_uri, $response_value, $challenge['maxbuf']);
- } else {
- return PEAR::raiseError('Invalid digest challenge');
- }
- }
-
- /**
- * Parses and verifies the digest challenge*
- *
- * @param string $challenge The digest challenge
- * @return array The parsed challenge as an assoc
- * array in the form "directive => value".
- * @access private
- */
- function _parseChallenge($challenge)
- {
- $tokens = array();
- while (preg_match('/^([a-z-]+)=("[^"]+(?<!\\\)"|[^,]+)/i', $challenge, $matches)) {
-
- // Ignore these as per rfc2831
- if ($matches[1] == 'opaque' OR $matches[1] == 'domain') {
- $challenge = substr($challenge, strlen($matches[0]) + 1);
- continue;
- }
-
- // Allowed multiple "realm" and "auth-param"
- if (!empty($tokens[$matches[1]]) AND ($matches[1] == 'realm' OR $matches[1] == 'auth-param')) {
- if (is_array($tokens[$matches[1]])) {
- $tokens[$matches[1]][] = preg_replace('/^"(.*)"$/', '\\1', $matches[2]);
- } else {
- $tokens[$matches[1]] = array($tokens[$matches[1]], preg_replace('/^"(.*)"$/', '\\1', $matches[2]));
- }
-
- // Any other multiple instance = failure
- } elseif (!empty($tokens[$matches[1]])) {
- $tokens = array();
- break;
-
- } else {
- $tokens[$matches[1]] = preg_replace('/^"(.*)"$/', '\\1', $matches[2]);
- }
-
- // Remove the just parsed directive from the challenge
- $challenge = substr($challenge, strlen($matches[0]) + 1);
- }
-
- /**
- * Defaults and required directives
- */
- // Realm
- if (empty($tokens['realm'])) {
- $uname = posix_uname();
- $tokens['realm'] = $uname['nodename'];
- }
-
- // Maxbuf
- if (empty($tokens['maxbuf'])) {
- $tokens['maxbuf'] = 65536;
- }
-
- // Required: nonce, algorithm
- if (empty($tokens['nonce']) OR empty($tokens['algorithm'])) {
- return array();
- }
-
- return $tokens;
- }
-
- /**
- * Creates the response= part of the digest response
- *
- * @param string $authcid Authentication id (username)
- * @param string $pass Password
- * @param string $realm Realm as provided by the server
- * @param string $nonce Nonce as provided by the server
- * @param string $cnonce Client nonce
- * @param string $digest_uri The digest-uri= value part of the response
- * @param string $authzid Authorization id
- * @return string The response= part of the digest response
- * @access private
- */
- function _getResponseValue($authcid, $pass, $realm, $nonce, $cnonce, $digest_uri, $authzid = '')
- {
- if ($authzid == '') {
- $A1 = sprintf('%s:%s:%s', pack('H32', md5(sprintf('%s:%s:%s', $authcid, $realm, $pass))), $nonce, $cnonce);
- } else {
- $A1 = sprintf('%s:%s:%s:%s', pack('H32', md5(sprintf('%s:%s:%s', $authcid, $realm, $pass))), $nonce, $cnonce, $authzid);
- }
- $A2 = 'AUTHENTICATE:' . $digest_uri;
- return md5(sprintf('%s:%s:00000001:%s:auth:%s', md5($A1), $nonce, $cnonce, md5($A2)));
- }
-
- /**
- * Creates the client nonce for the response
- *
- * @return string The cnonce value
- * @access private
- */
- function _getCnonce()
- {
- if (file_exists('/dev/urandom')) {
- return base64_encode(fread(fopen('/dev/urandom', 'r'), 32));
-
- } elseif (file_exists('/dev/random')) {
- return base64_encode(fread(fopen('/dev/random', 'r'), 32));
-
- } else {
- $str = '';
- mt_srand((double)microtime()*10000000);
- for ($i=0; $i<32; $i++) {
- $str .= chr(mt_rand(0, 255));
- }
-
- return base64_encode($str);
- }
- }
-
-
-
-
-
-
-
- /**
- * Authenticates the user using the CRAM-MD5 method.
- *
- * @param string The userid to authenticate as.
- * @param string The password to authenticate with.
- *
- * @return mixed Returns a PEAR_Error with an error message on any
- * kind of failure, or true on success.
- * @access private
- * @since 1.1.0
- */
- function _authCRAM_MD5($uid, $pwd)
- {
- $this->send_data('AUTH CRAM-MD5');
-
- /* 334: Continue authentication request */
- if(($error=$this->_parseResponse(334)) !== true)
- {
- /* 503: Error: already authenticated */
- if ($this->_code === 503) {
- return true;
- }
- return $error;
- }
-
- $challenge = base64_decode($this->_arguments[0]);
- $auth_str = base64_encode($uid . ' ' . $this->_HMAC_MD5($pwd, $challenge));
-
- $this->send_data($auth_str);
-
- /* 235: Authentication successful */
- if ( ($error = $this->_parseResponse(235)) ) {
- return $error;
- }
- }
-
- /**
- * Authenticates the user using the LOGIN method.
- *
- * @param string The userid to authenticate as.
- * @param string The password to authenticate with.
- *
- * @return mixed Returns a PEAR_Error with an error message on any
- * kind of failure, or true on success.
- * @access private
- * @since 1.1.0
- */
- function _authLogin($uid, $pwd)
- {
- $this->send_data('AUTH LOGIN');
-
- /* 334: Continue authentication request */
- if(($error=$this->_parseResponse(334)) !== true)
- {
- /* 503: Error: already authenticated */
- if ($this->_code === 503) {
- return true;
- }
- return $error;
- }
-
- $this->send_data( base64_encode($uid) );
-
- /* 334: Continue authentication request */
- if(($error=$this->_parseResponse(334)) !== true) return $error;
-
- $this->send_data( base64_encode($pwd) );
-
- /* 235: Authentication successful */
- if (($error=$this->_parseResponse(235)) !== true) return $error;
-
- return true;
- }
-
- /**
- * Authenticates the user using the PLAIN method.
- *
- * @param string The userid to authenticate as.
- * @param string The password to authenticate with.
- *
- * @return mixed Returns a PEAR_Error with an error message on any
- * kind of failure, or true on success.
- * @access private
- * @since 1.1.0
- */
- function _authPlain($uid, $pwd)
- {
- $this->send_data('AUTH PLAIN');
-
- /* 334: Continue authentication request */
- if(($error=$this->_parseResponse(334)) !== true)
- {
- /* 503: Error: already authenticated */
- if ($this->_code === 503) {
- return true;
- }
- return $error;
- }
-
- $auth_str = base64_encode(chr(0) . $uid . chr(0) . $pwd);
- $this->send_data($auth_str);
-
- /* 235: Authentication successful */
- if (($error=$this->_parseResponse(235)) !== true) return $error;
-
- return true;
- }
-// ============= AUTH METHODS: END ==========================
-
- /**
- * 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;
- }
-
-
-
- /**
- * 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 mixed True if the server returned a valid response code or
- * a PEAR_Error object is an error condition is reached.
- *
- * @access private
- * @since 1.1.0
- *
- * @see getResponse
- */
- function _parseResponse($valid)
- {
-
- $this->_code = -1;
- $this->_arguments = array();
-
- if(!is_resource($this->connection)) return false;
-
- while ($line = fgets($this->connection, 512)) {
- if ($this->debug) {
- $this->debugtext.= "DEBUG: Recv: $line\n";
- }
-
- /* If we receive an empty line, the connection has been closed. */
- if (empty($line)) {
- $this->disconnect();
- return 'Connection was unexpectedly closed';
- }
-
- /* Read the code and store the rest in the arguments array. */
- $code = substr($line, 0, 3);
- $this->_arguments[] = trim(substr($line, 4));
-
- /* Check the syntax of the response code. */
- if (is_numeric($code)) {
- $this->_code = (int)$code;
- } else {
- $this->_code = -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->_code === $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->_code === $valid_code) {
- return true;
- }
- }
- }
-
- return 'Invalid response code received from server';
- }
-
-
- /***************************************
- ** Function that handles the MAIL FROM: cmd
- ***************************************/
-
- function mail($from){
-
- if($this->is_connected()
- AND $this->send_data('MAIL FROM:'.$from.'')
- AND substr(trim($this->get_data()), 0, 2) === '250' ){
-
- return TRUE;
-
- }else
- return FALSE;
- }
-
- /***************************************
- ** Function that handles the RCPT TO: cmd
- ***************************************/
-
- function rcpt($to){
-
- if($this->is_connected()
- AND $this->send_data('RCPT TO:'.$to.'')
- AND substr(trim($error = $this->get_data()), 0, 2) === '25' ){
-
- return TRUE;
-
- }else{
- $this->errors[] = trim(substr(trim($error), 3));
- return FALSE;
- }
- }
-
- /***************************************
- ** Function that sends the DATA cmd
- ***************************************/
-
- function data(){
-
- if($this->is_connected()
- AND $this->send_data('DATA')
- AND substr(trim($error = $this->get_data()), 0, 3) === '354' ){
-
- return TRUE;
-
- }else{
- $this->errors[] = trim(substr(trim($error), 3));
- return FALSE;
- }
- }
-
- /***************************************
- ** Function to determine if this object
- ** is connected to the server or not.
- ***************************************/
-
- function is_connected(){
-
- return (is_resource($this->connection) AND ($this->status === SMTP_STATUS_CONNECTED));
- }
-
- /***************************************
- ** Function to send a bit of data
- ***************************************/
-
- function send_data($data){
-
- if($this->debug)
- {
- $this->buffer[] = "SEND: $data\n";
- }
- if ($this->debug) {
- $this->debugtext.= "DEBUG: Send: $data\n";
- }
- if(is_resource($this->connection)){
- return fwrite($this->connection, $data.$this->CRLF, strlen($data)+2);
- }else
- return FALSE;
- }
-
- function bytes_left($fp)
- {
- $status = socket_get_status ($fp);
- //print_r($status);
- $bytes = $status["unread_bytes"];
- return $bytes;
- }
-
- /***************************************
- ** Function to get data.
- ***************************************/
- function &get_data(){
-
- $return = '';
- $line = '';
-
- if(is_resource($this->connection))
- {
- while(strpos($return, $this->CRLF) === FALSE OR substr($line,3,1) !== ' ')
- {
- $line = fgets($this->connection, 512);
- $return .= $line;
- }
- if($this->debug)
- {
- $this->buffer[] = "GET: ".$return."\n";
- }
- return $return;
-
- }else
- return FALSE;
- }
-
- /***************************************
- ** Sets a variable
- ***************************************/
-
- function set($var, $value){
-
- $this->$var = $value;
- return TRUE;
- }
-
-
-}
-
-?>
\ No newline at end of file
Property changes on: branches/unlabeled/unlabeled-1.3.62/core/kernel/utility/smtp_client.php
___________________________________________________________________
Deleted: cvs2svn:cvs-rev
## -1 +0,0 ##
-1.3
\ No newline at end of property
Deleted: svn:executable
## -1 +0,0 ##
-*
\ No newline at end of property
Index: branches/unlabeled/unlabeled-1.29.2/core/units/email_events/email_events_event_handler.php
===================================================================
--- branches/unlabeled/unlabeled-1.29.2/core/units/email_events/email_events_event_handler.php (revision 7747)
+++ branches/unlabeled/unlabeled-1.29.2/core/units/email_events/email_events_event_handler.php (revision 7748)
@@ -1,276 +1,379 @@
<?php
+ define('EVENT_TYPE_FRONTEND', 0);
+ define('EVENT_TYPE_ADMIN', 1);
+
+ define('EVENT_STATUS_DISABLED', 0);
+ define('EVENT_STATUS_ENABLED', 1);
+ define('EVENT_STATUS_FRONTEND', 2);
+
class EmailEventsEventsHandler extends kDBEventHandler
{
/**
* Allows to override standart permission mapping
*
*/
function mapPermissions()
{
parent::mapPermissions();
$permissions = Array(
'OnFrontOnly' => Array('self' => 'edit'),
'OnSaveSelected' => Array('self' => 'view'),
);
$this->permMapping = array_merge($this->permMapping, $permissions);
}
/**
* Changes permission section to one from REQUEST, not from config
*
* @param kEvent $event
*/
function CheckPermission(&$event)
{
$module = $this->Application->GetVar('module');
$module = explode(':', $module, 2);
if (count($module) == 1) {
$main_prefix = $this->Application->findModule('Name', $module[0], 'Var');
}
else {
$exceptions = Array('Category' => 'c', 'Users' => 'u');
$main_prefix = $exceptions[ $module[1] ];
}
$section = $this->Application->getUnitOption($main_prefix.'.email', 'PermSection');
$event->setEventParam('PermSection', $section);
return parent::CheckPermission($event);
}
/**
* Apply any custom changes to list's sql query
*
* @param kEvent $event
* @access protected
* @see OnListBuild
*/
function SetCustomQuery(&$event)
{
if ($event->Special == 'module') {
$object =& $event->getObject();
$module = $this->Application->GetVar('module');
$object->addFilter('module_filter', '%1$s.Module = '.$this->Conn->qstr($module));
}
}
/**
* Sets status Front-End Only to selected email events
*
* @param kEvent $event
*/
function OnFrontOnly(&$event)
{
$ids = implode(',', $this->StoreSelectedIDs($event));
$table_name = $this->Application->getUnitOption($event->Prefix, 'TableName');
$sql = 'UPDATE '.$table_name.'
SET Enabled = 2
WHERE EventId IN ('.$ids.')';
$this->Conn->Query($sql);
}
/**
* Sets selected user to email events selected
*
* @param kEvent $event
*/
function OnSelectUser(&$event)
{
$items_info = $this->Application->GetVar('u');
if ($items_info) {
$user_id = array_shift( array_keys($items_info) );
$selected_ids = $this->getSelectedIDs($event, true);
$ids = $this->Application->RecallVar($event->getPrefixSpecial().'_selected_ids');
$id_field = $this->Application->getUnitOption($event->Prefix, 'IDField');
$table_name = $this->Application->getUnitOption($event->Prefix, 'TableName');
$sql = 'UPDATE '.$table_name.'
SET '.$this->Application->RecallVar('dst_field').' = '.$user_id.'
WHERE '.$id_field.' IN ('.$ids.')';
$this->Conn->Query($sql);
}
$this->finalizePopup($event);
}
/**
* Saves selected ids to session
*
* @param kEvent $event
*/
function OnSaveSelected(&$event)
{
$this->StoreSelectedIDs($event);
}
/**
- * Raised when email message shoul be sent
+ * Returns sender & recipients ids plus event_id (as parameter by reference)
*
* @param kEvent $event
+ * @param int $event_id id of email event used
+ *
+ * @return mixed
*/
- function OnEmailEvent(&$event){
-
- $email_event = $event->getEventParam('EmailEventName');
- if( strpos($email_event, '_') !== false )
- {
- trigger_error('<span class="debug_error">Invalid email event name</span> <b>'.$email_event.'</b>. Use only <b>UPPERCASE characters</b> and <b>dots</b> as email event names', E_USER_ERROR);
+ function GetMessageRecipients(&$event, &$event_id)
+ {
+ $email_event =& $event->getObject( Array('skip_autoload' => true) );
+ /* @var $email_event kDBItem */
+
+ // get event parameters by name & type
+ $load_keys = Array (
+ 'Event' => $event->getEventParam('EmailEventName'),
+ 'Type' => $event->getEventParam('EmailEventType'),
+ );
+ $email_event->Load($load_keys);
+
+ if (!$email_event->isLoaded()) {
+ // event record not found
+ return false;
+ }
+
+ $enabled = $email_event->GetDBField('Enabled');
+ if ($enabled == EVENT_STATUS_DISABLED) {
+ return false;
+ }
+ if ($enabled == EVENT_STATUS_FRONTEND && $this->Application->IsAdmin()) {
+ return false;
}
+ // initial values
$to_user_id = $event->getEventParam('EmailEventToUserId');
- $email_event_type = $event->getEventParam('EmailEventType');
-
- $message_object = &$this->Application->recallObject('emailmessages', null, Array('skip_autoload' => true));
- $event_table = $this->Application->getUnitOption('emailevents', 'TableName');
-
- $event_object =& $event->getObject( Array('skip_autoload' => true) );
- $event_object->Load(array('Event'=>$email_event, 'Type'=>$email_event_type));
-
- $event_id = $event_object->GetDBField('EventId');
- $from_user_id = $event_object->GetDBField('FromUserId');
- $type = $event_object->GetDBField('Type');
- $enabled = $event_object->GetDBField('Enabled');
-
- $direct_send_params = $event->getEventParam('DirectSendParams');
-
- if ($enabled == 0) return; // disabled event
- if ($enabled == 2 && $this->Application->IsAdmin() ) return; // event only for front-end
-
- if ($type == 1){
+ $from_user_id = $email_event->GetDBField('FromUserId');
+
+ if ($email_event->GetDBField('Type') == EVENT_TYPE_ADMIN) {
// For type "Admin" recipient is a user from field FromUserId which means From/To user in Email events list
$to_user_id = $from_user_id;
$from_user_id = -1;
}
- /*
- if (!($to_user_id > 0) && !$direct_send_params){
- // if we can not determine recepient we will not send email
- return;
- }
- */
- //Parse Message Template
- $message_object->Load(array('EventId' => $event_id, 'LanguageId' => $this->Application->GetVar('m_lang')));
- $message_type = $message_object->GetDBField('MessageType');
-
- $email_object = &$this->Application->recallObject('kEmailMessage');
- $email_object->Clear();
-
- // add footer: begin
- $sql = 'SELECT em.Template
- FROM '.$message_object->TableName.' em
- LEFT JOIN '.TABLE_PREFIX.'Events e ON e.EventId = em.EventId
- WHERE em.LanguageId = '.$message_object->GetDBField('LanguageId').' AND e.Event = "COMMON.FOOTER"';
- $footer = explode("\n\n", $this->Conn->GetOne($sql));
- $footer = $message_object->GetDBField('MessageType') == 'text' ? $email_object->convertHTMLtoPlain($footer[1]) : $footer[1];
- $message_template = $message_object->GetDBField('Template')."\r\n".$footer;
- // add footer: end
-
- $from_user_object = &$this->Application->recallObject('u.email-from', null, Array('skip_autoload' => true));
- $from_user_object->Load($from_user_id);
- // here if we don't have from_user loaded, it takes a default user from config values
- if ( $from_user_object->IsLoaded() ) {
- $from_user_email = $from_user_object->GetDBField('Email');
- $from_user_name = trim($from_user_object->GetDBField('FirstName').' '.$from_user_object->GetDBField('LastName'));
+
+ $event_id = $email_event->GetDBField('EventId');
+
+ return Array ($from_user_id, $to_user_id);
+ }
+
+ /**
+ * Returns user name, email by id, or ones, that specified in $direct_params
+ *
+ * @param int $user_id
+ * @param string $user_type type of user = {to,from}
+ * @param Array $direct_params
+ * @return Array
+ */
+ function GetRecipientInfo($user_id, $user_type, $direct_params = null)
+ {
+ // load user, because it can be addressed from email template tags
+ $user =& $this->Application->recallObject('u.email-'.$user_type, null, Array('skip_autoload' => true));
+ /* @var $user UsersItem */
+
+ $email = $name = '';
+ $result = $user_id > 0 ? $user->Load($user_id) : $user->Clear();
+ if ($user->IsLoaded()) {
+ $email = $user->GetDBField('Email');
+ $name = trim($user->GetDBField('FirstName').' '.$user->GetDBField('LastName'));
+ }
+
+ if (is_array($direct_params)) {
+ if (isset($direct_params[$user_type.'_email'])) {
+ $email = $direct_params[$user_type.'_email'];
+ }
+
+ if (isset($direct_params[$user_type.'_name'])) {
+ $name = $direct_params[$user_type.'_name'];
+ }
}
- else {
- $from_user_email = $this->Application->ConfigValue('Smtp_AdminMailFrom');
+
+ if (!$email) {
+ // if email is empty, then use admins email
+ $email = $this->Application->ConfigValue('Smtp_AdminMailFrom');
+ }
+
+ if (!$name) {
+ $name = $user_type == 'from' ? strip_tags($this->Application->ConfigValue('Site_Name')) : $email;
}
+
+ return Array ($email, $name);
+ }
+
+ /**
+ * Returns email event message by ID (headers & body in one piece)
+ *
+ * @param int $event_id
+ * @param string $message_type contains message type = {text,html}
+ */
+ function GetMessageBody($event_id, &$message_type)
+ {
+ $current_language = $this->Application->GetVar('m_lang');
+ $message =& $this->Application->recallObject('emailmessages', null, Array('skip_autoload' => true));
+ /* @var $message kDBItem */
+
+ $message->Load( Array('EventId' => $event_id, 'LanguageId' => $current_language) );
+ if (!$message->isLoaded()) {
+ // event translation on required language not found
+ return false;
+ }
+
+ $message_type = $message->GetDBField('MessageType');
+
+ // 1. get message body
+ $message_body = $message->GetDBField('Template');
+
+ // 2. add footer
+ $sql = 'SELECT em.Template
+ FROM '.$message->TableName.' em
+ LEFT JOIN '.TABLE_PREFIX.'Events e ON e.EventId = em.EventId
+ WHERE em.LanguageId = '.$current_language.' AND e.Event = "COMMON.FOOTER"';
+
+ list (, $footer) = explode("\n\n", $this->Conn->GetOne($sql));
+ if ($message_type == 'text') {
+ $esender =& $this->Application->recallObject('EmailSender');
+ /* @var $esender kEmailSendingHelper */
+
+ $footer = $esender->ConvertToText($footer);
+ }
+
+ if ($footer) {
+ $message_body .= "\r\n".$footer;
+ }
+
+ // 3. replace tags if needed
+ // $replacement_tags = $message->GetDBField('ReplacementTags');
+ // $replacement_tags = $replacement_tags ? unserialize($replacement_tags) : Array ();
+
+ $replacement_tags = Array (
+ '<inp:touser _Field="password"' => '<inp2:u_Field name="Password_plain"',
+ '<inp:touser _Field="UserName"' => '<inp2:u_Field name="Login"',
+ '<inp:touser _Field' => '<inp2:u_Field name',
+ );
- $to_user_object = &$this->Application->recallObject('u.email-to', null, Array('skip_autoload' => true));
- $to_user_object->Load($to_user_id);
- $to_user_email = $to_user_object->GetDBField('Email');
- $to_user_name = trim($to_user_object->GetDBField('FirstName').' '.$to_user_object->GetDBField('LastName'));
-
- if($direct_send_params){
- $to_user_email = ( $direct_send_params['to_email'] ? $direct_send_params['to_email'] : $to_user_email );
- $to_user_name = ( $direct_send_params['to_name'] ? $direct_send_params['to_name'] : $to_user_name );
- $from_user_email = ( $direct_send_params['from_email'] ? $direct_send_params['from_email'] : $from_user_email);
- $from_user_name = ( $direct_send_params['from_name'] ? $direct_send_params['from_name'] : $from_user_name );
- $message_body_additional = $direct_send_params['message'];
+ foreach ($replacement_tags as $replace_from => $replace_to) {
+ $message_body = str_replace($replace_from, $replace_to, $message_body);
}
-
- $to_user_email = $to_user_email ? $to_user_email : $this->Application->ConfigValue('Smtp_AdminMailFrom');
-
- $this->Application->makeClass('Template');
+
+ return $message_body;
+ }
+
+ /**
+ * Parse message template and return headers (as array) and message body part
+ *
+ * @param string $message
+ * @param Array $direct_params
+ * @return Array
+ */
+ function ParseMessageBody($message, $direct_params = null)
+ {
+ $direct_params['message_text'] = isset($direct_params['message']) ? $direct_params['message'] : ''; // parameter alias
+
+ // 1. parse template
$this->Application->InitParser();
- $parser_params = $this->Application->Parser->Params;
- $direct_send_params['message_text'] = $message_body_additional;
- $this->Application->Parser->Params = array_merge_recursive2($this->Application->Parser->Params, $direct_send_params);
- $message_template = str_replace('<inp:touser _Field="password"', '<inp2:u_Field name="Password_plain"', $message_template);
- $message_template = str_replace('<inp:touser _Field="Password"', '<inp2:u_Field name="Password_plain"', $message_template);
- $message_template = str_replace('<inp:touser _Field="UserName"', '<inp2:u_Field name="Login"', $message_template);
- $message_template = str_replace('<inp:touser _Field', '<inp2:u_Field name', $message_template);
- $message_template = $this->Application->Parser->Parse($message_template, 'email_template', 0);
- $this->Application->Parser->Params = $parser_params;
-
- $message_template = str_replace("\r", "", $message_template);
-
- list($message_headers, $message_body) = explode("\n\n", $message_template, 2);
-
-
- $email_object->setFrom($from_user_email, $from_user_name);
- $email_object->setTo($to_user_email, $to_user_name);
- $email_object->setSubject('Mail message');
-
- $email_object->setHeaders($message_headers);
-
- if ($message_type == 'html'){
- $email_object->setHTMLBody($message_body);
- }
- else {
- $email_object->setTextBody($message_body);
+ $parser_params = $this->Application->Parser->Params; // backup parser params
+ $this->Application->Parser->Params = array_merge_recursive2($this->Application->Parser->Params, $direct_params);
+ $message = $this->Application->Parser->Parse($message, 'email_template', 0);
+ $this->Application->Parser->Params = $parser_params; // restore parser params
+
+ // 2. replace line endings, that are send with data submitted via request
+ $message = str_replace("\r\n", "\n", $message); // possible case
+ $message = str_replace("\r", "\n", $message); // impossible case, but just in case replace this too
+
+ // 3. separate headers from body
+ $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]);
}
+
+ return Array ($message_headers, $message_body);
+ }
+
+ /**
+ * Raised when email message shoul be sent
+ *
+ * @param kEvent $event
+ */
+ function OnEmailEvent(&$event)
+ {
+ $email_event_name = $event->getEventParam('EmailEventName');
+ if (strpos($email_event_name, '_') !== false) {
+ trigger_error('<span class="debug_error">Invalid email event name</span> <b>'.$email_event_name.'</b>. Use only <b>UPPERCASE characters</b> and <b>dots</b> as email event names', E_USER_ERROR);
+ }
+
+ // additional parameters from kApplication->EmailEvent
+ $send_params = $event->getEventParam('DirectSendParams');
+
+ // 1. get information about message sender and recipient
+ $recipients = $this->GetMessageRecipients($event, $event_id);
+ if ($recipients === false) {
+ // if not valid recipients found, then don't send event
+ return false;
+ }
+
+ list ($from_id, $to_id) = $recipients;
+ list ($from_email, $from_name) = $this->GetRecipientInfo($from_id, 'from', $send_params);
+ list ($to_email, $to_name) = $this->GetRecipientInfo($to_id, 'to', $send_params);
+
+ // 2. prepare message to be sent
+ $message_template = $this->GetMessageBody($event_id, $message_type);
+ if (!trim($message_template)) {
+ return false;
+ }
+
+ list ($message_headers, $message_body) = $this->ParseMessageBody($message_template, $send_params);
+ if (!trim($message_body)) {
+ return false;
+ }
+
+ // 3. set headers & send message
+ $esender =& $this->Application->recallObject('EmailSender');
+ /* @var $esender kEmailSendingHelper */
+
+ $esender->SetFrom($from_email, $from_name);
+ $esender->AddTo($to_email, $to_name);
+
+ $message_subject = isset($message_headers['Subject']) ? $message_headers['Subject'] : 'Mail message';
+ $esender->SetSubject($message_subject);
- $smtp_object = &$this->Application->recallObject('kSmtpClient');
- $smtp_object->debug = $this->Application->isDebugMode() && constOn('DBG_SMTP');
-
- $smtp_server = $this->Application->ConfigValue('Smtp_Server');
- $smtp_port = $this->Application->ConfigValue('Smtp_Port');
-
- $smtp_authenticate = $this->Application->ConfigValue('Smtp_Authenticate');
- if ($smtp_authenticate){
- $smtp_user = $this->Application->ConfigValue('Smtp_User');
- $smtp_pass = $this->Application->ConfigValue('Smtp_Pass');
- }else{
- $smtp_user = '';
- $smtp_pass = '';
+ foreach ($message_headers as $header_name => $header_value) {
+ $esender->SetEncodedHeader($header_name, $header_value);
}
+ $esender->CreateTextHtmlPart($message_body, $message_type == 'html');
- if ($smtp_server){
- if ($email_object->sendSMTP($smtp_object, $smtp_server, $smtp_user, $smtp_pass, $smtp_authenticate)){
- $event->status=erSUCCESS;
- }
- else {
- $event->status=erFAIL;
- }
- }else{
- if($email_object->send()){
- $event->status=erSUCCESS;
- }
- else {
- $event->status=erFAIL;
- }
- }
+ $event->status = $esender->Deliver() ? erSUCCESS : erFAIL;
if ($event->status == erSUCCESS){
- if (!$from_user_name) {
- $from_user_name = strip_tags( $this->Application->ConfigValue('Site_Name') );
+ // all keys, that are not used in email sending are written to log record
+ $send_keys = Array ('from_email', 'from_name', 'to_email', 'to_name', 'message');
+ foreach ($send_keys as $send_key) {
+ unset($send_params[$send_key]);
}
- $sql = 'INSERT INTO '.TABLE_PREFIX.'EmailLog SET
- fromuser = '.$this->Conn->qstr($from_user_name.' ('.$from_user_email.')').',
- addressto = '.$this->Conn->qstr($to_user_name.' ('.$to_user_email.')').',
- subject = '.$this->Conn->qstr($email_object->Subject).',
- timestamp = UNIX_TIMESTAMP(),
- event = '.$this->Conn->qstr($email_event);
- $this->Conn->Query($sql);
+
+ $fields_hash = Array (
+ 'fromuser' => $from_name.' ('.$from_email.')',
+ 'addressto' => $to_name.' ('.$to_email.')',
+ 'subject' => $message_subject,
+ 'timestamp' => adodb_mktime(),
+ 'event' => $email_event_name,
+ 'EventParams' => serialize($send_params),
+ );
+
+ $this->Conn->doInsert($fields_hash, TABLE_PREFIX.'EmailLog');
}
$this->Application->removeObject('u.email-from');
$this->Application->removeObject('u.email-to');
- return $event;
}
}
?>
\ No newline at end of file
Property changes on: branches/unlabeled/unlabeled-1.29.2/core/units/email_events/email_events_event_handler.php
___________________________________________________________________
Modified: cvs2svn:cvs-rev
## -1 +1 ##
-1.29.2.1
\ No newline at end of property
+1.29.2.2
\ No newline at end of property
Index: branches/unlabeled/unlabeled-1.1.2/admin/install/upgrades/inportal_upgrade_v4.0.1.sql
===================================================================
--- branches/unlabeled/unlabeled-1.1.2/admin/install/upgrades/inportal_upgrade_v4.0.1.sql (revision 7747)
+++ branches/unlabeled/unlabeled-1.1.2/admin/install/upgrades/inportal_upgrade_v4.0.1.sql (revision 7748)
@@ -1,6 +1,11 @@
INSERT INTO ConfigurationValues VALUES (NULL, 'RegistrationCaptcha', '0', 'In-Portal:Users', 'in-portal:configure_users');
INSERT INTO ConfigurationAdmin VALUES ('RegistrationCaptcha', 'la_Text_General', 'la_registration_captcha', 'checkbox', NULL, NULL, 10.025, 0, 0);
ALTER TABLE EmailMessage ADD `Subject` TINYTEXT NULL ;
+ALTER TABLE EmailLog ADD EventParams TEXT NOT NULL;
+
+INSERT INTO ConfigurationAdmin VALUES ('MailFunctionHeaderSeparator', 'la_Text_smtp_server', 'la_config_MailFunctionHeaderSeparator', 'radio', NULL, '1=la_Linux,2=la_Windows', 30.08, 0, 0);
+INSERT INTO ConfigurationValues VALUES (0, 'MailFunctionHeaderSeparator', 1, 'In-Portal', 'in-portal:configure_general');
+
UPDATE Modules SET Version = '4.0.1' WHERE Name = 'In-Portal';
\ No newline at end of file
Property changes on: branches/unlabeled/unlabeled-1.1.2/admin/install/upgrades/inportal_upgrade_v4.0.1.sql
___________________________________________________________________
Modified: cvs2svn:cvs-rev
## -1 +1 ##
-1.1.2.2
\ No newline at end of property
+1.1.2.3
\ No newline at end of property
Index: branches/unlabeled/unlabeled-1.1.4/core/kernel/utility/email_send.php
===================================================================
--- branches/unlabeled/unlabeled-1.1.4/core/kernel/utility/email_send.php (nonexistent)
+++ branches/unlabeled/unlabeled-1.1.4/core/kernel/utility/email_send.php (revision 7748)
@@ -0,0 +1,1939 @@
+<?php
+
+ /**
+ * 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 = strrpos($filename, '.');
+ return $last_dot !== false ? 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);
+ }
+
+
+ /**
+ * 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 = 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->SetEncodedEmailHeader('To', $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 ();
+
+ $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 = strrpos($text, ' ');
+ $name = trim(substr($text, 0, $lastspace - 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 "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);
+ }
+
+ /**
+ * 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 = '')
+ {
+ if (!$name) {
+ $name = $email;
+ }
+
+ $value = isset($this->headers[$header_name]) ? $this->headers[$header_name] : '';
+ $value .= ', '.$this->QuotedPrintableEncode($name, $this->charset).' <'.$email.'>';
+
+ $value = preg_replace('/^,(.*)/', '\\1', $value); // remove first comma
+ $this->SetHeader($header_name, $value);
+ }
+
+ /**
+ * 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
+ * @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
+ $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 && $immediate_send) {
+ $send_method = 'Send'.$this->sendMethod;
+ $result = $this->$send_method($message_headers, $message_body);
+
+ if ($immediate_clear) {
+ $this->Clear();
+ }
+ return $result;
+ }
+
+ // if not immediate send, then send result is positive :)
+ return !$immediate_send ? true : false;
+ }
+ }
+
+?>
\ No newline at end of file
Property changes on: branches/unlabeled/unlabeled-1.1.4/core/kernel/utility/email_send.php
___________________________________________________________________
Added: cvs2svn:cvs-rev
## -0,0 +1 ##
+1.1.4.1
\ No newline at end of property
Added: svn:executable
## -0,0 +1 ##
+*
\ No newline at end of property
Index: branches/unlabeled/unlabeled-1.1.4/core/kernel/utility/socket.php
===================================================================
--- branches/unlabeled/unlabeled-1.1.4/core/kernel/utility/socket.php (nonexistent)
+++ branches/unlabeled/unlabeled-1.1.4/core/kernel/utility/socket.php (revision 7748)
@@ -0,0 +1,361 @@
+<?php
+
+ /**
+ * Generalized Socket class.
+ *
+ */
+ class kSocket extends kBase {
+
+ /**
+ * Socket file pointer.
+ * @var resource $fp
+ */
+ var $fp = null;
+
+ /**
+ * Whether the socket is blocking. Defaults to true.
+ * @var boolean $blocking
+ */
+ var $blocking = true;
+
+ /**
+ * Whether the socket is persistent. Defaults to false.
+ * @var boolean $persistent
+ */
+ var $persistent = false;
+
+ /**
+ * The IP address to connect to.
+ * @var string $addr
+ */
+ var $addr = '';
+
+ /**
+ * The port number to connect to.
+ * @var integer $port
+ */
+ var $port = 0;
+
+ /**
+ * Number of seconds to wait on socket connections before assuming
+ * there's no more data. Defaults to no timeout.
+ * @var integer $timeout
+ */
+ var $timeout = false;
+
+ /**
+ * Number of bytes to read at a time in readLine() and
+ * readAll(). Defaults to 2048.
+ * @var integer $lineLength
+ */
+ var $lineLength = 2048;
+
+ /**
+ * Connect to the specified port. If called when the socket is
+ * already connected, it disconnects and connects again.
+ *
+ * @param string $addr IP address or host name.
+ * @param integer $port TCP port number.
+ * @param boolean $persistent (optional) Whether the connection is
+ * persistent (kept open between requests
+ * by the web server).
+ * @param integer $timeout (optional) How long to wait for data.
+ *
+ * @access public
+ *
+ * @return boolean | PEAR_Error True on success or a PEAR_Error on failure.
+ */
+ function connect($addr, $port = 0, $persistent = null, $timeout = null)
+ {
+ if (is_resource($this->fp)) {
+ @fclose($this->fp);
+ $this->fp = null;
+ }
+
+ // convert hostname to ip address
+ if (!$addr) {
+ return $this->raiseError('host address cannot be empty');
+ } elseif (strspn($addr, '.0123456789') == strlen($addr) || strstr($addr, '/') !== false) {
+ $this->addr = $addr;
+ } else {
+ $this->addr = @gethostbyname($addr);
+ }
+
+ $this->port = $port % 65536;
+
+ if ($persistent !== null) {
+ $this->persistent = $persistent;
+ }
+
+ if ($timeout !== null) {
+ $this->timeout = $timeout;
+ }
+
+ $openfunc = $this->persistent ? 'pfsockopen' : 'fsockopen';
+ $errno = 0;
+ $errstr = '';
+
+ if ($this->timeout) {
+ $fp = @$openfunc($this->addr, $this->port, $errno, $errstr, $this->timeout);
+ } else {
+ $fp = @$openfunc($this->addr, $this->port, $errno, $errstr);
+ }
+
+ if (!$fp) {
+ return $this->raiseError($errstr, Array($errno));
+ }
+
+ $this->fp = $fp;
+
+ return $this->setBlocking($this->blocking);
+ }
+
+ /**
+ * Disconnects from the peer, closes the socket.
+ *
+ * @access public
+ * @return mixed true on success or an error object otherwise
+ */
+ function disconnect()
+ {
+ if (!is_resource($this->fp)) {
+ return $this->raiseError('not connected');
+ }
+
+ @fclose($this->fp);
+ $this->fp = null;
+ return true;
+ }
+
+ /**
+ * Find out if the socket is in blocking mode.
+ *
+ * @access public
+ * @return boolean The current blocking mode.
+ */
+ function isBlocking()
+ {
+ return $this->blocking;
+ }
+
+ /**
+ * Sets whether the socket connection should be blocking or
+ * not. A read call to a non-blocking socket will return immediately
+ * if there is no data available, whereas it will block until there
+ * is data for blocking sockets.
+ *
+ * @param boolean $mode True for blocking sockets, false for nonblocking.
+ * @access public
+ * @return mixed true on success or an error object otherwise
+ */
+ function setBlocking($mode)
+ {
+ if (!is_resource($this->fp)) {
+ return $this->raiseError('not connected');
+ }
+
+ $this->blocking = $mode;
+ socket_set_blocking($this->fp, $this->blocking);
+ return true;
+ }
+
+ /**
+ * Sets the timeout value on socket descriptor,
+ * expressed in the sum of seconds and microseconds
+ *
+ * @param integer $seconds Seconds.
+ * @param integer $microseconds Microseconds.
+ * @access public
+ * @return mixed true on success or an error object otherwise
+ */
+ function setTimeout($seconds, $microseconds)
+ {
+ if (!is_resource($this->fp)) {
+ return $this->raiseError('not connected');
+ }
+
+ return socket_set_timeout($this->fp, $seconds, $microseconds);
+ }
+
+ /**
+ * Returns information about an existing socket resource.
+ * Currently returns four entries in the result array:
+ *
+ * <p>
+ * timed_out (bool) - The socket timed out waiting for data<br>
+ * blocked (bool) - The socket was blocked<br>
+ * eof (bool) - Indicates EOF event<br>
+ * unread_bytes (int) - Number of bytes left in the socket buffer<br>
+ * </p>
+ *
+ * @access public
+ * @return mixed Array containing information about existing socket resource or an error object otherwise
+ */
+ function getStatus()
+ {
+ if (!is_resource($this->fp)) {
+ return $this->raiseError('not connected');
+ }
+
+ return socket_get_status($this->fp);
+ }
+
+ /**
+ * Get a specified line of data
+ *
+ * @access public
+ * @return $size bytes of data from the socket, or a PEAR_Error if
+ * not connected.
+ */
+ function gets($size)
+ {
+ if (!is_resource($this->fp)) {
+ return $this->raiseError('not connected');
+ }
+
+ return @fgets($this->fp, $size);
+ }
+
+ /**
+ * Read a specified amount of data. This is guaranteed to return,
+ * and has the added benefit of getting everything in one fread()
+ * chunk; if you know the size of the data you're getting
+ * beforehand, this is definitely the way to go.
+ *
+ * @param integer $size The number of bytes to read from the socket.
+ * @access public
+ * @return $size bytes of data from the socket, or a PEAR_Error if
+ * not connected.
+ */
+ function read($size)
+ {
+ if (!is_resource($this->fp)) {
+ return $this->raiseError('not connected');
+ }
+
+ return @fread($this->fp, $size);
+ }
+
+ /**
+ * Write a specified amount of data.
+ *
+ * @param string $data Data to write.
+ * @param integer $blocksize Amount of data to write at once.
+ * NULL means all at once.
+ *
+ * @access public
+ * @return mixed true on success or an error object otherwise
+ */
+ function write($data, $blocksize = null)
+ {
+ if (!is_resource($this->fp)) {
+ return $this->raiseError('not connected');
+ }
+
+ if (is_null($blocksize) && !OS_WINDOWS) {
+ return fwrite($this->fp, $data);
+ } else {
+ if (is_null($blocksize)) {
+ $blocksize = 1024;
+ }
+
+ $pos = 0;
+ $size = strlen($data);
+ while ($pos < $size) {
+ $written = @fwrite($this->fp, substr($data, $pos, $blocksize));
+ if ($written === false) {
+ return false;
+ }
+ $pos += $written;
+ }
+
+ return $pos;
+ }
+ }
+
+ /**
+ * Write a line of data to the socket, followed by a trailing "\r\n".
+ *
+ * @access public
+ * @return mixed fputs result, or an error
+ */
+ function writeLine($data)
+ {
+ if (!is_resource($this->fp)) {
+ return $this->raiseError('not connected');
+ }
+
+ return fwrite($this->fp, $data . "\r\n");
+ }
+
+ /**
+ * Tests for end-of-file on a socket descriptor.
+ *
+ * @access public
+ * @return bool
+ */
+ function eof()
+ {
+ return (is_resource($this->fp) && feof($this->fp));
+ }
+
+ /**
+ * Read until either the end of the socket or a newline, whichever
+ * comes first. Strips the trailing newline from the returned data.
+ *
+ * @access public
+ * @return All available data up to a newline, without that
+ * newline, or until the end of the socket, or a PEAR_Error if
+ * not connected.
+ */
+ function readLine()
+ {
+ if (!is_resource($this->fp)) {
+ return $this->raiseError('not connected');
+ }
+
+ $line = '';
+ $timeout = time() + $this->timeout;
+ while (!feof($this->fp) && (!$this->timeout || time() < $timeout)) {
+ $line .= @fgets($this->fp, $this->lineLength);
+ if (substr($line, -1) == "\n") {
+ return rtrim($line, "\r\n");
+ }
+ }
+ return $line;
+ }
+
+ /**
+ * Read until the socket closes, or until there is no more data in
+ * the inner PHP buffer. If the inner buffer is empty, in blocking
+ * mode we wait for at least 1 byte of data. Therefore, in
+ * blocking mode, if there is no data at all to be read, this
+ * function will never exit (unless the socket is closed on the
+ * remote end).
+ *
+ * @access public
+ *
+ * @return string All data until the socket closes, or a PEAR_Error if
+ * not connected.
+ */
+ function readAll()
+ {
+ if (!is_resource($this->fp)) {
+ return $this->raiseError('not connected');
+ }
+
+ $data = '';
+ while (!feof($this->fp)) {
+ $data .= @fread($this->fp, $this->lineLength);
+ }
+ return $data;
+ }
+
+ function raiseError($text, $params = Array())
+ {
+ trigger_error(vsprintf($text, $params), E_USER_WARNING);
+ return false;
+ }
+ }
+
+?>
\ No newline at end of file
Property changes on: branches/unlabeled/unlabeled-1.1.4/core/kernel/utility/socket.php
___________________________________________________________________
Added: cvs2svn:cvs-rev
## -0,0 +1 ##
+1.1.4.1
\ No newline at end of property
Added: svn:executable
## -0,0 +1 ##
+*
\ No newline at end of property
Index: branches/unlabeled/unlabeled-1.5.2/core/install/install_data.sql
===================================================================
--- branches/unlabeled/unlabeled-1.5.2/core/install/install_data.sql (revision 7747)
+++ branches/unlabeled/unlabeled-1.5.2/core/install/install_data.sql (revision 7748)
@@ -1,580 +1,582 @@
INSERT INTO ConfigurationAdmin VALUES ('Site_Name', 'la_Text_Website', 'la_config_website_name', 'text', '', '', 10.02, 0, 1);
INSERT INTO ConfigurationAdmin VALUES ('Site_Path', 'la_Text_Website', 'la_config_web_address', 'text', '', '', 10.01, 0, 1);
INSERT INTO ConfigurationAdmin VALUES ('Backup_Path', 'la_Text_BackupPath', 'la_config_backup_path', 'text', '', '', 40.01, 0, 1);
INSERT INTO ConfigurationAdmin VALUES ('Domain_Detect', 'la_Text_Website', 'la_config_detect_domain', 'text', '', '', 8, 0, 1);
INSERT INTO ConfigurationAdmin VALUES ('Category_Sortfield', 'la_Text_General', 'la_category_sortfield_prompt', 'select', '', 'Name=la_Category_Name,Description=la_Category_Description,CreatedOn=la_Category_Date,EditorsPick=la_Category_Pick,<SQL>SELECT Prompt AS OptionName, CONCAT("cust_", FieldName) AS OptionValue FROM <PREFIX>CustomField WHERE (Type = 1) AND (IsSystem = 0)</SQL>', 10.01, 1, 1);
INSERT INTO ConfigurationAdmin VALUES ('Category_Sortorder', 'la_Text_General', 'la_category_sortfield_prompt', 'select', '', 'asc=la_common_ascending,desc=la_common_descending', 10.01, 2, 1);
INSERT INTO ConfigurationAdmin VALUES ('Category_Sortfield2', 'la_Text_General', 'la_category_sortfield2_prompt', 'select', '', 'Name=la_Category_Name,Description=la_Category_Description,CreatedOn=la_Category_Date,EditorsPick=la_Category_Pick,<SQL>SELECT Prompt AS OptionName, CONCAT("cust_", FieldName) AS OptionValue FROM <PREFIX>CustomField WHERE (Type = 1) AND (IsSystem = 0)</SQL>', 10.02, 1, 1);
INSERT INTO ConfigurationAdmin VALUES ('Category_Sortorder2', 'la_Text_General', 'la_category_sortfield2_prompt', 'select', '', 'asc=la_common_ascending,desc=la_common_descending', 10.02, 2, 1);
INSERT INTO ConfigurationAdmin VALUES ('Perpage_Category', 'la_Text_General', 'la_category_perpage_prompt', 'text', '', '', 10.03, 0, 1);
INSERT INTO ConfigurationAdmin VALUES ('Category_DaysNew', 'la_Text_General', 'la_category_daysnew_prompt', 'text', '', '', 10.05, 0, 1);
INSERT INTO ConfigurationAdmin VALUES ('Category_ShowPick', 'la_Text_General', 'la_category_showpick_prompt', 'checkbox', '', '', 10.06, 0, 1);
INSERT INTO ConfigurationAdmin VALUES ('Category_MetaKey', 'la_Text_MetaInfo', 'la_category_metakey', 'text', '', '', 20.01, 0, 1);
INSERT INTO ConfigurationAdmin VALUES ('Category_MetaDesc', 'la_Text_MetaInfo', 'la_category_metadesc', 'text', '', '', 20.02, 0, 1);
INSERT INTO ConfigurationAdmin VALUES ('User_NewGroup', 'la_Text_General', 'la_users_new_group', 'select', NULL, '0=lu_none,<SQL+>SELECT GroupId as OptionValue, Name as OptionName FROM <PREFIX>PortalGroup WHERE Enabled=1 AND Personal=0</SQL>', 10.08, 0, 1);
INSERT INTO ConfigurationAdmin VALUES ('User_GuestGroup', 'la_Text_General', 'la_users_guest_group', 'select', NULL, '0=lu_none,<SQL+>SELECT GroupId as OptionValue, Name as OptionName FROM <PREFIX>PortalGroup WHERE Enabled=1 AND Personal=0</SQL>', 10.1, 0, 1);
INSERT INTO ConfigurationAdmin VALUES ('RootPass', 'la_Text_General', 'la_prompt_root_pass', 'password', NULL, NULL, 10.12, 0, 0);
INSERT INTO ConfigurationAdmin VALUES ('Users_AllowReset', 'la_Text_General', 'la_prompt_allow_reset', 'text', NULL, NULL, 10.05, 0, 0);
INSERT INTO ConfigurationAdmin VALUES ('User_Allow_New', 'la_Text_General', 'la_users_allow_new', 'radio', '', '1=la_User_Instant,2=la_User_Not_Allowed,3=la_User_Upon_Approval', 10.01, 0, 1);
INSERT INTO ConfigurationAdmin VALUES ('User_Password_Auto', 'la_Text_General', 'la_users_password_auto', 'checkbox', '', '', 10.06, 0, 1);
INSERT INTO ConfigurationAdmin VALUES ('User_Votes_Deny', 'la_Text_Restrictions', 'la_users_votes_deny', 'text', '', '', 20.01, 0, 1);
INSERT INTO ConfigurationAdmin VALUES ('User_MembershipExpirationReminder', 'la_Text_General', 'la_MembershipExpirationReminder', 'text', NULL, '', 10.07, 0, 1);
INSERT INTO ConfigurationAdmin VALUES ('User_Review_Deny', 'la_Text_Restrictions', 'la_users_review_deny', 'text', '', '', 20.02, 0, 1);
INSERT INTO ConfigurationAdmin VALUES ('Server_Name', 'la_Text_Website', 'la_config_server_name', 'text', '', '', 4, 0, 0);
INSERT INTO ConfigurationAdmin VALUES ('Config_Server_Time', 'la_Text_Date_Time_Settings', 'la_config_time_server', 'select', '', '1=la_m12,2=la_m11,3=la_m10,5=la_m9,6=la_m8,7=la_m7,8=la_m6,9=la_m5,10=la_m4,11=la_m3,12=la_m2,13=la_m1,14=la_m0,15=la_p1,16=la_p2,17=la_p3,18=la_p4,19=la_p5,20=la_p6,21=la_p7,22=la_p8,23=la_p9,24=la_p10,25=la_p11,26=la_p12,27=la_p13', 20.01, 0, 1);
INSERT INTO ConfigurationAdmin VALUES ('Config_Site_Time', 'la_Text_Date_Time_Settings', 'la_config_site_zone', 'select', '', '1=la_m12,2=la_m11,3=la_m10,5=la_m9,6=la_m8,7=la_m7,8=la_m6,9=la_m5,10=la_m4,11=la_m3,12=la_m2,13=la_m1,14=la_m0,15=la_p1,16=la_p2,17=la_p3,18=la_p4,19=la_p5,20=la_p6,21=la_p7,22=la_p8,23=la_p9,24=la_p10,25=la_p11,26=la_p12,27=la_p13', 20.02, 0, 1);
INSERT INTO ConfigurationAdmin VALUES ('Smtp_Server', 'la_Text_smtp_server', 'la_prompt_mailserver', 'text', NULL, NULL, 30.01, 0, 1);
INSERT INTO ConfigurationAdmin VALUES ('Smtp_Port', 'la_Text_smtp_server', 'la_prompt_mailport', 'text', NULL, NULL, 30.02, 0, 1);
INSERT INTO ConfigurationAdmin VALUES ('Smtp_Authenticate', 'la_Text_smtp_server', 'la_prompt_mailauthenticate', 'checkbox', NULL, NULL, 30.03, 0, 1);
INSERT INTO ConfigurationAdmin VALUES ('Smtp_User', 'la_Text_smtp_server', 'la_prompt_smtp_user', 'text', NULL, NULL, 30.04, 0, 1);
INSERT INTO ConfigurationAdmin VALUES ('Smtp_Pass', 'la_Text_smtp_server', 'la_prompt_smtp_pass', 'text', NULL, NULL, 30.05, 0, 1);
INSERT INTO ConfigurationAdmin VALUES ('Smtp_DefaultHeaders', 'la_Text_smtp_server', 'la_prompt_smtpheaders', 'textarea', NULL, 'COLS=40 ROWS=5', 30.06, 0, 0);
INSERT INTO ConfigurationAdmin VALUES ('Smtp_AdminMailFrom', 'la_Text_smtp_server', 'la_prompt_AdminMailFrom', 'text', NULL, NULL, 30.07, 0, 1);
INSERT INTO ConfigurationAdmin VALUES ('Perpage_Category_Short', 'la_Text_General', 'la_category_perpage__short_prompt', 'text', '', '', 10.04, 0, 1);
INSERT INTO ConfigurationAdmin VALUES ('CookieSessions', 'la_Text_Website', 'la_prompt_session_management', 'select', NULL, '0=lu_query_string,1=lu_cookies,2=lu_auto', 10.03, 0, 1);
INSERT INTO ConfigurationAdmin VALUES ('SearchRel_Keyword_category', 'la_config_SearchRel_DefaultKeyword', 'la_text_keyword', 'text', NULL, NULL, 0, 0, 1);
INSERT INTO ConfigurationAdmin VALUES ('SearchRel_Pop_category', 'la_config_DefaultPop', 'la_text_popularity', 'text', NULL, NULL, 0, 0, 1);
INSERT INTO ConfigurationAdmin VALUES ('SearchRel_Rating_category', 'la_config_DefaultRating', 'la_prompt_Rating', 'text', NULL, NULL, 0, 0, 1);
INSERT INTO ConfigurationAdmin VALUES ('SearchRel_Increase_category', 'la_config_DefaultIncreaseImportance', 'la_text_increase_importance', 'text', NULL, NULL, 0, 0, 1);
INSERT INTO ConfigurationAdmin VALUES ('SessionTimeout', 'la_Text_Website', 'la_prompt_session_timeout', 'text', '', '', 10.05, 0, 1);
INSERT INTO ConfigurationAdmin VALUES ('SystemTagCache', 'la_Text_Website', 'la_prompt_syscache_enable', 'checkbox', NULL, NULL, 10.07, 0, 0);
INSERT INTO ConfigurationAdmin VALUES ('User_SubscriberGroup', 'la_Text_General', 'la_users_subscriber_group', 'select', NULL, '0=lu_none,<SQL+>SELECT GroupId as OptionValue, Name as OptionName FROM <PREFIX>PortalGroup WHERE Enabled=1 AND Personal=0</SQL>', 10.11, 0, 1);
INSERT INTO ConfigurationAdmin VALUES ('Root_Name', 'la_Text_General', 'la_prompt_root_name', 'text', '', '', 10.07, 0, 1);
INSERT INTO ConfigurationAdmin VALUES ('SocketBlockingMode', 'la_Text_Website', 'la_prompt_socket_blocking_mode', 'checkbox', NULL, NULL, 10.08, 0, 0);
INSERT INTO ConfigurationAdmin VALUES ('Min_UserName', 'la_Text_General', 'la_text_min_username', 'text', '', '', 10.03, 0, 0);
INSERT INTO ConfigurationAdmin VALUES ('Min_Password', 'la_Text_General', 'la_text_min_password', 'text', '', '', 10.04, 0, 0);
INSERT INTO ConfigurationAdmin VALUES ('Email_As_Login', 'la_Text_General', 'la_use_emails_as_login', 'checkbox', NULL, NULL, 10.02, 0, 0);
INSERT INTO ConfigurationAdmin VALUES ('RegistrationCaptcha', 'la_Text_General', 'la_registration_captcha', 'checkbox', NULL, NULL, 10.025, 0, 0);
INSERT INTO ConfigurationAdmin VALUES ('User_LoggedInGroup', 'la_Text_General', 'la_users_assign_all_to', 'select', NULL, '0=lu_none,<SQL+>SELECT GroupId as OptionValue, Name as OptionName FROM <PREFIX>PortalGroup WHERE Enabled=1 AND Personal=0</SQL>', 10.09, 0, 1);
INSERT INTO ConfigurationAdmin VALUES ('FirstDayOfWeek', 'la_Text_Date_Time_Settings', 'la_config_first_day_of_week', 'select', '', '0=la_sunday,1=la_monday', 20.03, 0, 1);
INSERT INTO ConfigurationAdmin VALUES ('SSL_URL', 'la_Text_Website', 'la_config_ssl_url', 'text', '', '', 10.09, 0, 1);
INSERT INTO ConfigurationAdmin VALUES ('Require_SSL', 'la_Text_Website', 'la_config_require_ssl', 'checkbox', '', '', 10.1, 0, 1);
INSERT INTO ConfigurationAdmin VALUES ('Force_HTTP_When_SSL_Not_Required', 'la_Text_Website', 'la_config_force_http', 'checkbox', '', '', 10.11, 0, 1);
INSERT INTO ConfigurationAdmin VALUES ('SessionCookieName', 'la_Text_Website', 'la_prompt_session_cookie_name', 'text', '', '', 10.04, 0, 1);
INSERT INTO ConfigurationAdmin VALUES ('SessionReferrerCheck', 'la_Text_Website', 'la_promt_ReferrerCheck', 'checkbox', NULL, NULL, 10.06, 0, 1);
INSERT INTO ConfigurationAdmin VALUES ('UseModRewrite', 'la_Text_Website', 'la_config_use_modrewrite', 'checkbox', '', '', 10.12, 0, 1);
INSERT INTO ConfigurationAdmin VALUES ('UseModRewriteWithSSL', 'la_Text_Website', 'la_config_use_modrewrite_with_ssl', 'checkbox', '', '', 10.13, 0, 1);
INSERT INTO ConfigurationAdmin VALUES ('ErrorTemplate', 'la_Text_Website', 'la_config_error_template', 'text', '', '', 10.16, 0, 0);
INSERT INTO ConfigurationAdmin VALUES ('UseJSRedirect', 'la_Text_Website', 'la_config_use_js_redirect', 'checkbox', '', '', 10.14, 0, 0);
INSERT INTO ConfigurationAdmin VALUES ('MaxImportCategoryLevels', 'la_Text_General', 'la_prompt_max_import_category_levels', 'text', '', '', 10.08, 0, 1);
INSERT INTO ConfigurationAdmin VALUES ('UseCronForRegularEvent', 'la_Text_Website', 'la_UseCronForRegularEvent', 'checkbox', NULL, NULL, 10.15, 0, 0);
INSERT INTO ConfigurationAdmin VALUES ('NoPermissionTemplate', 'la_Text_Website', 'la_config_nopermission_template', 'text', '', '', 10.17, 0, 0);
INSERT INTO ConfigurationAdmin (VariableName, heading, prompt, element_type, validation, ValueList, DisplayOrder, GroupDisplayOrder, Install) VALUES ('UseOutputCompression', 'la_Text_Website', 'la_config_UseOutputCompression', 'checkbox', '', '', 10.18, 0, 1);
INSERT INTO ConfigurationAdmin (VariableName, heading, prompt, element_type, validation, ValueList, DisplayOrder, GroupDisplayOrder, Install) VALUES ('OutputCompressionLevel', 'la_Text_Website', 'la_config_OutputCompressionLevel', 'text', '', '', 10.19, 0, 1);
+INSERT INTO ConfigurationAdmin VALUES ('MailFunctionHeaderSeparator', 'la_Text_smtp_server', 'la_config_MailFunctionHeaderSeparator', 'radio', NULL, '1=la_Linux,2=la_Windows', 30.08, 0, 0);
INSERT INTO ConfigurationValues VALUES (NULL, 'Columns_Category', '2', 'In-Portal', 'Categories');
INSERT INTO ConfigurationValues VALUES (NULL, 'DomainSelect','1','In-Portal','in-portal:configure_general');
INSERT INTO ConfigurationValues VALUES (NULL, 'Site_Path', '/', 'In-Portal', 'in-portal:configure_general');
INSERT INTO ConfigurationValues VALUES (NULL, 'Perpage_Archive', '25', 'inportal', '');
INSERT INTO ConfigurationValues VALUES (NULL, 'debug', '1', 'inportal', '');
INSERT INTO ConfigurationValues VALUES (NULL, 'Perpage_User', '100', 'inportal', '');
INSERT INTO ConfigurationValues VALUES (NULL, 'Perpage_LangEmail', '20', 'inportal', '');
INSERT INTO ConfigurationValues VALUES (NULL, 'Default_FromAddr', '', 'inportal', '');
INSERT INTO ConfigurationValues VALUES (NULL, 'email_replyto', '', 'inportal', '');
INSERT INTO ConfigurationValues VALUES (NULL, 'email_footer', 'message footer goes here', 'inportal', '');
INSERT INTO ConfigurationValues VALUES (NULL, 'Default_Theme', 'default', 'In-Portal', '');
INSERT INTO ConfigurationValues VALUES (NULL, 'Default_Language', 'English', 'inportal', '');
INSERT INTO ConfigurationValues VALUES (NULL, 'SessionTimeout', '3600', 'In-Portal', 'in-portal:configure_general');
INSERT INTO ConfigurationValues VALUES (NULL, 'User_SortOrder', 'asc', 'In-Portal', '');
INSERT INTO ConfigurationValues VALUES (NULL, 'Suggest_MinInterval', '3600', 'inportal', '');
INSERT INTO ConfigurationValues VALUES (NULL, 'SubCat_ListCount', '3', 'inportal', '');
INSERT INTO ConfigurationValues VALUES (NULL, 'Timeout_Rating', '3600', 'In-Portal', 'System');
INSERT INTO ConfigurationValues VALUES (NULL, 'User_SortField', 'u.CreatedOn', 'In-Portal', '');
INSERT INTO ConfigurationValues VALUES (NULL, 'Perpage_Relations', '10', 'In-Portal', '');
INSERT INTO ConfigurationValues VALUES (NULL, 'Group_SortField', 'GroupName', 'In-Portal', '');
INSERT INTO ConfigurationValues VALUES (NULL, 'Group_SortOrder', 'asc', 'In-Portal', '');
INSERT INTO ConfigurationValues VALUES (NULL, 'Default_FromName', 'Webmaster', 'In-Portal', '');
INSERT INTO ConfigurationValues VALUES (NULL, 'Perpage_Category', '10', 'In-Portal', 'in-portal:configure_categories');
INSERT INTO ConfigurationValues VALUES (NULL, 'Category_Sortfield', 'Name', 'In-Portal', 'in-portal:configure_categories');
INSERT INTO ConfigurationValues VALUES (NULL, 'Category_Sortorder', 'asc', 'In-Portal', 'in-portal:configure_categories');
INSERT INTO ConfigurationValues VALUES (NULL, 'MetaKeywords', NULL, 'In-Portal', 'in-portal:configure_general');
INSERT INTO ConfigurationValues VALUES (NULL, 'Relation_LV_Sortfield', 'ItemType', 'In-Portal', '');
INSERT INTO ConfigurationValues VALUES (NULL, 'ampm_time', '1', 'In-Portal', '');
INSERT INTO ConfigurationValues VALUES (NULL, 'Perpage_Template', '10', 'In-Portal', '');
INSERT INTO ConfigurationValues VALUES (NULL, 'Perpage_Phrase', '40', 'In-Portal', '');
INSERT INTO ConfigurationValues VALUES (NULL, 'Perpage_Sessionlist', '20', 'In-Portal', '');
INSERT INTO ConfigurationValues VALUES (NULL, 'Category_Sortfield2', 'Description', 'In-Portal', 'in-portal:configure_categories');
INSERT INTO ConfigurationValues VALUES (NULL, 'Category_Sortorder2', 'asc', 'In-Portal', 'in-portal:configure_categories');
INSERT INTO ConfigurationValues VALUES (NULL, 'Category_DaysNew', '8', 'In-Portal', 'in-portal:configure_categories');
INSERT INTO ConfigurationValues VALUES (NULL, 'Category_ShowPick', '', 'In-Portal', 'in-portal:configure_categories');
INSERT INTO ConfigurationValues VALUES (NULL, 'Category_MetaKey', '', 'In-Portal', 'in-portal:configure_categories');
INSERT INTO ConfigurationValues VALUES (NULL, 'Category_MetaDesc', '', 'In-Portal', 'in-portal:configure_categories');
INSERT INTO ConfigurationValues VALUES (NULL, 'MetaDescription', NULL, 'In-Portal', 'in-portal:configure_general');
INSERT INTO ConfigurationValues VALUES (NULL, 'User_NewGroup', '13', 'In-Portal:Users', 'in-portal:configure_users');
INSERT INTO ConfigurationValues VALUES (NULL, 'User_Allow_New', '3', 'In-Portal:Users', 'in-portal:configure_users');
INSERT INTO ConfigurationValues VALUES (NULL, 'User_Password_Auto', '0', 'In-Portal:Users', 'in-portal:configure_users');
INSERT INTO ConfigurationValues VALUES (NULL, 'User_Votes_Deny', '5', 'In-Portal:Users', 'in-portal:configure_users');
INSERT INTO ConfigurationValues VALUES (NULL, 'User_Review_Deny', '5', 'In-Portal:Users', 'in-portal:configure_users');
INSERT INTO ConfigurationValues VALUES (NULL, 'Config_Name', '', 'In-Portal', 'in-portal:configure_general');
INSERT INTO ConfigurationValues VALUES (NULL, 'Config_Company', '', 'In-Portal', 'in-portal:configure_general');
INSERT INTO ConfigurationValues VALUES (NULL, 'Config_Reg_Number', '', 'In-Portal', 'in-portal:configure_general');
INSERT INTO ConfigurationValues VALUES (NULL, 'Config_Website_Name', '', 'In-Portal', 'in-portal:configure_general');
INSERT INTO ConfigurationValues VALUES (NULL, 'Config_Web_Address', '', 'In-Portal', 'in-portal:configure_general');
INSERT INTO ConfigurationValues VALUES (NULL, 'Config_Server_Time', '14', 'In-Portal', 'in-portal:configure_general');
INSERT INTO ConfigurationValues VALUES (NULL, 'Config_Site_Time', '14', 'In-Portal', 'in-portal:configure_general');
INSERT INTO ConfigurationValues VALUES (NULL, 'Site_Name', 'In-Portal', 'In-Portal', 'in-portal:configure_general');
INSERT INTO ConfigurationValues VALUES (NULL, 'Backup_Path', '', 'In-Portal', 'in-portal:configure_general');
INSERT INTO ConfigurationValues VALUES (NULL, 'Perpage_Items', '20', 'In-Portal', '');
INSERT INTO ConfigurationValues VALUES (NULL, 'GuestSessions', '1', 'In-Portal', '');
INSERT INTO ConfigurationValues VALUES (NULL, 'Smtp_Server', NULL, 'In-Portal', 'in-portal:configure_general');
INSERT INTO ConfigurationValues VALUES (NULL, 'Smtp_Port', NULL, 'In-Portal', 'in-portal:configure_general');
INSERT INTO ConfigurationValues VALUES (NULL, 'Smtp_User', NULL, 'In-Portal', 'in-portal:configure_general');
INSERT INTO ConfigurationValues VALUES (NULL, 'Smtp_Pass', NULL, 'In-Portal', 'in-portal:configure_general');
INSERT INTO ConfigurationValues VALUES (NULL, 'Smtp_SendHTML', '1', 'In-Portal', 'in-portal:configure_general');
INSERT INTO ConfigurationValues VALUES (NULL, 'Smtp_Authenticate', '0', 'In-Portal', 'in-portal:configure_general');
INSERT INTO ConfigurationValues VALUES (NULL, 'Perpage_Email', '10', 'In-Portal', '');
INSERT INTO ConfigurationValues VALUES (NULL, 'Smtp_DefaultHeaders', 'X-Priority: 1\r\nX-MSMail-Priority: High\r\nX-Mailer: In-Portal', 'In-Portal', 'in-portal:configure_general');
INSERT INTO ConfigurationValues VALUES (NULL, 'Smtp_AdminMailFrom', 'portal@user.domain.name', 'In-Portal', 'in-portal:configure_general');
INSERT INTO ConfigurationValues VALUES (NULL, 'Category_Highlight_OpenTag', '<span class="match">', 'In-Portal', 'in-portal:configure_categories');
INSERT INTO ConfigurationValues VALUES (NULL, 'Category_Highlight_CloseTag', '</span>', 'In-Portal', 'in-portal:configure_categories');
INSERT INTO ConfigurationValues VALUES (NULL, 'User_GuestGroup', '14', 'In-Portal:Users', 'in-portal:configure_users');
INSERT INTO ConfigurationValues VALUES (NULL, 'RootPass', '', 'In-Portal:Users', 'in-portal:configure_users');
INSERT INTO ConfigurationValues VALUES (NULL, 'Perpage_Category_Short', '3', 'In-Portal', 'in-portal:configure_categories');
INSERT INTO ConfigurationValues VALUES (NULL, 'CookieSessions', '2', 'In-Portal', 'in-portal:configure_general');
INSERT INTO ConfigurationValues VALUES (NULL, 'SearchRel_Increase_category', '30', 'In-Portal', 'in-portal:configuration_search');
INSERT INTO ConfigurationValues VALUES (NULL, 'SearchRel_Keyword_category', '90', 'In-Portal', 'in-portal:configuration_search');
INSERT INTO ConfigurationValues VALUES (NULL, 'SearchRel_Pop_category', '5', 'In-Portal', 'in-portal:configuration_search');
INSERT INTO ConfigurationValues VALUES (NULL, 'SearchRel_Rating_category', '5', 'In-Portal', 'in-portal:configuration_search');
INSERT INTO ConfigurationValues VALUES (NULL, 'SearchRel_DefaultIncrease', '30', 'In-Portal', 'inportal:configure_searchdefault');
INSERT INTO ConfigurationValues VALUES (NULL, 'SearchRel_DefaultKeyword', '80', 'In-Portal', 'SearchRel_DefaultKeyword');
INSERT INTO ConfigurationValues VALUES (NULL, 'SearchRel_DefaultPop', '10', 'In-Portal', 'inportal:configuration_searchdefault');
INSERT INTO ConfigurationValues VALUES (NULL, 'SearchRel_DefaultRating', '10', 'In-Portal', 'inportal:configure_searchdefault');
INSERT INTO ConfigurationValues VALUES (NULL, 'SystemTagCache', '0', 'In-Portal', 'in-portal:configure_general');
INSERT INTO ConfigurationValues VALUES (NULL, 'Root_Name', 'lu_rootcategory_name', 'In-Portal', 'in-portal:configure_categories');
INSERT INTO ConfigurationValues VALUES (NULL, 'User_SubscriberGroup', '12', 'In-Portal:Users', 'in-portal:configure_users');
INSERT INTO ConfigurationValues VALUES (NULL, 'SocketBlockingMode', '0', 'In-Portal', 'in-portal:configure_general');
INSERT INTO ConfigurationValues VALUES (NULL, 'Min_UserName', '3', 'In-Portal:Users', 'in-portal:configure_users');
INSERT INTO ConfigurationValues VALUES (NULL, 'Min_Password', '5', 'In-Portal:Users', 'in-portal:configure_users');
INSERT INTO ConfigurationValues VALUES (NULL, 'LinksValidation_LV_Sortfield', 'ValidationTime', 'In-Portal', '');
INSERT INTO ConfigurationValues VALUES (NULL, 'CustomConfig_LV_Sortfield', 'FieldName', 'In-Portal', '');
INSERT INTO ConfigurationValues VALUES (NULL, 'Event_LV_SortField', 'Description', 'In-Portal', '');
INSERT INTO ConfigurationValues VALUES (NULL, 'Theme_LV_SortField', 'Name', 'In-Portal', '');
INSERT INTO ConfigurationValues VALUES (NULL, 'Template_LV_SortField', 'FileName', 'In-Portal', '');
INSERT INTO ConfigurationValues VALUES (NULL, 'Lang_LV_SortField', 'PackName', 'In-Portal', '');
INSERT INTO ConfigurationValues VALUES (NULL, 'Phrase_LV_SortField', 'Phrase', 'In-Portal', '');
INSERT INTO ConfigurationValues VALUES (NULL, 'LangEmail_LV_SortField', 'Description', 'In-Portal', '');
INSERT INTO ConfigurationValues VALUES (NULL, 'CustomData_LV_SortField', 'FieldName', 'In-Portal', '');
INSERT INTO ConfigurationValues VALUES (NULL, 'Summary_SortField', 'Module', 'In-Portal', '');
INSERT INTO ConfigurationValues VALUES (NULL, 'Session_SortField', 'UserName', 'In-Portal', '');
INSERT INTO ConfigurationValues VALUES (NULL, 'SearchLog_SortField', 'Keyword', 'In-Portal', '');
INSERT INTO ConfigurationValues VALUES (NULL, 'Perpage_StatItem', '10', 'inportal', '');
INSERT INTO ConfigurationValues VALUES (NULL, 'Perpage_Groups', '20', 'In-Portal', '');
INSERT INTO ConfigurationValues VALUES (NULL, 'Perpage_Event', '20', 'In-Portal', '');
INSERT INTO ConfigurationValues VALUES (NULL, 'Perpage_BanRules', '20', 'In-Portal', '');
INSERT INTO ConfigurationValues VALUES (NULL, 'Perpage_SearchLog', '20', 'In-Portal', '');
INSERT INTO ConfigurationValues VALUES (NULL, 'Perpage_LV_lang', '20', 'In-Portal', '');
INSERT INTO ConfigurationValues VALUES (NULL, 'Perpage_LV_Themes', '20', 'In-Portal', '');
INSERT INTO ConfigurationValues VALUES (NULL, 'Perpage_LV_Catlist', '20', 'In-Portal', '');
INSERT INTO ConfigurationValues VALUES (NULL, 'Perpage_Reviews', '20', 'In-Portal', '');
INSERT INTO ConfigurationValues VALUES (NULL, 'Perpage_Modules', '20', 'In-Portal', '');
INSERT INTO ConfigurationValues VALUES (NULL, 'Perpage_Grouplist', '20', 'In-Portal', '');
INSERT INTO ConfigurationValues VALUES (NULL, 'Perpage_Images', '20', 'In-Portal', '');
INSERT INTO ConfigurationValues VALUES (NULL, 'EmailsL_SortField', 'time_sent', 'In-Portal', '');
INSERT INTO ConfigurationValues VALUES (NULL, 'Perpage_EmailsL', '20', 'In-Portal', '');
INSERT INTO ConfigurationValues VALUES (NULL, 'Perpage_CustomData', '20', 'In-Portal', '');
INSERT INTO ConfigurationValues VALUES (NULL, 'Perpage_Review', '10', 'In-Portal', '');
INSERT INTO ConfigurationValues VALUES (NULL, 'Search_MinKeyword_Length', '3', 'In-Portal', '');
INSERT INTO ConfigurationValues VALUES (NULL, 'Users_AllowReset', '180', 'In-Portal:Users', 'in-portal:configure_users');
INSERT INTO ConfigurationValues VALUES (NULL, 'Email_As_Login', '0', 'In-Portal:Users', 'in-portal:configure_users');
INSERT INTO ConfigurationValues VALUES (NULL, 'RegistrationCaptcha', '0', 'In-Portal:Users', 'in-portal:configure_users');
INSERT INTO ConfigurationValues VALUES (NULL, 'User_LoggedInGroup', '15', 'In-Portal:Users', 'in-portal:configure_users');
INSERT INTO ConfigurationValues VALUES (NULL, 'User_MembershipExpirationReminder', '10', 'In-Portal:Users', 'in-portal:configure_users');
INSERT INTO ConfigurationValues VALUES (NULL, 'FirstDayOfWeek', '1', 'In-Portal', 'in-portal:configure_general');
INSERT INTO ConfigurationValues VALUES (NULL, 'SSL_URL', '', 'In-Portal', 'in-portal:configure_general');
INSERT INTO ConfigurationValues VALUES (NULL, 'Require_SSL', '', 'In-Portal', 'in-portal:configure_general');
INSERT INTO ConfigurationValues VALUES (NULL, 'Force_HTTP_When_SSL_Not_Required', '1', 'In-Portal', 'in-portal:configure_general');
INSERT INTO ConfigurationValues VALUES (NULL, 'SessionCookieName', 'sid', 'In-Portal', 'in-portal:configure_general');
INSERT INTO ConfigurationValues VALUES (NULL, 'UseModRewrite', '0', 'In-Portal', 'in-portal:configure_general');
INSERT INTO ConfigurationValues VALUES (NULL, 'UseModRewriteWithSSL', '0', 'In-Portal', 'in-portal:configure_general');
INSERT INTO ConfigurationValues VALUES (NULL, 'SessionReferrerCheck', '1', 'In-Portal', 'in-portal:configure_general');
INSERT INTO ConfigurationValues VALUES (NULL, 'ErrorTemplate', 'error_notfound', 'In-Portal', 'in-portal:configure_general');
INSERT INTO ConfigurationValues VALUES (NULL, 'UseJSRedirect', '0', 'In-Portal', 'in-portal:configure_general');
INSERT INTO ConfigurationValues VALUES (NULL, 'MaxImportCategoryLevels', '10', 'In-Portal', 'in-portal:configure_categories');
INSERT INTO ConfigurationValues VALUES (NULL, 'UseCronForRegularEvent', '0', 'In-Portal', 'in-portal:configure_general');
INSERT INTO ConfigurationValues VALUES (NULL, 'NoPermissionTemplate', 'no_permission', 'In-Portal', 'in-portal:configure_general');
INSERT INTO ConfigurationValues (VariableName, VariableValue, ModuleOwner, Section) VALUES ('UseOutputCompression', '0', 'In-Portal', 'in-portal:configure_general');
INSERT INTO ConfigurationValues (VariableName, VariableValue, ModuleOwner, Section) VALUES ('OutputCompressionLevel', '7', 'In-Portal', 'in-portal:configure_general');
+INSERT INTO ConfigurationValues VALUES (0, 'MailFunctionHeaderSeparator', 1, 'In-Portal', 'in-portal:configure_general');
INSERT INTO Events VALUES (30, 'USER.ADD', 1, 0, 'In-Portal:Users', 'la_event_user.add', 0);
INSERT INTO Events VALUES (32, 'USER.ADD', 2, 0, 'In-Portal:Users', 'la_event_user.add', 1);
INSERT INTO Events VALUES (31, 'USER.APPROVE', 1, 0, 'In-Portal:Users', 'la_event_user.approve', 0);
INSERT INTO Events VALUES (33, 'USER.APPROVE', 2, 0, 'In-Portal:Users', 'la_event_user.approve', 1);
INSERT INTO Events VALUES (34, 'USER.VALIDATE', 1, 0, 'In-Portal:Users', 'la_event_user.validate', 0);
INSERT INTO Events VALUES (35, 'USER.VALIDATE', 2, 0, 'In-Portal:Users', 'la_event_user.validate', 1);
INSERT INTO Events VALUES (36, 'USER.DENY', 1, 0, 'In-Portal:Users', 'la_event_user.deny', 0);
INSERT INTO Events VALUES (37, 'USER.DENY', 2, 0, 'In-Portal:Users', 'la_event_user.deny', 1);
INSERT INTO Events VALUES (38, 'USER.PSWD', 2, 0, 'In-Portal:Users', 'la_event_user.forgotpw', 1);
INSERT INTO Events VALUES (39, 'USER.PSWD', 1, 0, 'In-Portal:Users', 'la_event_user.forgotpw', 0);
INSERT INTO Events VALUES (45, 'USER.ADD.PENDING', 1, 0, 'In-Portal:Users', 'la_event_user.add.pending', 0);
INSERT INTO Events VALUES (68, 'USER.ADD.PENDING', 2, 0, 'In-Portal:Users', 'la_event_user.add.pending', 1);
INSERT INTO Events VALUES (47, 'CATEGORY.ADD', 1, 0, 'In-Portal:Category', 'la_event_category.add', 0);
INSERT INTO Events VALUES (48, 'CATEGORY.ADD.PENDING', 1, 0, 'In-Portal:Category', 'la_event_category.add.pending', 0);
INSERT INTO Events VALUES (49, 'CATEGORY.ADD.PENDING', 2, 0, 'In-Portal:Category', 'la_event_category.add.pending', 1);
INSERT INTO Events VALUES (50, 'CATEGORY.ADD', 2, 0, 'In-Portal:Category', 'la_event_category.add', 1);
INSERT INTO Events VALUES (51, 'CATEGORY.DELETE', 1, 0, 'In-Portal:Category', 'la_event_category_delete', 0);
INSERT INTO Events VALUES (52, 'CATEGORY.DELETE', 2, 0, 'In-Portal:Category', 'la_event_category_delete', 1);
INSERT INTO Events VALUES (53, 'CATEGORY.MODIFY', 1, 0, 'In-Portal:Category', 'la_event_category.modify', 0);
INSERT INTO Events VALUES (54, 'CATEGORY.MODIFY', 2, 0, 'In-Portal:Category', 'la_event_category.modify', 1);
INSERT INTO Events VALUES (56, 'CATEGORY.APPROVE', 1, 0, 'In-Portal:Category', 'la_event_category.approve', 0);
INSERT INTO Events VALUES (57, 'CATEGORY.APPROVE', 2, 0, 'In-Portal:Category', 'la_event_category.approve', 1);
INSERT INTO Events VALUES (58, 'CATEGORY.DENY', 1, 0, 'In-Portal:Category', 'la_event_category.deny', 0);
INSERT INTO Events VALUES (59, 'CATEGORY.DENY', 2, 0, 'In-Portal:Category', 'la_event_category.deny', 1);
INSERT INTO Events VALUES (60, 'USER.SUBSCRIBE', 1, 0, 'In-Portal:Users', 'la_event_user.subscribe', 0);
INSERT INTO Events VALUES (61, 'USER.SUBSCRIBE', 2, 0, 'In-Portal:Users', 'la_event_user.subscribe', 1);
INSERT INTO Events VALUES (62, 'USER.UNSUBSCRIBE', 1, 0, 'In-Portal:Users', 'la_event_user.unsubscribe', 0);
INSERT INTO Events VALUES (63, 'USER.UNSUBSCRIBE', 2, 0, 'In-Portal:Users', 'la_event_user.unsubscribe', 1);
INSERT INTO Events VALUES (64, 'USER.SUGGEST', '1', '0', 'In-Portal:Users', 'la_event_user.suggest', '0');
INSERT INTO Events VALUES (65, 'USER.SUGGEST', '2', '0', 'In-Portal:Users', 'la_event_user.suggest', '1');
INSERT INTO Events VALUES (67, 'USER.PSWDC', '1', '0', 'In-Portal:Users', 'la_event_user.pswd_confirm', '0');
INSERT INTO Events VALUES ('', 'USER.MEMBERSHIP.EXPIRED', '1', '0', 'In-Portal:Users', 'la_event_user.membership_expired', '0');
INSERT INTO Events VALUES ('', 'USER.MEMBERSHIP.EXPIRED', '1', '0', 'In-Portal:Users', 'la_event_user.membership_expired', '1');
INSERT INTO Events VALUES ('', 'USER.MEMBERSHIP.EXPIRATION.NOTICE', '1', '0', 'In-Portal:Users', 'la_event_user.membership_expiration_notice', '0');
INSERT INTO Events VALUES ('', 'USER.MEMBERSHIP.EXPIRATION.NOTICE', '1', '0', 'In-Portal:Users', 'la_event_user.membership_expiration_notice', '1');
INSERT INTO Events (Event, Enabled, FromUserId, Module, Description, Type) VALUES ('COMMON.FOOTER', 1, 0, 'In-Portal', 'la_event_common.footer', 1);
INSERT INTO IdGenerator VALUES ('100');
INSERT INTO PortalGroup VALUES (15, 'Everyone', 'Everyone', 0, 1, 0, 1, 15);
INSERT INTO PortalGroup VALUES (13, 'Member', '', '1054738682', 0, 0, 1, 13);
INSERT INTO PortalGroup VALUES (12, 'Subscribers', '', '1054738670', 0, 0, 1, 12);
INSERT INTO PortalGroup VALUES (14, 'Guest', 'Guest User', '0', 1, 0, 1, 14);
INSERT INTO PortalGroup VALUES (11, 'admin', '', '1054738405', 0, 0, 1, 11);
INSERT INTO StdDestinations VALUES (1, 1, NULL, 'la_country_AFG', 'AFG', 'AF');
INSERT INTO StdDestinations VALUES (2, 1, NULL, 'la_country_ALB', 'ALB', 'AL');
INSERT INTO StdDestinations VALUES (3, 1, NULL, 'la_country_DZA', 'DZA', 'DZ');
INSERT INTO StdDestinations VALUES (4, 1, NULL, 'la_country_ASM', 'ASM', 'AS');
INSERT INTO StdDestinations VALUES (5, 1, NULL, 'la_country_AND', 'AND', 'AD');
INSERT INTO StdDestinations VALUES (6, 1, NULL, 'la_country_AGO', 'AGO', 'AO');
INSERT INTO StdDestinations VALUES (7, 1, NULL, 'la_country_AIA', 'AIA', 'AI');
INSERT INTO StdDestinations VALUES (8, 1, NULL, 'la_country_ATA', 'ATA', 'AQ');
INSERT INTO StdDestinations VALUES (9, 1, NULL, 'la_country_ATG', 'ATG', 'AG');
INSERT INTO StdDestinations VALUES (10, 1, NULL, 'la_country_ARG', 'ARG', 'AR');
INSERT INTO StdDestinations VALUES (11, 1, NULL, 'la_country_ARM', 'ARM', 'AM');
INSERT INTO StdDestinations VALUES (12, 1, NULL, 'la_country_ABW', 'ABW', 'AW');
INSERT INTO StdDestinations VALUES (13, 1, NULL, 'la_country_AUS', 'AUS', 'AU');
INSERT INTO StdDestinations VALUES (14, 1, NULL, 'la_country_AUT', 'AUT', 'AT');
INSERT INTO StdDestinations VALUES (15, 1, NULL, 'la_country_AZE', 'AZE', 'AZ');
INSERT INTO StdDestinations VALUES (16, 1, NULL, 'la_country_BHS', 'BHS', 'BS');
INSERT INTO StdDestinations VALUES (17, 1, NULL, 'la_country_BHR', 'BHR', 'BH');
INSERT INTO StdDestinations VALUES (18, 1, NULL, 'la_country_BGD', 'BGD', 'BD');
INSERT INTO StdDestinations VALUES (19, 1, NULL, 'la_country_BRB', 'BRB', 'BB');
INSERT INTO StdDestinations VALUES (20, 1, NULL, 'la_country_BLR', 'BLR', 'BY');
INSERT INTO StdDestinations VALUES (21, 1, NULL, 'la_country_BEL', 'BEL', 'BE');
INSERT INTO StdDestinations VALUES (22, 1, NULL, 'la_country_BLZ', 'BLZ', 'BZ');
INSERT INTO StdDestinations VALUES (23, 1, NULL, 'la_country_BEN', 'BEN', 'BJ');
INSERT INTO StdDestinations VALUES (24, 1, NULL, 'la_country_BMU', 'BMU', 'BM');
INSERT INTO StdDestinations VALUES (25, 1, NULL, 'la_country_BTN', 'BTN', 'BT');
INSERT INTO StdDestinations VALUES (26, 1, NULL, 'la_country_BOL', 'BOL', 'BO');
INSERT INTO StdDestinations VALUES (27, 1, NULL, 'la_country_BIH', 'BIH', 'BA');
INSERT INTO StdDestinations VALUES (28, 1, NULL, 'la_country_BWA', 'BWA', 'BW');
INSERT INTO StdDestinations VALUES (29, 1, NULL, 'la_country_BVT', 'BVT', 'BV');
INSERT INTO StdDestinations VALUES (30, 1, NULL, 'la_country_BRA', 'BRA', 'BR');
INSERT INTO StdDestinations VALUES (31, 1, NULL, 'la_country_IOT', 'IOT', 'IO');
INSERT INTO StdDestinations VALUES (32, 1, NULL, 'la_country_BRN', 'BRN', 'BN');
INSERT INTO StdDestinations VALUES (33, 1, NULL, 'la_country_BGR', 'BGR', 'BG');
INSERT INTO StdDestinations VALUES (34, 1, NULL, 'la_country_BFA', 'BFA', 'BF');
INSERT INTO StdDestinations VALUES (35, 1, NULL, 'la_country_BDI', 'BDI', 'BI');
INSERT INTO StdDestinations VALUES (36, 1, NULL, 'la_country_KHM', 'KHM', 'KH');
INSERT INTO StdDestinations VALUES (37, 1, NULL, 'la_country_CMR', 'CMR', 'CM');
INSERT INTO StdDestinations VALUES (38, 1, NULL, 'la_country_CAN', 'CAN', 'CA');
INSERT INTO StdDestinations VALUES (39, 1, NULL, 'la_country_CPV', 'CPV', 'CV');
INSERT INTO StdDestinations VALUES (40, 1, NULL, 'la_country_CYM', 'CYM', 'KY');
INSERT INTO StdDestinations VALUES (41, 1, NULL, 'la_country_CAF', 'CAF', 'CF');
INSERT INTO StdDestinations VALUES (42, 1, NULL, 'la_country_TCD', 'TCD', 'TD');
INSERT INTO StdDestinations VALUES (43, 1, NULL, 'la_country_CHL', 'CHL', 'CL');
INSERT INTO StdDestinations VALUES (44, 1, NULL, 'la_country_CHN', 'CHN', 'CN');
INSERT INTO StdDestinations VALUES (45, 1, NULL, 'la_country_CXR', 'CXR', 'CX');
INSERT INTO StdDestinations VALUES (46, 1, NULL, 'la_country_CCK', 'CCK', 'CC');
INSERT INTO StdDestinations VALUES (47, 1, NULL, 'la_country_COL', 'COL', 'CO');
INSERT INTO StdDestinations VALUES (48, 1, NULL, 'la_country_COM', 'COM', 'KM');
INSERT INTO StdDestinations VALUES (49, 1, NULL, 'la_country_COD', 'COD', 'CD');
INSERT INTO StdDestinations VALUES (50, 1, NULL, 'la_country_COG', 'COG', 'CG');
INSERT INTO StdDestinations VALUES (51, 1, NULL, 'la_country_COK', 'COK', 'CK');
INSERT INTO StdDestinations VALUES (52, 1, NULL, 'la_country_CRI', 'CRI', 'CR');
INSERT INTO StdDestinations VALUES (53, 1, NULL, 'la_country_CIV', 'CIV', 'CI');
INSERT INTO StdDestinations VALUES (54, 1, NULL, 'la_country_HRV', 'HRV', 'HR');
INSERT INTO StdDestinations VALUES (55, 1, NULL, 'la_country_CUB', 'CUB', 'CU');
INSERT INTO StdDestinations VALUES (56, 1, NULL, 'la_country_CYP', 'CYP', 'CY');
INSERT INTO StdDestinations VALUES (57, 1, NULL, 'la_country_CZE', 'CZE', 'CZ');
INSERT INTO StdDestinations VALUES (58, 1, NULL, 'la_country_DNK', 'DNK', 'DK');
INSERT INTO StdDestinations VALUES (59, 1, NULL, 'la_country_DJI', 'DJI', 'DJ');
INSERT INTO StdDestinations VALUES (60, 1, NULL, 'la_country_DMA', 'DMA', 'DM');
INSERT INTO StdDestinations VALUES (61, 1, NULL, 'la_country_DOM', 'DOM', 'DO');
INSERT INTO StdDestinations VALUES (62, 1, NULL, 'la_country_TLS', 'TLS', 'TL');
INSERT INTO StdDestinations VALUES (63, 1, NULL, 'la_country_ECU', 'ECU', 'EC');
INSERT INTO StdDestinations VALUES (64, 1, NULL, 'la_country_EGY', 'EGY', 'EG');
INSERT INTO StdDestinations VALUES (65, 1, NULL, 'la_country_SLV', 'SLV', 'SV');
INSERT INTO StdDestinations VALUES (66, 1, NULL, 'la_country_GNQ', 'GNQ', 'GQ');
INSERT INTO StdDestinations VALUES (67, 1, NULL, 'la_country_ERI', 'ERI', 'ER');
INSERT INTO StdDestinations VALUES (68, 1, NULL, 'la_country_EST', 'EST', 'EE');
INSERT INTO StdDestinations VALUES (69, 1, NULL, 'la_country_ETH', 'ETH', 'ET');
INSERT INTO StdDestinations VALUES (70, 1, NULL, 'la_country_FLK', 'FLK', 'FK');
INSERT INTO StdDestinations VALUES (71, 1, NULL, 'la_country_FRO', 'FRO', 'FO');
INSERT INTO StdDestinations VALUES (72, 1, NULL, 'la_country_FJI', 'FJI', 'FJ');
INSERT INTO StdDestinations VALUES (73, 1, NULL, 'la_country_FIN', 'FIN', 'FI');
INSERT INTO StdDestinations VALUES (74, 1, NULL, 'la_country_FRA', 'FRA', 'FR');
INSERT INTO StdDestinations VALUES (75, 1, NULL, 'la_country_FXX', 'FXX', 'FX');
INSERT INTO StdDestinations VALUES (76, 1, NULL, 'la_country_GUF', 'GUF', 'GF');
INSERT INTO StdDestinations VALUES (77, 1, NULL, 'la_country_PYF', 'PYF', 'PF');
INSERT INTO StdDestinations VALUES (78, 1, NULL, 'la_country_ATF', 'ATF', 'TF');
INSERT INTO StdDestinations VALUES (79, 1, NULL, 'la_country_GAB', 'GAB', 'GA');
INSERT INTO StdDestinations VALUES (80, 1, NULL, 'la_country_GMB', 'GMB', 'GM');
INSERT INTO StdDestinations VALUES (81, 1, NULL, 'la_country_GEO', 'GEO', 'GE');
INSERT INTO StdDestinations VALUES (82, 1, NULL, 'la_country_DEU', 'DEU', 'DE');
INSERT INTO StdDestinations VALUES (83, 1, NULL, 'la_country_GHA', 'GHA', 'GH');
INSERT INTO StdDestinations VALUES (84, 1, NULL, 'la_country_GIB', 'GIB', 'GI');
INSERT INTO StdDestinations VALUES (85, 1, NULL, 'la_country_GRC', 'GRC', 'GR');
INSERT INTO StdDestinations VALUES (86, 1, NULL, 'la_country_GRL', 'GRL', 'GL');
INSERT INTO StdDestinations VALUES (87, 1, NULL, 'la_country_GRD', 'GRD', 'GD');
INSERT INTO StdDestinations VALUES (88, 1, NULL, 'la_country_GLP', 'GLP', 'GP');
INSERT INTO StdDestinations VALUES (89, 1, NULL, 'la_country_GUM', 'GUM', 'GU');
INSERT INTO StdDestinations VALUES (90, 1, NULL, 'la_country_GTM', 'GTM', 'GT');
INSERT INTO StdDestinations VALUES (91, 1, NULL, 'la_country_GIN', 'GIN', 'GN');
INSERT INTO StdDestinations VALUES (92, 1, NULL, 'la_country_GNB', 'GNB', 'GW');
INSERT INTO StdDestinations VALUES (93, 1, NULL, 'la_country_GUY', 'GUY', 'GY');
INSERT INTO StdDestinations VALUES (94, 1, NULL, 'la_country_HTI', 'HTI', 'HT');
INSERT INTO StdDestinations VALUES (95, 1, NULL, 'la_country_HMD', 'HMD', 'HM');
INSERT INTO StdDestinations VALUES (96, 1, NULL, 'la_country_HND', 'HND', 'HN');
INSERT INTO StdDestinations VALUES (97, 1, NULL, 'la_country_HKG', 'HKG', 'HK');
INSERT INTO StdDestinations VALUES (98, 1, NULL, 'la_country_HUN', 'HUN', 'HU');
INSERT INTO StdDestinations VALUES (99, 1, NULL, 'la_country_ISL', 'ISL', 'IS');
INSERT INTO StdDestinations VALUES (100, 1, NULL, 'la_country_IND', 'IND', 'IN');
INSERT INTO StdDestinations VALUES (101, 1, NULL, 'la_country_IDN', 'IDN', 'ID');
INSERT INTO StdDestinations VALUES (102, 1, NULL, 'la_country_IRN', 'IRN', 'IR');
INSERT INTO StdDestinations VALUES (103, 1, NULL, 'la_country_IRQ', 'IRQ', 'IQ');
INSERT INTO StdDestinations VALUES (104, 1, NULL, 'la_country_IRL', 'IRL', 'IE');
INSERT INTO StdDestinations VALUES (105, 1, NULL, 'la_country_ISR', 'ISR', 'IL');
INSERT INTO StdDestinations VALUES (106, 1, NULL, 'la_country_ITA', 'ITA', 'IT');
INSERT INTO StdDestinations VALUES (107, 1, NULL, 'la_country_JAM', 'JAM', 'JM');
INSERT INTO StdDestinations VALUES (108, 1, NULL, 'la_country_JPN', 'JPN', 'JP');
INSERT INTO StdDestinations VALUES (109, 1, NULL, 'la_country_JOR', 'JOR', 'JO');
INSERT INTO StdDestinations VALUES (110, 1, NULL, 'la_country_KAZ', 'KAZ', 'KZ');
INSERT INTO StdDestinations VALUES (111, 1, NULL, 'la_country_KEN', 'KEN', 'KE');
INSERT INTO StdDestinations VALUES (112, 1, NULL, 'la_country_KIR', 'KIR', 'KI');
INSERT INTO StdDestinations VALUES (113, 1, NULL, 'la_country_PRK', 'PRK', 'KP');
INSERT INTO StdDestinations VALUES (114, 1, NULL, 'la_country_KOR', 'KOR', 'KR');
INSERT INTO StdDestinations VALUES (115, 1, NULL, 'la_country_KWT', 'KWT', 'KW');
INSERT INTO StdDestinations VALUES (116, 1, NULL, 'la_country_KGZ', 'KGZ', 'KG');
INSERT INTO StdDestinations VALUES (117, 1, NULL, 'la_country_LAO', 'LAO', 'LA');
INSERT INTO StdDestinations VALUES (118, 1, NULL, 'la_country_LVA', 'LVA', 'LV');
INSERT INTO StdDestinations VALUES (119, 1, NULL, 'la_country_LBN', 'LBN', 'LB');
INSERT INTO StdDestinations VALUES (120, 1, NULL, 'la_country_LSO', 'LSO', 'LS');
INSERT INTO StdDestinations VALUES (121, 1, NULL, 'la_country_LBR', 'LBR', 'LR');
INSERT INTO StdDestinations VALUES (122, 1, NULL, 'la_country_LBY', 'LBY', 'LY');
INSERT INTO StdDestinations VALUES (123, 1, NULL, 'la_country_LIE', 'LIE', 'LI');
INSERT INTO StdDestinations VALUES (124, 1, NULL, 'la_country_LTU', 'LTU', 'LT');
INSERT INTO StdDestinations VALUES (125, 1, NULL, 'la_country_LUX', 'LUX', 'LU');
INSERT INTO StdDestinations VALUES (126, 1, NULL, 'la_country_MAC', 'MAC', 'MO');
INSERT INTO StdDestinations VALUES (127, 1, NULL, 'la_country_MKD', 'MKD', 'MK');
INSERT INTO StdDestinations VALUES (128, 1, NULL, 'la_country_MDG', 'MDG', 'MG');
INSERT INTO StdDestinations VALUES (129, 1, NULL, 'la_country_MWI', 'MWI', 'MW');
INSERT INTO StdDestinations VALUES (130, 1, NULL, 'la_country_MYS', 'MYS', 'MY');
INSERT INTO StdDestinations VALUES (131, 1, NULL, 'la_country_MDV', 'MDV', 'MV');
INSERT INTO StdDestinations VALUES (132, 1, NULL, 'la_country_MLI', 'MLI', 'ML');
INSERT INTO StdDestinations VALUES (133, 1, NULL, 'la_country_MLT', 'MLT', 'MT');
INSERT INTO StdDestinations VALUES (134, 1, NULL, 'la_country_MHL', 'MHL', 'MH');
INSERT INTO StdDestinations VALUES (135, 1, NULL, 'la_country_MTQ', 'MTQ', 'MQ');
INSERT INTO StdDestinations VALUES (136, 1, NULL, 'la_country_MRT', 'MRT', 'MR');
INSERT INTO StdDestinations VALUES (137, 1, NULL, 'la_country_MUS', 'MUS', 'MU');
INSERT INTO StdDestinations VALUES (138, 1, NULL, 'la_country_MYT', 'MYT', 'YT');
INSERT INTO StdDestinations VALUES (139, 1, NULL, 'la_country_MEX', 'MEX', 'MX');
INSERT INTO StdDestinations VALUES (140, 1, NULL, 'la_country_FSM', 'FSM', 'FM');
INSERT INTO StdDestinations VALUES (141, 1, NULL, 'la_country_MDA', 'MDA', 'MD');
INSERT INTO StdDestinations VALUES (142, 1, NULL, 'la_country_MCO', 'MCO', 'MC');
INSERT INTO StdDestinations VALUES (143, 1, NULL, 'la_country_MNG', 'MNG', 'MN');
INSERT INTO StdDestinations VALUES (144, 1, NULL, 'la_country_MSR', 'MSR', 'MS');
INSERT INTO StdDestinations VALUES (145, 1, NULL, 'la_country_MAR', 'MAR', 'MA');
INSERT INTO StdDestinations VALUES (146, 1, NULL, 'la_country_MOZ', 'MOZ', 'MZ');
INSERT INTO StdDestinations VALUES (147, 1, NULL, 'la_country_MMR', 'MMR', 'MM');
INSERT INTO StdDestinations VALUES (148, 1, NULL, 'la_country_NAM', 'NAM', 'NA');
INSERT INTO StdDestinations VALUES (149, 1, NULL, 'la_country_NRU', 'NRU', 'NR');
INSERT INTO StdDestinations VALUES (150, 1, NULL, 'la_country_NPL', 'NPL', 'NP');
INSERT INTO StdDestinations VALUES (151, 1, NULL, 'la_country_NLD', 'NLD', 'NL');
INSERT INTO StdDestinations VALUES (152, 1, NULL, 'la_country_ANT', 'ANT', 'AN');
INSERT INTO StdDestinations VALUES (153, 1, NULL, 'la_country_NCL', 'NCL', 'NC');
INSERT INTO StdDestinations VALUES (154, 1, NULL, 'la_country_NZL', 'NZL', 'NZ');
INSERT INTO StdDestinations VALUES (155, 1, NULL, 'la_country_NIC', 'NIC', 'NI');
INSERT INTO StdDestinations VALUES (156, 1, NULL, 'la_country_NER', 'NER', 'NE');
INSERT INTO StdDestinations VALUES (157, 1, NULL, 'la_country_NGA', 'NGA', 'NG');
INSERT INTO StdDestinations VALUES (158, 1, NULL, 'la_country_NIU', 'NIU', 'NU');
INSERT INTO StdDestinations VALUES (159, 1, NULL, 'la_country_NFK', 'NFK', 'NF');
INSERT INTO StdDestinations VALUES (160, 1, NULL, 'la_country_MNP', 'MNP', 'MP');
INSERT INTO StdDestinations VALUES (161, 1, NULL, 'la_country_NOR', 'NOR', 'NO');
INSERT INTO StdDestinations VALUES (162, 1, NULL, 'la_country_OMN', 'OMN', 'OM');
INSERT INTO StdDestinations VALUES (163, 1, NULL, 'la_country_PAK', 'PAK', 'PK');
INSERT INTO StdDestinations VALUES (164, 1, NULL, 'la_country_PLW', 'PLW', 'PW');
INSERT INTO StdDestinations VALUES (165, 1, NULL, 'la_country_PSE', 'PSE', 'PS');
INSERT INTO StdDestinations VALUES (166, 1, NULL, 'la_country_PAN', 'PAN', 'PA');
INSERT INTO StdDestinations VALUES (167, 1, NULL, 'la_country_PNG', 'PNG', 'PG');
INSERT INTO StdDestinations VALUES (168, 1, NULL, 'la_country_PRY', 'PRY', 'PY');
INSERT INTO StdDestinations VALUES (169, 1, NULL, 'la_country_PER', 'PER', 'PE');
INSERT INTO StdDestinations VALUES (170, 1, NULL, 'la_country_PHL', 'PHL', 'PH');
INSERT INTO StdDestinations VALUES (171, 1, NULL, 'la_country_PCN', 'PCN', 'PN');
INSERT INTO StdDestinations VALUES (172, 1, NULL, 'la_country_POL', 'POL', 'PL');
INSERT INTO StdDestinations VALUES (173, 1, NULL, 'la_country_PRT', 'PRT', 'PT');
INSERT INTO StdDestinations VALUES (174, 1, NULL, 'la_country_PRI', 'PRI', 'PR');
INSERT INTO StdDestinations VALUES (175, 1, NULL, 'la_country_QAT', 'QAT', 'QA');
INSERT INTO StdDestinations VALUES (176, 1, NULL, 'la_country_REU', 'REU', 'RE');
INSERT INTO StdDestinations VALUES (177, 1, NULL, 'la_country_ROU', 'ROU', 'RO');
INSERT INTO StdDestinations VALUES (178, 1, NULL, 'la_country_RUS', 'RUS', 'RU');
INSERT INTO StdDestinations VALUES (179, 1, NULL, 'la_country_RWA', 'RWA', 'RW');
INSERT INTO StdDestinations VALUES (180, 1, NULL, 'la_country_KNA', 'KNA', 'KN');
INSERT INTO StdDestinations VALUES (181, 1, NULL, 'la_country_LCA', 'LCA', 'LC');
INSERT INTO StdDestinations VALUES (182, 1, NULL, 'la_country_VCT', 'VCT', 'VC');
INSERT INTO StdDestinations VALUES (183, 1, NULL, 'la_country_WSM', 'WSM', 'WS');
INSERT INTO StdDestinations VALUES (184, 1, NULL, 'la_country_SMR', 'SMR', 'SM');
INSERT INTO StdDestinations VALUES (185, 1, NULL, 'la_country_STP', 'STP', 'ST');
INSERT INTO StdDestinations VALUES (186, 1, NULL, 'la_country_SAU', 'SAU', 'SA');
INSERT INTO StdDestinations VALUES (187, 1, NULL, 'la_country_SEN', 'SEN', 'SN');
INSERT INTO StdDestinations VALUES (188, 1, NULL, 'la_country_SYC', 'SYC', 'SC');
INSERT INTO StdDestinations VALUES (189, 1, NULL, 'la_country_SLE', 'SLE', 'SL');
INSERT INTO StdDestinations VALUES (190, 1, NULL, 'la_country_SGP', 'SGP', 'SG');
INSERT INTO StdDestinations VALUES (191, 1, NULL, 'la_country_SVK', 'SVK', 'SK');
INSERT INTO StdDestinations VALUES (192, 1, NULL, 'la_country_SVN', 'SVN', 'SI');
INSERT INTO StdDestinations VALUES (193, 1, NULL, 'la_country_SLB', 'SLB', 'SB');
INSERT INTO StdDestinations VALUES (194, 1, NULL, 'la_country_SOM', 'SOM', 'SO');
INSERT INTO StdDestinations VALUES (195, 1, NULL, 'la_country_ZAF', 'ZAF', 'ZA');
INSERT INTO StdDestinations VALUES (196, 1, NULL, 'la_country_SGS', 'SGS', 'GS');
INSERT INTO StdDestinations VALUES (197, 1, NULL, 'la_country_ESP', 'ESP', 'ES');
INSERT INTO StdDestinations VALUES (198, 1, NULL, 'la_country_LKA', 'LKA', 'LK');
INSERT INTO StdDestinations VALUES (199, 1, NULL, 'la_country_SHN', 'SHN', 'SH');
INSERT INTO StdDestinations VALUES (200, 1, NULL, 'la_country_SPM', 'SPM', 'PM');
INSERT INTO StdDestinations VALUES (201, 1, NULL, 'la_country_SDN', 'SDN', 'SD');
INSERT INTO StdDestinations VALUES (202, 1, NULL, 'la_country_SUR', 'SUR', 'SR');
INSERT INTO StdDestinations VALUES (203, 1, NULL, 'la_country_SJM', 'SJM', 'SJ');
INSERT INTO StdDestinations VALUES (204, 1, NULL, 'la_country_SWZ', 'SWZ', 'SZ');
INSERT INTO StdDestinations VALUES (205, 1, NULL, 'la_country_SWE', 'SWE', 'SE');
INSERT INTO StdDestinations VALUES (206, 1, NULL, 'la_country_CHE', 'CHE', 'CH');
INSERT INTO StdDestinations VALUES (207, 1, NULL, 'la_country_SYR', 'SYR', 'SY');
INSERT INTO StdDestinations VALUES (208, 1, NULL, 'la_country_TWN', 'TWN', 'TW');
INSERT INTO StdDestinations VALUES (209, 1, NULL, 'la_country_TJK', 'TJK', 'TJ');
INSERT INTO StdDestinations VALUES (210, 1, NULL, 'la_country_TZA', 'TZA', 'TZ');
INSERT INTO StdDestinations VALUES (211, 1, NULL, 'la_country_THA', 'THA', 'TH');
INSERT INTO StdDestinations VALUES (212, 1, NULL, 'la_country_TGO', 'TGO', 'TG');
INSERT INTO StdDestinations VALUES (213, 1, NULL, 'la_country_TKL', 'TKL', 'TK');
INSERT INTO StdDestinations VALUES (214, 1, NULL, 'la_country_TON', 'TON', 'TO');
INSERT INTO StdDestinations VALUES (215, 1, NULL, 'la_country_TTO', 'TTO', 'TT');
INSERT INTO StdDestinations VALUES (216, 1, NULL, 'la_country_TUN', 'TUN', 'TN');
INSERT INTO StdDestinations VALUES (217, 1, NULL, 'la_country_TUR', 'TUR', 'TR');
INSERT INTO StdDestinations VALUES (218, 1, NULL, 'la_country_TKM', 'TKM', 'TM');
INSERT INTO StdDestinations VALUES (219, 1, NULL, 'la_country_TCA', 'TCA', 'TC');
INSERT INTO StdDestinations VALUES (220, 1, NULL, 'la_country_TUV', 'TUV', 'TV');
INSERT INTO StdDestinations VALUES (221, 1, NULL, 'la_country_UGA', 'UGA', 'UG');
INSERT INTO StdDestinations VALUES (222, 1, NULL, 'la_country_UKR', 'UKR', 'UA');
INSERT INTO StdDestinations VALUES (223, 1, NULL, 'la_country_ARE', 'ARE', 'AE');
INSERT INTO StdDestinations VALUES (224, 1, NULL, 'la_country_GBR', 'GBR', 'GB');
INSERT INTO StdDestinations VALUES (225, 1, NULL, 'la_country_USA', 'USA', 'US');
INSERT INTO StdDestinations VALUES (226, 1, NULL, 'la_country_UMI', 'UMI', 'UM');
INSERT INTO StdDestinations VALUES (227, 1, NULL, 'la_country_URY', 'URY', 'UY');
INSERT INTO StdDestinations VALUES (228, 1, NULL, 'la_country_UZB', 'UZB', 'UZ');
INSERT INTO StdDestinations VALUES (229, 1, NULL, 'la_country_VUT', 'VUT', 'VU');
INSERT INTO StdDestinations VALUES (230, 1, NULL, 'la_country_VAT', 'VAT', 'VA');
INSERT INTO StdDestinations VALUES (231, 1, NULL, 'la_country_VEN', 'VEN', 'VE');
INSERT INTO StdDestinations VALUES (232, 1, NULL, 'la_country_VNM', 'VNM', 'VN');
INSERT INTO StdDestinations VALUES (233, 1, NULL, 'la_country_VGB', 'VGB', 'VG');
INSERT INTO StdDestinations VALUES (234, 1, NULL, 'la_country_VIR', 'VIR', 'VI');
INSERT INTO StdDestinations VALUES (235, 1, NULL, 'la_country_WLF', 'WLF', 'WF');
INSERT INTO StdDestinations VALUES (236, 1, NULL, 'la_country_ESH', 'ESH', 'EH');
INSERT INTO StdDestinations VALUES (237, 1, NULL, 'la_country_YEM', 'YEM', 'YE');
INSERT INTO StdDestinations VALUES (238, 1, NULL, 'la_country_YUG', 'YUG', 'YU');
INSERT INTO StdDestinations VALUES (239, 1, NULL, 'la_country_ZMB', 'ZMB', 'ZM');
INSERT INTO StdDestinations VALUES (240, 1, NULL, 'la_country_ZWE', 'ZWE', 'ZW');
INSERT INTO StdDestinations VALUES (370, 2, 38, 'la_state_YT', 'YT', NULL);
INSERT INTO StdDestinations VALUES (369, 2, 38, 'la_state_SK', 'SK', NULL);
INSERT INTO StdDestinations VALUES (368, 2, 38, 'la_state_QC', 'QC', NULL);
INSERT INTO StdDestinations VALUES (367, 2, 38, 'la_state_PE', 'PE', NULL);
INSERT INTO StdDestinations VALUES (366, 2, 38, 'la_state_ON', 'ON', NULL);
INSERT INTO StdDestinations VALUES (365, 2, 38, 'la_state_NU', 'NU', NULL);
INSERT INTO StdDestinations VALUES (364, 2, 38, 'la_state_NS', 'NS', NULL);
INSERT INTO StdDestinations VALUES (363, 2, 38, 'la_state_NT', 'NT', NULL);
INSERT INTO StdDestinations VALUES (362, 2, 38, 'la_state_NL', 'NL', NULL);
INSERT INTO StdDestinations VALUES (361, 2, 38, 'la_state_NB', 'NB', NULL);
INSERT INTO StdDestinations VALUES (360, 2, 38, 'la_state_MB', 'MB', NULL);
INSERT INTO StdDestinations VALUES (359, 2, 38, 'la_state_BC', 'BC', NULL);
INSERT INTO StdDestinations VALUES (358, 2, 38, 'la_state_AB', 'AB', NULL);
INSERT INTO StdDestinations VALUES (357, 2, 225, 'la_state_DC', 'DC', NULL);
INSERT INTO StdDestinations VALUES (356, 2, 225, 'la_state_WY', 'WY', NULL);
INSERT INTO StdDestinations VALUES (355, 2, 225, 'la_state_WI', 'WI', NULL);
INSERT INTO StdDestinations VALUES (354, 2, 225, 'la_state_WV', 'WV', NULL);
INSERT INTO StdDestinations VALUES (353, 2, 225, 'la_state_WA', 'WA', NULL);
INSERT INTO StdDestinations VALUES (352, 2, 225, 'la_state_VA', 'VA', NULL);
INSERT INTO StdDestinations VALUES (351, 2, 225, 'la_state_VT', 'VT', NULL);
INSERT INTO StdDestinations VALUES (350, 2, 225, 'la_state_UT', 'UT', NULL);
INSERT INTO StdDestinations VALUES (349, 2, 225, 'la_state_TX', 'TX', NULL);
INSERT INTO StdDestinations VALUES (348, 2, 225, 'la_state_TN', 'TN', NULL);
INSERT INTO StdDestinations VALUES (347, 2, 225, 'la_state_SD', 'SD', NULL);
INSERT INTO StdDestinations VALUES (346, 2, 225, 'la_state_SC', 'SC', NULL);
INSERT INTO StdDestinations VALUES (345, 2, 225, 'la_state_RI', 'RI', NULL);
INSERT INTO StdDestinations VALUES (344, 2, 225, 'la_state_PR', 'PR', NULL);
INSERT INTO StdDestinations VALUES (343, 2, 225, 'la_state_PA', 'PA', NULL);
INSERT INTO StdDestinations VALUES (342, 2, 225, 'la_state_OR', 'OR', NULL);
INSERT INTO StdDestinations VALUES (341, 2, 225, 'la_state_OK', 'OK', NULL);
INSERT INTO StdDestinations VALUES (340, 2, 225, 'la_state_OH', 'OH', NULL);
INSERT INTO StdDestinations VALUES (339, 2, 225, 'la_state_ND', 'ND', NULL);
INSERT INTO StdDestinations VALUES (338, 2, 225, 'la_state_NC', 'NC', NULL);
INSERT INTO StdDestinations VALUES (337, 2, 225, 'la_state_NY', 'NY', NULL);
INSERT INTO StdDestinations VALUES (336, 2, 225, 'la_state_NM', 'NM', NULL);
INSERT INTO StdDestinations VALUES (335, 2, 225, 'la_state_NJ', 'NJ', NULL);
INSERT INTO StdDestinations VALUES (334, 2, 225, 'la_state_NH', 'NH', NULL);
INSERT INTO StdDestinations VALUES (333, 2, 225, 'la_state_NV', 'NV', NULL);
INSERT INTO StdDestinations VALUES (332, 2, 225, 'la_state_NE', 'NE', NULL);
INSERT INTO StdDestinations VALUES (331, 2, 225, 'la_state_MT', 'MT', NULL);
INSERT INTO StdDestinations VALUES (330, 2, 225, 'la_state_MO', 'MO', NULL);
INSERT INTO StdDestinations VALUES (329, 2, 225, 'la_state_MS', 'MS', NULL);
INSERT INTO StdDestinations VALUES (328, 2, 225, 'la_state_MN', 'MN', NULL);
INSERT INTO StdDestinations VALUES (327, 2, 225, 'la_state_MI', 'MI', NULL);
INSERT INTO StdDestinations VALUES (326, 2, 225, 'la_state_MA', 'MA', NULL);
INSERT INTO StdDestinations VALUES (325, 2, 225, 'la_state_MD', 'MD', NULL);
INSERT INTO StdDestinations VALUES (324, 2, 225, 'la_state_ME', 'ME', NULL);
INSERT INTO StdDestinations VALUES (323, 2, 225, 'la_state_LA', 'LA', NULL);
INSERT INTO StdDestinations VALUES (322, 2, 225, 'la_state_KY', 'KY', NULL);
INSERT INTO StdDestinations VALUES (321, 2, 225, 'la_state_KS', 'KS', NULL);
INSERT INTO StdDestinations VALUES (320, 2, 225, 'la_state_IA', 'IA', NULL);
INSERT INTO StdDestinations VALUES (319, 2, 225, 'la_state_IN', 'IN', NULL);
INSERT INTO StdDestinations VALUES (318, 2, 225, 'la_state_IL', 'IL', NULL);
INSERT INTO StdDestinations VALUES (317, 2, 225, 'la_state_ID', 'ID', NULL);
INSERT INTO StdDestinations VALUES (316, 2, 225, 'la_state_HI', 'HI', NULL);
INSERT INTO StdDestinations VALUES (315, 2, 225, 'la_state_GA', 'GA', NULL);
INSERT INTO StdDestinations VALUES (314, 2, 225, 'la_state_FL', 'FL', NULL);
INSERT INTO StdDestinations VALUES (313, 2, 225, 'la_state_DE', 'DE', NULL);
INSERT INTO StdDestinations VALUES (312, 2, 225, 'la_state_CT', 'CT', NULL);
INSERT INTO StdDestinations VALUES (311, 2, 225, 'la_state_CO', 'CO', NULL);
INSERT INTO StdDestinations VALUES (310, 2, 225, 'la_state_CA', 'CA', NULL);
INSERT INTO StdDestinations VALUES (309, 2, 225, 'la_state_AR', 'AR', NULL);
INSERT INTO StdDestinations VALUES (308, 2, 225, 'la_state_AZ', 'AZ', NULL);
INSERT INTO StdDestinations VALUES (307, 2, 225, 'la_state_AK', 'AK', NULL);
INSERT INTO StdDestinations VALUES (306, 2, 225, 'la_state_AL', 'AL', NULL);
INSERT INTO PermissionConfig (PermissionName, Description, ErrorMessage, ModuleId) VALUES ('CATEGORY.VIEW', 'lu_PermName_Category.View_desc', 'lu_PermName_Category.View_error', 'In-Portal');
INSERT INTO PermCache (CategoryId, PermId, ACL) VALUES (0, 1, '11,12,13,14,15');
INSERT INTO Permissions VALUES (0, 'LOGIN', 13, 1, 1, 0);
INSERT INTO Permissions VALUES (0, 'LOGIN', 11, 1, 1, 0);
INSERT INTO Permissions VALUES (0, 'ADMIN', 11, 1, 1, 0);
INSERT INTO Permissions VALUES (0, 'in-portal:root.view', 11, 1, 1, 0);
INSERT INTO Permissions VALUES (0, 'in-portal:system.view', 11, 1, 1, 0);
INSERT INTO Permissions VALUES (0, 'in-portal:user_list.view', 11, 1, 1, 0);
INSERT INTO Permissions VALUES (0, 'in-portal:user_list.add', 11, 1, 1, 0);
INSERT INTO Permissions VALUES (0, 'in-portal:user_list.edit', 11, 1, 1, 0);
INSERT INTO Permissions VALUES (0, 'in-portal:user_list.delete', 11, 1, 1, 0);
INSERT INTO Permissions VALUES (0, 'in-portal:configure_lang.view', 11, 1, 1, 0);
INSERT INTO Permissions VALUES (0, 'in-portal:configure_lang.add', 11, 1, 1, 0);
INSERT INTO Permissions VALUES (0, 'in-portal:configure_lang.edit', 11, 1, 1, 0);
INSERT INTO Permissions VALUES (0, 'in-portal:configure_lang.delete', 11, 1, 1, 0);
INSERT INTO Permissions VALUES (0, 'CATEGORY.VIEW', 11, 1, 0, 0);
INSERT INTO Permissions VALUES (0, 'CATEGORY.ADD', 11, 1, 0, 0);
INSERT INTO Permissions VALUES (0, 'CATEGORY.DELETE', 11, 1, 0, 0);
INSERT INTO Permissions VALUES (0, 'CATEGORY.MODIFY', 11, 1, 0, 0);
INSERT INTO Permissions VALUES (0, 'in-portal:service.view', 11, 1, 1, 0);
INSERT INTO Modules (Name, Path, Var, Version, Loaded, LoadOrder, TemplatePath, RootCat, BuildDate) VALUES ('Core', 'core/', 'adm', '4.0.1', 1, 1, '', 0, '0');
Property changes on: branches/unlabeled/unlabeled-1.5.2/core/install/install_data.sql
___________________________________________________________________
Modified: cvs2svn:cvs-rev
## -1 +1 ##
-1.5.2.2
\ No newline at end of property
+1.5.2.3
\ No newline at end of property
Index: branches/unlabeled/unlabeled-1.170.2/core/kernel/application.php
===================================================================
--- branches/unlabeled/unlabeled-1.170.2/core/kernel/application.php (revision 7747)
+++ branches/unlabeled/unlabeled-1.170.2/core/kernel/application.php (revision 7748)
@@ -1,2421 +1,2421 @@
<?php
/**
* Basic class for Kernel3-based Application
*
* This class is a Facade for any other class which needs to deal with Kernel3 framework.<br>
* The class incapsulates the main run-cycle of the script, provide access to all other objects in the framework.<br>
* <br>
* The class is a singleton, which means that there could be only one instance of KernelApplication in the script.<br>
* This could be guranteed by NOT calling the class constuctor directly, but rather calling KernelApplication::Instance() method,
* which returns an instance of the application. The method gurantees that it will return exactly the same instance for any call.<br>
* See singleton pattern by GOF.
* @package kernel4
*/
class kApplication {
/**
* Is true, when Init method was called already, prevents double initialization
*
* @var bool
*/
var $InitDone = false;
/**
* Holds internal TemplateParser object
* @access private
* @var TemplateParser
*/
var $Parser;
/**
* Holds parser output buffer
* @access private
* @var string
*/
var $HTML;
/**
* Prevents request from beeing proceeded twice in case if application init is called mere then one time
*
* @var bool
* @todo This is not good anyway (by Alex)
*/
var $RequestProcessed = false;
/**
* The main Factory used to create
* almost any class of kernel and
* modules
*
* @access private
* @var kFactory
*/
var $Factory;
/**
* All ConfigurationValues table content (hash) here
*
* @var Array
* @access private
*/
var $ConfigHash = Array();
/**
* Ids of config variables used in current run (for caching)
*
* @var Array
* @access private
*/
var $ConfigCacheIds = array();
/**
* Template names, that will be used instead of regular templates
*
* @var Array
*/
var $ReplacementTemplates = Array ();
/**
* Reference to debugger
*
* @var Debugger
*/
var $Debugger = null;
/**
* Holds all phrases used
* in code and template
*
* @var PhrasesCache
*/
var $Phrases;
/**
* Modules table content, key - module name
*
* @var Array
*/
var $ModuleInfo = Array();
/**
* Holds DBConnection
*
* @var kDBConnection
*/
var $Conn = null;
/**
* Maintains list of user-defined error handlers
*
* @var Array
*/
var $errorHandlers = Array();
// performance needs:
/**
* Holds a refererence to httpquery
*
* @var kHttpQuery
*/
var $HttpQuery = null;
/**
* Holds a reference to UnitConfigReader
*
* @var kUnitConfigReader
*/
var $UnitConfigReader = null;
/**
* Holds a reference to Session
*
* @var Session
*/
var $Session = null;
/**
* Holds a ref to kEventManager
*
* @var kEventManager
*/
var $EventManager = null;
/**
* Ref to itself, needed because everybody used to write $this->Application, even inside kApplication
*
* @var kApplication
*/
var $Application = null;
/**
* Ref for TemplatesChache
*
* @var TemplatesCache
*/
var $TemplatesCache = null;
var $CompilationCache = array(); //used when compiling templates
var $CachedProcessors = array(); //used when running compiled templates
/**
* Returns kApplication instance anywhere in the script.
*
* This method should be used to get single kApplication object instance anywhere in the
* Kernel-based application. The method is guranteed to return the SAME instance of kApplication.
* Anywhere in the script you could write:
* <code>
* $application =& kApplication::Instance();
* </code>
* or in an object:
* <code>
* $this->Application =& kApplication::Instance();
* </code>
* to get the instance of kApplication. Note that we call the Instance method as STATIC - directly from the class.
* To use descendand of standard kApplication class in your project you would need to define APPLICATION_CLASS constant
* BEFORE calling kApplication::Instance() for the first time. If APPLICATION_CLASS is not defined the method would
* create and return default KernelApplication instance.
* @static
* @access public
* @return kApplication
*/
function &Instance()
{
static $instance = false;
if(!$instance)
{
safeDefine('APPLICATION_CLASS', 'kApplication');
$class = APPLICATION_CLASS;
$instance = new $class();
$instance->Application =& $instance;
}
return $instance;
}
/**
* Initializes the Application
*
* @access public
* @see kHTTPQuery
* @see Session
* @see TemplatesCache
* @return bool Was Init actually made now or before
*/
function Init()
{
if($this->InitDone) return false;
if (!constOn('SKIP_OUT_COMPRESSION')) {
ob_start(); // collect any output from method (other then tags) into buffer
}
if(defined('DEBUG_MODE') && $this->isDebugMode() && constOn('DBG_PROFILE_MEMORY')) {
$this->Debugger->appendMemoryUsage('Application before Init:');
}
if (!$this->isDebugMode() && !constOn('DBG_ZEND_PRESENT')) {
error_reporting(0);
ini_set('display_errors', 0);
}
if (!constOn('DBG_ZEND_PRESENT')) {
$error_handler = set_error_handler( Array(&$this,'handleError') );
if ($error_handler) $this->errorHandlers[] = $error_handler;
}
$this->Conn = new kDBConnection(SQL_TYPE, Array(&$this, 'handleSQLError') );
$this->Conn->Connect(SQL_SERVER, SQL_USER, SQL_PASS, SQL_DB);
$this->Conn->debugMode = $this->isDebugMode();
$this->Factory = new kFactory();
$this->registerDefaultClasses();
$this->Phrases = new PhrasesCache();
$this->EventManager =& $this->Factory->makeClass('EventManager');
$this->Factory->Storage['EventManager'] =& $this->EventManager;
$this->RegisterDefaultBuildEvents();
$this->SetDefaultConstants();
$this->UnitConfigReader =& $this->recallObject('kUnitConfigReader');
$this->UnitConfigReader->scanModules(MODULES_PATH);
$this->registerModuleConstants();
$rewrite_on = $this->ConfigValue('UseModRewrite');
// admin=1 - when front is browsed using admin session
$admin_on = getArrayValue($_REQUEST, 'admin') || $this->IsAdmin();
define('MOD_REWRITE', $rewrite_on && !$admin_on ? 1 : 0);
$this->HttpQuery =& $this->recallObject('HTTPQuery');
$this->Session =& $this->recallObject('Session');
$this->HttpQuery->AfterInit();
$this->LoadCache();
$this->InitConfig();
$this->Phrases->Init('phrases');
$this->UnitConfigReader->AfterConfigRead();
/*// Module items are recalled during url parsing & PhrasesCache is needed already there,
// because it's used in their build events. That's why phrases cache initialization is
// called from kHTTPQuery in case when mod_rewrite is used
if (!$this->RewriteURLs()) {
$this->Phrases = new PhrasesCache();
}*/
if(!$this->RecallVar('UserGroups')) {
$session =& $this->recallObject('Session');
$user_groups = trim($session->GetField('GroupList'), ',');
if (!$user_groups) $user_groups = $this->ConfigValue('User_GuestGroup');
$this->StoreVar('UserGroups', $user_groups);
}
if ($this->GetVar('m_cat_id') === false) $this->SetVar('m_cat_id', 0);
if( !$this->RecallVar('curr_iso') ) $this->StoreVar('curr_iso', $this->GetPrimaryCurrency() );
$this->SetVar('visits_id', $this->RecallVar('visit_id') );
$language =& $this->recallObject( 'lang.current', null, Array('live_table' => true) );
$this->ValidateLogin();
if($this->isDebugMode()) {
$this->Debugger->profileFinish('kernel4_startup');
}
$this->InitDone = true;
$this->HandleEvent( new kEvent('adm:OnStartup') );
return true;
}
/**
* Returns module information. Searches module by requested field
*
* @param string $field
* @param mixed $value
* @param string field value to returns, if not specified, then return all fields
* @param string field to return
* @return Array
*/
function findModule($field, $value, $return_field = null)
{
$found = false;
foreach ($this->ModuleInfo as $module_name => $module_info) {
if (strtolower($module_info[$field]) == strtolower($value)) {
$found = true;
break;
}
}
if ($found) {
return isset($return_field) ? $module_info[$return_field] : $module_info;
}
return false;
}
function refreshModuleInfo()
{
$modules_helper =& $this->recallObject('ModulesHelper');
$sql = 'SELECT *
FROM '.TABLE_PREFIX.'Modules
WHERE '.$modules_helper->getWhereClause().'
ORDER BY LoadOrder';
$this->ModuleInfo = $this->Conn->Query($sql, 'Name');
$this->registerModuleConstants();
}
/**
* Checks if passed language id if valid and sets it to primary otherwise
*
*/
function VerifyLanguageId()
{
$language_id = $this->GetVar('m_lang');
if (!$language_id) {
$language_id = 'default';
}
$this->SetVar('lang.current_id', $language_id );
$this->SetVar('m_lang', $language_id );
$lang_mode = $this->GetVar('lang_mode');
$this->SetVar('lang_mode', '');
$lang =& $this->recallObject('lang.current');
if ( !$lang->IsLoaded() || (!$this->Application->IsAdmin() && !$lang->GetDBField('Enabled')) ) {
if (!defined('IS_INSTALL')) $this->ApplicationDie('Unknown or disabled language');
}
$this->SetVar('lang_mode',$lang_mode);
}
/**
* Checks if passed theme id if valid and sets it to primary otherwise
*
*/
function VerifyThemeId()
{
if ($this->Application->IsAdmin()) {
safeDefine('THEMES_PATH', '/core/admin_templates');
return;
}
$path = $this->GetFrontThemePath();
if ($path === false) {
$this->ApplicationDie('No Primary Theme Selected or Current Theme is Unknonw or Disabled');
}
safeDefine('THEMES_PATH', $path);
/*
$theme_id = $this->GetVar('m_theme');
if (!$theme_id) {
$theme_id = $this->GetDefaultThemeId();
if (!$theme_id) {
if (!defined('IS_INSTALL')) $this->ApplicationDie('No Primary Theme Selected');
}
}
$this->SetVar('m_theme', $theme_id);
$this->SetVar('theme.current_id', $theme_id ); // KOSTJA: this is to fool theme' getPassedId
$theme =& $this->recallObject('theme.current');
if (!$theme->IsLoaded() || !$theme->GetDBField('Enabled')) {
if (!defined('IS_INSTALL')) $this->ApplicationDie('Unknown or disabled theme');
}
safeDefine('THEMES_PATH', '/themes/'.$theme->GetDBField('Name'));
*/
}
function GetFrontThemePath($force=0)
{
static $path=null;
if (!$force && isset($path)) return $path;
$theme_id = $this->GetVar('m_theme');
if (!$theme_id) {
$theme_id = $this->GetDefaultThemeId(1); //1 to force front-end mode!
if (!$theme_id) {
return false;
}
}
$this->SetVar('m_theme', $theme_id);
$this->SetVar('theme.current_id', $theme_id ); // KOSTJA: this is to fool theme' getPassedId
$theme =& $this->recallObject('theme.current');
if (!$theme->IsLoaded() || !$theme->GetDBField('Enabled')) {
return false;
}
$path = '/themes/'.$theme->GetDBField('Name');
return $path;
}
function GetDefaultLanguageId()
{
static $language_id = 0;
if ($language_id > 0) return $language_id;
$table = $this->getUnitOption('lang','TableName');
$id_field = $this->getUnitOption('lang','IDField');
$sql = 'SELECT '.$id_field.'
FROM '.$table.'
WHERE (PrimaryLang = 1) AND (Enabled = 1)';
$language_id = $this->Conn->GetOne($sql);
if (!$language_id && defined('IS_INSTALL') && IS_INSTALL) {
$language_id = 1;
}
return $language_id;
}
function GetDefaultThemeId($force_front=0)
{
static $theme_id = 0;
if($theme_id > 0) return $theme_id;
if (constOn('DBG_FORCE_THEME')) {
$theme_id = DBG_FORCE_THEME;
}
elseif (!$force_front && $this->IsAdmin()) {
$theme_id = 999;
}
else {
$table = $this->getUnitOption('theme','TableName');
$id_field = $this->getUnitOption('theme','IDField');
$sql = 'SELECT '.$id_field.'
FROM '.$table.'
WHERE (PrimaryTheme = 1) AND (Enabled = 1)';
$theme_id = $this->Conn->GetOne($sql);
}
return $theme_id;
}
function GetPrimaryCurrency()
{
if ($this->isModuleEnabled('In-Commerce')) {
$table = $this->getUnitOption('curr', 'TableName');
return $this->Conn->GetOne('SELECT ISO FROM '.$table.' WHERE IsPrimary = 1');
}
else {
return 'USD';
}
}
/**
* Registers default classes such as ItemController, GridController and LoginController
*
* Called automatically while initializing Application
* @access private
* @return void
*/
function RegisterDefaultClasses()
{
$this->registerClass('kTempTablesHandler', KERNEL_PATH.'/utility/temp_handler.php');
$this->registerClass('kEventManager', KERNEL_PATH.'/event_manager.php', 'EventManager');
$this->registerClass('kUnitConfigReader', KERNEL_PATH.'/utility/unit_config_reader.php');
$this->registerClass('kArray', KERNEL_PATH.'/utility/params.php');
$this->registerClass('Params', KERNEL_PATH.'/utility/params.php');
$this->registerClass('kHelper', KERNEL_PATH.'/kbase.php');
$this->registerClass('kCache', KERNEL_PATH.'/utility/cache.php', 'Cache', Array('Params'));
$this->registerClass('kHTTPQuery', KERNEL_PATH.'/utility/http_query.php', 'HTTPQuery', Array('Params') );
$this->registerClass('Session', KERNEL_PATH.'/session/session.php');
$this->registerClass('SessionStorage', KERNEL_PATH.'/session/session.php');
$this->registerClass('Params', KERNEL_PATH.'/utility/params.php', 'kActions');
$this->registerClass('kMultipleFilter', KERNEL_PATH.'/utility/filters.php');
$this->registerClass('kDBList', KERNEL_PATH.'/db/dblist.php');
$this->registerClass('kDBItem', KERNEL_PATH.'/db/dbitem.php');
$this->registerClass('kDBEventHandler', KERNEL_PATH.'/db/db_event_handler.php');
$this->registerClass('kTagProcessor', KERNEL_PATH.'/processors/tag_processor.php');
$this->registerClass('kMainTagProcessor', KERNEL_PATH.'/processors/main_processor.php','m_TagProcessor', 'kTagProcessor');
$this->registerClass('kDBTagProcessor', KERNEL_PATH.'/db/db_tag_processor.php', null, 'kTagProcessor');
$this->registerClass('TemplatesCache', KERNEL_PATH.'/parser/template.php');
$this->registerClass('Template', KERNEL_PATH.'/parser/template.php');
$this->registerClass('TemplateParser', KERNEL_PATH.'/parser/template_parser.php',null, 'kDBTagProcessor');
- $this->registerClass('kEmailMessage', KERNEL_PATH.'/utility/email.php');
- $this->registerClass('kSmtpClient', KERNEL_PATH.'/utility/smtp_client.php');
+ $this->registerClass('kEmailSendingHelper', KERNEL_PATH.'/utility/email_send.php', 'EmailSender', Array('kHelper'));
+ $this->registerClass('kSocket', KERNEL_PATH.'/utility/socket.php', 'Socket');
if (file_exists(MODULES_PATH.'/in-commerce/units/currencies/currency_rates.php')) {
$this->registerClass('kCurrencyRates', MODULES_PATH.'/in-commerce/units/currencies/currency_rates.php');
}
$this->registerClass('FCKeditor', FULL_PATH.'/admin/editor/cmseditor/fckeditor.php'); // need this?
/* Moved from MyApplication */
$this->registerClass('Inp1Parser',KERNEL_PATH.'/../units/general/inp1_parser.php','Inp1Parser');
$this->registerClass('InpSession',KERNEL_PATH.'/../units/general/inp_ses_storage.php','Session');
$this->registerClass('InpSessionStorage',KERNEL_PATH.'/../units/general/inp_ses_storage.php','SessionStorage');
$this->registerClass('kCatDBItem',KERNEL_PATH.'/../units/general/cat_dbitem.php');
$this->registerClass('kCatDBItemExportHelper',KERNEL_PATH.'/../units/general/cat_dbitem_export.php', 'CatItemExportHelper');
$this->registerClass('kCatDBList',KERNEL_PATH.'/../units/general/cat_dblist.php');
$this->registerClass('kCatDBEventHandler',KERNEL_PATH.'/../units/general/cat_event_handler.php');
$this->registerClass('kCatDBTagProcessor',KERNEL_PATH.'/../units/general/cat_tag_processor.php');
// Do not move to config - this helper is used before configs are read
$this->registerClass('kModulesHelper', KERNEL_PATH.'/../units/general/helpers/modules.php', 'ModulesHelper');
/* End moved */
}
function RegisterDefaultBuildEvents()
{
$event_manager =& $this->recallObject('EventManager');
$event_manager->registerBuildEvent('kTempTablesHandler', 'OnTempHandlerBuild');
}
/**
* Returns item's filename that corresponds id passed. If possible, then get it from cache
*
* @param string $prefix
* @param int $id
* @return string
*/
function getFilename($prefix, $id, $category_id=null)
{
$filename = $this->getCache('filenames', $prefix.'_'.$id);
if ($filename === false) {
$table = $this->getUnitOption($prefix, 'TableName');
$id_field = $this->getUnitOption($prefix, 'IDField');
if ($prefix == 'c') {
if(!$id) {
$this->setCache('filenames', $prefix.'_'.$id, '');
return '';
}
// this allows to save 2 sql queries for each category
$sql = 'SELECT NamedParentPath, CachedCategoryTemplate
FROM '.$table.'
WHERE '.$id_field.' = '.$this->Conn->qstr($id);
$category_data = $this->Conn->GetRow($sql);
$filename = $category_data['NamedParentPath'];
$this->setCache('category_templates', $id, $category_data['CachedCategoryTemplate']);
// $this->setCache('item_templates', $id, $category_data['CachedItemTemplate']);
}
else {
$resource_id = $this->Conn->GetOne('SELECT ResourceId FROM '.$table.' WHERE '.$id_field.' = '.$this->Conn->qstr($id));
if (is_null($category_id)) $category_id = $this->GetVar('m_cat_id');
$sql = 'SELECT Filename FROM '.TABLE_PREFIX.'CategoryItems WHERE ItemResourceId = '.$resource_id.' AND CategoryId = '.$category_id;
$filename = $this->Conn->GetOne($sql);
/*if (!$filename) {
$sql = 'SELECT Filename FROM '.TABLE_PREFIX.'CategoryItems WHERE ItemResourceId = '.$resource_id.' AND PrimaryCat = 1';
$filename = $this->Conn->GetOne($sql);
}*/
/*$sql = 'SELECT Filename
FROM '.$table.'
WHERE '.$id_field.' = '.$this->Conn->qstr($id);
$filename = $this->Conn->GetOne($sql);*/
}
$this->setCache('filenames', $prefix.'_'.$id, $filename);
}
return $filename;
}
/**
* Adds new value to cache $cache_name and identified by key $key
*
* @param string $cache_name cache name
* @param int $key key name to add to cache
* @param mixed $value value of chached record
*/
function setCache($cache_name, $key, $value)
{
$cache =& $this->recallObject('Cache');
$cache->setCache($cache_name, $key, $value);
}
/**
* Returns cached $key value from cache named $cache_name
*
* @param string $cache_name cache name
* @param int $key key name from cache
* @return mixed
*/
function getCache($cache_name, $key)
{
$cache =& $this->recallObject('Cache');
return $cache->getCache($cache_name, $key);
}
/**
* Defines default constants if it's not defined before - in config.php
*
* @access private
*/
function SetDefaultConstants() // it's defined in startup.php - can be removed??
{
safeDefine('SERVER_NAME', $_SERVER['HTTP_HOST']);
}
/**
* Registers each module specific constants if any found
*
*/
function registerModuleConstants()
{
if (file_exists(KERNEL_PATH.'/constants.php')) {
k4_include_once(KERNEL_PATH.'/constants.php');
}
if (!$this->ModuleInfo) return false;
foreach($this->ModuleInfo as $module_name => $module_info)
{
$module_path = '/'.$module_info['Path'];
$contants_file = FULL_PATH.$module_path.'constants.php';
if( file_exists($contants_file) ) k4_include_once($contants_file);
}
return true;
}
function ProcessRequest()
{
$event_manager =& $this->recallObject('EventManager');
/* @var $event_manager kEventManager */
if($this->isDebugMode() && constOn('DBG_SHOW_HTTPQUERY')) {
$this->Debugger->appendHTML('HTTPQuery:');
$this->Debugger->dumpVars($this->HttpQuery->_Params);
}
$event_manager->ProcessRequest();
$event_manager->RunRegularEvents(reBEFORE);
$this->RequestProcessed = true;
}
/**
* Actually runs the parser against current template and stores parsing result
*
* This method gets t variable passed to the script, loads the template given in t variable and
* parses it. The result is store in {@link $this->HTML} property.
* @access public
* @return void
*/
function Run()
{
if($this->isDebugMode() && constOn('DBG_PROFILE_MEMORY')) {
$this->Debugger->appendMemoryUsage('Application before Run:');
}
if ($this->IsAdmin()) {
// for permission checking in events & templates
$this->LinkVar('module'); // for common configuration templates
$this->LinkVar('section'); // for common configuration templates
if ($this->GetVar('m_opener') == 'p') {
$this->LinkVar('main_prefix'); // window prefix, that opened selector
$this->LinkVar('dst_field'); // field to set value choosed in selector
// $this->LinkVar('return_template'); // template to go, when something was coosen from popup (from finalizePopup)
// $this->LinkVar('return_m'); // main env part to restore after popup will be closed (from finalizePopup)
}
if ($this->GetVar('ajax') == 'yes') {
// hide debug output from ajax requests automatically
define('DBG_SKIP_REPORTING', 1);
}
}
if (!$this->RequestProcessed) $this->ProcessRequest();
$this->InitParser();
$t = $this->GetVar('t');
if ($this->isModuleEnabled('In-Edit')) {
$cms_handler =& $this->recallObject('cms_EventHandler');
if (!$this->TemplatesCache->TemplateExists($t) && !$this->IsAdmin()) {
$t = $cms_handler->GetDesignTemplate();
}
/*else {
$cms_handler->SetCatByTemplate();
}*/
}
if ($this->isModuleEnabled('Proj-CMS')) {
$cms_handler =& $this->recallObject('st_EventHandler');
if (!$this->TemplatesCache->TemplateExists($t) && !$this->IsAdmin()) {
$t = $cms_handler->GetDesignTemplate();
}
/*else {
$cms_handler->SetCatByTemplate();
}*/
}
if($this->isDebugMode() && constOn('DBG_PROFILE_MEMORY')) {
$this->Debugger->appendMemoryUsage('Application before Parsing:');
}
$this->HTML = $this->Parser->ParseTemplate( $t );
if ($this->isDebugMode() && constOn('DBG_PROFILE_MEMORY')) {
$this->Debugger->appendMemoryUsage('Application after Parsing:');
}
}
function InitParser()
{
if( !is_object($this->Parser) ) {
$this->Parser =& $this->recallObject('TemplateParser');
$this->TemplatesCache =& $this->recallObject('TemplatesCache');
}
}
/**
* Send the parser results to browser
*
* Actually send everything stored in {@link $this->HTML}, to the browser by echoing it.
* @access public
* @return void
*/
function Done()
{
if ($this->isDebugMode() && constOn('DBG_PROFILE_MEMORY')) {
$this->Debugger->appendMemoryUsage('Application before Done:');
}
if ($this->GetVar('admin')) {
$reg = '/('.preg_quote(BASE_PATH, '/').'.*\.html)(#.*){0,1}(")/sU';
$this->HTML = preg_replace($reg, "$1?admin=1$2$3", $this->HTML);
}
//eval("?".">".$this->HTML);
if ($this->isDebugMode()) {
$this->EventManager->RunRegularEvents(reAFTER);
$this->Session->SaveData();
$this->HTML = ob_get_clean() . $this->HTML . $this->Debugger->printReport(true);
}
else {
$this->HTML = ob_get_clean().$this->HTML;
}
if ($this->UseOutputCompression()) {
header('Content-Encoding: gzip');
$compression_level = $this->ConfigValue('OutputCompressionLevel');
if ($compression_level < 0 || $compression_level > 9) $compression_level = 7;
echo gzencode($this->HTML, $compression_level);
}
else {
echo $this->HTML;
}
$this->UpdateCache();
flush();
if ($this->isDebugMode() && constOn('DBG_CACHE')) {
$cache =& $this->recallObject('Cache');
$cache->printStatistics();
}
$this->EventManager->RunRegularEvents(reAFTER);
$this->Session->SaveData();
}
/**
* Checks if output compression options is available
*
* @return string
*/
function UseOutputCompression()
{
if (constOn('IS_INSTALL') || constOn('DBG_ZEND_PRESENT') || constOn('SKIP_OUT_COMPRESSION')) return false;
return $this->ConfigValue('UseOutputCompression') && function_exists('gzencode') && strstr($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip');
}
// Facade
/**
* Returns current session id (SID)
* @access public
* @return longint
*/
function GetSID()
{
$session =& $this->recallObject('Session');
return $session->GetID();
}
function DestroySession()
{
$session =& $this->recallObject('Session');
$session->Destroy();
}
/**
* Returns variable passed to the script as GET/POST/COOKIE
*
* @access public
* @param string $name Name of variable to retrieve
* @param int $default default value returned in case if varible not present
* @return mixed
*/
function GetVar($name, $default = false)
{
// $http_query =& $this->recallObject('HTTPQuery');
return isset($this->HttpQuery->_Params[$name]) ? $this->HttpQuery->_Params[$name] : $default;
}
/**
* Returns ALL variables passed to the script as GET/POST/COOKIE
*
* @access public
* @return array
*/
function GetVars()
{
return $this->HttpQuery->GetParams();
}
/**
* Set the variable 'as it was passed to the script through GET/POST/COOKIE'
*
* This could be useful to set the variable when you know that
* other objects would relay on variable passed from GET/POST/COOKIE
* or you could use SetVar() / GetVar() pairs to pass the values between different objects.<br>
*
* This method is formerly known as $this->Session->SetProperty.
* @param string $var Variable name to set
* @param mixed $val Variable value
* @access public
* @return void
*/
function SetVar($var,$val)
{
// $http_query =& $this->recallObject('HTTPQuery');
return $this->HttpQuery->Set($var,$val);
}
/**
* Deletes kHTTPQuery variable
*
* @param string $var
* @todo think about method name
*/
function DeleteVar($var)
{
return $this->HttpQuery->Remove($var);
}
/**
* Deletes Session variable
*
* @param string $var
*/
function RemoveVar($var)
{
return $this->Session->RemoveVar($var);
}
function RemovePersistentVar($var)
{
return $this->Session->RemovePersistentVar($var);
}
/**
* Restores Session variable to it's db version
*
* @param string $var
*/
function RestoreVar($var)
{
return $this->Session->RestoreVar($var);
}
/**
* Returns session variable value
*
* Return value of $var variable stored in Session. An optional default value could be passed as second parameter.
*
* @see SimpleSession
* @access public
* @param string $var Variable name
* @param mixed $default Default value to return if no $var variable found in session
* @return mixed
*/
function RecallVar($var,$default=false)
{
return $this->Session->RecallVar($var,$default);
}
function RecallPersistentVar($var, $default = false)
{
return $this->Session->RecallPersistentVar($var, $default);
}
/**
* Stores variable $val in session under name $var
*
* Use this method to store variable in session. Later this variable could be recalled.
* @see RecallVar
* @access public
* @param string $var Variable name
* @param mixed $val Variable value
*/
function StoreVar($var, $val)
{
$session =& $this->recallObject('Session');
$this->Session->StoreVar($var, $val);
}
function StorePersistentVar($var, $val)
{
$this->Session->StorePersistentVar($var, $val);
}
function StoreVarDefault($var, $val)
{
$session =& $this->recallObject('Session');
$this->Session->StoreVarDefault($var, $val);
}
/**
* Links HTTP Query variable with session variable
*
* If variable $var is passed in HTTP Query it is stored in session for later use. If it's not passed it's recalled from session.
* This method could be used for making sure that GetVar will return query or session value for given
* variable, when query variable should overwrite session (and be stored there for later use).<br>
* This could be used for passing item's ID into popup with multiple tab -
* in popup script you just need to call LinkVar('id', 'current_id') before first use of GetVar('id').
* After that you can be sure that GetVar('id') will return passed id or id passed earlier and stored in session
* @access public
* @param string $var HTTP Query (GPC) variable name
* @param mixed $ses_var Session variable name
* @param mixed $default Default variable value
*/
function LinkVar($var, $ses_var = null, $default = '')
{
if (!isset($ses_var)) $ses_var = $var;
if ($this->GetVar($var) !== false) {
$this->StoreVar($ses_var, $this->GetVar($var));
}
else {
$this->SetVar($var, $this->RecallVar($ses_var, $default));
}
}
/**
* Returns variable from HTTP Query, or from session if not passed in HTTP Query
*
* The same as LinkVar, but also returns the variable value taken from HTTP Query if passed, or from session if not passed.
* Returns the default value if variable does not exist in session and was not passed in HTTP Query
*
* @see LinkVar
* @access public
* @param string $var HTTP Query (GPC) variable name
* @param mixed $ses_var Session variable name
* @param mixed $default Default variable value
* @return mixed
*/
function GetLinkedVar($var, $ses_var = null, $default = '')
{
$this->LinkVar($var, $ses_var, $default);
return $this->GetVar($var);
}
function AddBlock($name, $tpl)
{
$this->cache[$name] = $tpl;
}
/* Seems to be not used anywhere... /Kostja
function SetTemplateBody($title,$body)
{
$templates_cache =& $this->recallObject('TemplatesCache');
$templates_cache->SetTemplateBody($title,$body);
}*/
function ProcessTag($tag_data)
{
$a_tag = new Tag($tag_data,$this->Parser);
return $a_tag->DoProcessTag();
}
function ProcessParsedTag($prefix, $tag, $params)
{
$a_tag = new Tag('',$this->Parser);
$a_tag->Tag = $tag;
$tmp=$this->Application->processPrefix($prefix);
$a_tag->Processor = $tmp['prefix'];
$a_tag->Special = $tmp['special'];
$a_tag->NamedParams = $params;
return $a_tag->DoProcessTag();
}
/**
* Return ADODB Connection object
*
* Returns ADODB Connection object already connected to the project database, configurable in config.php
* @access public
* @return kDBConnection
*/
function &GetADODBConnection()
{
return $this->Conn;
}
function ParseBlock($params,$pass_params=0,$as_template=false)
{
if (substr($params['name'], 0, 5) == 'html:') return substr($params['name'], 6);
return $this->Parser->ParseBlock($params, $pass_params, $as_template);
}
/**
* Returns index file, that could be passed as parameter to method, as parameter to tag and as constant or not passed at all
*
* @param string $prefix
* @param string $index_file
* @param Array $params
* @return string
*/
function getIndexFile($prefix, $index_file, &$params)
{
if (isset($params['index_file'])) {
$index_file = $params['index_file'];
unset($params['index_file']);
return $index_file;
}
if (isset($index_file)) {
return $index_file;
}
if (defined('INDEX_FILE')) {
return INDEX_FILE;
}
$cut_prefix = trim(BASE_PATH, '/').'/'.trim($prefix, '/');
return trim(preg_replace('/'.preg_quote($cut_prefix, '/').'(.*)/', '\\1', $_SERVER['PHP_SELF']), '/');
}
/**
* Return href for template
*
* @access public
* @param string $t Template path
* @var string $prefix index.php prefix - could be blank, 'admin'
*/
function HREF($t, $prefix='', $params=null, $index_file=null)
{
if(!$t) $t = $this->GetVar('t'); // moved from kMainTagProcessor->T()
if ($this->isModuleEnabled('Proj-CMS')) {
$t = preg_replace('/^Content\//', '', $t);
}
/*if ($this->GetVar('skip_last_template')) {
$params['opener'] = 'p';
$this->SetVar('m_opener', 'p');
}
if ($t == 'incs/close_popup') {
// because this template closes the popup and we don't need popup mark here anymore
$params['m_opener'] = 's';
}*/
if( substr($t, -4) == '.tpl' ) $t = substr($t, 0, strlen($t) - 4 );
if ( $this->IsAdmin() && $prefix == '') $prefix = '/admin';
if ( $this->IsAdmin() && $prefix == '_FRONT_END_') $prefix = '';
$index_file = $this->getIndexFile($prefix, $index_file, $params);
if (isset($params['_auto_prefix_'])) {
unset($params['_auto_prefix_']); // this is parser-related param, do not need to pass it here
}
$ssl = isset($params['__SSL__']) ? $params['__SSL__'] : null;
if ($ssl !== null) {
$session =& $this->recallObject('Session');
$cookie_url = trim($session->CookieDomain.$session->CookiePath, '/.');
if ($ssl) {
$target_url = $this->ConfigValue('SSL_URL');
}
else {
$target_url = 'http://'.DOMAIN.$this->ConfigValue('Site_Path');
}
if (!preg_match('#'.preg_quote($cookie_url).'#', $target_url)) {
$session->SetMode(smGET_ONLY);
}
}
if (getArrayValue($params, 'opener') == 'u') {
$wid = $this->Application->GetVar('m_wid');
$stack_name = rtrim('opener_stack_'.$wid, '_');
$opener_stack = $this->RecallVar($stack_name);
if ($opener_stack && $opener_stack != serialize(Array())) {
$opener_stack = unserialize($opener_stack);
list($index_file, $env) = explode('|', $opener_stack[count($opener_stack) - 1]);
$ret = $this->BaseURL($prefix, $ssl).$index_file.'?'.ENV_VAR_NAME.'='.$env;
if ( getArrayValue($params,'escape') ) $ret = addslashes($ret);
if (isset($params['m_opener']) && $params['m_opener'] == 'u') {
array_pop($opener_stack);
if (!$opener_stack) {
$this->RemoveVar($stack_name);
// remove popups last templates, because popup is closing now
$this->RemoveVar('last_template_'.$wid);
$this->RemoveVar('last_template_popup_'.$wid);
// don't save popups last templates again :)
$this->SetVar('skip_last_template', 1);
}
else {
$this->StoreVar($stack_name, serialize($opener_stack));
}
}
return $ret;
}
else {
//define('DBG_REDIRECT', 1);
$t = $this->GetVar('t');
}
}
$pass = isset($params['pass']) ? $params['pass'] : '';
$pass_events = isset($params['pass_events']) ? $params['pass_events'] : false; // pass events with url
$map_link = '';
if( isset($params['anchor']) )
{
$map_link = '#'.$params['anchor'];
unset($params['anchor']);
}
if ( isset($params['no_amp']) )
{
$params['__URLENCODE__'] = $params['no_amp'];
unset($params['no_amp']);
}
$no_rewrite = false;
if( isset($params['__NO_REWRITE__']) )
{
$no_rewrite = true;
unset($params['__NO_REWRITE__']);
}
$force_rewrite = false;
if( isset($params['__MOD_REWRITE__']) )
{
$force_rewrite = true;
unset($params['__MOD_REWRITE__']);
}
$force_no_sid = false;
if( isset($params['__NO_SID__']) )
{
$force_no_sid = true;
unset($params['__NO_SID__']);
}
// append pass through variables to each link to be build
$params = array_merge_recursive2($this->getPassThroughVariables($params), $params);
if ($force_rewrite || ($this->RewriteURLs($ssl) && !$no_rewrite))
{
$session =& $this->recallObject('Session');
if( $session->NeedQueryString() && !$force_no_sid ) $params['sid'] = $this->GetSID();
$url = $this->BuildEnv_NEW($t, $params, $pass, $pass_events);
$ret = $this->BaseURL($prefix, $ssl).$url.$map_link;
}
else
{
unset($params['pass_category']); // we don't need to pass it when mod_rewrite is off
$env = $this->BuildEnv($t, $params, $pass, $pass_events);
$ret = $this->BaseURL($prefix, $ssl).$index_file.'?'.$env.$map_link;
}
return $ret;
}
/**
* Returns variables with values that should be passed throught with this link + variable list
*
* @param Array $params
* @return Array
*/
function getPassThroughVariables(&$params)
{
static $cached_pass_through = null;
if (isset($params['no_pass_through']) && $params['no_pass_through']) {
unset($params['no_pass_through']);
return Array();
}
// because pass through is not changed during script run, then we can cache it
if (is_null($cached_pass_through)) {
$cached_pass_through = Array();
$pass_through = $this->Application->GetVar('pass_through');
if ($pass_through) {
// names of variables to pass to each link
$cached_pass_through['pass_through'] = $pass_through;
$pass_through = explode(',', $pass_through);
foreach ($pass_through as $pass_through_var) {
$cached_pass_through[$pass_through_var] = $this->Application->GetVar($pass_through_var);
}
}
}
return $cached_pass_through;
}
/**
* Returns sorted array of passed prefixes (to build url from)
*
* @param string $pass
* @return Array
*/
function getPassInfo($pass = 'all')
{
if (!$pass) $pass = 'all';
$pass = trim(
preg_replace(
'/(?<=,|\\A)all(?=,|\\z)/',
trim($this->GetVar('passed'), ','),
trim($pass, ',')
),
',');
if (!$pass) {
return Array();
}
$pass_info = array_unique( explode(',', $pass) ); // array( prefix[.special], prefix[.special] ...
sort($pass_info, SORT_STRING); // to be prefix1,prefix1.special1,prefix1.special2,prefix3.specialX
// ensure that "m" prefix is at the beginning
$main_index = array_search('m', $pass_info);
if ($main_index !== false) {
unset($pass_info[$main_index]);
array_unshift($pass_info, 'm');
}
return $pass_info;
}
function BuildEnv_NEW($t, $params, $pass='all', $pass_events = false)
{
// $session =& $this->recallObject('Session');
$force_admin = getArrayValue($params,'admin') || $this->GetVar('admin');
// if($force_admin) $sid = $this->GetSID();
$ret = '';
$env = '';
$encode = false;
if (isset($params['__URLENCODE__']))
{
$encode = $params['__URLENCODE__'];
unset($params['__URLENCODE__']);
}
if (isset($params['__SSL__'])) {
unset($params['__SSL__']);
}
$m_only = true;
$pass_info = $this->getPassInfo($pass);
if ($pass_info) {
if ($pass_info[0] == 'm') array_shift($pass_info);
$params['t'] = $t;
foreach($pass_info as $pass_index => $pass_element)
{
list($prefix) = explode('.', $pass_element);
$require_rewrite = $this->findModule('Var', $prefix) && $this->getUnitOption($prefix, 'CatalogItem');
if ($require_rewrite) {
// if next prefix is same as current, but with special => exclude current prefix from url
$next_prefix = getArrayValue($pass_info, $pass_index + 1);
if ($next_prefix) {
$next_prefix = substr($next_prefix, 0, strlen($prefix) + 1);
if ($prefix.'.' == $next_prefix) continue;
}
$a = $this->BuildModuleEnv_NEW($pass_element, $params, $pass_events);
if ($a) {
$ret .= '/'.$a;
$m_only = false;
}
}
else
{
$env .= ':'.$this->BuildModuleEnv($pass_element, $params, $pass_events);
}
}
if (!$m_only) $params['pass_category'] = 1;
$ret = $this->BuildModuleEnv_NEW('m', $params, $pass_events).$ret;
$cat_processed = isset($params['category_processed']) && $params['category_processed'];
if ($cat_processed) {
unset($params['category_processed']);
}
if (!$m_only || !$cat_processed || !defined('EXP_DIR_URLS')) {
$ret = trim($ret, '/').'.html';
}
else {
$ret .= '/';
}
// $ret = trim($ret, '/').'/';
if($env) $params[ENV_VAR_NAME] = ltrim($env, ':');
}
unset($params['pass'], $params['opener'], $params['m_event']);
if ($force_admin) $params['admin'] = 1;
if( getArrayValue($params,'escape') )
{
$ret = addslashes($ret);
unset($params['escape']);
}
$ret = str_replace('%2F', '/', urlencode($ret));
$params_str = '';
$join_string = $encode ? '&' : '&amp;';
foreach ($params as $param => $value)
{
$params_str .= $join_string.$param.'='.$value;
}
$ret .= preg_replace('/^'.$join_string.'(.*)/', '?\\1', $params_str);
if ($encode) {
$ret = str_replace('\\', '%5C', $ret);
}
return $ret;
}
function BuildModuleEnv_NEW($prefix_special, &$params, $pass_events = false)
{
$event_params = Array('pass_events' => $pass_events, 'url_params' => $params);
$event = new kEvent($prefix_special.':BuildEnv', $event_params);
$this->HandleEvent($event);
$params = $event->getEventParam('url_params'); // save back unprocessed parameters
$ret = '';
if ($event->getEventParam('env_string')) {
$ret = trim( $event->getEventParam('env_string'), '/');
}
return $ret;
}
/**
* Builds env part that corresponds prefix passed
*
* @param string $prefix_special item's prefix & [special]
* @param Array $params url params
* @param bool $pass_events
*/
function BuildModuleEnv($prefix_special, &$params, $pass_events = false)
{
list($prefix) = explode('.', $prefix_special);
$query_vars = $this->getUnitOption($prefix, 'QueryString');
//if pass events is off and event is not implicity passed
if( !$pass_events && !isset($params[$prefix_special.'_event']) ) {
$params[$prefix_special.'_event'] = ''; // remove event from url if requested
//otherwise it will use value from get_var
}
if(!$query_vars) return '';
$tmp_string = Array(0 => $prefix_special);
foreach($query_vars as $index => $var_name)
{
//if value passed in params use it, otherwise use current from application
$var_name = $prefix_special.'_'.$var_name;
$tmp_string[$index] = isset( $params[$var_name] ) ? $params[$var_name] : $this->GetVar($var_name);
if ( isset($params[$var_name]) ) unset( $params[$var_name] );
}
$escaped = array();
foreach ($tmp_string as $tmp_val) {
$escaped[] = str_replace(Array('-',':'), Array('\-','\:'), $tmp_val);
}
$ret = implode('-', $escaped);
if ($this->getUnitOption($prefix, 'PortalStyleEnv') == true)
{
$ret = preg_replace('/^([a-zA-Z]+)-([0-9]+)-(.*)/','\\1\\2-\\3', $ret);
}
return $ret;
}
function BuildEnv($t, $params, $pass='all', $pass_events = false, $env_var = true)
{
$session =& $this->recallObject('Session');
$ssl = isset($params['__SSL__']) ? $params['__SSL__'] : 0;
$sid = $session->NeedQueryString() && !$this->RewriteURLs($ssl) ? $this->GetSID() : '';
// if (getArrayValue($params,'admin') == 1) $sid = $this->GetSID();
$ret = '';
if ($env_var) {
$ret = ENV_VAR_NAME.'=';
}
$ret .= $sid.(constOn('INPORTAL_ENV') ? '-' : ':');
$encode = false;
if (isset($params['__URLENCODE__'])) {
$encode = $params['__URLENCODE__'];
unset($params['__URLENCODE__']);
}
if (isset($params['__SSL__'])) {
unset($params['__SSL__']);
}
$env_string = '';
$category_id = isset($params['m_cat_id']) ? $params['m_cat_id'] : $this->GetVar('m_cat_id');
$item_id = 0;
$pass_info = $this->getPassInfo($pass);
if ($pass_info) {
if ($pass_info[0] == 'm') array_shift($pass_info);
foreach ($pass_info as $pass_element) {
list($prefix) = explode('.', $pass_element);
$require_rewrite = $this->findModule('Var', $prefix);
if ($require_rewrite) {
$item_id = isset($params[$pass_element.'_id']) ? $params[$pass_element.'_id'] : $this->GetVar($pass_element.'_id');
}
$env_string .= ':'.$this->BuildModuleEnv($pass_element, $params, $pass_events);
}
}
if (strtolower($t) == '__default__') {
// to put category & item templates into cache
$filename = $this->getFilename('c', $category_id);
if ($item_id) {
$mod_rw_helper =& $this->Application->recallObject('ModRewriteHelper');
$t = $mod_rw_helper->GetItemTemplate($category_id, $pass_element); // $pass_element should be the last processed element
// $t = $this->getCache('item_templates', $category_id);
}
elseif ($category_id) {
$t = $this->getCache('category_templates', $category_id);
}
else {
$t = 'index';
}
}
$ret .= $t.':'.$this->BuildModuleEnv('m', $params, $pass_events).$env_string;
unset($params['pass']);
unset($params['opener']);
unset($params['m_event']);
if ($this->GetVar('admin') && !isset($params['admin'])) {
$params['admin'] = 1;
}
if( getArrayValue($params,'escape') )
{
$ret = addslashes($ret);
unset($params['escape']);
}
$join_string = $encode ? '&' : '&amp;';
$params_str = '';
foreach ($params as $param => $value)
{
$params_str .= $join_string.$param.'='.$value;
}
$ret .= $params_str;
if ($encode) {
$ret = str_replace('\\', '%5C', $ret);
}
return $ret;
}
function BaseURL($prefix='', $ssl=null)
{
if ($ssl === null) {
return PROTOCOL.SERVER_NAME.(defined('PORT')?':'.PORT : '').rtrim(BASE_PATH, '/').$prefix.'/';
}
else {
if ($ssl) {
return rtrim( $this->ConfigValue('SSL_URL'), '/').$prefix.'/';
}
else {
return 'http://'.DOMAIN.(defined('PORT')?':'.PORT : '').rtrim( $this->ConfigValue('Site_Path'), '/').$prefix.'/';
}
}
}
function Redirect($t='', $params=null, $prefix='', $index_file=null)
{
$js_redirect = getArrayValue($params, 'js_redirect');
if (preg_match("/external:(.*)/", $t, $rets)) {
$location = $rets[1];
}
else {
if ($t == '' || $t === true) $t = $this->GetVar('t');
// pass prefixes and special from previous url
if( isset($params['js_redirect']) ) unset($params['js_redirect']);
if (!isset($params['pass'])) $params['pass'] = 'all';
if ($this->GetVar('ajax') == 'yes' && $t == $this->GetVar('t')) {
// redirects to the same template as current
$params['ajax'] = 'yes';
}
$params['__URLENCODE__'] = 1;
$location = $this->HREF($t, $prefix, $params, $index_file);
//echo " location : $location <br>";
}
$a_location = $location;
$location = "Location: $location";
if ($this->isDebugMode() && constOn('DBG_REDIRECT')) {
$this->Debugger->appendTrace();
echo "<b>Debug output above!!!</b> Proceed to redirect: <a href=\"$a_location\">$a_location</a><br>";
}
else {
if ($js_redirect) {
$this->SetVar('t', 'redirect');
$this->SetVar('redirect_to_js', addslashes($a_location) );
$this->SetVar('redirect_to', $a_location);
return true;
}
else {
if ($this->GetVar('ajax') == 'yes' && $t != $this->GetVar('t')) {
// redirection to other then current template during ajax request
echo '#redirect#'.$a_location;
}
elseif (headers_sent() != '') {
// some output occured -> redirect using javascript
echo '<script type="text/javascript">window.location.href = \''.$a_location.'\';</script>';
}
else {
// no output before -> redirect using HTTP header
// header('HTTP/1.1 302 Found');
header("$location");
}
}
}
ob_end_flush();
// session expiration is called from session initialization,
// that's why $this->Session may be not defined here
if (is_object($this->Session)) {
$this->Session->SaveData();
}
exit;
}
function Phrase($label)
{
return $this->Phrases->GetPhrase($label);
}
/**
* Replace language tags in exclamation marks found in text
*
* @param string $text
* @param bool $force_escape force escaping, not escaping of resulting string
* @return string
* @access public
*/
function ReplaceLanguageTags($text, $force_escape=null)
{
// !!!!!!!!
// if( !is_object($this->Phrases) ) $this->Debugger->appendTrace();
return $this->Phrases->ReplaceLanguageTags($text,$force_escape);
}
/**
* Checks if user is logged in, and creates
* user object if so. User object can be recalled
* later using "u.current" prefix_special. Also you may
* get user id by getting "u.current_id" variable.
*
* @access private
*/
function ValidateLogin()
{
$session =& $this->recallObject('Session');
$user_id = $session->GetField('PortalUserId');
if (!$user_id && $user_id != -1) $user_id = -2;
$this->SetVar('u.current_id', $user_id);
if (!$this->IsAdmin()) {
// needed for "profile edit", "registration" forms ON FRONT ONLY
$this->SetVar('u_id', $user_id);
}
$this->StoreVar('user_id', $user_id);
if ($this->GetVar('expired') == 1) {
// this parameter is set only from admin
$user =& $this->recallObject('u.current');
$user->SetError('ValidateLogin', 'session_expired', 'la_text_sess_expired');
}
if (($user_id != -2) && constOn('DBG_REQUREST_LOG') ) {
$http_query =& $this->recallObject('HTTPQuery');
$http_query->writeRequestLog(DBG_REQUREST_LOG);
}
if ($user_id != -2) {
// normal users + root
$this->LoadPersistentVars();
}
}
/**
* Loads current user persistent session data
*
*/
function LoadPersistentVars()
{
$this->Session->LoadPersistentVars();
}
function LoadCache() {
$cache_key = $this->GetVar('t').$this->GetVar('m_theme').$this->GetVar('m_lang').$this->IsAdmin();
$query = sprintf("SELECT PhraseList, ConfigVariables FROM %s WHERE Template = %s",
TABLE_PREFIX.'PhraseCache',
$this->Conn->Qstr(md5($cache_key)));
$res = $this->Conn->GetRow($query);
if ($res) {
$this->Caches['PhraseList'] = $res['PhraseList'] ? explode(',', $res['PhraseList']) : array();
$config_ids = $res['ConfigVariables'] ? explode(',', $res['ConfigVariables']) : array();
$config_ids = array_diff($config_ids, $this->Caches['ConfigVariables']);
}
else {
$config_ids = array();
}
$this->Caches['ConfigVariables'] = $config_ids;
$this->ConfigCacheIds = $config_ids;
}
function UpdateCache()
{
$update = false;
//something changed
$update = $update || $this->Phrases->NeedsCacheUpdate();
$update = $update || (count($this->ConfigCacheIds) && $this->ConfigCacheIds != $this->Caches['ConfigVariables']);
if ($update) {
$cache_key = $this->GetVar('t').$this->GetVar('m_theme').$this->GetVar('m_lang').$this->IsAdmin();
$query = sprintf("REPLACE %s (PhraseList, CacheDate, Template, ConfigVariables)
VALUES (%s, %s, %s, %s)",
TABLE_PREFIX.'PhraseCache',
$this->Conn->Qstr(join(',', $this->Phrases->Ids)),
adodb_mktime(),
$this->Conn->Qstr(md5($cache_key)),
$this->Conn->qstr(implode(',', array_unique($this->ConfigCacheIds))));
$this->Conn->Query($query);
}
}
function InitConfig()
{
if (isset($this->Caches['ConfigVariables']) && count($this->Caches['ConfigVariables']) > 0) {
$this->ConfigHash = array_merge($this->ConfigHash, $this->Conn->GetCol(
'SELECT VariableValue, VariableName FROM '.TABLE_PREFIX.'ConfigurationValues
WHERE VariableId IN ('.implode(',', $this->Caches['ConfigVariables']).')', 'VariableName'));
}
}
/**
* Returns configuration option value by name
*
* @param string $name
* @return string
*/
function ConfigValue($name)
{
$res = isset($this->ConfigHash[$name]) ? $this->ConfigHash[$name] : false;
if ($res !== false) return $res;
$res = $this->Conn->GetRow('SELECT VariableId, VariableValue FROM '.TABLE_PREFIX.'ConfigurationValues WHERE VariableName = '.$this->Conn->qstr($name));
if ($res) {
$this->ConfigHash[$name] = $res['VariableValue'];
$this->ConfigCacheIds[] = $res['VariableId'];
return $res['VariableValue'];
}
return false;
}
function UpdateConfigCache()
{
if ($this->ConfigCacheIds) {
}
}
/**
* Allows to process any type of event
*
* @param kEvent $event
* @access public
* @author Alex
*/
function HandleEvent(&$event, $params=null, $specificParams=null)
{
if ( isset($params) ) {
$event = new kEvent( $params, $specificParams );
}
if (!isset($this->EventManager)) {
$this->EventManager =& $this->recallObject('EventManager');
}
$this->EventManager->HandleEvent($event);
}
/**
* Registers new class in the factory
*
* @param string $real_class Real name of class as in class declaration
* @param string $file Filename in what $real_class is declared
* @param string $pseudo_class Name under this class object will be accessed using getObject method
* @param Array $dependecies List of classes required for this class functioning
* @access public
* @author Alex
*/
function registerClass($real_class, $file, $pseudo_class = null, $dependecies = Array() )
{
$this->Factory->registerClass($real_class, $file, $pseudo_class, $dependecies);
}
/**
* Add $class_name to required classes list for $depended_class class.
* All required class files are included before $depended_class file is included
*
* @param string $depended_class
* @param string $class_name
* @author Alex
*/
function registerDependency($depended_class, $class_name)
{
$this->Factory->registerDependency($depended_class, $class_name);
}
/**
* Registers Hook from subprefix event to master prefix event
*
* @param string $hookto_prefix
* @param string $hookto_special
* @param string $hookto_event
* @param string $mode
* @param string $do_prefix
* @param string $do_special
* @param string $do_event
* @param string $conditional
* @access public
* @todo take care of a lot parameters passed
* @author Kostja
*/
function registerHook($hookto_prefix, $hookto_special, $hookto_event, $mode, $do_prefix, $do_special, $do_event, $conditional)
{
$event_manager =& $this->recallObject('EventManager');
$event_manager->registerHook($hookto_prefix, $hookto_special, $hookto_event, $mode, $do_prefix, $do_special, $do_event, $conditional);
}
/**
* Allows one TagProcessor tag act as other TagProcessor tag
*
* @param Array $tag_info
* @author Kostja
*/
function registerAggregateTag($tag_info)
{
$aggregator =& $this->recallObject('TagsAggregator', 'kArray');
$aggregator->SetArrayValue($tag_info['AggregateTo'], $tag_info['AggregatedTagName'], Array($tag_info['LocalPrefix'], $tag_info['LocalTagName'], getArrayValue($tag_info, 'LocalSpecial')));
}
/**
* Returns object using params specified,
* creates it if is required
*
* @param string $name
* @param string $pseudo_class
* @param Array $event_params
* @return Object
* @author Alex
*/
function &recallObject($name,$pseudo_class=null,$event_params=Array())
{
$result =& $this->Factory->getObject($name, $pseudo_class, $event_params);
return $result;
}
/**
* Returns object using Variable number of params,
* all params starting with 4th are passed to object consturctor
*
* @param string $name
* @param string $pseudo_class
* @param Array $event_params
* @return Object
* @author Alex
*/
function &recallObjectP($name,$pseudo_class=null,$event_params=Array())
{
$func_args = func_get_args();
$result =& ref_call_user_func_array( Array(&$this->Factory, 'getObjectP'), $func_args );
return $result;
}
/**
* Returns tag processor for prefix specified
*
* @param string $prefix
* @return kDBTagProcessor
*/
function &recallTagProcessor($prefix)
{
$result =& $this->recallObject($prefix.'_TagProcessor');
return $result;
}
/**
* Checks if object with prefix passes was already created in factory
*
* @param string $name object presudo_class, prefix
* @return bool
* @author Kostja
*/
function hasObject($name)
{
return isset($this->Factory->Storage[$name]);
}
/**
* Removes object from storage by given name
*
* @param string $name Object's name in the Storage
* @author Kostja
*/
function removeObject($name)
{
$this->Factory->DestroyObject($name);
}
/**
* Get's real class name for pseudo class,
* includes class file and creates class
* instance
*
* @param string $pseudo_class
* @return Object
* @access public
* @author Alex
*/
function &makeClass($pseudo_class)
{
$func_args = func_get_args();
$result =& ref_call_user_func_array( Array(&$this->Factory, 'makeClass'), $func_args);
return $result;
}
/**
* Checks if application is in debug mode
*
* @param bool $check_debugger check if kApplication debugger is initialized too, not only for defined DEBUG_MODE constant
* @return bool
* @author Alex
* @access public
*/
function isDebugMode($check_debugger = true)
{
$debug_mode = defined('DEBUG_MODE') && DEBUG_MODE;
if($check_debugger)
{
$debug_mode = $debug_mode && is_object($this->Debugger);
}
return $debug_mode;
}
/**
* Checks if it is admin
*
* @return bool
* @author Alex
*/
function IsAdmin()
{
return constOn('ADMIN');
}
/**
* Apply url rewriting used by mod_rewrite or not
*
* @param bool $ssl Force ssl link to be build
* @return bool
*/
function RewriteURLs($ssl = false)
{
// case #1,#4:
// we want to create https link from http mode
// we want to create https link from https mode
// conditions: ($ssl || PROTOCOL == 'https://') && $this->ConfigValue('UseModRewriteWithSSL')
// case #2,#3:
// we want to create http link from https mode
// we want to create http link from http mode
// conditions: !$ssl && (PROTOCOL == 'https://' || PROTOCOL == 'http://')
$allow_rewriting =
(!$ssl && (PROTOCOL == 'https://' || PROTOCOL == 'http://')) // always allow mod_rewrite for http
|| // or allow rewriting for redirect TO httpS or when already in httpS
(($ssl || PROTOCOL == 'https://') && $this->ConfigValue('UseModRewriteWithSSL')); // but only if it's allowed in config!
return constOn('MOD_REWRITE') && $allow_rewriting;
}
/**
* Reads unit (specified by $prefix)
* option specified by $option
*
* @param string $prefix
* @param string $option
* @param mixed $default
* @return string
* @access public
* @author Alex
*/
function getUnitOption($prefix, $option, $default = false)
{
/*if (!isset($this->UnitConfigReader)) {
$this->UnitConfigReader =& $this->recallObject('kUnitConfigReader');
}*/
return $this->UnitConfigReader->getUnitOption($prefix, $option, $default);
}
/**
* Set's new unit option value
*
* @param string $prefix
* @param string $name
* @param string $value
* @author Alex
* @access public
*/
function setUnitOption($prefix, $option, $value)
{
// $unit_config_reader =& $this->recallObject('kUnitConfigReader');
return $this->UnitConfigReader->setUnitOption($prefix,$option,$value);
}
/**
* Read all unit with $prefix options
*
* @param string $prefix
* @return Array
* @access public
* @author Alex
*/
function getUnitOptions($prefix)
{
// $unit_config_reader =& $this->recallObject('kUnitConfigReader');
return $this->UnitConfigReader->getUnitOptions($prefix);
}
/**
* Returns true if config exists and is allowed for reading
*
* @param string $prefix
* @return bool
*/
function prefixRegistred($prefix)
{
/*if (!isset($this->UnitConfigReader)) {
$this->UnitConfigReader =& $this->recallObject('kUnitConfigReader');
}*/
return $this->UnitConfigReader->prefixRegistred($prefix);
}
/**
* Splits any mixing of prefix and
* special into correct ones
*
* @param string $prefix_special
* @return Array
* @access public
* @author Alex
*/
function processPrefix($prefix_special)
{
return $this->Factory->processPrefix($prefix_special);
}
/**
* Set's new event for $prefix_special
* passed
*
* @param string $prefix_special
* @param string $event_name
* @access public
*/
function setEvent($prefix_special,$event_name)
{
$event_manager =& $this->recallObject('EventManager');
$event_manager->setEvent($prefix_special,$event_name);
}
/**
* SQL Error Handler
*
* @param int $code
* @param string $msg
* @param string $sql
* @return bool
* @access private
* @author Alex
*/
function handleSQLError($code, $msg, $sql)
{
if ( isset($this->Debugger) )
{
$errorLevel = constOn('DBG_SQL_FAILURE') && !defined('IS_INSTALL') ? E_USER_ERROR : E_USER_WARNING;
$this->Debugger->dumpVars($_REQUEST);
$this->Debugger->appendTrace();
$error_msg = '<span class="debug_error">'.$msg.' ('.$code.')</span><br><a href="javascript:$Debugger.SetClipboard(\''.htmlspecialchars($sql).'\');"><b>SQL</b></a>: '.$this->Debugger->formatSQL($sql);
$long_id = $this->Debugger->mapLongError($error_msg);
trigger_error( substr($msg.' ('.$code.') ['.$sql.']',0,1000).' #'.$long_id, $errorLevel);
return true;
}
else
{
//$errorLevel = constOn('IS_INSTALL') ? E_USER_WARNING : E_USER_ERROR;
$errorLevel = E_USER_WARNING;
trigger_error('<b>SQL Error</b> in sql: '.$sql.', code <b>'.$code.'</b> ('.$msg.')', $errorLevel);
/*echo '<b>xProcessing SQL</b>: '.$sql.'<br>';
echo '<b>Error ('.$code.'):</b> '.$msg.'<br>';*/
return $errorLevel == E_USER_ERROR ? false : true;
}
}
/**
* Default error handler
*
* @param int $errno
* @param string $errstr
* @param string $errfile
* @param int $errline
* @param Array $errcontext
*/
function handleError($errno, $errstr, $errfile = '', $errline = '', $errcontext = '')
{
if( constOn('SILENT_LOG') )
{
$fp = fopen(FULL_PATH.'/silent_log.txt','a');
$time = adodb_date('d/m/Y H:i:s');
fwrite($fp, '['.$time.'] #'.$errno.': '.strip_tags($errstr).' in ['.$errfile.'] on line '.$errline."\n");
fclose($fp);
}
if( !$this->errorHandlers ) return true;
$i = 0; // while (not foreach) because it is array of references in some cases
$eh_count = count($this->errorHandlers);
while($i < $eh_count)
{
if( is_array($this->errorHandlers[$i]) )
{
$object =& $this->errorHandlers[$i][0];
$method = $this->errorHandlers[$i][1];
$object->$method($errno, $errstr, $errfile, $errline, $errcontext);
}
else
{
$function = $this->errorHandlers[$i];
$function($errno, $errstr, $errfile, $errline, $errcontext);
}
$i++;
}
}
/**
* Returns & blocks next ResourceId available in system
*
* @return int
* @access public
* @author Alex
*/
function NextResourceId()
{
$table_name = TABLE_PREFIX.'IdGenerator';
$this->Conn->Query('LOCK TABLES '.$table_name.' WRITE');
$this->Conn->Query('UPDATE '.$table_name.' SET lastid = lastid + 1');
$id = $this->Conn->GetOne('SELECT lastid FROM '.$table_name);
if($id === false)
{
$this->Conn->Query('INSERT INTO '.$table_name.' (lastid) VALUES (2)');
$id = 2;
}
$this->Conn->Query('UNLOCK TABLES');
return $id - 1;
}
/**
* Returns genealogical main prefix for subtable prefix passes
* OR prefix, that has been found in REQUEST and some how is parent of passed subtable prefix
*
* @param string $current_prefix
* @param string $real_top if set to true will return real topmost prefix, regardless of its id is passed or not
* @return string
* @access public
* @author Kostja / Alex
*/
function GetTopmostPrefix($current_prefix, $real_top=false)
{
// 1. get genealogical tree of $current_prefix
$prefixes = Array ($current_prefix);
while ( $parent_prefix = $this->getUnitOption($current_prefix, 'ParentPrefix') ) {
$current_prefix = $parent_prefix;
array_unshift($prefixes, $current_prefix);
}
if ($real_top) return $current_prefix;
// 2. find what if parent is passed
$passed = explode(',', $this->GetVar('all_passed'));
foreach ($prefixes as $a_prefix) {
if (in_array($a_prefix, $passed)) {
return $a_prefix;
}
}
return $current_prefix;
}
/**
* Triggers email event of type Admin
*
* @param string $email_event_name
* @param int $to_user_id
* @param array $send_params associative array of direct send params, possible keys: to_email, to_name, from_email, from_name, message, message_text
* @return unknown
*/
function &EmailEventAdmin($email_event_name, $to_user_id = -1, $send_params = false)
{
return $this->EmailEvent($email_event_name, 1, $to_user_id, $send_params);
}
/**
* Triggers email event of type User
*
* @param string $email_event_name
* @param int $to_user_id
* @param array $send_params associative array of direct send params, possible keys: to_email, to_name, from_email, from_name, message, message_text
* @return unknown
*/
function &EmailEventUser($email_event_name, $to_user_id = -1, $send_params = false)
{
return $this->EmailEvent($email_event_name, 0, $to_user_id, $send_params);
}
/**
* Triggers general email event
*
* @param string $email_event_name
* @param int $email_event_type ( 0 for User, 1 for Admin)
* @param int $to_user_id
* @param array $send_params associative array of direct send params,
* possible keys: to_email, to_name, from_email, from_name, message, message_text
* @return unknown
*/
function &EmailEvent($email_event_name, $email_event_type, $to_user_id = -1, $send_params = false)
{
$params = array(
'EmailEventName' => $email_event_name,
'EmailEventToUserId' => $to_user_id,
'EmailEventType' => $email_event_type,
);
if ($send_params) {
$params['DirectSendParams'] = $send_params;
}
$event_str = isset($send_params['use_special']) ? 'emailevents.'.$send_params['use_special'].':OnEmailEvent' : 'emailevents:OnEmailEvent';
$this->HandleEvent($event, $event_str, $params);
return $event;
}
function LoggedIn()
{
$user_id = $this->Application->RecallVar('user_id');
$ret = $user_id > 0;
if ($this->IsAdmin() && ($user_id == -1)) {
$ret = true;
}
return $ret;
}
/**
* Check current user permissions based on it's group permissions in specified category
*
* @param string $name permission name
* @param int $cat_id category id, current used if not specified
* @param int $type permission type {1 - system, 0 - per category}
* @return int
*/
function CheckPermission($name, $type = 1, $cat_id = null)
{
$perm_helper =& $this->recallObject('PermissionsHelper');
return $perm_helper->CheckPermission($name, $type, $cat_id);
}
/**
* Set's any field of current visit
*
* @param string $field
* @param mixed $value
*/
function setVisitField($field, $value)
{
$visit =& $this->recallObject('visits');
$visit->SetDBField($field, $value);
$visit->Update();
}
/**
* Allows to check if in-portal is installed
*
* @return bool
*/
function isInstalled()
{
return $this->InitDone && (count($this->ModuleInfo) > 0);
}
/**
* Allows to determine if module is installed & enabled
*
* @param string $module_name
* @return bool
*/
function isModuleEnabled($module_name)
{
return $this->findModule('Name', $module_name) !== false;
}
function reportError($class, $method)
{
$this->Debugger->appendTrace();
trigger_error('depricated method <b>'.$class.'->'.$method.'(...)</b>', E_USER_ERROR);
}
/**
* Returns Window ID of passed prefix main prefix (in edit mode)
*
* @param string $prefix
* @return mixed
*/
function GetTopmostWid($prefix)
{
$top_prefix = $this->GetTopmostPrefix($prefix);
$mode = $this->GetVar($top_prefix.'_mode');
return $mode != '' ? substr($mode, 1) : '';
}
/**
* Get temp table name
*
* @param string $table
* @param mixed $wid
* @return string
*/
function GetTempName($table, $wid = '')
{
if (preg_match('/prefix:(.*)/', $wid, $regs)) {
$wid = $this->GetTopmostWid($regs[1]);
}
return TABLE_PREFIX.'ses_'.$this->GetSID().($wid ? '_'.$wid : '').'_edit_'.$table;
}
function GetTempTablePrefix($wid = '')
{
if (preg_match('/prefix:(.*)/', $wid, $regs)) {
$wid = $this->GetTopmostWid($regs[1]);
}
return TABLE_PREFIX.'ses_'.$this->GetSID().($wid ? '_'.$wid : '').'_edit_';
}
function IsTempTable($table)
{
return preg_match('/'.TABLE_PREFIX.'ses_'.$this->GetSID().'(_[\d]+){0,1}_edit_(.*)/',$table);
}
/**
* Return live table name based on temp table name
*
* @param string $temp_table
* @return string
*/
function GetLiveName($temp_table)
{
if( preg_match('/'.TABLE_PREFIX.'ses_'.$this->GetSID().'(_[\d]+){0,1}_edit_(.*)/',$temp_table, $rets) )
{
// cut wid from table end if any
return $rets[2];
}
else
{
return $temp_table;
}
}
function CheckProcessors($processors)
{
foreach ($processors as $a_processor)
{
if (!isset($this->CachedProcessors[$a_processor])) {
$this->CachedProcessors[$a_processor] =& $this->recallObject($a_processor.'_TagProcessor');
}
}
}
function TimeZoneAdjustment($time_zone=null)
{
$target_zone = isset($time_zone) ? $time_zone : $this->ConfigValue('Config_Site_Time');
return 3600 * ($target_zone - $this->ConfigValue('Config_Server_Time'));
}
function ApplicationDie($message = '')
{
$message = ob_get_clean().$message;
if ($this->isDebugMode()) {
$message .= $this->Debugger->printReport(true);
}
echo $this->UseOutputCompression() ? gzencode($message, DBG_COMPRESSION_LEVEL) : $message;
exit;
}
/* moved from MyApplication */
function getUserGroups($user_id)
{
switch($user_id)
{
case -1:
$user_groups = $this->ConfigValue('User_LoggedInGroup');
break;
case -2:
$user_groups = $this->ConfigValue('User_LoggedInGroup');
$user_groups .= ','.$this->ConfigValue('User_GuestGroup');
break;
default:
$sql = 'SELECT GroupId FROM '.TABLE_PREFIX.'UserGroup WHERE PortalUserId = '.$user_id;
$res = $this->Conn->GetCol($sql);
$user_groups = Array( $this->ConfigValue('User_LoggedInGroup') );
if(is_array($res))
{
$user_groups = array_merge($user_groups, $res);
}
$user_groups = implode(',', $user_groups);
}
return $user_groups;
}
}
?>
\ No newline at end of file
Property changes on: branches/unlabeled/unlabeled-1.170.2/core/kernel/application.php
___________________________________________________________________
Modified: cvs2svn:cvs-rev
## -1 +1 ##
-1.170.2.1
\ No newline at end of property
+1.170.2.2
\ No newline at end of property
Index: branches/unlabeled/unlabeled-1.4.2/core/kernel/constants.php
===================================================================
--- branches/unlabeled/unlabeled-1.4.2/core/kernel/constants.php (revision 7747)
+++ branches/unlabeled/unlabeled-1.4.2/core/kernel/constants.php (revision 7748)
@@ -1,48 +1,52 @@
<?php
// kDBList filter types (then, types are divided into classes)
define('HAVING_FILTER', 1);
define('WHERE_FILTER', 2);
define('AGGREGATE_FILTER', 3);
// kDBList filter classes
define('FLT_SYSTEM', 1); // System Having/Where filter [AND]
define('FLT_NORMAL', 2); // User Having/Where filter [OR]
define('FLT_SEARCH', 3); // User "Search" Having/Where filter [OR]
define('FLT_VIEW', 4); // User "View Menu" Having/Where filter [AND]
define('FLT_CUSTOM', 5); // Custom fields (above) grid columns [AND]
// kMultipleFilter types
define('FLT_TYPE_AND', 'AND');
define('FLT_TYPE_OR', 'OR');
// item statuses
safeDefine('STATUS_DISABLED', 0);
safeDefine('STATUS_ACTIVE', 1);
safeDefine('STATUS_PENDING', 2);
// sections
define('stTREE', 1);
define('stTAB', 2);
// event statuses
define('erSUCCESS', 0); // event finished working succsessfully
define('erFAIL', -1); // event finished working, but result is unsuccsessfull
define('erFATAL', -2); // event experienced FATAL error - no hooks should continue!
define('erPERM_FAIL', -3); // event failed on internal permission checking (user has not permission)
// permission types
define('ptCATEGORY', 0);
define('ptSYSTEM', 1);
define('EDIT_MARK', '&|edit|&'); // replace this sequence inside filters to SID[_main_wid]
$application =& kApplication::Instance();
$spacer_url = $application->BaseURL().'core/admin_templates/img/spacer.gif';
define('SPACER_URL', $spacer_url);
if (!$application->IsAdmin()) {
// don't show debugger buttons on front (if not overrided in "debug.php")
safeDefine('DBG_TOOLBAR_BUTTONS', 0);
}
+
+ // common usage regular expressions
+ define('REGEX_EMAIL_USER', '[-a-zA-Z0-9!\#$%&*+\/=?^_`{|}~.]+');
+ define('REGEX_EMAIL_DOMAIN', '[a-zA-Z0-9]{1}[-.a-zA-Z0-9_]*\.[a-zA-Z]{2,6}');
?>
\ No newline at end of file
Property changes on: branches/unlabeled/unlabeled-1.4.2/core/kernel/constants.php
___________________________________________________________________
Modified: cvs2svn:cvs-rev
## -1 +1 ##
-1.4
\ No newline at end of property
+1.4.2.1
\ No newline at end of property
Index: branches/unlabeled/unlabeled-1.4.2/core/install/install_schema.sql
===================================================================
--- branches/unlabeled/unlabeled-1.4.2/core/install/install_schema.sql (revision 7747)
+++ branches/unlabeled/unlabeled-1.4.2/core/install/install_schema.sql (revision 7748)
@@ -1,423 +1,424 @@
CREATE TABLE PermissionConfig (
PermissionConfigId int(11) NOT NULL auto_increment,
PermissionName varchar(30) NOT NULL default '',
Description varchar(255) NOT NULL default '',
ErrorMessage varchar(255) NOT NULL default '',
ModuleId varchar(20) NOT NULL default '0',
PRIMARY KEY (PermissionConfigId),
KEY PermissionName (PermissionName)
);
CREATE TABLE Permissions (
PermissionId int(11) NOT NULL auto_increment,
Permission varchar(255) NOT NULL default '',
GroupId int(11) default '0',
PermissionValue int(11) NOT NULL default '0',
`Type` tinyint(4) NOT NULL default '0',
CatId int(11) NOT NULL default '0',
PRIMARY KEY (PermissionId),
UNIQUE KEY PermIndex (Permission,GroupId,CatId,`Type`)
);
CREATE TABLE CustomField (
CustomFieldId int(11) NOT NULL auto_increment,
Type int(11) NOT NULL default '0',
FieldName varchar(255) NOT NULL default '',
FieldLabel varchar(40) default NULL,
Heading varchar(60) default NULL,
Prompt varchar(60) default NULL,
ElementType varchar(50) NOT NULL default '',
ValueList varchar(255) default NULL,
DisplayOrder int(11) NOT NULL default '0',
OnGeneralTab tinyint(4) NOT NULL default '0',
IsSystem tinyint(3) unsigned NOT NULL default '0',
PRIMARY KEY (CustomFieldId),
KEY Type (Type)
);
CREATE TABLE ConfigurationAdmin (
VariableName varchar(80) NOT NULL default '',
heading varchar(255) default NULL,
prompt varchar(255) default NULL,
element_type varchar(20) NOT NULL default '',
validation varchar(255) default NULL,
ValueList text default NULL,
DisplayOrder double NOT NULL default '0',
GroupDisplayOrder double NOT NULL default '0',
Install int(11) NOT NULL default '1',
PRIMARY KEY (VariableName)
);
CREATE TABLE ConfigurationValues (
VariableId int(11) NOT NULL auto_increment,
VariableName varchar(255) NOT NULL default '',
VariableValue varchar(255) default NULL,
ModuleOwner varchar(20) default 'In-Portal',
Section varchar(255) NOT NULL default '',
PRIMARY KEY (VariableId),
UNIQUE KEY VariableName (VariableName)
);
CREATE TABLE EmailMessage (
EmailMessageId int(10) NOT NULL auto_increment,
Template longtext,
MessageType enum('html','text') NOT NULL default 'text',
LanguageId int(11) NOT NULL default '0',
EventId int(11) NOT NULL default '0',
Subject text,
PRIMARY KEY (EmailMessageId)
);
CREATE TABLE EmailQueue (
Subject text NOT NULL,
toaddr text NOT NULL,
fromaddr text NOT NULL,
message blob,
headers blob,
queued timestamp NOT NULL
);
CREATE TABLE EmailSubscribers (
EmailMessageId int(11) NOT NULL default '0',
PortalUserId int(11) NOT NULL default '0'
);
CREATE TABLE Events (
EventId int(11) NOT NULL auto_increment,
Event varchar(40) NOT NULL default '',
Enabled int(11) NOT NULL default '1',
FromUserId int(11) NOT NULL default '0',
Module varchar(40) NOT NULL default '',
Description varchar(255) NOT NULL default '',
Type int(11) NOT NULL default '0',
PRIMARY KEY (EventId)
);
CREATE TABLE IdGenerator (
lastid int(11) default NULL
);
CREATE TABLE Language (
LanguageId int(11) NOT NULL auto_increment,
PackName varchar(40) NOT NULL default '',
LocalName varchar(40) NOT NULL default '',
Enabled int(11) NOT NULL default '0',
PrimaryLang int(11) NOT NULL default '0',
IconURL varchar(255) default NULL,
DateFormat varchar(50) NOT NULL default '',
TimeFormat varchar(50) NOT NULL default '',
InputDateFormat varchar(50) NOT NULL default '',
InputTimeFormat varchar(50) NOT NULL default '',
DecimalPoint char(2) NOT NULL default '.',
ThousandSep tinytext NULL,
Charset varchar(20) NOT NULL default '',
UnitSystem tinyint(4) NOT NULL default '1',
PRIMARY KEY (LanguageId)
);
CREATE TABLE Modules (
Name varchar(255) NOT NULL default '',
Path varchar(255) NOT NULL default '',
Var varchar(10) NOT NULL default '',
Version varchar(10) NOT NULL default '',
Loaded tinyint(4) NOT NULL default '1',
LoadOrder tinyint(4) NOT NULL default '0',
TemplatePath varchar(255) NOT NULL default '',
RootCat int(11) NOT NULL default '0',
BuildDate double NOT NULL default '0',
PRIMARY KEY (Name)
);
CREATE TABLE PersistantSessionData (
PortalUserId int(11) NOT NULL default '0',
VariableName varchar(255) NOT NULL default '',
VariableValue text NOT NULL,
PRIMARY KEY (PortalUserId,VariableName),
KEY UserId (PortalUserId),
KEY VariableName (VariableName)
);
CREATE TABLE Phrase (
Phrase varchar(255) NOT NULL default '',
Translation text NOT NULL default '',
PhraseType int(11) NOT NULL default '0',
PhraseId int(11) NOT NULL auto_increment,
LanguageId int(11) NOT NULL default '0',
LastChanged int(10) unsigned NOT NULL default '0',
LastChangeIP varchar(15) NOT NULL default '',
Module varchar(30) NOT NULL default '',
PRIMARY KEY (PhraseId),
KEY LanguageId (LanguageId),
INDEX Phrase_Index (Phrase)
);
CREATE TABLE PhraseCache (
Template varchar(40) NOT NULL default '',
PhraseList text NOT NULL,
CacheDate int(11) NOT NULL default '0',
ThemeId int(11) NOT NULL default '0',
StylesheetId int(10) unsigned NOT NULL default '0',
ConfigVariables text,
PRIMARY KEY (Template)
);
CREATE TABLE PortalGroup (
GroupId int(11) NOT NULL auto_increment,
Name varchar(255) NOT NULL default '',
Description varchar(255) default NULL,
CreatedOn double NOT NULL default '0',
System tinyint(4) NOT NULL default '0',
Personal tinyint(4) NOT NULL default '0',
Enabled tinyint(4) NOT NULL default '1',
ResourceId int(11) NOT NULL default '0',
PRIMARY KEY (GroupId),
UNIQUE KEY Name (Name),
UNIQUE KEY ResourceId (ResourceId),
KEY Personal (Personal),
KEY Enabled (Enabled)
);
CREATE TABLE PortalUser (
PortalUserId int(11) NOT NULL auto_increment,
Login varchar(255) default NULL,
`Password` varchar(255) default NULL,
FirstName varchar(255) default NULL,
LastName varchar(255) default NULL,
Company varchar(255) NOT NULL default '',
Email varchar(255) NOT NULL default '',
CreatedOn double NOT NULL default '0',
Phone varchar(20) default NULL,
Fax varchar(255) NOT NULL default '',
Street varchar(255) default NULL,
Street2 varchar(255) NOT NULL default '',
City varchar(20) default NULL,
State varchar(20) NOT NULL default '',
Zip varchar(20) default NULL,
Country varchar(20) NOT NULL default '',
ResourceId int(11) NOT NULL default '0',
`Status` tinyint(4) NOT NULL default '2',
Modified int(11) NOT NULL default '0',
dob double NOT NULL default '0',
tz int(11) default NULL,
ip varchar(20) default NULL,
IsBanned tinyint(1) NOT NULL default '0',
PassResetTime bigint(20) default NULL,
PwResetConfirm varchar(255) default NULL,
PwRequestTime bigint(25) default NULL,
MinPwResetDelay int(11) NOT NULL default '1800',
PRIMARY KEY (PortalUserId),
UNIQUE KEY ResourceId (ResourceId),
UNIQUE KEY Login (Login),
KEY CreatedOn (CreatedOn)
);
CREATE TABLE PortalUserCustomData (
CustomDataId int(11) NOT NULL auto_increment,
ResourceId int(10) unsigned NOT NULL default '0',
KEY ResourceId (ResourceId),
PRIMARY KEY (CustomDataId)
);
CREATE TABLE SessionData (
SessionKey varchar(50) NOT NULL default '',
VariableName varchar(255) NOT NULL default '',
VariableValue text NOT NULL,
PRIMARY KEY (SessionKey,VariableName),
KEY SessionKey (SessionKey),
KEY VariableName (VariableName)
);
CREATE TABLE Theme (
ThemeId int(11) NOT NULL auto_increment,
Name varchar(40) NOT NULL default '',
Enabled int(11) NOT NULL default '1',
Description varchar(255) default NULL,
PrimaryTheme int(11) NOT NULL default '0',
CacheTimeout int(11) NOT NULL default '0',
StylesheetId int(10) unsigned NOT NULL default '0',
PRIMARY KEY (ThemeId)
);
CREATE TABLE ThemeFiles (
FileId int(11) NOT NULL auto_increment,
ThemeId int(11) NOT NULL default '0',
FileName varchar(255) NOT NULL default '',
FilePath varchar(255) NOT NULL default '',
Description varchar(255) default NULL,
FileType int(11) NOT NULL default '0',
FileFound tinyint(3) unsigned NOT NULL default '0',
PRIMARY KEY (FileId),
KEY theme (ThemeId),
KEY FileName (FileName),
KEY FilePath (FilePath),
KEY FileFound (FileFound)
);
CREATE TABLE UserGroup (
PortalUserId int(11) NOT NULL default '0',
GroupId int(11) NOT NULL default '0',
MembershipExpires int(10) unsigned default NULL,
PrimaryGroup tinyint(4) NOT NULL default '1',
ExpirationReminderSent tinyint(4) NOT NULL default '0',
PRIMARY KEY (PortalUserId,GroupId),
KEY GroupId (GroupId),
KEY PrimaryGroup (PrimaryGroup)
);
CREATE TABLE UserSession (
SessionKey varchar(50) NOT NULL default '',
CurrentTempKey varchar(50) default NULL,
PrevTempKey varchar(50) default NULL,
LastAccessed double NOT NULL default '0',
PortalUserId varchar(255) NOT NULL default '',
Language varchar(255) NOT NULL default '',
Theme varchar(255) NOT NULL default '',
GroupId int(11) NOT NULL default '0',
IpAddress varchar(20) NOT NULL default '0.0.0.0',
Status int(11) NOT NULL default '1',
GroupList varchar(255) default NULL,
tz int(11) default NULL,
PRIMARY KEY (SessionKey),
KEY UserId (PortalUserId),
KEY LastAccessed (LastAccessed)
);
CREATE TABLE EmailLog (
EmailLogId int(11) NOT NULL auto_increment,
fromuser varchar(200) default NULL,
addressto varchar(255) default NULL,
- subject varchar(255) default NULL,
- timestamp bigint(20) default '0',
+ `subject` varchar(255) default NULL,
+ `timestamp` bigint(20) default '0',
event varchar(100) default NULL,
+ EventParams text NOT NULL,
PRIMARY KEY (EmailLogId)
);
CREATE TABLE Cache (
VarName varchar(255) NOT NULL default '',
Data longtext,
Cached int(11) default NULL,
LifeTime int(11) NOT NULL default '-1',
PRIMARY KEY (VarName),
KEY Cached (Cached)
);
CREATE TABLE StdDestinations (
DestId int(11) NOT NULL auto_increment,
DestType int(11) NOT NULL default '0',
DestParentId int(11) default NULL,
DestName varchar(255) NOT NULL default '',
DestAbbr char(3) NOT NULL default '',
DestAbbr2 char(2) default '',
PRIMARY KEY (DestId)
);
CREATE TABLE Category (
CategoryId int(11) NOT NULL auto_increment,
`Type` int(11) NOT NULL default '0',
ParentId int(11) NOT NULL default '0',
Name varchar(255) NOT NULL default '',
l1_Name varchar(255) NOT NULL default '',
l2_Name varchar(255) NOT NULL default '',
l3_Name varchar(255) NOT NULL default '',
l4_Name varchar(255) NOT NULL default '',
l5_Name varchar(255) NOT NULL default '',
Filename varchar(255) NOT NULL default '',
AutomaticFilename tinyint(3) unsigned NOT NULL default '1',
Description text NOT NULL,
l1_Description text NOT NULL,
l2_Description text NOT NULL,
l3_Description text NOT NULL,
l4_Description text NOT NULL,
l5_Description text NOT NULL,
CreatedOn int(11) NOT NULL default '0',
EditorsPick tinyint(4) NOT NULL default '0',
`Status` tinyint(4) NOT NULL default '0',
Pop tinyint(4) default NULL,
Priority int(11) NOT NULL default '0',
MetaKeywords varchar(255) default NULL,
CachedDescendantCatsQty int(11) default NULL,
CachedNavbar text NOT NULL,
l1_CachedNavbar text NOT NULL,
l2_CachedNavbar text NOT NULL,
l3_CachedNavbar text NOT NULL,
l4_CachedNavbar text NOT NULL,
l5_CachedNavbar text NOT NULL,
CreatedById int(11) NOT NULL default '0',
ResourceId int(11) default NULL,
ParentPath text NOT NULL,
NamedParentPath text NOT NULL,
MetaDescription varchar(255) default NULL,
HotItem int(11) NOT NULL default '2',
NewItem int(11) NOT NULL default '2',
PopItem int(11) NOT NULL default '2',
Modified int(11) NOT NULL default '0',
ModifiedById int(11) NOT NULL default '0',
CategoryTemplate varchar(255) NOT NULL default '',
CachedCategoryTemplate varchar(255) NOT NULL default '',
PRIMARY KEY (CategoryId),
UNIQUE KEY ResourceId (ResourceId),
KEY ParentId (ParentId),
KEY Modified (Modified),
KEY Priority (Priority),
KEY sorting (Name,Priority),
KEY Filename (Filename(5)),
KEY l1_Name (l1_Name(5)),
KEY l2_Name (l2_Name(5)),
KEY l3_Name (l3_Name(5)),
KEY l4_Name (l4_Name(5)),
KEY l5_Name (l5_Name(5)),
KEY l1_Description (l1_Description(5)),
KEY l2_Description (l2_Description(5)),
KEY l3_Description (l3_Description(5)),
KEY l4_Description (l4_Description(5)),
KEY l5_Description (l5_Description(5))
);
CREATE TABLE CategoryCustomData (
CustomDataId int(11) NOT NULL auto_increment,
ResourceId int(10) unsigned NOT NULL default '0',
KEY ResourceId (ResourceId),
PRIMARY KEY (CustomDataId)
);
CREATE TABLE CategoryItems (
`CategoryId` int(11) NOT NULL default '0',
`ItemResourceId` int(11) NOT NULL default '0',
`PrimaryCat` tinyint(4) NOT NULL default '0',
`ItemPrefix` varchar(50) NOT NULL default '',
`Filename` varchar(255) NOT NULL default '',
UNIQUE KEY `CategoryId` (`CategoryId`,`ItemResourceId`),
KEY `PrimaryCat` (`PrimaryCat`),
KEY `ItemPrefix` (`ItemPrefix`),
KEY `Filename` (`Filename`(4))
);
CREATE TABLE PermCache (
PermCacheId int(11) NOT NULL auto_increment,
CategoryId int(11) NOT NULL default '0',
PermId int(11) NOT NULL default '0',
ACL varchar(255) NOT NULL default '',
DACL varchar(255) NOT NULL default '',
PRIMARY KEY (PermCacheId),
KEY CategoryId (CategoryId),
KEY PermId (PermId)
);
CREATE TABLE Stylesheets (
StylesheetId int(11) NOT NULL auto_increment,
Name varchar(255) NOT NULL default '',
Description varchar(255) NOT NULL default '',
AdvancedCSS text NOT NULL,
LastCompiled int(10) unsigned NOT NULL default '0',
Enabled int(11) NOT NULL default '0',
PRIMARY KEY (StylesheetId)
);
CREATE TABLE PopupSizes (
PopupId int(10) unsigned NOT NULL auto_increment,
TemplateName varchar(255) NOT NULL default '',
PopupWidth int(11) NOT NULL default '0',
PopupHeight int(11) NOT NULL default '0',
PRIMARY KEY (PopupId),
KEY TemplateName (TemplateName)
);
Property changes on: branches/unlabeled/unlabeled-1.4.2/core/install/install_schema.sql
___________________________________________________________________
Modified: cvs2svn:cvs-rev
## -1 +1 ##
-1.4
\ No newline at end of property
+1.4.2.1
\ No newline at end of property
Index: branches/unlabeled/unlabeled-1.33.2/core/units/categories/categories_tag_processor.php
===================================================================
--- branches/unlabeled/unlabeled-1.33.2/core/units/categories/categories_tag_processor.php (revision 7747)
+++ branches/unlabeled/unlabeled-1.33.2/core/units/categories/categories_tag_processor.php (revision 7748)
@@ -1,528 +1,526 @@
<?php
class CategoriesTagProcessor extends kDBTagProcessor {
function SubCatCount($params)
{
$cat_object =& $this->Application->recallObject($this->getPrefixSpecial(),$this->Prefix, $params);
$sql = ' SELECT COUNT(*) - 1
FROM '.$cat_object->TableName.'
WHERE ParentPath LIKE "'.$cat_object->GetDBField('ParentPath').'%"';
if (isset($params['today'])) {
$sql .= ' AND CreatedOn > '.(adodb_mktime()-86400);
}
return $this->Conn->GetOne($sql);
}
function IsNew($params)
{
$object =& $this->Application->recallObject($this->getPrefixSpecial(), $this->Prefix, $params);
$ret = $object->GetDBField('IsNew') ? 1 : 0;
return $ret;
}
function IsPick($params)
{
$object =& $this->Application->recallObject($this->getPrefixSpecial(), $this->Prefix, $params);
$ret = $object->GetDBField('EditorsPick') ? 1 : 0;
return $ret;
}
function ItemIcon($params)
{
// only for categories, not structure
if ($this->Prefix != 'c') {
return parent::ItemIcon($params);
}
$object =& $this->Application->recallObject($this->getPrefixSpecial(), $this->Prefix, $params);
$status = $object->GetDBField('Status');
if($status == 1)
{
$ret = $object->GetDBField('IsNew') ? 'icon16_cat_new.gif' : 'icon16_cat.gif';
}
else
{
$ret = $status ? 'icon16_cat_pending.gif' : 'icon16_cat_disabled.gif';
}
return $ret;
}
function ItemCount($params)
{
$cat_object =& $this->getObject($params);
$ci_table = $this->Application->getUnitOption('l-ci', 'TableName');
$sql = ' SELECT COUNT(*)
FROM '.$cat_object->TableName.' c
LEFT JOIN '.$ci_table.' ci
ON c.CategoryId=ci.CategoryId
WHERE c.ParentPath LIKE "'.$cat_object->GetDBField('ParentPath').'%"
AND NOT (ci.CategoryId IS NULL)';
return $this->Conn->GetOne($sql);
}
function ListCategories($params)
{
return $this->PrintList2($params);
}
function RootCategoryName($params)
{
return $this->Application->ProcessParsedTag('m', 'RootCategoryName', $params);
}
function CheckModuleRoot($params)
{
$module_name = getArrayValue($params, 'module') ? $params['module'] : 'In-Commerce';
$module =& $this->Application->recallObject('mod.'.$module_name);
$module_root_cat = $module->GetDBField('RootCat');
$additional_cats = $this->SelectParam($params, 'add_cats');
if ($additional_cats) {
$additional_cats = explode(',', $additional_cats);
}
else {
$additional_cats = array();
}
if ($this->Application->GetVar('m_cat_id') == $module_root_cat || in_array($this->Application->GetVar('m_cat_id'), $additional_cats)) {
$home_template = getArrayValue($params, 'home_template');
if (!$home_template) return;
$this->Application->Redirect($home_template, Array('pass'=>'all'));
};
}
function CategoryPath($params)
{
$module_name = getArrayValue($params, 'module') ? $params['module'] : 'In-Commerce';
$module_category_id = $this->Application->findModule('Name', $module_name, 'RootCat');
$module_item_id = $this->Application->GetVar($this->Application->findModule('Name', $module_name, 'Var').'_id');
$block_params['separator'] = $params['separator'];
if (!isset($params['cat_id'])) {
$params['cat_id'] = getArrayValue($params, 'cat_id') ? $params['cat_id'] : $this->Application->GetVar('m_cat_id');
}
if ($params['cat_id'] == 0) {
$block_params['current'] = 1;
$block_params['cat_id'] = 0;
$block_params['cat_name'] = $this->Application->ProcessParsedTag('m', 'RootCategoryName', $params);
$block_params['name'] = $this->SelectParam($params, 'root_cat_render_as,block_root_cat,rootcatblock,render_as');
return $this->Application->ParseBlock($block_params);
}
else {
$ml_formatter =& $this->Application->recallObject('kMultiLanguage');
$navbar_field = $ml_formatter->LangFieldName('CachedNavBar');
$id_field = $this->Application->getUnitOption($this->Prefix, 'IDField');
$table_name = $this->Application->getUnitOption($this->Prefix, 'TableName');
$sql = 'SELECT '.$navbar_field.', ParentPath
FROM '.$table_name.'
WHERE '.$id_field.' = '.$params['cat_id'];
$category_data = $this->Conn->GetRow($sql);
$ret = '';
if ($category_data) {
$category_names = explode('&|&', $category_data[$navbar_field]);
$category_ids = explode('|', substr($category_data['ParentPath'], 1, -1));
// add "Home" category at beginning of path
array_unshift($category_names, $this->Application->ProcessParsedTag('m', 'RootCategoryName', $params));
array_unshift($category_ids, 0);
foreach ($category_ids as $category_pos => $category_id) {
$block_params['cat_id'] = $category_id;
$block_params['cat_name'] = $category_names[$category_pos];
$block_params['current'] = ($params['cat_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 ($category_id == 0) {
$block_params['name'] = $this->SelectParam($params, 'root_cat_render_as,block_root_cat,rootcatblock,render_as,block');
}
if ($block_params['is_module_root'] == 1) { // module root
$block_params['name'] = $this->SelectParam($params, 'module_root_render_as,block_module_root,rootmoduleblock,render_as,block');
}
if ($block_params['current'] == 1) { // current cat (label)
$block_params['name'] = $this->SelectParam($params, 'current_render_as,block_current,currentblock,render_as,block');
}
$this->Application->SetVar($this->Prefix.'_id', $category_id);
$ret .= $this->Application->ParseBlock($block_params, 1);
}
}
return $ret;
}
}
function CurrentCategoryName($params)
{
$cat_object =& $this->Application->recallObject($this->getPrefixSpecial(), $this->Prefix.'_List');
$sql = 'SELECT '.$this->getTitleField().'
FROM '.$cat_object->TableName.'
WHERE CategoryId = '.$this->Application->GetVar('m_cat_id');
return $this->Conn->GetOne($sql);
}
function getTitleField()
{
$ml_formatter =& $this->Application->recallObject('kMultiLanguage');
return $ml_formatter->LangFieldName('Name');
}
function CategoryLink($params)
{
// 'p_id'=>'0', ??
$params = array_merge(array('pass'=>'m'), $params);
$cat_id = getArrayValue($params,'cat_id');
if ($cat_id === false) {
// $cat_id = $this->Application->Parser->GetParam('cat_id');
$cat_id = $this->Application->GetVar($this->getPrefixSpecial().'_id');
}
- if($cat_id == 'Root')
- {
- $object =& $this->Application->recallObject('mod.'.$params['module']);
- $params['m_cat_id'] = $object->GetDBField('RootCat');
+ if ("$cat_id" == 'Root') {
+ $params['m_cat_id'] = $this->Application->findModule('Name', $params['module'], 'RootCat');
unset($params['module']);
}
- else{
+ else {
$params['m_cat_id'] = $cat_id;
}
unset($params['cat_id']);
$params['pass_category'] = 1;
$main_processor =& $this->Application->recallObject('m_TagProcessor');
return $main_processor->T($params);
}
function CategoryList($params)
{
//$object =& $this->Application->recallObject( $this->getPrefixSpecial() , $this->Prefix.'_List', $params );
$object =& $this->GetList($params);
if ($object->RecordsCount == 0)
{
if (isset($params['block_no_cats'])) {
$params['name'] = $params['block_no_cats'];
return $this->Application->ParseBlock($params);
}
else {
return '';
}
}
if (isset($params['block'])) {
return $this->PrintList($params);
}
else {
$params['block'] = $params['block_main'];
if (isset($params['block_row_start'])) {
$params['row_start_block'] = $params['block_row_start'];
}
if (isset($params['block_row_end'])) {
$params['row_end_block'] = $params['block_row_end'];
}
return $this->PrintList2($params);
}
}
function Meta($params)
{
$name = getArrayValue($params, 'name');
$object =& $this->Application->recallObject($this->Prefix.'.-item');
$field = $object->GetField('Meta'.$name);
if ($field) return $field;
switch ($name) {
case 'Description':
$conf = 'Category_MetaDesc';
break;
case 'Keywords':
$conf = 'Category_MetaKey';
break;
}
return $this->Application->ConfigValue($conf);
}
function BuildListSpecial($params)
{
if ( isset($params['parent_cat_id']) ) {
$parent_cat_id = $params['parent_cat_id'];
}
else {
$parent_cat_id = $this->Application->GetVar($this->Prefix.'_id');
if (!$parent_cat_id) {
$parent_cat_id = $this->Application->GetVar('m_cat_id');
}
if (!$parent_cat_id) {
$parent_cat_id = 0;
}
}
$types = $this->SelectParam($params, 'types');
$except = $this->SelectParam($params, 'except');
$no_special = isset($params['no_special']) && $params['no_special'];
if ($no_special) return $this->Special;
if ($types.$except.$parent_cat_id == '') {
return parent::BuildListSpecial($params);
}
$special = crc32($types.$except.$parent_cat_id);
return $special;
}
function IsCurrent($params)
{
$object =& $this->getObject($params);
if ($object->GetID() == $this->Application->GetVar('m_cat_id')) {
return true;
}
else {
return false;
}
}
/**
* Substitutes category in last template base on current category
* This is required becasue when you navigate catalog using AJAX, last_template is not updated
* but when you open item edit from catalog last_template is used to build opener_stack
* So, if we don't substitute m_cat_id in last_template, after saving item we'll get redirected
* to the first category we've opened, not the one we navigated to using AJAX
*
* @param Array $params
*/
function UpdateLastTemplate($params)
{
$category_id = $this->Application->GetVar('m_cat_id');
$wid = $this->Application->GetVar('m_wid');
list($index_file, $env) = explode('|', $this->Application->RecallVar(rtrim('last_template_'.$wid, '_')), 2);
$this->Application->SetVar(ENV_VAR_NAME, str_replace('%5C', '\\', $env));
$this->Application->HttpQuery->processQueryString();
// update required fields
$this->Application->SetVar('m_cat_id', $category_id);
$this->Application->Session->SaveLastTemplate($params['template']);
}
function GetParentCategory($params)
{
$parent_id = 0;
$id_field = $this->Application->getUnitOption($this->Prefix, 'IDField');
$table = $this->Application->getUnitOption($this->Prefix,'TableName');
$cat_id = $this->Application->GetVar('m_cat_id');
if ($cat_id > 0) {
$sql = 'SELECT ParentId
FROM '.$table.'
WHERE '.$id_field.' = '.$cat_id;
$parent_id = $this->Conn->GetOne($sql);
}
return $parent_id;
}
function InitCacheUpdater($params)
{
safeDefine('CACHE_PERM_CHUNK_SIZE', 30);
$continue = $this->Application->GetVar('continue');
$total_cats = (int) $this->Conn->GetOne('SELECT COUNT(*) FROM '.TABLE_PREFIX.'Category');
if ($continue === false && $total_cats > CACHE_PERM_CHUNK_SIZE) {
// first step, if category count > CACHE_PERM_CHUNK_SIZE, then ask for cache update
return true;
}
if ($continue === false) {
// if we don't have to ask, then assume user selected "Yes" in permcache update dialog
$continue = 1;
}
$updater =& $this->Application->recallObject('kPermCacheUpdater', null, Array('continue' => $continue));
if ($continue === '0') { // No in dialog
$updater->clearData();
$this->Application->Redirect($params['destination_template']);
}
$ret = false; // don't ask for update
if ($continue == 1) { // Initial run
$updater->setData();
}
if ($continue == 2) { // Continuing
// called from AJAX request => returns percent
$needs_more = true;
while ($needs_more && $updater->iteration <= CACHE_PERM_CHUNK_SIZE) {
// until proceeeded in this step category count exceeds category per step limit
$needs_more = $updater->DoTheJob();
}
if ($needs_more) {
// still some categories are left for next step
$updater->setData();
}
else {
// all done -> redirect
$updater->clearData();
$this->Application->RemoveVar('PermCache_UpdateRequired');
$this->Application->Redirect($params['destination_template']);
}
$ret = $updater->getDonePercent();
}
return $ret;
}
/**
* Parses warning block, but with style="display: none;". Used during permissions saving from AJAX
*
* @param Array $params
* @return string
*/
function SaveWarning($params)
{
if ($this->Prefix != 'c') {
// don't use this method for other prefixes then Category, that use this tag processor
parent::SaveWarning($params);
return ;
}
$main_prefix = getArrayValue($params, 'main_prefix');
if ($main_prefix && $main_prefix != '$main_prefix') {
$top_prefix = $main_prefix;
}
else {
$top_prefix = $this->Application->GetTopmostPrefix($this->Prefix);
}
$temp_tables = substr($this->Application->GetVar($top_prefix.'_mode'), 0, 1) == 't';
$modified = $this->Application->RecallVar($top_prefix.'_modified');
if (!$temp_tables) {
$this->Application->RemoveVar($top_prefix.'_modified');
return '';
}
$block_name = $this->SelectParam($params, 'render_as,name');
if ($block_name) {
$block_params = $this->prepareTagParams($params);
$block_params['name'] = $block_name;
$block_params['edit_mode'] = $temp_tables ? 1 : 0;
$block_params['display'] = $temp_tables && $modified ? 1 : 0;
return $this->Application->ParseBlock($block_params);
}
else {
return $temp_tables && $modified ? 1 : 0;
}
return ;
}
/**
* Allows to detect if this prefix has something in clipboard
*
* @param Array $params
* @return bool
*/
function HasClipboard($params)
{
$clipboard = $this->Application->RecallVar('clipboard');
if ($clipboard) {
$clipboard = unserialize($clipboard);
foreach ($clipboard as $prefix => $clipboard_data) {
foreach ($clipboard_data as $mode => $ids) {
if (count($ids)) return 1;
}
}
}
return 0;
}
/**
* Allows to detect if root category being edited
*
* @param Array $params
*/
function IsRootCategory($params)
{
$object =& $this->getObject($params);
return $object->IsRoot();
}
function CatalogItemCount($params)
{
$object =& $this->GetList($params);
if (!$object->Counted) {
$object->CountRecs();
}
return $object->NoFilterCount != $object->RecordsCount ? $object->RecordsCount.' / '.$object->NoFilterCount : $object->RecordsCount;
}
/**
* Print grid pagination using
* block names specified
*
* @param Array $params
* @return string
* @access public
*/
function PrintPages($params)
{
if ($this->Application->Parser->GetParam('no_special')) {
$params['no_special'] = $this->Application->Parser->GetParam('no_special');
}
return parent::PrintPages($params);
}
function InitCatalog($params)
{
$tab_prefixes = $this->Application->GetVar('tp'); // {all, <prefixes_list>, none}
if ($tab_prefixes === false) $tab_prefixes = 'all';
$skip_prefixes = isset($params['skip_prefixes']) && $params['skip_prefixes'] ? explode(',', $params['skip_prefixes']) : Array();
// get all prefixes available
$prefixes = Array();
foreach ($this->Application->ModuleInfo as $module_name => $module_data) {
if ($module_data['Var'] == 'm') continue;
$prefixes[] = $module_data['Var'];
}
if ($tab_prefixes == 'none') {
$skip_prefixes = array_unique(array_merge($skip_prefixes, $prefixes));
}
elseif ($tab_prefixes != 'all') {
// prefix list here
$tab_prefixes = explode(',', $tab_prefixes); // list of prefixes that should stay
$skip_prefixes = array_unique(array_merge($skip_prefixes, array_diff($prefixes, $tab_prefixes)));
}
$params['name'] = $params['render_as'];
$params['skip_prefixes'] = implode(',', $skip_prefixes);
return $this->Application->ParseBlock($params, 1);
}
function IsActive($params)
{
$cat_id = $this->Application->GetVar('c_id');
$current_cat = $this->getObject($params);
$current_path = $current_cat->GetDBField('ParentPath');
static $parent_path = null;
if (!isset($parent_path)) {
$parent_path = $this->Conn->GetOne('SELECT ParentPath FROM '.TABLE_PREFIX.'Category WHERE CategoryId = '.$this->Application->GetVar('m_cat_id'));
}
return strpos($parent_path, $current_path) !== false;
}
}
?>
\ No newline at end of file
Property changes on: branches/unlabeled/unlabeled-1.33.2/core/units/categories/categories_tag_processor.php
___________________________________________________________________
Modified: cvs2svn:cvs-rev
## -1 +1 ##
-1.33
\ No newline at end of property
+1.33.2.1
\ No newline at end of property

Event Timeline