Jump to content

PHP function to export xml data not working as expected - please help!


Greywacke
Go to solution Solved by Greywacke,

Recommended Posts

hi there everyone! :)

 

i currently have, in my php document (which generates various xml depending on post and querystring request values) - the following function:

function getdbconfig($file = "") {
	if ($_GLOBALS["ssl_enabled"] == 1 && ((!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off') || $_SERVER['SERVER_PORT'] == 443) || $_GLOBALS["ssl_enabled"] == 0) {
		$pattern = '/^\$conn = mysql_connect\("([a-zA-Z._0-9\-]+)", "([a-zA-Z_0-9]+)", "([a-zA-Z_0-9]+)"\);$'.
				   '|^mysql_select_db\("([a-zA-Z_0-9]+)", \$conn\);$'.
				   '|^date_default_timezone_set\([\'"]([A-Za-z0-9\/+\-]+)[\'"]\);$'.
				   '|^\$GLOBALS\["dtmstyle"\] = "([^"]+)";$'.
				   '|^\$GLOBALS\["dtlast"\] = ([0|1]);$'.
				   '|^\$GLOBALS\["prod_prodmode"\] = ([0|1]);$'.
				   '|^\$GLOBALS\["prod_prodmail"\] = "([^@]+@[^"]+)";$'.
				   '|^\$GLOBALS\["curl"\] = ([0|1]);$'.
				   '|^\$GLOBALS\["conn_timeout"\] = ([0-9]+);$'.
				   '|^\$GLOBALS\["post_timeout"\] = ([0-9]+);$'.
				   '|^\$GLOBALS\["ssl_enabled"\] = ([0|1]);$/m';
		$connstr = file_get_contents($file, FILE_USE_INCLUDE_PATH);
		echo "<sql>".$connstr."</sql>\n";
		$arr = array();
		if (preg_match_all($pattern,$connstr,$arr,PREG_PATTERN_ORDER)) {
			echo "<sql>".print_r($arr,true)."</sql>\n";
			array_push($GLOBALS["sql"],print_r($arr,true));
			echo "	<conn dbsrvr=\"".$arr[1][6]."\" dbname=\"".$arr[4][7]."\" user=\"".$arr[2][6]."\" pass=\"".$arr[3][6]."\" php_tz=\"".$arr[5][10]."\" php_dtf=\"".$arr[6][8]."\" php_dta=\"".$arr[7][9]."\" pt_on=\"".$arr[8][0]."\" pt_mail=\"".$arr[9][1]."\" curl=\"".$arr[10][2]."\" cto=\"".$arr[11][3]."\" pto=\"".$arr[12][4]."\" ssl=\"".$arr[13][5]."\" />\n";
		}
	} else {
                $redirect = "https://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
                header("Location: $redirect");
	}
}

however - there is something wrong somewhere in the outer if statements, as i get nothing printed! the global variables should post the following, according to the currently parsed file contents:

<?xml version="1.0" encoding="utf-8"?>
<root>
	<conn dbsrvr="localhost" dbname="*****" user="*****" pass="*****" php_tz="Africa/Johannesburg" php_dtf="Y/m/d H:i:s" php_dta="0" pt_on="0" pt_mail="greywacke@outlook.com" curl="1" cto="15" pto="30" ssl="0" />
	<sql></sql>
</root>

please note - private information such as database names, usernames and passwords were replaced with *****

can anyone help me out please, in resolving this issue? (to get the regular expression values printed!)

any comments, questions and/or suggestions are welcome! ;)

sincerely,

Pierre du Toit.

Edited by Greywacke
Link to comment
Share on other sites

PS:

the phpinfo() function returns the following for the environment:

 




PHP Version 5.3.10-1ubuntu3.10




System Linux Performatix-01 3.2.0-59-virtual #90-Ubuntu SMP Tue Jan 7 23:02:33 UTC 2014 x86_64
Build Date Feb 28 2014 22:57:53
Server API Apache 2.0 Handler
Virtual Directory Support disabled
Configuration File (php.ini) Path /etc/php5/apache2
Loaded Configuration File /etc/php5/apache2/php.ini
Scan this dir for additional .ini files /etc/php5/apache2/conf.d
Additional .ini files parsed /etc/php5/apache2/conf.d/apc.ini, /etc/php5/apache2/conf.d/curl.ini, /etc/php5/apache2/conf.d/gd.ini, /etc/php5/apache2/conf.d/mcrypt.ini, /etc/php5/apache2/conf.d/memcached.ini, /etc/php5/apache2/conf.d/mysql.ini, /etc/php5/apache2/conf.d/mysqli.ini, /etc/php5/apache2/conf.d/pdo.ini, /etc/php5/apache2/conf.d/pdo_mysql.ini, /etc/php5/apache2/conf.d/suhosin.ini, /etc/php5/apache2/conf.d/xsl.ini
PHP API 20090626
PHP Extension 20090626
Zend Extension 220090626
Zend Extension Build API220090626,NTS
PHP Extension Build API20090626,NTS
Debug Build no
Thread Safety disabled
Zend Memory Manager enabled
Zend Multibyte Support disabled
IPv6 Support enabled
Registered PHP Streams https, ftps, compress.zlib, compress.bzip2, php, file, glob, data, http, ftp, zip, phar
Registered Stream Socket Transports tcp, udp, unix, udg, ssl, sslv3, tls
Registered Stream Filters zlib.*, bzip2.*, convert.iconv.*, string.rot13, string.toupper, string.tolower, string.strip_tags, convert.*, consumed, dechunk, mcrypt.*, mdecrypt.*


This server is protected with the Suhosin Patch 0.9.10
Copyright (c) 2006-2007 Hardened-PHP Project Copyright (c) 2007-2009 SektionEins GmbH


This program makes use of the Zend Scripting Language Engine:
Zend Engine v2.3.0, Copyright (c) 1998-2012 Zend Technologies
    with Suhosin v0.9.33, Copyright (c) 2007-2012, by SektionEins GmbH


Configuration


apache2handler


Apache Version Apache
Apache API Version 20051115
Server Administrator [no address given]
Hostname:Port performatix.co:0
User/Group www-data(33)/33
Max Requests Per Child: 1000 - Keep Alive: on - Max Per Connection: 100
Timeouts Connection: 30 - Keep-Alive: 5
Virtual Server Yes
Server Root /etc/apache2
Loaded Modules core mod_log_config mod_logio prefork http_core mod_so mod_alias mod_auth_basic mod_authn_file mod_authz_default mod_authz_groupfile mod_authz_host mod_authz_user mod_autoindex mod_cache mod_cgi mod_deflate mod_dir mod_env mod_mem_cache mod_mime mod_negotiation mod_php5 mod_reqtimeout mod_rewrite mod_setenvif mod_ssl mod_status


Directive Local Value Master Value
engine 1 1
last_modified 0 0
xbithack 0 0


Apache Environment


Variable Value
HTTP_HOST performatix.co
HTTP_CONNECTION keep-alive
HTTP_ACCEPT text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
HTTP_USER_AGENT Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.154 Safari/537.36
HTTP_DNT 1
HTTP_ACCEPT_ENCODING gzip,deflate,sdch
HTTP_ACCEPT_LANGUAGE en-US,en;q=0.8,af;q=0.6
HTTP_COOKIE PHPSESSID=ffvc6micfftj7okslt11lvk2m2
PATH /usr/local/bin:/usr/bin:/bin
SERVER_SIGNATURE no value
SERVER_SOFTWARE Apache
SERVER_NAME performatix.co
SERVER_ADDR 31.222.157.140
SERVER_PORT 80
REMOTE_ADDR 41.135.198.25
DOCUMENT_ROOT /var/www/performatix.co
SERVER_ADMIN [no address given]
SCRIPT_FILENAME /var/www/performatix.co/phpinfo.php
REMOTE_PORT 15554
GATEWAY_INTERFACE CGI/1.1
SERVER_PROTOCOL HTTP/1.1
REQUEST_METHOD GET
QUERY_STRING no value
REQUEST_URI /phpinfo.php
SCRIPT_NAME /phpinfo.php


HTTP Headers Information


HTTP Request Headers
HTTP Request GET /phpinfo.php HTTP/1.1
Host performatix.co
Connection keep-alive
Accept text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
User-Agent Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.154 Safari/537.36
DNT 1
Accept-Encoding gzip,deflate,sdch
Accept-Language en-US,en;q=0.8,af;q=0.6
Cookie PHPSESSID=ffvc6micfftj7okslt11lvk2m2
HTTP Response Headers


apc


APC Support enabled
Version 3.1.7
APC Debugging Disabled
MMAP Support Enabled
MMAP File Mask no value
Locking type pthread mutex Locks
Serialization Support php
Revision $Revision: 307215 $
Build Date May 2 2011 19:00:42


Directive Local Value Master Value
apc.cache_by_default On On
apc.canonicalize On On
apc.coredump_unmap Off Off
apc.enable_cli Off Off
apc.enabled On On
apc.file_md5 Off Off
apc.file_update_protection 2 2
apc.filters no value no value
apc.gc_ttl 3600 3600
apc.include_once_override Off Off
apc.lazy_classes Off Off
apc.lazy_functions Off Off
apc.max_file_size 1M 1M
apc.mmap_file_mask no value no value
apc.num_files_hint 1000 1000
apc.preload_path no value no value
apc.report_autofilter Off Off
apc.rfc1867 Off Off
apc.rfc1867_freq 0 0
apc.rfc1867_name APC_UPLOAD_PROGRESS APC_UPLOAD_PROGRESS
apc.rfc1867_prefix upload_ upload_
apc.rfc1867_ttl 3600 3600
apc.serializer default default
apc.shm_segments 1 1
apc.shm_size 32M 32M
apc.slam_defense On On
apc.stat On On
apc.stat_ctime Off Off
apc.ttl 0 0
apc.use_request_time On On
apc.user_entries_hint 4096 4096
apc.user_ttl 0 0
apc.write_lock On On


bcmath


BCMath support enabled


Directive Local Value Master Value
bcmath.scale 0 0


bz2


BZip2 Support Enabled
Stream Wrapper support compress.bzip2://
Stream Filter support bzip2.decompress, bzip2.compress
BZip2 Version 1.0.6, 6-Sept-2010


calendar


Calendar support enabled


Core


PHP Version 5.3.10-1ubuntu3.10


Directive Local Value Master Value
allow_call_time_pass_reference Off Off
allow_url_fopen On On
allow_url_include On On
always_populate_raw_post_data Off Off
arg_separator.input & &
arg_separator.output & &
asp_tags Off Off
auto_append_file no value no value
auto_globals_jit On On
auto_prepend_file no value no value
browscap no value no value
default_charset no value no value
default_mimetype text/html text/html
define_syslog_variables Off Off
disable_classes no value no value
disable_functions no value no value
display_errors Off Off
display_startup_errors Off Off
doc_root no value no value
docref_ext no value no value
docref_root no value no value
enable_dl Off Off
error_append_string no value no value
error_log /tmp/php.log /tmp/php.log
error_prepend_string no value no value
error_reporting 30711 30711
exit_on_timeout Off Off
expose_php Off Off
extension_dir /usr/lib/php5/20090626 /usr/lib/php5/20090626
file_uploads On On
highlight.bg #FFFFFF #FFFFFF
highlight.comment #FF8000 #FF8000
highlight.default #0000BB #0000BB
highlight.html #000000 #000000
highlight.keyword #007700 #007700
highlight.string #DD0000 #DD0000
html_errors Off Off
ignore_repeated_errors Off Off
ignore_repeated_source Off Off
ignore_user_abort Off Off
implicit_flush Off Off
include_path .:/usr/share/php:/usr/share/pear .:/usr/share/php:/usr/share/pear
log_errors On On
log_errors_max_len 1024 1024
magic_quotes_gpc Off Off
magic_quotes_runtime Off Off
magic_quotes_sybase Off Off
mail.add_x_header On On
mail.force_extra_parameters no value no value
mail.log no value no value
max_execution_time 3600 3600
max_file_uploads 20 20
max_input_nesting_level 64 64
max_input_time 3600 3600
max_input_vars 1000 1000
memory_limit 1024M 1024M
open_basedir no value no value
output_buffering 1 1
output_handler no value no value
post_max_size 136M 136M
precision 14 14
realpath_cache_size 16K 16K
realpath_cache_ttl 120 120
register_argc_argv Off Off
register_globals On On
register_long_arrays On On
report_memleaks On On
report_zend_debug On On
request_order GP GP
safe_mode Off Off
safe_mode_exec_dir no value no value
safe_mode_gid Off Off
safe_mode_include_dir no value no value
sendmail_from no value no value
sendmail_path /usr/sbin/sendmail -t -i /usr/sbin/sendmail -t -i
serialize_precision 100 100
short_open_tag On On
SMTP localhost localhost
smtp_port 25 25
sql.safe_mode Off Off
track_errors Off Off
unserialize_callback_func no value no value
upload_max_filesize 128M 128M
upload_tmp_dir no value no value
user_dir no value no value
user_ini.cache_ttl 300 300
user_ini.filename .user.ini .user.ini
variables_order GPCS GPCS
xmlrpc_error_number 0 0
xmlrpc_errors Off Off
y2k_compliance On On
zend.enable_gc On On


ctype


ctype functions enabled


curl


cURL support enabled
cURL Information 7.22.0
Age 3
Features
AsynchDNS No
Debug No
GSS-Negotiate Yes
IDN Yes
IPv6 Yes
Largefile Yes
NTLM Yes
SPNEGO No
SSL Yes
SSPI No
krb4 No
libz Yes
CharConv No
Protocols dict, file, ftp, ftps, gopher, http, https, imap, imaps, ldap, pop3, pop3s, rtmp, rtsp, smtp, smtps, telnet, tftp
Host x86_64-pc-linux-gnu
SSL Version OpenSSL/1.0.1
ZLib Version 1.2.3.4


date


date/time support enabled
"Olson" Timezone Database Version 0.system
Timezone Database internal
Default timezone Europe/London


Directive Local Value Master Value
date.default_latitude 31.7667 31.7667
date.default_longitude 35.2333 35.2333
date.sunrise_zenith 90.583333 90.583333
date.sunset_zenith 90.583333 90.583333
date.timezone Europe/London Europe/London


dba


DBA support enabled
Supported handlers cdb cdb_make db4 inifile flatfile


Directive Local Value Master Value
dba.default_handler flatfile flatfile


dom


DOM/XML enabled
DOM/XML API Version 20031129
libxml Version 2.7.8
HTML Support enabled
XPath Support enabled
XPointer Support enabled
Schema Support enabled
RelaxNG Support enabled


ereg


Regex Library Bundled library enabled


exif


EXIF Support enabled
EXIF Version 1.4 $Id: exif.c 321634 2012-01-01 13:15:04Z felipe $
Supported EXIF Version 0220
Supported filetypes JPEG,TIFF


Directive Local Value Master Value
exif.decode_jis_intel JIS JIS
exif.decode_jis_motorola JIS JIS
exif.decode_unicode_intel UCS-2LE UCS-2LE
exif.decode_unicode_motorola UCS-2BE UCS-2BE
exif.encode_jis no value no value
exif.encode_unicode ISO-8859-15 ISO-8859-15


fileinfo


fileinfo support enabled
version 1.0.5-dev


filter


Input Validation and Filtering enabled
Revision $Revision: 321634 $


Directive Local Value Master Value
filter.default unsafe_raw unsafe_raw
filter.default_flags no value no value


ftp


FTP support enabled


gd


GD Support enabled
GD Version 2.0
FreeType Support enabled
FreeType Linkage with freetype
FreeType Version 2.4.8
T1Lib Support enabled
GIF Read Support enabled
GIF Create Support enabled
JPEG Support enabled
libJPEG Version unknown
PNG Support enabled
libPNG Version 1.2.46
WBMP Support enabled


Directive Local Value Master Value
gd.jpeg_ignore_warning 0 0


gettext


GetText Support enabled


hash


hash support enabled
Hashing Engines md2 md4 md5 sha1 sha224 sha256 sha384 sha512 ripemd128 ripemd160 ripemd256 ripemd320 whirlpool tiger128,3 tiger160,3 tiger192,3 tiger128,4 tiger160,4 tiger192,4 snefru snefru256 gost adler32 crc32 crc32b salsa10 salsa20 haval128,3 haval160,3 haval192,3 haval224,3 haval256,3 haval128,4 haval160,4 haval192,4 haval224,4 haval256,4 haval128,5 haval160,5 haval192,5 haval224,5 haval256,5


iconv


iconv support enabled
iconv implementation glibc
iconv library version 2.15


Directive Local Value Master Value
iconv.input_encoding ISO-8859-1 ISO-8859-1
iconv.internal_encoding ISO-8859-1 ISO-8859-1
iconv.output_encoding ISO-8859-1 ISO-8859-1


json


json support enabled
json version 1.2.1


libxml


libXML support active
libXML Compiled Version 2.7.8
libXML Loaded Version 20708
libXML streams enabled


mbstring


Multibyte Support enabled
Multibyte string engine libmbfl
HTTP input encoding translation disabled


mbstring extension makes use of "streamable kanji code filter and converter", which is distributed under the GNU Lesser General Public License version 2.1.


Multibyte (japanese) regex support enabled
Multibyte regex (oniguruma) backtrack check On
Multibyte regex (oniguruma) version 4.7.1


Directive Local Value Master Value
mbstring.detect_order no value no value
mbstring.encoding_translation Off Off
mbstring.func_overload 0 0
mbstring.http_input pass pass
mbstring.http_output pass pass
mbstring.http_output_conv_mimetypes ^(text/|application/xhtml\+xml) ^(text/|application/xhtml\+xml)
mbstring.internal_encoding no value no value
mbstring.language neutral neutral
mbstring.strict_detection Off Off
mbstring.substitute_character no value no value


mcrypt


mcrypt support enabled
mcrypt_filter support enabled
Version 2.5.8
Api No 20021217
Supported ciphers cast-128 gost rijndael-128 twofish arcfour cast-256 loki97 rijndael-192 saferplus wake blowfish-compat des rijndael-256 serpent xtea blowfish enigma rc2 tripledes
Supported modes cbc cfb ctr ecb ncfb nofb ofb stream


Directive Local Value Master Value
mcrypt.algorithms_dir no value no value
mcrypt.modes_dir no value no value


memcached


memcached support enabled
Version 1.0.2
libmemcached version 0.44
Session support yes
igbinary support no


mhash


MHASH support Enabled
MHASH API Version Emulated Support


mysql


MySQL Support enabled
Active Persistent Links 0
Active Links 0
Client API version 5.5.35
MYSQL_MODULE_TYPE external
MYSQL_SOCKET /var/run/mysqld/mysqld.sock
MYSQL_INCLUDE -I/usr/include/mysql
MYSQL_LIBS -L/usr/lib/x86_64-linux-gnu -lmysqlclient_r


Directive Local Value Master Value
mysql.allow_local_infile On On
mysql.allow_persistent Off Off
mysql.connect_timeout 60 60
mysql.default_host no value no value
mysql.default_password no value no value
mysql.default_port no value no value
mysql.default_socket /var/run/mysqld/mysqld.sock /var/run/mysqld/mysqld.sock
mysql.default_user no value no value
mysql.max_links Unlimited Unlimited
mysql.max_persistent Unlimited Unlimited
mysql.trace_mode Off Off


mysqli


MysqlI Support enabled
Client API library version 5.5.35
Active Persistent Links 0
Inactive Persistent Links 0
Active Links 0
Client API header version 5.5.35
MYSQLI_SOCKET /var/run/mysqld/mysqld.sock


Directive Local Value Master Value
mysqli.allow_local_infile On On
mysqli.allow_persistent On On
mysqli.default_host no value no value
mysqli.default_port 3306 3306
mysqli.default_pw no value no value
mysqli.default_socket /var/run/mysqld/mysqld.sock /var/run/mysqld/mysqld.sock
mysqli.default_user no value no value
mysqli.max_links Unlimited Unlimited
mysqli.max_persistent Unlimited Unlimited
mysqli.reconnect Off Off


openssl


OpenSSL support enabled
OpenSSL Library Version OpenSSL 1.0.1 14 Mar 2012
OpenSSL Header Version OpenSSL 1.0.1 14 Mar 2012


pcre


PCRE (Perl Compatible Regular Expressions) Support enabled
PCRE Library Version 8.12 2011-01-15


Directive Local Value Master Value
pcre.backtrack_limit 1000000 1000000
pcre.recursion_limit 100000 100000


PDO


PDO support enabled
PDO drivers mysql


pdo_mysql


PDO Driver for MySQL enabled
Client API version 5.5.35


Directive Local Value Master Value
pdo_mysql.default_socket /var/run/mysqld/mysqld.sock /var/run/mysqld/mysqld.sock


Phar


Phar: PHP Archive support enabled
Phar EXT version 2.0.1
Phar API version 1.1.1
SVN revision $Revision: 321634 $
Phar-based phar archives enabled
Tar-based phar archives enabled
ZIP-based phar archives enabled
gzip compression enabled
bzip2 compression enabled
Native OpenSSL support enabled


Phar based on pear/PHP_Archive, original concept by Davey Shafik.
Phar fully realized by Gregory Beaver and Marcus Boerger.
Portions of tar implementation Copyright (c) 2003-2009 Tim Kientzle.


Directive Local Value Master Value
phar.cache_list no value no value
phar.readonly On On
phar.require_hash On On


posix


Revision $Revision: 321634 $


Reflection


Reflection enabled
Version $Revision: 321634 $


session


Session Support enabled
Registered save handlers files user memcached
Registered serializer handlers php php_binary wddx


Directive Local Value Master Value
session.auto_start Off Off
session.bug_compat_42 Off Off
session.bug_compat_warn Off Off
session.cache_expire 180 180
session.cache_limiter nocache nocache
session.cookie_domain no value no value
session.cookie_httponly Off Off
session.cookie_lifetime 0 0
session.cookie_path / /
session.cookie_secure Off Off
session.entropy_file no value no value
session.entropy_length 0 0
session.gc_divisor 1000 1000
session.gc_maxlifetime 1440 1440
session.gc_probability 1 1
session.hash_bits_per_character 5 5
session.hash_function 0 0
session.name PHPSESSID PHPSESSID
session.referer_check no value no value
session.save_handler files files
session.save_path /var/lib/php5/session /var/lib/php5/session
session.serialize_handler php php
session.use_cookies On On
session.use_only_cookies On On
session.use_trans_sid 0 0


shmop


shmop support enabled


SimpleXML


Simplexml support enabled
Revision $Revision: 321634 $
Schema support enabled


soap


Soap Client enabled
Soap Server enabled


Directive Local Value Master Value
soap.wsdl_cache 1 1
soap.wsdl_cache_dir /tmp /tmp
soap.wsdl_cache_enabled 1 1
soap.wsdl_cache_limit 5 5
soap.wsdl_cache_ttl 86400 86400


sockets


Sockets Support enabled


SPL


SPL support enabled
Interfaces Countable, OuterIterator, RecursiveIterator, SeekableIterator, SplObserver, SplSubject
Classes AppendIterator, ArrayIterator, ArrayObject, BadFunctionCallException, BadMethodCallException, CachingIterator, DirectoryIterator, DomainException, EmptyIterator, FilesystemIterator, FilterIterator, GlobIterator, InfiniteIterator, InvalidArgumentException, IteratorIterator, LengthException, LimitIterator, LogicException, MultipleIterator, NoRewindIterator, OutOfBoundsException, OutOfRangeException, OverflowException, ParentIterator, RangeException, RecursiveArrayIterator, RecursiveCachingIterator, RecursiveDirectoryIterator, RecursiveFilterIterator, RecursiveIteratorIterator, RecursiveRegexIterator, RecursiveTreeIterator, RegexIterator, RuntimeException, SplDoublyLinkedList, SplFileInfo, SplFileObject, SplFixedArray, SplHeap, SplMinHeap, SplMaxHeap, SplObjectStorage, SplPriorityQueue, SplQueue, SplStack, SplTempFileObject, UnderflowException, UnexpectedValueException


standard


Dynamic Library Support enabled
Path to sendmail /usr/sbin/sendmail -t -i


Directive Local Value Master Value
assert.active 1 1
assert.bail 0 0
assert.callback no value no value
assert.quiet_eval 0 0
assert.warning 1 1
auto_detect_line_endings 0 0
default_socket_timeout 60 60
from no value no value
safe_mode_allowed_env_vars PHP_ PHP_
safe_mode_protected_env_vars LD_LIBRARY_PATH LD_LIBRARY_PATH
url_rewriter.tags a=href,area=href,frame=src,input=src,form=fakeentry a=href,area=href,frame=src,input=src,form=fakeentry
user_agent no value no value


suhosin


Suhosin logo This server is protected with the Suhosin Extension 0.9.33


Copyright (c) 2006-2007 Hardened-PHP Project
Copyright (c) 2007-2012 SektionEins GmbH


Directive Local Value Master Value
suhosin.apc_bug_workaround Off Off
suhosin.cookie.checkraddr 0 0
suhosin.cookie.cryptdocroot On On
suhosin.cookie.cryptkey [ protected ] [ protected ]
suhosin.cookie.cryptlist no value no value
suhosin.cookie.cryptraddr 0 0
suhosin.cookie.cryptua On On
suhosin.cookie.disallow_nul 1 1
suhosin.cookie.disallow_ws 1 1
suhosin.cookie.encrypt Off Off
suhosin.cookie.max_array_depth 50 50
suhosin.cookie.max_array_index_length 64 64
suhosin.cookie.max_name_length 64 64
suhosin.cookie.max_totalname_length 256 256
suhosin.cookie.max_value_length 10000 10000
suhosin.cookie.max_vars 100 100
suhosin.cookie.plainlist no value no value
suhosin.coredump Off Off
suhosin.disable.display_errors Off Off
suhosin.executor.allow_symlink Off Off
suhosin.executor.disable_emodifier Off Off
suhosin.executor.disable_eval Off Off
suhosin.executor.eval.blacklist no value no value
suhosin.executor.eval.whitelist no value no value
suhosin.executor.func.blacklist no value no value
suhosin.executor.func.whitelist no value no value
suhosin.executor.include.allow_writable_files On On
suhosin.executor.include.blacklist no value no value
suhosin.executor.include.max_traversal 0 0
suhosin.executor.include.whitelist no value no value
suhosin.executor.max_depth 0 0
suhosin.filter.action no value no value
suhosin.get.disallow_nul 1 1
suhosin.get.disallow_ws 0 0
suhosin.get.max_array_depth 50 50
suhosin.get.max_array_index_length 64 64
suhosin.get.max_name_length 64 64
suhosin.get.max_totalname_length 256 256
suhosin.get.max_value_length 512 512
suhosin.get.max_vars 100 100
suhosin.log.file 0 0
suhosin.log.file.name no value no value
suhosin.log.phpscript 0 0
suhosin.log.phpscript.is_safe Off Off
suhosin.log.phpscript.name no value no value
suhosin.log.sapi 0 0
suhosin.log.script 0 0
suhosin.log.script.name no value no value
suhosin.log.syslog no value no value
suhosin.log.syslog.facility no value no value
suhosin.log.syslog.priority no value no value
suhosin.log.use-x-forwarded-for Off Off
suhosin.mail.protect 1 1
suhosin.memory_limit 0 0
suhosin.mt_srand.ignore On On
suhosin.multiheader Off Off
suhosin.perdir 0 0
suhosin.post.disallow_nul 1 1
suhosin.post.disallow_ws 0 0
suhosin.post.max_array_depth 50 50
suhosin.post.max_array_index_length 64 64
suhosin.post.max_name_length 64 64
suhosin.post.max_totalname_length 256 256
suhosin.post.max_value_length 1000000 1000000
suhosin.post.max_vars 1000 1000
suhosin.protectkey On On
suhosin.request.disallow_nul 1 1
suhosin.request.disallow_ws 0 0
suhosin.request.max_array_depth 50 50
suhosin.request.max_array_index_length 64 64
suhosin.request.max_totalname_length 256 256
suhosin.request.max_value_length 1000000 1000000
suhosin.request.max_varname_length 64 64
suhosin.request.max_vars 1000 1000
suhosin.server.encode On On
suhosin.server.strip On On
suhosin.session.checkraddr 0 0
suhosin.session.cryptdocroot On On
suhosin.session.cryptkey [ protected ] [ protected ]
suhosin.session.cryptraddr 0 0
suhosin.session.cryptua Off Off
suhosin.session.encrypt On On
suhosin.session.max_id_length 128 128
suhosin.simulation On On
suhosin.sql.bailout_on_error Off Off
suhosin.sql.comment 0 0
suhosin.sql.multiselect 0 0
suhosin.sql.opencomment 0 0
suhosin.sql.union 0 0
suhosin.sql.user_postfix no value no value
suhosin.sql.user_prefix no value no value
suhosin.srand.ignore On On
suhosin.stealth On On
suhosin.upload.disallow_binary 0 0
suhosin.upload.disallow_elf 1 1
suhosin.upload.max_uploads 25 25
suhosin.upload.remove_binary 0 0
suhosin.upload.verification_script no value no value


sysvmsg


sysvmsg support enabled
Revision $Revision: 321634 $


tokenizer


Tokenizer Support enabled


wddx


WDDX Support enabled
WDDX Session Serializer enabled


xml


XML Support active
XML Namespace Support active
libxml2 Version 2.7.8


xmlreader


XMLReader enabled


xmlwriter


XMLWriter enabled


xsl


XSL enabled
libxslt Version 1.1.26
libxslt compiled against libxml Version 2.7.8
EXSLT enabled
libexslt Version 1.1.26


zip


Zip enabled
Extension Version $Id: php_zip.c 321634 2012-01-01 13:15:04Z felipe $
Zip version 1.9.1
Libzip version 0.9.0


zlib


ZLib Support enabled
Stream Wrapper support compress.zlib://
Stream Filter support zlib.inflate, zlib.deflate
Compiled Version 1.2.1.1
Linked Version 1.2.3.4


Directive Local Value Master Value
zlib.output_compression Off Off
zlib.output_compression_level -1 -1
zlib.output_handler no value no value


Additional Modules


Module Name
sysvsem
sysvshm


Environment


Variable Value
APACHE_RUN_DIR /var/run/apache2
APACHE_PID_FILE /var/run/apache2.pid
PATH /usr/local/bin:/usr/bin:/bin
APACHE_LOCK_DIR /var/lock/apache2
LANG C
APACHE_RUN_USER www-data
APACHE_RUN_GROUP www-data
APACHE_LOG_DIR /var/log/apache2
PWD /


PHP Variables


Variable Value
PHP_SELF /phpinfo.php
_COOKIE["PHPSESSID"] ffvc6micfftj7okslt11lvk2m2
_SERVER["HTTP_HOST"] performatix.co
_SERVER["HTTP_CONNECTION"] keep-alive
_SERVER["HTTP_ACCEPT"] text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
_SERVER["HTTP_USER_AGENT"] Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.154 Safari/537.36
_SERVER["HTTP_DNT"] 1
_SERVER["HTTP_ACCEPT_ENCODING"] gzip,deflate,sdch
_SERVER["HTTP_ACCEPT_LANGUAGE"] en-US,en;q=0.8,af;q=0.6
_SERVER["HTTP_COOKIE"] PHPSESSID=ffvc6micfftj7okslt11lvk2m2
_SERVER["PATH"] /usr/local/bin:/usr/bin:/bin
_SERVER["SERVER_SIGNATURE"] no value
_SERVER["SERVER_SOFTWARE"] Apache
_SERVER["SERVER_NAME"] performatix.co
_SERVER["SERVER_ADDR"] 31.222.157.140
_SERVER["SERVER_PORT"] 80
_SERVER["REMOTE_ADDR"] 41.135.198.25
_SERVER["DOCUMENT_ROOT"] /var/www/performatix.co
_SERVER["SERVER_ADMIN"] [no address given]
_SERVER["SCRIPT_FILENAME"] /var/www/performatix.co/phpinfo.php
_SERVER["REMOTE_PORT"] 15554
_SERVER["GATEWAY_INTERFACE"] CGI/1.1
_SERVER["SERVER_PROTOCOL"] HTTP/1.1
_SERVER["REQUEST_METHOD"] GET
_SERVER["QUERY_STRING"] no value
_SERVER["REQUEST_URI"] /phpinfo.php
_SERVER["SCRIPT_NAME"] /phpinfo.php
_SERVER["PHP_SELF"] /phpinfo.php
_SERVER["REQUEST_TIME"] 1395930993


PHP License


This program is free software; you can redistribute it and/or modify it under the terms of the PHP License as published by the PHP Group and included in the distribution in the file: LICENSE


This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.


If you did not receive a copy of the PHP license, or have any questions about PHP licensing, please contact license@php.net.

 

sincerely,

Pierre "Greywacke" du Toit

Edited by Ch0cu3r
Link to comment
Share on other sites

Well, to help you here you need to print out the $conn variable, to see what result you want to match. Most likely the regExp pattern does not match the string as expected.

 

Add the following else condition,

if (preg_match_all($pattern,$connstr,$arr,PREG_PATTERN_ORDER)) {
echo "<sql>".print_r($arr,true)."</sql>\n";
array_push($GLOBALS["sql"],print_r($arr,true));
echo " <conn dbsrvr=\"".$arr[1][6]."\" dbname=\"".$arr[4][7]."\" user=\"".$arr[2][6]."\" pass=\"".$arr[3][6]."\" php_tz=\"".$arr[5][10]."\" php_dtf=\"".$arr[6][8]."\" php_dta=\"".$arr[7][9]."\" pt_on=\"".$arr[8][0]."\" pt_mail=\"".$arr[9][1]."\" curl=\"".$arr[10][2]."\" cto=\"".$arr[11][3]."\" pto=\"".$arr[12][4]."\" ssl=\"".$arr[13][5]."\" />\n";
} else {

echo "NOT match";

}
Link to comment
Share on other sites

ok with the following code

<?php
include("production/includes/content/performatix.php");
header("Cache-Control: no-store");
header("Content-type: text/xml; charset=utf-8");
echo "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n";
echo "<root>\n";
function getdbconfig($file = "") {
	if ($_GLOBALS["ssl_enabled"] == 1 && ((!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off') || $_SERVER['SERVER_PORT'] == 443) || $_GLOBALS["ssl_enabled"] == 0) {
		$pattern =	'/^\$conn = mysql_connect\("([a-zA-Z._0-9\-]+)", "([a-zA-Z_0-9]+)", "([a-zA-Z_0-9]+)"\);$'.
				 	'|^mysql_select_db\("([a-zA-Z_0-9]+)", \$conn\);$'.
				 	'|^date_default_timezone_set\([\'"]([A-Za-z0-9\/+\-]+)[\'"]\);$'.
				 	'|^\$GLOBALS\["dtmstyle"\] = "([^"]+)";$'.
				 	'|^\$GLOBALS\["dtlast"\] = ([0|1]);$'.
				 	'|^\$GLOBALS\["prod_prodmode"\] = ([0|1]); \/\/ [a-z ]+$'.
				 	'|^\$GLOBALS\["prod_prodmail"\] = "([^@]+@[^"]+)";$'.
				 	'|^\$GLOBALS\["curl"\] = ([0|1]);$'.
					'|^\$GLOBALS\["conn_timeout"\] = ([0-9]+);$'.
					'|^\$GLOBALS\["post_timeout"\] = ([0-9]+);$'.
					'|^\$GLOBALS\["ssl_enabled"\] = ([0|1]);$/m';
		$connstr = file_get_contents($file, FILE_USE_INCLUDE_PATH);
		$arr = array();
		if (preg_match_all($pattern,$connstr,$arr,PREG_PATTERN_ORDER)!==false) {
			echo "	<sql>".print_r($arr,true)."</sql>\n";
			echo "	<conn dbsrvr=\"".$arr[1][6]."\" dbname=\"".$arr[4][7]."\" user=\"".$arr[2][6]."\" pass=\"".$arr[3][6]."\" php_tz=\"".$arr[5][10]."\" php_dtf=\"".$arr[6][8]."\" php_dta=\"".$arr[7][9]."\" pt_on=\"".$arr[8][0]."\" pt_mail=\"".$arr[9][1]."\" curl=\"".$arr[10][2]."\" cto=\"".$arr[11][3]."\" pto=\"".$arr[12][4]."\" ssl=\"".$arr[13][5]."\" />\n";
			echo "	<sql>".xmlentities(print_r($connstr,true))."</sql>\n";
		} else {
			echo "	<error>NO PREG MATCH FOUND!</error>\n";
		}
	} else {
                $redirect = "https://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
                header("Location: $redirect");
	}
}
getdbconfig("production/includes/content/performatix.php");
echo "</root>";
?>

i've managed to get the following:

<?xml version="1.0" encoding="utf-8"?>
<root>
	<sql>Array
(
    [0] => Array
        (
        )

    [1] => Array
        (
        )

    [2] => Array
        (
        )

    [3] => Array
        (
        )

    [4] => Array
        (
        )

    [5] => Array
        (
        )

    [6] => Array
        (
        )

    [7] => Array
        (
        )

    [8] => Array
        (
        )

    [9] => Array
        (
        )

    [10] => Array
        (
        )

    [11] => Array
        (
        )

    [12] => Array
        (
        )

    [13] => Array
        (
        )

)
</sql>
	<conn dbsrvr="" dbname="" user="" pass="" php_tz="" php_dtf="" php_dta="" pt_on="" pt_mail="" curl="" cto="" pto="" ssl="" />
	<sql><?php\r\n/*\r\nMYSQL CONNECTION INCLUDE\r\nVersion 2.2.5\r\n*/\r\n// set error log files\r\nmb_internal_encoding("UTF-8");\r\nini_set('log_errors', 1);\r\nini_set('error_log', dirname(__FILE__) . DIRECTORY_SEPARATOR . 'error.log');\r\nini_set('html_errors', 0);\r\nini_set('display_errors', 0); // has to be off so lead managers do not return invalid xml!\r\n$GLOBALS["prod_prodmode"] = 0; // enable to send to production test email\r\n$GLOBALS["prod_prodmail"] = "*****@*****.***";\r\n$GLOBALS["curl"] = 1;\r\n$GLOBALS["conn_timeout"] = 15;\r\n$GLOBALS["post_timeout"] = 30;\r\n$GLOBALS["ssl_enabled"] = 0;\r\n$sql = array();\r\n$urlencode = false;\r\nerror_reporting(E_ALL);\r\n//$conn = mysql_connect("*****", "*****", "*****");\r\n$conn = mysql_connect("*****", "*****", "*****");\r\nif (!$conn) {\r\n	$err = "ERROR #".mysql_errno()."Could not connect: ".mysql_error()." in ".$doc." on Line ".$line;\r\n	array_push($GLOBALS["sql"],$err."\n");\r\n} else {\r\n	mysql_query("SET NAMES utf8;",$conn);\r\n}\r\nfunction mysql_query_errors($sql, $conn, $doc, $line, $expret = false) {\r\n	$line--;\r\n	$err = "";\r\n	$result = false;\r\n	global $conn;\r\n	$msc = microtime(true);\r\n	$result = mysql_query($sql,$conn);\r\n	$msc = microtime(true)-$msc;\r\n	if (mysql_errno()) {\r\n		$err = "ERROR #".mysql_errno().": ".mysql_error()." in ".$doc." on Line ".$line;\r\n		array_push($GLOBALS["sql"],$sql."\n",$err."\n",'$_SESSION = '.print_r($_SESSION,true),print_r($_POST,true),"Line ".$line." in ".$doc." executed in ".$msc." seconds.\n");\r\n	} elseif ($expret === true) {\r\n		if ($msc >= 1) {\r\n			$err = "NOTICE #0505: The query in ".$doc." on line ".$line--." executed in ".$msc." milliseconds.";\r\n		} elseif (is_null($result)) {\r\n			$err = "NOTICE #0504: A null value was returned by the query defined in ".$doc." on line ".$line--;\r\n		} elseif (!isset($result)) {\r\n			$err = "NOTICE #0503: An undefined value was returned by the query defined in ".$doc." on line ".$line--;\r\n		} elseif ($result === false) {\r\n			$err = "NOTICE #0502: A false value was returned by the query defined in ".$doc." on line ".$line--;\r\n		} elseif ($result === true) {\r\n			$err = "NOTICE #0501: A true value was returned by the query defined in ".$doc." on line ".$line--;\r\n		} elseif (mysql_num_rows($result) < 1) {\r\n			$err = "NOTICE #0500: An empty result set was returned by the query defined in ".$doc." on line ".$line--;\r\n		}\r\n		array_push($GLOBALS["sql"],$sql."\n",$err."\n",'$_SESSION = '.print_r($_SESSION,true),"\$_POST = ".print_r($_POST,true),"Line ".$line."  in ".$doc." executed in ".$msc." seconds.\n");\r\n	}\r\n	return $result;\r\n}\r\nfunction getFile($filename) {\r\n	$return = '';\r\n	if (@filesize($filename)) {\r\n		if ($fp = fopen($filename,'r')) {\r\n			$return = fread($fp, filesize($filename));\r\n			fclose($fp);\r\n			return $return;\r\n		} else {\r\n			return false;\r\n		}\r\n	} else {\r\n		return file_get_contents($filename);\r\n	}\r\n}\r\nfunction do_post_request($url, $data, $options = array()) {\r\n	$old = ini_set('default_socket_timeout', $GLOBALS["conn_timeout"]);\r\n	$params = array('http' => array(\r\n			'method' => 'post',\r\n			'content' => (is_array($data))?http_build_query($data):$data\r\n		)\r\n	);\r\n	if(isset($options['Referer']) && isset($options['User-Agent']) && isset($options['Username']) && isset($options['Password'])) {\r\n		$params['http']['authorisation'] = $options['Username'].':'.$options['Password'];\r\n		$params['http']['user-agent'] = $options['User-Agent'];\r\n		$params['http']['referer'] = $options['Referer'];\r\n	}\r\n	$ctx = stream_context_create($params);\r\n	$fp = @fopen($url, 'rb', false, $ctx);\r\n	ini_set('default_socket_timeout', $old);\r\n	stream_set_timeout($fp, $GLOBALS["post_timeout"]);\r\n	if (!$fp) {\r\n		trigger_error("Problem with ".$url.", ".$php_errormsg);\r\n	}\r\n	$response = @stream_get_contents($fp);\r\n	$info = stream_get_meta_data($fp);\r\n    fclose($fp);\r\n	if ($info['timed_out']) {\r\n		return 'Connection timed out!';\r\n	} else {\r\n		if ($response === false) {\r\n			trigger_error("Problem reading data from ".$url.", ".$php_errormsg);\r\n		}\r\n		return $response;\r\n	}\r\n}\r\nfunction curl_post($url, $post = array(), array $options = array()) {\r\n	$user_agent='Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.149 Safari/537.36';\r\n	\r\n	$defaults = array(\r\n		CURLOPT_POST           => 1,\r\n		CURLOPT_USERAGENT      => $user_agent,\r\n		CURLOPT_HEADER         => 0,\r\n		CURLOPT_VERBOSE        => 1,\r\n		CURLOPT_TIMEOUT        => $GLOBALS["post_timeout"],\r\n		CURLOPT_CONNECTTIMEOUT => $GLOBALS["conn_timeout"],\r\n		CURLOPT_FRESH_CONNECT  => 1,\r\n		CURLOPT_RETURNTRANSFER => 1,\r\n		CURLOPT_FORBID_REUSE   => 0,\r\n		CURLOPT_URL            => $url,\r\n		CURLOPT_POSTFIELDS     => (is_array($post))?http_build_query($post):$post,\r\n		CURLOPT_ENCODING       => "",                          // handle all encodings\r\n		CURLOPT_AUTOREFERER    => true,                        // set referer on redirect\r\n		CURLOPT_CONNECTTIMEOUT => 120,                         // timeout on connect\r\n		CURLOPT_TIMEOUT        => 120,                         // timeout on response\r\n		CURLOPT_MAXREDIRS      => 10,                          // stop after 10 redirects\r\n	);\r\n	$opts = array();\r\n	if(isset($options['Referer']) && isset($options['User-Agent']) && isset($options['Username']) && isset($options['Password'])) {\r\n		$opts = array(\r\n			CURLOPT_USERPWD => $options['Username'].':'.$options['Password'],\r\n			CURLOPT_USERAGENT => $options['User-Agent'],\r\n			CURLOPT_REFERER => $options['Referer']\r\n		);\r\n	}\r\n	\r\n	$ch = curl_init();\r\n	curl_setopt_array($ch, ($opts + $defaults));\r\n	$content = curl_exec($ch);\r\n	$err     = curl_errno($ch);\r\n	$errmsg  = curl_error($ch);\r\n	$header  = curl_getinfo($ch);\r\n	curl_close($ch);\r\n	\r\n	$header['errno']   = $err;\r\n	$header['errmsg']  = $errmsg;\r\n	$header['content'] = $content;\r\n	return $header;\r\n}\r\nfunction get_web_page($method="GET", $url="http://www.google.com/") {\r\n	$user_agent='Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.149 Safari/537.36';\r\n\r\n	$options = array(\r\n		CURLOPT_HTTPAUTH       => CURLAUTH_BASIC,              // set authtype\r\n		CURLOPT_USERPWD        => "quomoto:qu0m0t0",           // set htaccess details\r\n		CURLOPT_CUSTOMREQUEST  => $method,                     // set request type post or get\r\n		CURLOPT_POST           => ($method=="GET")?false:true, // set to GET (false) or POST (true)\r\n		CURLOPT_USERAGENT      => $user_agent,                 // set user agent\r\n		CURLOPT_COOKIEFILE     => "cookie.txt",                // set cookie file\r\n		CURLOPT_COOKIEJAR      => "cookie.txt",                // set cookie jar\r\n		CURLOPT_RETURNTRANSFER => true,                        // return web page\r\n		CURLOPT_HEADER         => true,                       // don't return headers\r\n		CURLOPT_FOLLOWLOCATION => true,                        // follow redirects\r\n		CURLOPT_ENCODING       => "",                          // handle all encodings\r\n		CURLOPT_AUTOREFERER    => true,                        // set referer on redirect\r\n		CURLOPT_CONNECTTIMEOUT => 120,                         // timeout on connect\r\n		CURLOPT_TIMEOUT        => 120,                         // timeout on response\r\n		CURLOPT_MAXREDIRS      => 10,                          // stop after 10 redirects\r\n	);\r\n\r\n	$ch      = curl_init($url);\r\n	curl_setopt_array($ch, $options);\r\n	$content = curl_exec($ch);\r\n	$err     = curl_errno($ch);\r\n	$errmsg  = curl_error($ch);\r\n	$header  = curl_getinfo($ch);\r\n	curl_close($ch);\r\n\r\n	$header['errno']   = $err;\r\n	$header['errmsg']  = $errmsg;\r\n	$header['content'] = $content;\r\n	return $header;\r\n}\r\n// Make OnePage CRM API call\r\nfunction make_api_call($url, $http_method, $post_data = array(), $uid = null, $key = null, $v3 = false) {\r\n	$full_url = 'https://app.onepagecrm.com/api/'.$url;\r\n	$ch = curl_init($full_url);\r\n	//curl_setopt($ch, CURLOPT_TIMEOUT, 0);\r\n	//curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 0);\r\n	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);\r\n	curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $http_method);\r\n	$timestamp = time();\r\n	$auth_data = array($uid, $timestamp, $http_method, sha1($full_url));\r\n	// For POST and PUT methods we have to calculate request body hash\r\n	if($http_method == 'POST' || $http_method == 'PUT'){\r\n		$post_query = http_build_query($post_data);\r\n		curl_setopt($ch, CURLOPT_POSTFIELDS, $post_query);\r\n		$auth_data[] = sha1($post_query);\r\n	}\r\n	// Auth headers\r\n	if($uid != null){ // We are logged in\r\n		$hash = hash_hmac('sha256', implode('.', $auth_data), $key);\r\n		curl_setopt($ch, CURLOPT_HTTPHEADER, array(\r\n			"X-OnePageCRM-UID: $uid",\r\n			"X-OnePageCRM-TS: $timestamp",\r\n			"X-OnePageCRM-Auth: $hash"\r\n		));\r\n	}\r\n	$result = json_decode(curl_exec($ch));\r\n	if($ret = curl_errno($ch)) {\r\n		$info = curl_getinfo($ch);\r\n		return 'CURL ERROR '.$ret.': '.curl_error($ch).' \r'.print_r($info,true);\r\n	}\r\n	curl_close($ch);\r\n	if($result->status > 99){\r\n		return print_r("API call error {$result->status} - {$result->message}\n",true);\r\n	}\r\n	return $result;\r\n}\r\nfunction xmlentities($value) {\r\n	//replace $value's invalid xml characters with entities and unicode characters\r\n	// used with Hex NCR's (Hexadecimal Numeric Character Representations).\r\n	$patterns = array(\r\n			'/&/',			// ampersand symbol\r\n			'/\r/',			// carriage return\r\n			'/\n/',			// line feed\r\n			'/</',			// less than symbol\r\n			'/>/',			// greater than symbol\r\n			'/"/',			// double quotation mark\r\n			'//',			// SOH symbol\r\n			'/©/',			// (c) copyright symbols\r\n			'/ë/',			// e with diaresis\r\n			'/è/',			// e with grave\r\n			'/é/',			// e with acute\r\n			'/"/',			// left slanting double quotation mark\r\n			'/"/'			// right slanting double quotation mark\r\n		);\r\n	$replacements = array(\r\n			'&amp;',\r\n			'\r',\r\n			'\n',\r\n			'&lt;',\r\n			'&gt;',\r\n			'&quot;',\r\n			'',\r\n			'&#x00A9;',\r\n			'&#x00EB;',\r\n			'&#x00E8;',\r\n			'&#x00E9;',\r\n			'&#x201C;',\r\n			'&#x201D;'\r\n		);\r\n	$value = utf8_encode_deep($value);	// convert string to unicode to replace characters\r\n	$value = preg_replace($patterns, $replacements, $value);\r\n	return $value;\r\n}\r\nfunction utf8_encode_deep($input) {\r\n    if (is_string($input)) {\r\n		$input = mb_convert_encoding($input, 'UTF-8');\r\n        //$input = utf8_encode($input);\r\n    } else if (is_array($input)) {\r\n        foreach ($input as &$value) {\r\n            $value = utf8_encode_deep($value);\r\n        }\r\n        unset($value);\r\n    } else if (is_object($input)) {\r\n        $vars = array_keys(get_object_vars($input));\r\n        foreach ($vars as $var) {\r\n            $input->$var = utf8_encode_deep($input->$var);\r\n        }\r\n    }\r\n	return $input;\r\n}\r\nfunction idflags($input) {\r\n	global $conn;\r\n	foreach ($input as $in) {\r\n		// use to explode by first space if found, to get flag values\r\n		$in = preg_split("/ |&nbsp;/",$in,2,PREG_SPLIT_NO_EMPTY);\r\n		// print result array\r\n		// print_r($in);\r\n		// build and return the values to replace with\r\n		// state & country variable texts\r\n		switch (strip_tags($in[0])) {\r\n			// lead form flags\r\n			case "SOURCE":\r\n				return ($GLOBALS["formfromname"])?$GLOBALS["formfromname"]:$GLOBALS["source"];\r\n				break;\r\n			case "FORMFROMNAME":\r\n				return ($GLOBALS["usedefault"])?$GLOBALS["defaultfromname"]:$GLOBALS["formfromname"];\r\n				break;\r\n			case "FORMFROMCAPS":\r\n				return ($GLOBALS["usedefault"])?strtoupper($GLOBALS["defaultfromname"]):strtoupper($GLOBALS["formfromname"]);\r\n				break;\r\n			case "FORMFROMABBREV":\r\n				if (preg_match_all("/[A-Z]+/",($GLOBALS["usedefault"])?$GLOBALS["defaultname"]:$GLOBALS["formname"],$matches)) {\r\n					return implode("",$matches[0]);\r\n				} else {\r\n					return "NA";\r\n				}\r\n				break;\r\n			// mail configurable flags\r\n			case "COUNTRY":\r\n				return $GLOBALS["country"];\r\n				break;\r\n			case "STATE":\r\n				return $GLOBALS["state"];\r\n				break;\r\n			case "DISTANCE":\r\n				return number_format($GLOBALS["recipient"][14],0);\r\n				break;\r\n			case "TAFURL":\r\n				return ($GLOBALS["usedefault"])?$GLOBALS["defurl"]:$GLOBALS["tafurl"];\r\n				break;\r\n			case "TAFIMG":\r\n				return ($GLOBALS["usedefault"])?$GLOBALS["defimg"]:$GLOBALS["tafimg"];\r\n				break;\r\n			case "LOGO":\r\n				return ($GLOBALS["usedefault"])?$GLOBALS["defaultlogo"]:$GLOBALS["formlogo"];\r\n				break;\r\n			case "FORMNAME":\r\n				return ($GLOBALS["usedefault"])?$GLOBALS["defaultname"]:$GLOBALS["formname"];\r\n				break;\r\n			case "CRONLRSUBJECT":\r\n				if ($GLOBALS["limit"]=="UPPER") {\r\n					return "%CONFIGTEXT Cron | Supplier | Notification | Header | Low%";\r\n				} elseif ($GLOBALS["limit"]=="LOWER") {\r\n					return "%CONFIGTEXT Cron | Supplier | Notification | Header | Very Low%";\r\n				}\r\n				break;\r\n			case "CRONSTATESUBJECT":\r\n				if ($GLOBALS["limit"]=="MONTHLY") {\r\n					if ($GLOBALS["recipient"][10] == 0) {\r\n						return "%CONFIGTEXT Cron | Supplier | Statement | Header | Monthly | Premium%";\r\n					} else {\r\n						return "%CONFIGTEXT Cron | Supplier | Statement | Header | Monthly | Freemium%";\r\n					}\r\n				} elseif ($GLOBALS["limit"]=="WEEKLY") {\r\n					if ($GLOBALS["recipient"][10] == 0) {\r\n						return "%CONFIGTEXT Cron | Supplier | Statement | Header | Weekly | Premium%";\r\n					} else {\r\n						return "%CONFIGTEXT Cron | Supplier | Statement | Header | Weekly | Trial%";\r\n					}\r\n				} elseif ($GLOBALS["limit"]=="MANUAL") {\r\n					if ($GLOBALS["recipient"][10] == 0) {\r\n						return "%CONFIGTEXT Cron | Supplier | Statement | Header | Monthly | Premium%";\r\n					} else {\r\n						return "%CONFIGTEXT Cron | Supplier | Statement | Header | Monthly | Freemium%";\r\n					}\r\n				}\r\n				break;\r\n			case "CRONSTATEMESSAGE":\r\n				if ($GLOBALS["limit"]=="MONTHLY") {\r\n					return "%CONFIGTEXT Cron | Supplier | Statement | Message | Monthly | Premium%";\r\n				} elseif ($GLOBALS["limit"]=="WEEKLY") {\r\n					return "%CONFIGTEXT Cron | Supplier | Statement | Message | Weekly | Premium%";\r\n				} elseif ($GLOBALS["limit"]=="MANUAL") {\r\n					if (strlen($_POST["textarea_transactionmessage"]) > 0) {\r\n						return preg_replace(array("/\n\r/","/\n/"),"<br />\n",xmlentities($_POST["textarea_transactionmessage"]));\r\n					} else {\r\n						return "%CONFIGTEXT Cron | Supplier | Statement | Message | Weekly | Premium%";\r\n					}\r\n				}\r\n				break;\r\n			case "CRONSTATEFMESSAGE":\r\n				if ($GLOBALS["limit"]=="MONTHLY") {\r\n					if ($GLOBALS["recipient"][10] == 4) {\r\n						return "%CONFIGTEXT Cron | Supplier | Statement | Message | Monthly | Freemium%";\r\n					} elseif ($GLOBALS["recipient"][10] == 2) {\r\n						return "%CONFIGTEXT Cron | Supplier | Statement | Message | Monthly | Trial%";\r\n					}\r\n				} elseif ($GLOBALS["limit"]=="WEEKLY") {\r\n					if ($GLOBALS["recipient"][10] == 4) {\r\n						return "%CONFIGTEXT Cron | Supplier | Statement | Message | Weekly | Freemium%";\r\n					} elseif ($GLOBALS["recipient"][10] == 2) {\r\n						return "%CONFIGTEXT Cron | Supplier | Statement | Message | Weekly | Trial%";\r\n					}\r\n				} elseif ($GLOBALS["limit"]=="MANUAL") {\r\n					if (strlen($_POST["textarea_transactionmessage"]) > 0) {\r\n						return preg_replace(array("/\n\r/","/\n/"),"<br />\n",xmlentities($_POST["textarea_transactionmessage"]));\r\n					} else {\r\n						if ($GLOBALS["recipient"][10] == 4) {\r\n							return "%CONFIGTEXT Cron | Supplier | Statement | Message | Monthly | Freemium%";\r\n						} elseif ($GLOBALS["recipient"][10] == 2) {\r\n							return "%CONFIGTEXT Cron | Supplier | Statement | Message | Monthly | Trial%";\r\n						}\r\n					}\r\n				}\r\n				break;\r\n			case "LEADSLIST":\r\n				return $GLOBALS["transactions"];\r\n				break;\r\n			case "LIMITMESSAGE":\r\n				if ($GLOBALS["limit"]=="UPPER") {\r\n					return "%CONFIGTEXT Cron | Supplier | Notification | Message | Low%";\r\n				} elseif ($GLOBALS["limit"]=="LOWER") {\r\n					return "%CONFIGTEXT Cron | Supplier | Notification | Message | Very Low%";\r\n				}\r\n				break;\r\n			case "RESPONSESIGNATURE":\r\n				return "%CONFIGTEXT Email | Consumer | Message | Signature%";\r\n				break;\r\n			case "PREMIUMSUBJECT":\r\n				return "%CONFIGTEXT Email | Supplier | Premium | Header%";\r\n				break;\r\n			case "PREMIUMINTRO":\r\n				return "%CONFIGTEXT Email | Supplier | Premium | Message | Intro%";\r\n				break;\r\n			case "PREMIUMSIGNATURE":\r\n				return "%CONFIGTEXT Email | Supplier | Premium | Message | Signature%";\r\n				break;\r\n			case "FREEMIUMSUBJECT":\r\n				return "%CONFIGTEXT Email | Supplier | Freemium | Header%";\r\n				break;\r\n			case "FREEMIUMINTRO":\r\n				return "%CONFIGTEXT Email | Supplier | Freemium | Message | Intro%";\r\n				break;\r\n			case "FREEMIUMSIGNATURE":\r\n				return "%CONFIGTEXT Email | Supplier | Freemium | Message | Signature%";\r\n				break;\r\n			case "RESPONSEMESSAGES":\r\n				$msg = ((implode("",$GLOBALS["suppliers"]))?"    %CONFIGTEXT Email | Consumer | Message | Intro Premium%":"").\r\n					((implode("",$GLOBALS["supplierp"]))?"    %CONFIGTEXT Email | Consumer | Message | Intro Freemium%":"");\r\n				return $msg;\r\n				break;\r\n			// lead value determination flags\r\n			case "LVDKEYWEIGHT":\r\n				return round(floatval($GLOBALS["lvdkeyarr"][$in[1]])/1*100,3);\r\n				break;\r\n			case "LVDVALUEWEIGHT":\r\n				return round(floatval($GLOBALS["lvdvalarr"][$in[1]])/10*100,3);\r\n				break;\r\n			case "LVDSCORE":\r\n				$GLOBALS["lvdkeyarr"] = array();\r\n				$GLOBALS["lvdvalarr"] = array();\r\n				$GLOBALS["calc"] = 1;\r\n				$GLOBALS["lvdtot"] = 0.000;\r\n				foreach ($GLOBALS["attribsarr"] as $key => $value) {\r\n					$glue = '/ \| /';\r\n					if (preg_match($glue,$value)>0) {\r\n						$values = preg_split($glue, $value);\r\n						//array_push($GLOBALS["sql"],$values);\r\n						$x = 0;\r\n						$constraint = "";\r\n						foreach ($values as $val) {\r\n							$constraint .= (($x>=1)?" OR ":"")."SA0.text_AttributeValue = \"".mysql_escape_string($val)."\" AND SA0.text_AttributeDescription = \"".mysql_escape_string($key)."\"";\r\n							$x++;\r\n						}\r\n						$tsql = "SELECT \r\n									LVD.double_AttributeKeyWeighting, \r\n									SA0.double_AttributeValueWeighting, \r\n									SA0.text_AttributeDescription, \r\n									SA0.text_AttributeValue \r\n								FROM \r\n									3_serviceattributes SA0 \r\n								LEFT JOIN \r\n									42_leadvaluedetermination LVD \r\n								ON LVD.bigint_AttributeID = (\r\n									SELECT \r\n										SA1.bigint_AttributeID \r\n									FROM \r\n										3_serviceattributes SA1 \r\n									WHERE \r\n										SA1.text_AttributeDescription = SA0.text_AttributeDescription AND \r\n										SA1.bigint_AttributeServiceID = SA0.bigint_AttributeServiceID \r\n									ORDER BY \r\n										SA1.bigint_AttributeID ASC LIMIT 1\r\n								) \r\n								WHERE LVD.double_AttributeKeyWeighting > 0 \r\n									AND SA0.double_AttributeValueWeighting > 0  \r\n									AND SA0.bigint_AttributeServiceID = ".$GLOBALS["service"]." \r\n									AND (\r\n										".$constraint." \r\n									) \r\n								ORDER BY SA0.double_AttributeValueWeighting DESC LIMIT 1;";\r\n						//array_push($GLOBALS["sql"],$tsql);\r\n						$result = mysql_query_errors($tsql, $conn, __FILE__, __LINE__);\r\n						if ($result) {\r\n							if ($row = mysql_fetch_array($result)) {\r\n								$GLOBALS["lvdkeyarr"][$key] = floatval($row["double_AttributeKeyWeighting"]);\r\n								$GLOBALS["lvdvalarr"][$value] = floatval($row["double_AttributeValueWeighting"]);\r\n							}\r\n						}\r\n						$GLOBALS["lvdtot"] += round($GLOBALS["lvdkeyarr"][$key]*$GLOBALS["lvdvalarr"][$value],3);\r\n					} else {\r\n						$tsql = "SELECT \r\n									LVD.double_AttributeKeyWeighting, \r\n									SA0.double_AttributeValueWeighting, \r\n									SA0.text_AttributeDescription, \r\n									SA0.text_AttributeValue \r\n								FROM \r\n									3_serviceattributes SA0 \r\n								LEFT JOIN \r\n									42_leadvaluedetermination LVD \r\n								ON LVD.bigint_AttributeID = (\r\n									SELECT \r\n										SA1.bigint_AttributeID \r\n									FROM \r\n										3_serviceattributes SA1 \r\n									WHERE \r\n										SA1.text_AttributeDescription = SA0.text_AttributeDescription AND \r\n										SA1.bigint_AttributeServiceID = SA0.bigint_AttributeServiceID \r\n									ORDER BY \r\n										SA1.bigint_AttributeID ASC LIMIT 1\r\n								) \r\n								WHERE LVD.double_AttributeKeyWeighting > 0 \r\n									AND SA0.double_AttributeValueWeighting > 0 \r\n									AND SA0.bigint_AttributeServiceID = ".$GLOBALS["service"]." \r\n									AND (\r\n										SA0.text_AttributeDescription = \"".mysql_escape_string($key)."\" \r\n										AND SA0.text_AttributeValue = \"".mysql_escape_string($value)."\"\r\n									) \r\n								ORDER BY SA0.double_AttributeValueWeighting DESC LIMIT 1;";\r\n						$result = mysql_query_errors($tsql, $conn, __FILE__, __LINE__);\r\n						if ($result) {\r\n							if ($row = mysql_fetch_array($result)) {\r\n								$GLOBALS["lvdkeyarr"][$key] = floatval($row["double_AttributeKeyWeighting"]);\r\n								$GLOBALS["lvdvalarr"][$value] = floatval($row["double_AttributeValueWeighting"]);\r\n							}\r\n						}\r\n						$GLOBALS["lvdtot"] += round($GLOBALS["lvdkeyarr"][$key]*$GLOBALS["lvdvalarr"][$value],3);\r\n					}\r\n					$i++;\r\n				}\r\n				$GLOBALS["lvdtot"] = round($GLOBALS["lvdtot"]/10,3);\r\n				$GLOBALS["calc"] = 0;\r\n				return $GLOBALS["lvdtot"];\r\n				break;\r\n			// % lead share variable = (premium/freemium leads sent for this service in last 30 days + 1) / (number of leads_matched table records that match supplier_id in last 30 days) * 100\r\n			case "LEADSHARE":\r\n				if ($GLOBALS["status"] = 0) {			// PREMIUM LEAD SHARE\r\n					$tsql = "SELECT (\r\n										(\r\n											COUNT(\r\n												SELECT * FROM 27_leadssent LS \r\n												LEFT JOIN 25_serviceleads SL ON (LS.bigint_LeadID = SL.bigint_LeadID) \r\n												WHERE \r\n													SL.bigint_SupplierID = ".$GLOBALS["recipient"][6]." \r\n													AND SL.timestamp_LeadCreated > DATE_SUB(CURDATE(), INTERVAL 30 DAY)\r\n										)\r\n										+ 1\r\n										) / (\r\n											COUNT(\r\n												SELECT * FROM 43_leadsmatched LM \r\n												WHERE CONCAT(',',".$GLOBALS["recipient"][6].",',') LIKE CONCAT(',',LM.text_PremiumSupplierIDs,',') \r\n												AND LM.timestamp_LastUpdated > DATE_SUB(CURDATE(), INTERVAL 30 DAY)\r\n										)\r\n										* 100\r\n										)\r\n									) AS `lead_share`;";\r\n					$result = mysql_query_errors($tsql, $conn, __FILE__, __LINE__);\r\n				} elseif ($GLOBALS["status"] = 2 ||		// TRIAL LEAD SHARE\r\n						  $GLOBALS["status"] = 4) {		// FREEMIUM LEAD SHARE\r\n					$tsql = "SELECT (\r\n										(\r\n											COUNT(\r\n												SELECT * FROM 13_prospectleadsent PS \r\n												LEFT JOIN 10_serviceprospects SP ON (PS.bigint_ProspectID = SP.bigint_ProspectID) \r\n												WHERE \r\n													SP.bigint_SupplierID = ".$GLOBALS["recipient"][6]." \r\n													AND SP.timestamp_ProspectCreated > DATE_SUB(CURDATE(), INTERVAL 30 DAY)\r\n										)\r\n										+ 1\r\n										) / (\r\n											COUNT(\r\n												SELECT * FROM 43_leadsmatched LM \r\n												WHERE CONCAT(',',".$GLOBALS["recipient"][6].",',') LIKE CONCAT(',',LM.text_FreemiumSupplierIDs,',') \r\n												AND LM.timestamp_LastUpdated > DATE_SUB(CURDATE(), INTERVAL 30 DAY)\r\n										)\r\n										* 100\r\n										)\r\n									) AS `lead_share`;";\r\n					$result = mysql_query_errors($tsql, $conn, __FILE__, __LINE__);\r\n				}\r\n				if ($result) {\r\n					if ($row = mysql_fetch_array($result)) {\r\n						return $row["lead_share"];\r\n					}\r\n				}\r\n				break;\r\n			// attribute flags\r\n			case "ATTRIBUTE":\r\n				return $GLOBALS["attribsarr"][$in[1]];\r\n				break;\r\n			// survey flags\r\n			case "SURVEYHEADER":\r\n				return "%CONFIGTEXT Email | Consumer | Survey | Header%";\r\n				break;\r\n			case "SURVEYINTRO":\r\n				return "%CONFIGTEXT Email | Consumer | Survey | Intro%";\r\n				break;\r\n			case "SURVEYSIGNATURE":\r\n				return "%CONFIGTEXT Email | Consumer | Survey | Signature%";\r\n				break;\r\n			case "SURVEYTYPE":\r\n				return (!$$GLOBALS["urlencode"])?xmlentities($GLOBALS["surveytype"]):urlencode($GLOBALS["surveytype"]);\r\n				break;\r\n			case "SURVEYURL":\r\n				return $GLOBALS["surveyurl"];\r\n				break;\r\n			case "SURVEYQUESTIONS":\r\n				return $GLOBALS["surveyquestions"];\r\n				break;\r\n			case "SURVEYQCOUNT":\r\n				return $GLOBALS["qcnt"];\r\n				break;\r\n			case "SURVEYTHANKYOU":\r\n				return "%CONFIGTEXT Intellisource | Survey Manager | Thank you! Note%";\r\n				break;\r\n			// consumer flags\r\n			case "CONSUMERNAME":\r\n				$GLOBALS["consumerfullname"] = str_replace(", "," ",$GLOBALS["consumerfullname"]);\r\n				return (!$GLOBALS["urlencode"])?xmlentities($GLOBALS["consumerfullname"]):urlencode($GLOBALS["consumerfullname"]);\r\n				break;\r\n			case "CONSUMERFIRSTNAME":\r\n				$GLOBALS["consumerfullname"] = str_replace(", "," ",$GLOBALS["consumerfullname"]);\r\n				$str = (!$GLOBALS["urlencode"])?xmlentities($GLOBALS["consumerfullname"]):urlencode($GLOBALS["consumerfullname"]);\r\n				$del = array(' ', '.');\r\n				$arr = explode($del[0], str_replace($del, $del[0], $str),2);\r\n				return (count($arr)>1)?$arr[0]:"";\r\n				break;\r\n			case "CONSUMERLASTNAME":\r\n				$GLOBALS["consumerfullname"] = str_replace(", "," ",$GLOBALS["consumerfullname"]);\r\n				$str = (!$GLOBALS["urlencode"])?xmlentities($GLOBALS["consumerfullname"]):urlencode($GLOBALS["consumerfullname"]);\r\n				$del = array(' ', '.');\r\n				$arr = explode($del[0], str_replace($del, $del[0], $str),2);\r\n				return (count($arr)>1)?$arr[1]:"";\r\n				break;\r\n			case "CONSUMEREMAIL":\r\n				return $GLOBALS["consumeremail"];\r\n				break;\r\n			case "CONSUMERCELL":\r\n				return $GLOBALS["consumercell"];\r\n			case "POSTALCODE":\r\n				$arr = explode(", ",xmlentities($GLOBALS["city_town"]));\r\n				return $arr[1];\r\n				break;\r\n			case "CONSUMERCITY":\r\n				$arr = explode(", ",xmlentities($GLOBALS["city_town"]));\r\n				return $arr[0];\r\n				break;\r\n			case "MESSAGE":\r\n				return (!$GLOBALS["urlencode"])?xmlentities($GLOBALS["message"]):urlencode($GLOBALS["message"]);\r\n				break;\r\n			// expected by date\r\n			case "EXPECTEDBY":\r\n				//echo $GLOBALS["exby"]."\n";\r\n				$expected = (is_array($GLOBALS["exby"]))?$GLOBALS["exby"]:explode(" ",date($GLOBALS["dtmstyle"],strtotime($GLOBALS["exby"])));\r\n				//print_r(explode(" ",date($GLOBALS["dtmstyle"],strtotime($GLOBALS["exby"]))));\r\n				return $expected[$GLOBALS["dtlast"]];\r\n				break;\r\n			// supplier flags\r\n			case "OPUSERID":\r\n				return $GLOBALS["user_id"];\r\n				break;\r\n			case "SUPPLIERNAME":\r\n				return xmlentities($GLOBALS["recipient"][1]);\r\n				break;\r\n			case "CONTACTFNAME":\r\n				$fname = explode(" ",$GLOBALS["recipient"][0]);\r\n				return xmlentities($fname[0]);\r\n			case "CONTACTNAME":\r\n				return xmlentities($GLOBALS["recipient"][0]);\r\n				break;\r\n			case "ACCMGR":\r\n				return xmlentities($GLOBALS["recipient"][11]);\r\n				break;\r\n			case "ACCMGRMAIL":\r\n				return $GLOBALS["recipient"][12];\r\n				break;\r\n			case "PAYGBALANCE":\r\n				if ($GLOBALS["leadid"]) {\r\n					return $GLOBALS["newbalance"];\r\n				} else {\r\n					return $GLOBALS["balance"];\r\n				}\r\n			case "INVOICEAMOUNT":\r\n				return $GLOBALS["recipient"][13];\r\n				break;\r\n			// lead flags\r\n			case "LEADS360":\r\n				return str_replace(".","",$GLOBALS["leads360"].((strlen($GLOBALS["opret"])>2048)?" &amp; OnePage Lead ID = ".$GLOBALS["opret"]:""));\r\n				break;\r\n			case "LEADREFERENCE":\r\n				if ($GLOBALS["prospecting"]) {\r\n					return ($GLOBALS["leadid2"] + 9001100).$GLOBALS["ordinal"];\r\n				} elseif (isset($GLOBALS["reference"])) {\r\n					return $GLOBALS["reference"];\r\n				} else {\r\n					return ($GLOBALS["leadid"] + 11001000).$GLOBALS["ordinal"];\r\n				}\r\n				break;\r\n			case "MESSAGENO":\r\n				return ordinalSuffix($GLOBALS["messageno"]);\r\n				break;\r\n			case "LEADSUCCESS":\r\n				if ($GLOBALS["leadsuccess"]) {\r\n					return "SENT     ";\r\n				} else {\r\n					return "UNSENT";\r\n				}\r\n				break;\r\n			case "LEADCREATED":\r\n				return $GLOBALS["leadcreated"];\r\n				break;\r\n			case "LEADCATEGORY":\r\n				return $GLOBALS["cat"];\r\n				break;\r\n			case "PAYGCOST":\r\n				return $GLOBALS["servicecost"];\r\n				break;\r\n			case "DUPLICATES":\r\n				if ($GLOBALS["prospecting"]) {\r\n					return $GLOBALS["lappend"];\r\n				} else {\r\n					return $GLOBALS["append"];\r\n				}\r\n				break;\r\n			// other flags\r\n			case "PROSPECTMESSAGE":\r\n				return $GLOBALS["pmsg"];\r\n				break;\r\n			case "SUPPLIERLIST":\r\n				return join("",$GLOBALS["suppliers"]);\r\n				break;\r\n			case "PROSPECTLIST":\r\n				return join("",$GLOBALS["supplierp"]);\r\n				break;\r\n			case "SERVICENAME":\r\n				return (!$GLOBALS["urlencode"])?xmlentities($GLOBALS["servicename"]):urlencode($GLOBALS["servicename"]);\r\n				break;\r\n			case "REGIONNAME":\r\n				return $GLOBALS["regionname"];\r\n				break;\r\n			// cronjob flags\r\n			case "FROMDATE":\r\n				return date($GLOBALS["dtmstyle"],strtotime($GLOBALS["f"]));\r\n				break;\r\n			case "TODATE":\r\n				return date($GLOBALS["dtmstyle"],strtotime($GLOBALS["t"]));\r\n				break;\r\n			case "YEAR":\r\n				return date("Y",now());\r\n				break;\r\n			case "COPYRIGHT":\r\n				\r\n				break;\r\n			// configurable text flags ADD PARENT REGIONS OR INTO SELECT.\r\n			case "CONFIGTEXT":\r\n				$supplier = getconstraints(($GLOBALS["recipient"][6])?$GLOBALS["recipient"][6]:0,1);\r\n				$regions = getconstraints(($GLOBALS["region"])?$GLOBALS["region"]:0,0);\r\n				$service = getconstraints(($GLOBALS["service"])?$GLOBALS["service"]:0,2);\r\n				$constraints = array();\r\n				if (count($supplier)) array_push($constraints,(count($supplier)>1)?"(".implode(" OR ",$supplier).")":$supplier[0]);\r\n				if (count($regions)) array_push($constraints,(count($regions)>1)?"(".implode(" OR ",$regions).")":$regions[0]);\r\n				if (count($service)) array_push($constraints,(count($service)>1)?"(".implode(" OR ",$service).")":$service[0]);\r\n				$tsql = "SELECT * \r\n						 FROM \r\n							18_configurabletexts \r\n						 WHERE \r\n						 	18_configurabletexts.text_TextDescription = \"".$in[1]."\" AND \r\n							(".implode(" AND ",$constraints).");";\r\n				$result = mysql_query_errors($tsql, $conn, __FILE__, __LINE__ );\r\n				if ($result) {\r\n					if ($row = mysql_fetch_array($result)) {\r\n						return $row["text_TextFullContent"];\r\n					}\r\n				}\r\n		}\r\n	}\r\n}\r\nfunction populateflags($str,$urlencode=false,$usedefault=false) {\r\n	// replace flags used in string (parse entire template contents' as string), populating flags individually and sometimes recursively in callback function.\r\n	$GLOBALS["urlencode"] = $urlencode;\r\n	$GLOBALS["usedefault"] = $usedefault;\r\n	while (preg_match_all("/%([A-Z]+[^%]*)%/",$str,$arr)) {\r\n		$str = preg_replace_callback("/%([A-Z]+[^%]*)%/","idflags",$str);\r\n	}\r\n	return $str;\r\n}\r\nfunction formattribs($str = "") {\r\n	// split attributes string by html tags and space padded =, returning array\r\n	$str = preg_replace("/[\n\r]+/","//",$str);\r\n	$ret = preg_split("/<[^>]+>/",$str,-1,PREG_SPLIT_NO_EMPTY);\r\n	$attr = array();\r\n	foreach ($ret as $value) {\r\n		$val = explode(" = ",$value);\r\n		$attr[$val[0]] = $val[1];\r\n	}\r\n	return $attr;\r\n}\r\nfunction ordinalSuffix($num) {\r\n	if (substr($num,-2, 2) == 11 || substr($num,-2, 2) == 12 || substr($num,-2, 2) == 13) $suffix = "th  ";\r\n	else if (substr($num,-1, 1) == 1) $suffix = "st  ";\r\n	else if (substr($num,-1, 1) == 2) $suffix = "nd";\r\n	else if (substr($num,-1, 1) == 3) $suffix = "rd ";\r\n	else $suffix = "th  ";\r\n	return $num.$suffix;\r\n}\r\nfunction getSubText($body, $tagstart, $tagend) {\r\n	$startpos = strpos($body, $tagstart) + strlen($tagstart);\r\n	$sublen   = strpos($body,$tagend) - $startpos;\r\n	return substr($body,$startpos,$sublen);\r\n}\r\nfunction getconstraints($child,$constraint,$rarray = array()) {\r\n	global $conn;\r\n	mysql_select_db("*****", $conn);\r\n	if (!$child) $child = 0;\r\n	switch ($constraint) {\r\n		case 1:\r\n			// return supplier level constraint\r\n			if (intval($child) > 0) array_push($rarray,"18_configurabletexts.bigint_SupplierID = ".intval($child));\r\n			array_push($rarray,"18_configurabletexts.bigint_SupplierID = 0");\r\n			$return = $rarray;\r\n			break;\r\n		case 2:\r\n			// return service level constraint\r\n			if (intval($child) > 0) array_push($rarray,"18_configurabletexts.bigint_ServiceID = ".intval($child));\r\n			array_push($rarray,"18_configurabletexts.bigint_ServiceID = 0");\r\n			$return = $rarray;\r\n			break;\r\n		default:\r\n			// return parental region constraints for use in getsuppliers function\r\n			if (intval($child) == 0) {\r\n				array_push($rarray,"18_configurabletexts.bigint_RegionID = 0");\r\n				$return = $rarray;\r\n				//print_r($return);\r\n			} else {\r\n				array_push($rarray,"18_configurabletexts.bigint_RegionID = ".intval($child));\r\n				$sql = "SELECT bigint_ParentRegionID FROM 1_regions WHERE bigint_RegionID = ".intval($child).";";\r\n				$result = mysql_query_errors($sql , $conn, __FILE__, __LINE__);\r\n				if ($result) {\r\n					if ($row = mysql_fetch_array($result)) {\r\n						$return = getconstraints($row["bigint_ParentRegionID"],$constraint,$rarray);\r\n					}\r\n					mysql_free_result($result);\r\n				}\r\n			}\r\n	}\r\n	return $return;\r\n}\r\n//http://www.php.net/manual/en/function.html-entity-decode.php\r\nfunction html_entity_decode_utf8( $string, $convert_single_quotes = false ) {\r\n        static $trans_tbl;\r\n        //replace numeric entities\r\n        $string = preg_replace('~&#x0*([0-9a-f]+);~ei', '_code2utf8(hexdec("\\1"))', $string);\r\n        $string = preg_replace('~&#0*([0-9]+);~e', '_code2utf8(\\1)', $string);\r\n        //replace literal entities\r\n        if (!isset($trans_tbl))\r\n        {\r\n                $trans_tbl=array();\r\n                foreach (get_html_translation_table(HTML_ENTITIES) as $val=>$key)\r\n                        $trans_tbl[$key] = utf8_encode($val);\r\n        }\r\n        $decode = strtr($string, $trans_tbl);\r\n        if($convert_single_quotes) $decode = str_replace("'", "\'", $decode);\r\n\r\n        return $decode;\r\n}\r\n//Returns the utf string corresponding to the unicode value (from php.net, courtesy - romans@void.lv)\r\nfunction _code2utf8( $num ) {\r\n        if($num < 0) return '';\r\n        if($num < 128) return chr($num);\r\n\r\n        //Removing / Replacing Windows Illegals Characters\r\n        if($num < 160)\r\n        {\r\n                switch ($num)\r\n                {\r\n                        case 128: $num=8364; break;\r\n                        case 129: $num=160;  break; //(Rayo:) #129 using no relevant sign, thus, mapped to the saved-space #160\r\n                        case 130: $num=8218; break;\r\n                        case 131: $num=402;  break;\r\n                        case 132: $num=8222; break;\r\n                        case 133: $num=8230; break;\r\n                        case 134: $num=8224; break;\r\n                        case 135: $num=8225; break;\r\n                        case 136: $num=710;  break;\r\n                        case 137: $num=8240; break;\r\n                        case 138: $num=352;  break;\r\n                        case 139: $num=8249; break;\r\n                        case 140: $num=338;  break;\r\n                        case 141: $num=160;  break; //(Rayo:) #129 using no relevant sign, thus, mapped to the saved-space #160\r\n                        case 142: $num=381;  break;\r\n                        case 143: $num=160;  break; //(Rayo:) #129 using no relevant sign, thus, mapped to the saved-space #160\r\n                        case 144: $num=160;  break; //(Rayo:) #129 using no relevant sign, thus, mapped to the saved-space #160\r\n                        case 145: $num=8216; break;\r\n                        case 146: $num=8217; break;\r\n                        case 147: $num=8220; break;\r\n                        case 148: $num=8221; break;\r\n                        case 149: $num=8226; break;\r\n                        case 150: $num=8211; break;\r\n                        case 151: $num=8212; break;\r\n                        case 152: $num=732;  break;\r\n                        case 153: $num=8482; break;\r\n                        case 154: $num=353;  break;\r\n                        case 155: $num=8250; break;\r\n                        case 156: $num=339;  break;\r\n                        case 157: $num=160;  break; //(Rayo:) #129 using no relevant sign, thus, mapped to the saved-space #160\r\n                        case 158: $num=382;  break;\r\n                        case 159: $num=376;  break;\r\n                }\r\n        }\r\n        if ($num < 2048) return chr(($num >> 6) + 192) . chr(($num & 63) + 128);\r\n        if ($num < 65536) return chr(($num >> 12) + 224) . chr((($num >> 6) & 63) + 128) . chr(($num & 63) + 128);\r\n        if ($num < 2097152) return chr(($num >> 18) + 240) . chr((($num >> 12) & 63) + 128) . chr((($num >> 6) & 63) + 128) . chr(($num & 63) + 128);\r\n        return '';\r\n}\r\nfunction objectToArray($d) {\r\n	if (is_object($d)) {\r\n		// Gets the properties of the given object\r\n		// with get_object_vars function\r\n		$d = get_object_vars($d);\r\n	}\r\n	if (is_array($d)) {\r\n		/*\r\n		* Return array converted to object\r\n		* Using __FUNCTION__ (Magic constant)\r\n		* for recursive call\r\n		*/\r\n		return array_map(__FUNCTION__, $d);\r\n	} else {\r\n		// Return array\r\n		return $d;\r\n	}\r\n}\r\nfunction arrayToObject($d) {\r\n	if (is_array($d)) {\r\n		/*\r\n		* Return array converted to object\r\n		* Using __FUNCTION__ (Magic constant)\r\n		* for recursive call\r\n		*/\r\n		return (object) array_map(__FUNCTION__, $d);\r\n	}\r\n	else {\r\n		// Return object\r\n		return $d;\r\n	}\r\n}\r\nfunction gettypes($array) {\r\n	$types = "";\r\n	foreach ($array as $id=>$element) {\r\n		$types .= (($id>0)?",":"").$element->{"type"};\r\n	}\r\n	return $types;\r\n}\r\nfunction getkeys($array) {\r\n	$keys = "";\r\n	$id = 0;\r\n	foreach (get_object_vars($array[0]) as $property=>$value) {\r\n		$keys .= (($id>0)?",":"").$property;\r\n		$id++;\r\n	}\r\n	return $keys;\r\n}\r\nfunction opconvert($array,$types=NULL,$levels=1) {\r\n	$manual = (!empty($types))?"true":"false";\r\n	if ($manual=="true") {\r\n		$types = gettypes($array);\r\n		$keys = getkeys($array);\r\n	}\r\n	switch ($levels) {\r\n		case 1:	// pre-formatted array passed\r\n			return implode(",",$array);\r\n			break;\r\n		case 2: // unformatted hash passed\r\n			$i = 0;\r\n			$out = array();\r\n			$type = explode(",",$types);\r\n			$keys = explode(",",$keys);\r\n			array_push($GLOBALS["sql"],\r\n				"\$keys = ".print_r($keys,true),\r\n				"\$manual = ".print_r($manual,true),\r\n				"\$types = ".print_r($types,true),\r\n				"\$type = ".print_r($type,true)\r\n			);\r\n			foreach ($array as $key=>$value) {\r\n				$value = objectToArray($value);\r\n				if ($manual=="true") {\r\n					$out[$key] = $value["type"]."|".$value[$keys[$i+1]];\r\n				} else {\r\n					$out[$key] = $type[$i]."|".$value;\r\n				}\r\n				array_push($GLOBALS["sql"],\r\n					"\$key = ".print_r($key,true),\r\n					"\$value = ".print_r($value,true),\r\n					"\$out[\$key] = ".print_r($out[$key],true)\r\n				);\r\n				$i++;\r\n			}\r\n			return implode(",",$out);\r\n			break;\r\n	}\r\n}\r\nmysql_select_db("performatix", $conn);\r\n$GLOBALS["dtmstyle"] = "Y/m/d H:i:s";\r\n$GLOBALS["dtlast"] = 0;\r\ndate_default_timezone_set("Africa/Johannesburg");\r\n$tzsql = "SET `time_zone` = '".date('P')."'";\r\nmysql_query_errors($tzsql, $conn, __FILE__, __LINE__);\r\n?></sql>
</root>

my problem is that print_r, when returning - does not return all the levels of the matched array. -_- any ideas?

by the way - any sensitive data has been starred out. ;)

thanks in advance,

Pierre du Toit

Edited by Greywacke
Link to comment
Share on other sites

there is currently an issue on server - that it won't print multidimentional arrays deeper than depth 1. -_- for example $arr returns the following (when using var_export() as opposed to print_r()):

array (
  0 => 
  array (
  ),
  1 => 
  array (
  ),
  2 => 
  array (
  ),
  3 => 
  array (
  ),
  4 => 
  array (
  ),
  5 => 
  array (
  ),
  6 => 
  array (
  ),
  7 => 
  array (
  ),
  8 => 
  array (
  ),
  9 => 
  array (
  ),
  10 => 
  array (
  ),
  11 => 
  array (
  ),
  12 => 
  array (
  ),
  13 => 
  array (
  ),
)

for $pattern:

$pattern =	'/^\$conn = mysql_connect\("([a-zA-Z._0-9\-]+)", "([a-zA-Z_0-9]+)", "([a-zA-Z_0-9]+)"\);$'.
		'|^mysql_select_db\("([a-zA-Z_0-9]+)", \$conn\);$'.
		'|^date_default_timezone_set\([\'"]([A-Za-z0-9\/+\-]+)[\'"]\);$'.
		'|^\$GLOBALS\["dtmstyle"\] \= "([^"]+)";$'.
		'|^\$GLOBALS\["dtlast"\] \= ([0|1]);$'.
		'|^\$GLOBALS\["prod_prodmode"\] \= ([0|1]); \/\/ [a-z ]+$'.
		'|^\$GLOBALS\["prod_prodmail"\] \= "([^@]+@[^"]+)";$'.
		'|^\$GLOBALS\["curl"\] \= ([0|1]);$'.
		'|^\$GLOBALS\["conn_timeout"\] \= ([0-9]+);$'.
		'|^\$GLOBALS\["post_timeout"\] \= ([0-9]+);$'.
		'|^\$GLOBALS\["ssl_enabled"\] \= ([0|1]);$/m'; 

$connstr is a bit too long though, to put here - plus it contains quite a bit of confidential information. but 13 matches means its matching the strings - i just have to locate the ini setting to get the max array depth set on php 5.3.10... Suhosin's settings are all fine.

 

sincerely,

Pierre du Toit.

Edited by Greywacke
Link to comment
Share on other sites

those are | separated derivatives, thus the preg_mach_all does a or between them (see the | between the preg pattern lines, at the start of each line? the escaped = is due to what a server admin said (who does not really know preg though, but i am certain something is limiting the array return values... sofar it seems to be a php directive that is limiting the results returned.

as far as i am aware, an unescaped $ means "end of line" in a preg pattern, as ^ means start of line... the m switch at the end, is for multiline regex... as g usually is used for global matching.

Edited by Greywacke
Link to comment
Share on other sites

when searching for the following regex string in notepad++ - it gets the matches on the correct places of the document parsed (performatix.php)

^\$conn \= mysql_connect\("([a-zA-Z._0-9\-]+)", "([a-zA-Z_0-9]+)", "([a-zA-Z_0-9]+)"\);$|^mysql_select_db\("([a-zA-Z_0-9]+)", \$conn\);$|^date_default_timezone_set\([\'"]([A-Za-z0-9\/+\-]+)[\'"]\);$|^\$GLOBALS\["dtmstyle"\] \= "([^"]+)";$|^\$GLOBALS\["dtlast"\] \= ([0|1]);$|^\$GLOBALS\["prod_prodmode"\] \= ([0|1]); \/\/ [a-z ]+$|^\$GLOBALS\["prod_prodmail"\] \= "([^@]+@[^"]+)";$|^\$GLOBALS\["curl"\] \= ([0|1]);$|^\$GLOBALS\["conn_timeout"\] \= ([0-9]+);$|^\$GLOBALS\["post_timeout"\] \= ([0-9]+);$|^\$GLOBALS\["ssl_enabled"\] \= ([0|1]);$

however - when i try to match within php using preg_match_all($pattern,$connstr,$arr,PREG_PATTERN_ORDER), i keep getting the array of empty arrays. 11 in length though... in notepad++ it matches on the = in the strings, wether escaped or not. is there something i am missing here? 0o

Link to comment
Share on other sites

Show me how to match the following string using more than one dollar sign in the regexp pattern. 

Here it's my attempt (using your pattern to create the string)

<?php

$pattern = '~^\$conn = mysql_connect\("([a-zA-Z._0-9\-]+)", "([a-zA-Z_0-9]+)", "([a-zA-Z_0-9]+)"\);\$mysql_select_db\("([a-zA-Z_0-9]+)", \$conn\);$~';

$string = '$conn = mysql_connect("localhost", "jazzman", "password");';

$string .= '$mysql_select_db("db_name", $conn);';

$arr = array();

if (preg_match_all($pattern, $string, $arr, PREG_PATTERN_ORDER)) {
    echo '<pre>' . print_r($arr, true) . '</pre>';
} else {
    echo "a match was not found";
}

Result:

 

Array(    [0] => Array        (            [0] => $conn = mysql_connect("localhost", "jazzman", "password");$mysql_select_db("db_name", $conn);        )    [1] => Array        (            [0] => localhost        )    [2] => Array        (            [0] => jazzman        )    [3] => Array        (            [0] => password        )    [4] => Array        (            [0] => db_name        ))
Edited by jazzman1
Link to comment
Share on other sites

ok i understand but the m switch at the end allows one to do multiline selections (eg over \r\n characters... your string does not have them... this is making me think that i need to remove the caret and $ from the beginnning and end of the substrings, in order to get the correct selection?

Link to comment
Share on other sites

  • Solution

ok awesome thanks jazzman1! XD

by replacing the unescaped caret and dollar signs with [\r\n]*, the regex query now works ;) strange that it always did then not anymore though... ;)

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.