move to ThirdParty

This commit is contained in:
BigManzai
2020-02-19 12:44:07 +01:00
committed by GitHub
parent 2fb70019e5
commit a16dddd5f1
67 changed files with 22542 additions and 2 deletions
+71 -2
View File
@@ -1,2 +1,71 @@
# OpenSim-DTL-NSL-Currency-2020-2
OpenSim-DTL-NSL-Currency-2020-2
# OpenSim-DTL-NSL-Currency-2020
DTL/NSL MoneyServer 2020 für OpenSim 0.9.2.0
NPC und Hypergrid Avatare funktioniert auch mit dieser DTL-NSL-Currency Version.
Ab der Version opensim-0.9.2.0Dev-90-g8d8b5b7 braucht der OpenSimulator für den MoneyServer nicht mehr gepatcht werden.
Dieses Geld System ist nur zur unterhaltung geeignet und ist nicht sicher.
Verzeichnisstruktur
binary = Binäre ausführbare Dateien falls sie nicht selber kompilieren können oder wollen.
helper-php = helper Dateien die benötigt werden (helper.php, currency.php, landtool.php).
source = Quelldateien für den OpenSimulator die zum kompilieren benötigt werden.
# English
DTL/NSL MoneyServer 2020 for OpenSim 0.9.2.0
NPC and Hypergrid avatars also work with this DTL-NSL-Currency version.
As of version opensim-0.9.2.0Dev-90-g8d8b5b7, the OpenSimulator for the MoneyServer no longer needs to be patched.
This money system is for entertainment purposes only and is not secure.
directory structure
binary = binary executable files if you cannot or do not want to compile yourself.
helper-php = helper files needed (helper.php, currency.php, landtool.php).
source = source files needed to compile.
# Download
Fertige opensim 0.9.2.45 money Dev Version inclusive DTL-NSL-Currency
Diese Version läuft mit oder ohne Money, sowie ist sie für Standalone und Grid.
Finished opensim 0.9.2.45 money Dev version including DTL-NSL-Currency
This version runs with or without money, as well as for standalone and grid.
Download: https://www.mediafire.com/file/vvapjo9c7gvbl7l/opensim092-45-money.zip/file
# Wiki
click Wiki at the top of the page.
# Lizenz
MIT License
# Ausschluss aller Gewährleistungen:
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
Neither the name of the OpenSimulator Project nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE USERS ``AS IS'' AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
Binary file not shown.
+29
View File
@@ -0,0 +1,29 @@
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net" />
</configSections>
<appSettings>
</appSettings>
<log4net>
<appender name="Console" type="OpenSim.Framework.Console.OpenSimAppender, OpenSim.Framework.Console">
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date{HH:mm:ss} - %message%newline" />
</layout>
</appender>
<appender name="LogFileAppender" type="log4net.Appender.FileAppender">
<file value="MoneyServer.log" />
<appendToFile value="true" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date %-5level - %logger %message%newline" />
</layout>
</appender>
<root>
<level value="DEBUG" />
<appender-ref ref="Console" />
<appender-ref ref="LogFileAppender" />
</root>
</log4net>
</configuration>
+99
View File
@@ -0,0 +1,99 @@
[Startup]
;
; Place to create a PID file
; PIDFile = "/tmp/money.pid"
[MySql]
;
;Connection parameters of MySQL
hostname = localhost ; Name of MySQL Server
database = opensim_db
username = opensim_user
password = opensim_pass
pooling = false
port = 3306
;
; Max DB connections kept by money server.
MaxConnection = 50
[MoneyServer]
;
; If the user is not found in database,he/she will be created with the default balance.
DefaultBalance = 1000
;
; Is amount==0 transaction enable? Default is false.
EnableAmountZero = true
;
; If "00000000-0000-0000-0000-000000000000" is specified, all avatars can get money from system.
; If "" is specified, nobody can get money.
BankerAvatar = ""
;
; If you want to use llGiveMoney() function normally even when payer doesn't login to OpenSim,
; please set true to this valiable
EnableForceTransfer = true
;
; Send/Move money to/from avatar by Money Script
;EnableScriptSendMoney = false
;MoneyScriptAccessKey = "123456789" ;; Specify same secret key in include/config.php or WI(XoopenSim/Modlos)
;MoneyScriptIPaddress = "202.26.159.139" ;; Not use 127.0.0.1. This is used to generate Script key
;
; for HG/Guest Avatar. Foreign Avatar is always false
EnableHGAvatar = true
EnableGuestAvatar = true
HGAvatarDefaultBalance = 1000
GuestAvatarDefaultBalance = 1000
;
; Message that displayed in blue dialog, when balance is updated.
; If "" is specified, blue dialog is not displayed.
; You can use {0} and {1} in message string.
; {0} means amount and {1} means avatar name or object owner name.
BalanceMessageSendGift = "Sent Gift L${0} to {1}." ;; for send gift to other avatar
BalanceMessageReceiveGift = "Received Gift L${0} from {1}." ;; for receieve gift from other avatar
BalanceMessagePayCharge = "" ;; for upload and group creation charge
BalanceMessageBuyObject = "Bought the Object {2} from {1} by L${0}." ;; for buy the object
BalanceMessageSellObject = "{1} bought the Object {2} by L${0}." ;; for sell the object
BalanceMessageLandSale = "Paid the Money L${0} for Land." ;; for buy the land
BalanceMessageScvLandSale = "" ;; for get the money of the sold land
BalanceMessageGetMoney = "Got the Money L${0} from {1}." ;; for get the money from object by llGiveMoney()
BalanceMessageBuyMoney = "Bought the Money L${0}." ;; for buy the money from system
BalanceMessageRollBack = "RollBack the Transaction: L${0} from/to {1}.";; when roll back ocuurred
BalanceMessageSendMoney = "Paid the Money L${0} to {1}." ;; for sender of sending the money
BalanceMessageReceiveMoney = "Received L${0} from {1}." ;; for receive the money
[Certificate]
;
; Certification Configuration
;
; CA Cert to check Client/Server Cert
;CACertFilename = "cacert.crt"
;
; HTTPS Server Cert (Server Mode)
;ServerCertFilename = "SineWaveCert.pfx"
;ServerCertPassword = "123"
;ServerCertFilename = "server_cert.p12"
;ServerCertPassword = ""
; Client Authentication from Region Server
;CheckClientCert = false ;; check Region Server
;ClientCrlFilename = "clcrl.crt"
;
; XML RPC to Region Server (Client Mode)
;;CheckServerCert = false ;; check Region Server
;;ClientCertFilename = "client_cert.p12"
;;ClientCertPassword = ""
Binary file not shown.
Binary file not shown.
+43
View File
@@ -0,0 +1,43 @@
[Economy]
;; Enables selling things for $0. Default is true.
SellEnabled = true
;CurrencyServer = "" ;; ex.) "https://jogrid.net:8008/" Default is ""
EconomyModule = DTLNSLMoneyModule
;
;; CA
;CheckServerCert = false
;CACertFilename = "cacert.crt"
;
;; Client Cert
;ClientCertFilename = "region_cert.p12"
;ClientCertPassword = ""
;
;; Money Unit fee to upload textures, animations etc. Default is 0.
PriceUpload = 0
;; Mesh upload factors
;MeshModelUploadCostFactor = 0.0
;MeshModelUploadTextureCostFactor = 1.0
;MeshModelMinCostFactor = 0.0
;; Money Unit fee to create groups. Default is 0.
PriceGroupCreate = 0
;
;; Avatar Class for HG Avatar
;; {ForeignAvatar, HGAvatar, GuestAvatar, LocalAvatar} HGAvatar
;; HG Avatar is assumed as a specified avatar class. Default is HGAvatar
;; Processing for each avatar class is dependent on Money Server settings.
;HGAvatarAs = "HGAvatar"
;
;; in development
;SettlementByWeb = false
;SettlementURL = "http://www.jogrid.net"
;SettlementMessage = "Goto the settlement of accounts Web page. (Testing now)"
+3
View File
@@ -0,0 +1,3 @@
# Compiled with Ubuntu 19.04 Server OpenSim 0.9.2 mono 6.x
Copy all to /opensim/bin
Binary file not shown.
Binary file not shown.
+59
View File
@@ -0,0 +1,59 @@
command-script <script> - Run a command script from file
config get [<section>] [<key>] - Synonym for config show
config save <path> - Save current configuration to a file at the given path
config set <section> <key> <value> - Set a config option. In most cases this is not useful since changed parameters are not dynamically reloaded. Neither do changed parameters persist - you will have to change a config file manually and restart.
config show [<section>] [<key>] - Show config information
debug jobengine <start|stop|status|log> - Start, stop, get status or set logging level of the job engine.
debug threadpool level 0..3 - Turn on logging of activity in the main thread pool.
debug threadpool set worker|iocp min|max <n> - Set threadpool parameters. For debug purposes.
debug threadpool status - Show current debug threadpool parameters.
force gc - Manually invoke runtime garbage collection. For debugging purposes
get log level - Get the current console logging level
help [<item>] - Display help on a particular command or on a list of commands in a category
quit - Quit the application
set log level <level> - Set the console logging level for this session.
show checks - Show checks configured for this server
show info - Show general information about the server
show stats [list|all|(<category>[.<container>])+ - Alias for 'stats show' command
show threadpool calls complete - Show details about threadpool calls that have been completed.
show threads - Show thread status
show uptime - Show server uptime
show version - Show server version
shutdown - Quit the application
stats record start|stop - Control whether stats are being regularly recorded to a separate file.
stats save <path> - Save stats snapshot to a file. If the file already exists, then the report is appended.
stats show [list|all|(<category>[.<container>])+ - Show statistical information for this server
threads abort <thread-id> - Abort a managed thread. Use "show threads" to find possible threads.
threads show - Show thread status. Synonym for "show threads"
command-script <script> - Führt ein Befehlsskript aus einer Datei aus
config get [<section>] [<key>] - Synonym für config show
config save <Pfad> - Speichert die aktuelle Konfiguration in einer Datei unter dem angegebenen Pfad
config set <section> <key> <value> - Legt eine Konfigurationsoption fest. In den meisten Fällen ist dies nicht sinnvoll, da geänderte Parameter nicht dynamisch neu geladen werden. Die geänderten Parameter bleiben auch nicht erhalten - Sie müssen eine Konfigurationsdatei manuell ändern und neu starten.
config show [<section>] [<key>] - Konfigurationsinformationen anzeigen
debug jobengine <start|stop|status|log> - Startet, stoppt, ruft den Status ab oder legt die Protokollierungsstufe der Job-Engine fest.
debug threadpool level 0..3 - Aktiviert die Protokollierung von Aktivitäten im Haupt-Threadpool.
debug threadpool set worker | iocp min | max <n> - Threadpool-Parameter festlegen. Für Debug-Zwecke.
debug threadpool status - Zeigt die aktuellen Debug-Threadpool-Parameter an.
force gc - Ruft die Garbage Collection zur Laufzeit manuell auf. Zum Debuggen
get log level - Ruft die aktuelle Konsolenprotokollierungsstufe ab
help [<item>] - Zeigt die Hilfe zu einem bestimmten Befehl oder einer Liste von Befehlen in einer Kategorie an
quit - Beendet die Anwendung
set log level <level> - Legt die Konsolenprotokollierungsstufe für diese Sitzung fest.
show checks - Zeigt die für diesen Server konfigurierten Prüfungen an
show info - Zeigt allgemeine Informationen zum Server an
show stats [list|all|(<category>[.<container>])+ - Alias für den Befehl 'stats show'
show threadpool calls complete - Zeigt Details zu abgeschlossenen Threadpool-Aufrufen an.
show threads - Threadstatus anzeigen
show uptime - Zeigt die Betriebszeit des Servers an
show version - Zeigt die Serverversion an
shutdown - Beenden Sie die Anwendung
stats record start|stop - Legt fest, ob Statistiken regelmäßig in einer separaten Datei aufgezeichnet werden.
stats save <Pfad> - Speichert den Statistik-Snapshot in einer Datei. Wenn die Datei bereits vorhanden ist, wird der Bericht angehängt.
stats show [list|all|(<category>[.<container>])+ - Zeigt statistische Informationen für diesen Server an
threads abort <thread-id> - Bricht einen verwalteten Thread ab. Verwenden Sie "show threads", um mögliche Themen zu finden.
threads show - Threadstatus anzeigen. Synonym für "show threads"
@@ -0,0 +1 @@
# not works
@@ -0,0 +1,5 @@
<?php
require_once(realpath(dirname(__FILE__).'/../include/env_define.php'));
require_once(realpath(dirname(__FILE__).'/../helper/parser.php'));
@@ -0,0 +1,323 @@
<?php
#
# Copyright (c)Melanie Thielker and Teravus Ovares (http://opensimulator.org/)
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# * Neither the name of the OpenSim Project nor the
# names of its contributors may be used to endorse or promote products
# derived FROM this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
# EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
########################################################################
# This file enables buying currency in the client.
#
# For this to work, the all clients using currency need to add
#
# -helperURI <WebpathToThisDirectory>
#
# to the commandline parameters when starting the client!
#
# Example:
# client.exe -loginuri http://foo.com:8002/ -helperuri http://foo.com/
#
# Don't forget to change the currency conversion value in the wi_economy_money
# table!
#
# This requires PHP curl, XMLRPC, and MySQL extensions.
#
# If placed in the opensimwiredux web directory, it will share the db module
#
########################################################################
#
# Modified by Fumi.Iseki for XoopenSim/Modlos
#
if (!defined('ENV_READ_CONFIG')) require_once(realpath(dirname(__FILE__).'/../include/config.php'));
if (!defined('ENV_READ_DEFINE')) require_once(realpath(ENV_HELPER_PATH.'/../include/env_define.php'));
require_once(realpath(ENV_HELPER_PATH.'/helpers.php'));
#
# The XMLRPC server object
#
$xmlrpc_server = xmlrpc_server_create();
#
# Viewer retrieves currency buy quote
#
xmlrpc_server_register_method($xmlrpc_server, "getCurrencyQuote", "get_currency_quote");
function get_currency_quote($method_name, $params, $app_data)
{
$req = $params[0];
$agentid = $req['agentId'];
$secureid = $req['secureSessionId'];
$amount = $req['currencyBuy'];
$ipAddress = $_SERVER['REMOTE_ADDR'];
$ret = opensim_check_secure_session($agentid, null, $secureid);
if ($ret) {
$confirmvalue = get_confirm_value($ipAddress);
$cost = convert_to_real($amount);
$currency = array('estimatedCost'=> $cost, 'currencyBuy'=> $amount);
$response_xml = xmlrpc_encode(array('success' => True,
'currency' => $currency,
'confirm' => $confirmvalue));
}
else {
$response_xml = xmlrpc_encode(array('success' => False,
'errorMessage'=> "Unable to Authenticate\n\nClick URL for more info.",
'errorURI' => "".SYSURL.""));
}
header("Content-type: text/xml");
echo $response_xml;
return "";
}
#
# Viewer buys currency
#
xmlrpc_server_register_method($xmlrpc_server, "buyCurrency", "buy_currency");
function buy_currency($method_name, $params, $app_data)
{
$req = $params[0];
$agentid = $req['agentId'];
$secureid = $req['secureSessionId'];
$amount = $req['currencyBuy'];
$confim = $req['confirm'];
$ipAddress = $_SERVER['REMOTE_ADDR'];
//
if ($confim!=get_confirm_value($ipAddress)) {
$response_xml = xmlrpc_encode(array('success' => False,
'errorMessage'=> "\n\nMissmatch Confirm Value!!",
'errorURI' => "".SYSURL.""));
header("Content-type: text/xml");
echo $response_xml;
return "";
}
$checkSecure = opensim_check_secure_session($agentid, null, $secureid);
if (!$checkSecure) {
$response_xml = xmlrpc_encode(array('success' => False,
'errorMessage'=> "\n\nMissmatch Secure Session ID!!",
'errorURI' => "".SYSURL.""));
header("Content-type: text/xml");
echo $response_xml;
return "";
}
$ret = false;
$cost = convert_to_real($amount);
$transactionPermit = process_transaction($agentid, $cost, $ipAddress);
if ($transactionPermit) {
$res = add_money($agentid, $amount, $secureid);
if ($res) $ret = true;
}
if ($ret) {
$response_xml = xmlrpc_encode(array('success' => True));
}
else {
$response_xml = xmlrpc_encode(array('success' => False,
'errorMessage'=> "\n\nUnable to process the transaction. The gateway denied your charge",
'errorURI' => "".SYSURL.""));
}
header("Content-type: text/xml");
echo $response_xml;
return "";
}
#
# Region requests account balance
#
xmlrpc_server_register_method($xmlrpc_server, "simulatorUserBalanceRequest", "balance_request");
function balance_request($method_name, $params, $app_data)
{
$req = $params[0];
$agentid = $req['agentId'];
$secureid = $req['secureSessionId'];
$balance = get_balance($agentid, $secureid);
if ($balance>=0) {
$response_xml = xmlrpc_encode(array('success' => True,
'agentId' => $agentid,
'funds' => $balance));
}
else {
$response_xml = xmlrpc_encode(array('success' => False,
'errorMessage'=> "Could not authenticate your avatar. Money operations may be unavailable",
'errorURI' => " "));
}
header("Content-type: text/xml");
echo $response_xml;
return "";
}
#
# Region initiates money transfer (Direct DB Operation for security)
#
xmlrpc_server_register_method($xmlrpc_server, "regionMoveMoney", "region_move_money");
function region_move_money($method_name, $params, $app_data)
{
$req = $params[0];
$agentid = $req['agentId'];
$destid = $req['destId'];
$secureid = $req['secureSessionId'];
$regionid = $req['regionId'];
$secret = $req['secret'];
$currencySecret = $req['currencySecret'];
$cash = $req['cash'];
$aggregatePermInventory = $req['aggregatePermInventory'];
$aggregatePermNextOwner = $req['aggregatePermNextOwner'];
$flags = $req['flags'];
$transactiontype = $req['transactionType'];
$description = $req['description'];
$ipAddress = $_SERVER['REMOTE_ADDR'];
$ret = opensim_check_region_secret($regionid, $secret);
if ($ret) {
$ret = opensim_check_secure_session($agentid, $regionid, $secureid);
if ($ret) {
$balance = get_balance($agentid, $secureid);
if ($balance >= $cash) {
move_money($agentid, $destid, $cash, $transactiontype, $flags, $description,
$aggregatePermInventory, $aggregatePermNextOwner, $ipAddress);
$sbalance = get_balance($agentid, $secureid);
$dbalance = get_balance($destid);
$response_xml = xmlrpc_encode(array('success' => True,
'agentId' => $agentid,
'funds' => $balance,
'funds2' => $balance,
'currencySecret'=> " "));
update_simulator_balance($agentid, $sbalance, $secureid);
update_simulator_balance($destid, $dbalance);
}
else {
$response_xml = xmlrpc_encode(array('success' => False,
'errorMessage'=> "You do not have sufficient funds for this purchase",
'errorURI' => " "));
}
}
else {
$response_xml = xmlrpc_encode(array('success' => False,
'errorMessage'=> "Unable to authenticate avatar. Money operations may be unavailable",
'errorURI' => " "));
}
}
else {
$response_xml = xmlrpc_encode(array('success' => False,
'errorMessage'=> "This region is not authorized to manage your money.",
'errorURI' => " "));
}
header("Content-type: text/xml");
echo $response_xml;
return "";
}
#
# Region claims user
#
xmlrpc_server_register_method($xmlrpc_server, "simulatorClaimUserRequest", "claimUser_func");
function claimUser_func($method_name, $params, $app_data)
{
$req = $params[0];
$agentid = $req['agentId'];
$secureid = $req['secureSessionId'];
$regionid = $req['regionId'];
$secret = $req['secret'];
$ret = opensim_check_region_secret($regionid, $secret);
if ($ret) {
$ret = opensim_check_secure_session($agentid, null, $secureid);
if ($ret) {
$ret = opensim_set_current_region($agentid, $regionid);
if ($ret) {
$balance = get_balance($agentid, $secureid);
$response_xml = xmlrpc_encode(array('success' => True,
'agentId' => $agentid,
'funds' => $balance,
'currencySecret'=> " "));
}
else {
$response_xml = xmlrpc_encode(array('success' => False,
'errorMessage'=> "Error occurred, when DB was updated.",
'errorURI' => " "));
}
}
else {
$response_xml = xmlrpc_encode(array('success' => False,
'errorMessage'=> "Unable to authenticate avatar. Money operations may be unavailable.",
'errorURI' => " "));
}
}
else {
$response_xml = xmlrpc_encode(array('success' => False,
'errorMessage'=> "This region is not authorized to manage your money.",
'errorURI' => " "));
}
header("Content-type: text/xml");
echo $response_xml;
return "";
}
#
# Process the request
#
if (!isset($HTTP_RAW_POST_DATA)) $HTTP_RAW_POST_DATA = file_get_contents('php://input');
$request_xml = $HTTP_RAW_POST_DATA;
#error_log('currency.php: '.$request_xml);
xmlrpc_server_call_method($xmlrpc_server, $request_xml, '');
xmlrpc_server_destroy($xmlrpc_server);
@@ -0,0 +1,391 @@
<?php
#
# Copyright (c)Melanie Thielker and Teravus Ovares (http://opensimulator.org/)
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# * Neither the name of the OpenSim Project nor the
# names of its contributors may be used to endorse or promote products
# derived FROM this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
# EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
if (!defined('ENV_READ_CONFIG')) require_once(realpath(dirname(__FILE__).'/../include/config.php'));
if (!defined('ENV_READ_DEFINE')) require_once(realpath(ENV_HELPER_PATH.'/../include/env_define.php'));
#
require_once(realpath(ENV_HELPER_PATH.'/../include/opensim.mysql.php'));
require_once(realpath(ENV_HELPER_PATH.'/../include/env_lib.php'));
require_once(realpath(ENV_HELPER_PATH.'/../jbxl/jbxl_tools.php'));
if (!isset($HTTP_RAW_POST_DATA)) $HTTP_RAW_POST_DATA = file_get_contents('php://input');
#$request_xml = $HTTP_RAW_POST_DATA;
#error_log('helper.php: '.$request_xml);
####################################################################
#
# User provided interface routine to interface with payment processor
#
function process_transaction($avatarID, $cost, $ipAddress)
{
# Do Credit Card Processing here! Return False if it fails!
# Remember, $amount is stored without decimal places, however it's assumed
# that the transaction amount is in Cents and has two decimal places
# 5 dollars will be 500
# 15 dollars will be 1500
//if ($avatarID==CURRENCY_BANKER) return true;
//return false;
return true;
}
###################### No user serviceable parts below #####################
#
# Helper routines
#
function convert_to_real($amount)
{
/*
if($currency == 0) return 0;
$db = new DB(CURRENCY_DB_HOST, CURRENCY_DB_NAME, CURRENCY_DB_USER, CURRENCY_DB_PASS, CURRENCY_DB_MYSQLI);
# Get the currency conversion ratio in USD Cents per Money Unit
# Actually, it's whatever currency your credit card processor uses
$db->query("SELECT CentsPerMoneyUnit FROM ".CURRENCY_MONEY_TBL." limit 1");
list($CentsPerMoneyUnit) = $db->next_record();
$db->close();
if (!$CentsPerMoneyUnit) $CentsPerMoneyUnit = 0;
# Multiply the cents per unit times the requested amount
$real = $CentsPerMoneyUnit * $currency;
// Dealing in cents here. The XML requires an integer
// so we have to ceil out any decimal places and cast as an integer
$real = (integer)ceil($real);
return $real;
*/
$cost = $amount;
return $cost;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////
/*
下記関数は現在のところ,アバターがログインしていないと使用できない
function user_alert($agentID, $message, $secureID=null)
function update_simulator_balance($agentID, $amount=-1, $secureID=null)
function add_money($agentID, $amount, $secureID=null)
function get_balance($agentID, $secureID=null)
function move_money($srcID, $dstID, $amount, $type, $desc, $prminvent=0, $nxtowner=0, $ip='')
*/
//
// アバターがログインしていないと使用できない
//
function user_alert($agentID, $message, $secureID=null)
{
if (!USE_CURRENCY_SERVER) return false;
if (!isGUID($agentID)) return false;
if (!isGUID($secureID, true)) return false;
// XML RPC to Region Server
$results = opensim_get_userinfo($agentID);
$server = jbxl_make_url($results['simip'], 9000);
if ($server['host']=='') return false;
$results = opensim_get_avatar_session($agentID); // use Presence Table
if (!$results) return false;
$sessionID = $results['sessionID'];
if ($secureID==null) $secureID = $results['secureID'];
$req = array('clientUUID'=>$agentID, 'clientSessionID'=>$sessionID, 'clientSecureSessionID'=>$secureID, 'Description'=>$message);
$params = array($req);
$request = xmlrpc_encode_request('UserAlert', $params);
$response = do_call($server['url'], $server['port'], $request);
if ($response!=null and array_key_exists('success', $response)) return $response['success'];
return false;
}
//
// アバターがログインしていないと使用できない
//
function update_simulator_balance($agentID, $amount=-1, $secureID=null)
{
if (!USE_CURRENCY_SERVER) return false;
if (!isGUID($agentID)) return false;
if (!isGUID($secureID, true)) return false;
if ($amount<0) {
$amount = get_balance($agentID, $secureID);
if ($amount<0) return false;
}
// XML RPC to Region Server
$results = opensim_get_userinfo($agentID);
$server = jbxl_make_url($results['simip'], 9000);
if ($server['host']=='') return false;
$results = opensim_get_avatar_session($agentID);
if (!$results) return false;
$sessionID = $results['sessionID'];
if ($secureID==null) $secureID = $results['secureID'];
$req = array('clientUUID'=>$agentID, 'clientSessionID'=>$sessionID, 'clientSecureSessionID'=>$secureID, 'Balance'=>$amount);
$params = array($req);
$request = xmlrpc_encode_request('UpdateBalance', $params);
$response = do_call($server['url'], $server['port'], $request);
if ($response!=null and array_key_exists('success', $response)) return $response['success'];
return false;
}
//
// アバターがログインしていないと使用できない
//
function add_money($agentID, $amount, $secureID=null)
{
if (!USE_CURRENCY_SERVER) return false;
if (!isGUID($agentID)) return false;
if (!isGUID($secureID, true)) return false;
// XML RPC to Region Server
$results = opensim_get_userinfo($agentID);
$server = jbxl_make_url($results['simip'], 9000);
if ($server['host']=='') return false;
$results = opensim_get_avatar_session($agentID);
$sessionID = $results['sessionID'];
if ($secureID==null) $secureID = $results['secureID'];
$req = array('clientUUID'=>$agentID, 'clientSessionID'=>$sessionID, 'clientSecureSessionID'=>$secureID, 'amount'=>$amount);
$params = array($req);
$request = xmlrpc_encode_request('AddBankerMoney', $params);
$response = do_call($server['url'], $server['port'], $request);
if ($response!=null and array_key_exists('success', $response)) return $response['success'];
return false;
}
//
// アバターがログインしていないと使用できない
//
function get_balance($agentID, $secureID=null)
{
$cash = -1;
if (!USE_CURRENCY_SERVER) return (integer)$cash;
if (!isGUID($agentID)) return (integer)$cash;
if (!isGUID($secureID, true)) return (integer)$cash;
// XML RPC to Region Server
$results = opensim_get_userinfo($agentID);
$server = jbxl_make_url($results['simip'], 9000);
if ($server['host']=='') return (integer)$cash;
$results = opensim_get_avatar_session($agentID);
if ($sessionID=='') return (integer)$cash;
$sessionID = $results['sessionID'];
if ($secureID==null) $secureID = $results['secureID'];
$req = array('clientUUID'=>$agentID, 'clientSessionID'=>$sessionID, 'clientSecureSessionID'=>$secureID);
$params = array($req);
$request = xmlrpc_encode_request('GetBalance', $params);
$response = do_call($server['url'], $server['port'], $request);
if ($response!=null and array_key_exists('balance', $response)) $cash = $response['balance'];
return (integer)$cash;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////
//
// Send the money to avatar for bonus by Milo
//
// XMLRPC による正式な手順による送金
// アバターが一度もログインしていない場合は,送金できない.
//
// $type: トランザクションのタイプ.デフォルトは 5003:ReferBonus
// $serverURI: 処理を行うリージョンサーバの URI (オフライン時対応)
// $secretCode: MoneyServer.ini に書かれた MoneyScriptAccessKey の値.
//
function send_money($agentID, $amount, $type=5003, $serverURI=null, $secretCode=null)
{
if (!USE_CURRENCY_SERVER) return false;
if (!isGUID($agentID)) return false;
// XML RPC to Region Server
$server['url'] = null;
if ($serverURI!=null) $server = jbxl_make_url($serverURI, 9000);
if ($server['url']==null) {
$results = opensim_get_userinfo($agentID);
$server = jbxl_make_url($results['simip'], 9000);
}
if ($server['url']==null) return false;
if ($secretCode!=null) {
$secretCode = md5($secretCode.'_'.$server['host']);
}
else {
$secretCode = get_confirm_value($server['host']);
}
$req = array('agentUUID'=>$agentID, 'secretAccessCode'=>$secretCode, 'amount'=>$amount, 'type'=>$type);
$params = array($req);
$request = xmlrpc_encode_request('SendMoney', $params);
$response = do_call($server['url'], $server['port'], $request);
if ($response!=null and array_key_exists('success', $response)) return $response['success'];
return false;
}
//
// Send the money to avatar for bonus by Milo
//
// XMLRPC による正式な手順による送金
// アバターが一度もログインしていない場合は,送金できない.
//
// $serverURI: 処理を行うリージョンサーバの URI (オフライン時対応)
// $secretCode: MoneyServer.ini に書かれた MoneyScriptAccessKey の値.
//
function move_money($fromID, $toID, $amount, $serverURI=null, $secretCode=null)
{
if (!USE_CURRENCY_SERVER) return false;
if (!isGUID($fromID)) return false;
if (!isGUID($toID)) return false;
// XML RPC to Region Server
$server['url'] = null;
if ($serverURI!=null) $server = jbxl_make_url($serverURI, 9000);
if ($server['url']==null) {
$results = opensim_get_userinfo($fromID);
$server = jbxl_make_url($results['simip'], 9000);
}
if ($server['url']==null) return false;
if ($secretCode!=null) {
$secretCode = md5($secretCode.'_'.$server['host']);
}
else {
$secretCode = get_confirm_value($server['host']);
}
$req = array('fromUUID'=>$fromID, 'toUUID'=>$toID, 'secretAccessCode'=>$secretCode, 'amount'=>$amount);
$params = array($req);
$request = xmlrpc_encode_request('MoveMoney', $params);
$response = do_call($server['url'], $server['port'], $request);
if ($response!=null and array_key_exists('success', $response)) return $response['success'];
return false;
}
/*
function move_money($srcID, $dstID, $amount, $type, $desc, $prminvent=0, $nxtowner=0, $ip='')
{
if (!USE_CURRENCY_SERVER) return false;
$ret = opensim_set_currency_transaction($srcID, $dstID, $amount, $type, 0, $desc);
if ($ret) {
if (isGUID($srcID) and $srcID!='00000000-0000-0000-0000-0000000000000') {
opensim_set_currency_balance($srcID, -$amount);
}
if (isGUID($dstID) and $dstID !='00000000-0000-0000-0000-0000000000000') {
opensim_set_currency_balance($dstID, $amount);
}
}
return $ret;
}
*/
////////////////////////////////////////////////////////////////////////////////////////////////////////
// XML RPC
function do_call($uri, $port, $request)
{
$server = jbxl_make_url($uri, $port);
$header[] = 'Content-type: text/xml';
$header[] = 'Content-length: '.strlen($request);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $server['url']);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 3);
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
curl_setopt($ch, CURLOPT_POSTFIELDS, $request);
$data = curl_exec($ch);
if (!curl_errno($ch)) curl_close($ch);
$ret = false;
if ($data) $ret = xmlrpc_decode($data);
// for Debug
/*
ob_start();
print_r($ret);
$rt = ob_get_contents();
ob_end_clean();
error_log('[do_call] responce = '.$rt);
*/
return $ret;
}
function get_confirm_value($ipAddress)
{
$key = env_get_config('currency_script_key');
if ($key=='') $key = '123456789';
$confirmvalue = md5($key.'_'.$ipAddress);
return $confirmvalue;
}
@@ -0,0 +1 @@
<script>history.go(-1);</script>
@@ -0,0 +1,171 @@
<?php
#
# Copyright (c)Melanie Thielker and Teravus Ovares (http://opensimulator.org/)
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# * Neither the name of the OpenSim Project nor the
# names of its contributors may be used to endorse or promote products
# derived from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
# EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
//////////////////////////////////////////////////////////////////////////////
//
// Modified by Fumi.Iseki for CMS/LMS '09 5/31
//
if (!defined('ENV_READ_CONFIG')) require_once(realpath(dirname(__FILE__).'/../include/config.php'));
if (!defined('ENV_READ_DEFINE')) require_once(realpath(ENV_HELPER_PATH.'/../include/env_define.php'));
require_once(realpath(ENV_HELPER_PATH.'/helpers.php'));
###################### No user serviceable parts below #####################
#
# The XMLRPC server object
#
$xmlrpc_server = xmlrpc_server_create();
#
# Land purchase sections
#
# Functions are called by the viewer directly.
#
#
# Land buying functions
#
xmlrpc_server_register_method($xmlrpc_server, "preflightBuyLandPrep", "buy_land_prep");
function buy_land_prep($method_name, $params, $app_data)
{
$req = $params[0];
$agentid = $req['agentId'];
$secureid = $req['secureSessionId'];
$amount = $req['currencyBuy'];
$billableArea = $req['billableArea'];
$ipAddress = $_SERVER['REMOTE_ADDR'];
$ret = opensim_check_secure_session($agentid, null, $secureid);
if($ret) {
$confirmvalue = get_confirm_value($ipAddress);
$membership_levels = array('levels' => array('id' => "00000000-0000-0000-0000-000000000000", 'description' => "some level"));
$landUse = array('upgrade' => False, 'action' => "".SYSURL."");
$currency = array('estimatedCost' => convert_to_real($amount));
$membership = array('upgrade' => False, 'action' => "".SYSURL."", 'levels' => $membership_levels);
$response_xml = xmlrpc_encode(array('success' => True,
'currency' => $currency,
'membership'=> $membership,
'landUse' => $landUse,
'currency' => $currency,
'confirm' => $confirmvalue));
}
else {
$response_xml = xmlrpc_encode(array( 'success' => False,
'errorMessage' => "Unable to Authenticate\n\nClick URL for more info.",
'errorURI' => "".SYSURL.""));
}
header("Content-type: text/xml");
echo $response_xml;
return "";
}
#
# Perform the buy (所持金が足りないとき)
#
xmlrpc_server_register_method($xmlrpc_server, "buyLandPrep", "buy_land");
function buy_land($method_name, $params, $app_data)
{
$req = $params[0];
$agentid = $req['agentId'];
$secureid = $req['secureSessionId'];
$amount = $req['currencyBuy'];
$cost = $req['estimatedCost'];
$billableArea = $req['billableArea'];
$confim = $req['confirm'];
$ipAddress = $_SERVER['REMOTE_ADDR'];
//
if ($confim!=get_confirm_value($ipAddress)) {
$response_xml = xmlrpc_encode(array('success' => False,
'errorMessage'=> "\n\nMissmatch Confirm Value!!",
'errorURI' => "".SYSURL.""));
header("Content-type: text/xml");
echo $response_xml;
return "";
}
$ret = opensim_check_secure_session($agentid, null, $secureid);
if ($ret) {
if($amount>=0) {
if (!$cost) $cost = convert_to_real($amount);
if(!process_transaction($agentid, $cost, $ipAddress)) {
$response_xml = xmlrpc_encode(array(
'success' => False,
'errorMessage' => "\n\nThe gateway has declined your transaction. Please update your payment method AND try again later.",
'errorURI' => "".SYSURL.""));
}
//
$enough_money = false;
$res = add_money($agentid, $amount, $secureid);
if ($res["success"]) $enough_money = true;
if ($enough_money) {
$amount += get_balance($agentid);
move_money($agentid, null, $amount, 5002, 0, "Land Purchase", 0, 0, $ipAddress);
update_simulator_balance($agentid, -1, $secureid);
$response_xml = xmlrpc_encode(array('success' => True));
}
else {
$response_xml = xmlrpc_encode(array('success' => False,
'errorMessage'=> "\n\nYou do not have sufficient funds for this purchase",
'errorURI' => "".SYSURL.""));
}
}
}
else {
$response_xml = xmlrpc_encode(array('success' => False,
'errorMessage' => "\n\nUnable to Authenticate\n\nClick URL for more info.",
'errorURI' => "".SYSURL.""));
}
header("Content-type: text/xml");
echo $response_xml;
return "";
}
#
# Process XMLRPC request
#
if (!isset($HTTP_RAW_POST_DATA)) $HTTP_RAW_POST_DATA = file_get_contents('php://input');
$request_xml = $HTTP_RAW_POST_DATA;
//error_log("landtool.php: ".$request_xml);
xmlrpc_server_call_method($xmlrpc_server, $request_xml, '');
xmlrpc_server_destroy($xmlrpc_server);
@@ -0,0 +1,78 @@
<?php
if (!defined('ENV_READ_CONFIG')) require_once(realpath(dirname(__FILE__).'/../include/config.php'));
if (!defined('ENV_READ_DEFINE')) require_once(realpath(ENV_HELPER_PATH.'/../include/env_define.php'));
require_once(realpath(ENV_HELPER_PATH.'/../include/opensim.mysql.php'));
if (!isset($HTTP_RAW_POST_DATA)) $HTTP_RAW_POST_DATA = file_get_contents('php://input');
//$request_xml = $HTTP_RAW_POST_DATA;
//error_log('offline.php: '.$request_xml);
//
if (!opensim_is_access_from_region_server()) {
$remote_addr = $_SERVER['REMOTE_ADDR'];
error_log('offline.php: Illegal access from '.$remote_addr);
exit;
}
$DbLink = new DB($MESSAGE_DB_HOST, $MESSAGE_DB_NAME, $MESSAGE_DB_USER, $MESSAGE_DB_PASS, $MESSAGE_DB_MYSQLI);
$method = $_SERVER['PATH_INFO'];
if ($method=='/SaveMessage/') {
$msg = $HTTP_RAW_POST_DATA;
$start = strpos($msg, "?>");
if ($start!=-1) {
$start+=2;
$msg = substr($msg, $start);
$parts = preg_split("/[<>]/", $msg);
$from_agent = $parts[4];
$to_agent = $parts[12];
if (isGUID($from_agent) and isGUID($to_agent)) {
$esc_msg = $DbLink->escape($msg);
$query_str = "INSERT INTO ".OFFLINE_MESSAGE_TBL." (to_uuid,from_uuid,message) VALUES ('".$to_agent."','".$from_agent."','".$esc_msg."')";
$DbLink->query($query_str);
if ($DbLink->Errno==0) {
echo '<?xml version="1.0" encoding="utf-8"?><boolean>true</boolean>';
exit;
}
}
}
echo '<?xml version="1.0" encoding="utf-8"?><boolean>false</boolean>';
exit;
}
if ($method == '/RetrieveMessages/') {
$parms = $HTTP_RAW_POST_DATA;
$parts = preg_split("/[<>]/", $parms);
$agent_id = $parts[6];
$errno = -1;
if (isGUID($agent_id)) {
$DbLink->query("SELECT message FROM ".OFFLINE_MESSAGE_TBL." WHERE to_uuid='".$agent_id."'");
$errno = $DbLink->Errno;
}
echo '<?xml version="1.0" encoding="utf-8"?>';
echo '<ArrayOfGridInstantMessage xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">';
if ($errno==0) {
while(list($message) = $DbLink->next_record()) {
echo $message;
}
}
echo '</ArrayOfGridInstantMessage>';
if ($errno==0) {
$DbLink->query("DELETE FROM ".OFFLINE_MESSAGE_TBL." WHERE to_uuid='".$agent_id."'");
}
exit;
}
@@ -0,0 +1,55 @@
<?php
// +----------------------------------------------------------------------+
// | PHP Version 4 |
// +----------------------------------------------------------------------+
// | Copyright (c) 1997-2004 The PHP Group |
// +----------------------------------------------------------------------+
// | This source file is subject to version 3.0 of the PHP license, |
// | that is bundled with this package in the file LICENSE, and is |
// | available at through the world-wide-web at |
// | http://www.php.net/license/3_0.txt. |
// | If you did not receive a copy of the PHP license and are unable to |
// | obtain it through the world-wide-web, please send a note to |
// | license@php.net so we can mail you a copy immediately. |
// +----------------------------------------------------------------------+
// | Authors: Aidan Lister <aidan@php.net> |
// +----------------------------------------------------------------------+
//
// $Id: array_key_exists.php 2 2009-03-16 20:22:51Z ggiunta $
/**
* Replace array_key_exists()
*
* @category PHP
* @package PHP_Compat
* @link http://php.net/function.array_key_exists
* @author Aidan Lister <aidan@php.net>
* @version $Revision: 1.1 $
* @since PHP 4.1.0
* @require PHP 4.0.0 (user_error)
*/
if (!function_exists('array_key_exists')) {
function array_key_exists($key, $search)
{
if (!is_scalar($key)) {
user_error('array_key_exists() The first argument should be either a string or an integer',
E_USER_WARNING);
return false;
}
if (is_object($search)) {
$search = get_object_vars($search);
}
if (!is_array($search)) {
user_error('array_key_exists() The second argument should be either an array or an object',
E_USER_WARNING);
return false;
}
return in_array($key, array_keys($search));
}
}
?>
@@ -0,0 +1,47 @@
<?php
// +----------------------------------------------------------------------+
// | PHP Version 4 |
// +----------------------------------------------------------------------+
// | Copyright (c) 1997-2004 The PHP Group |
// +----------------------------------------------------------------------+
// | This source file is subject to version 3.0 of the PHP license, |
// | that is bundled with this package in the file LICENSE, and is |
// | available at through the world-wide-web at |
// | http://www.php.net/license/3_0.txt. |
// | If you did not receive a copy of the PHP license and are unable to |
// | obtain it through the world-wide-web, please send a note to |
// | license@php.net so we can mail you a copy immediately. |
// +----------------------------------------------------------------------+
// | Authors: Aidan Lister <aidan@php.net> |
// +----------------------------------------------------------------------+
//
// $Id: is_a.php 2 2009-03-16 20:22:51Z ggiunta $
/**
* Replace function is_a()
*
* @category PHP
* @package PHP_Compat
* @link http://php.net/function.is_a
* @author Aidan Lister <aidan@php.net>
* @version $Revision: 1.2 $
* @since PHP 4.2.0
* @require PHP 4.0.0 (user_error) (is_subclass_of)
*/
if (!function_exists('is_a')) {
function is_a($object, $class)
{
if (!is_object($object)) {
return false;
}
if (get_class($object) == strtolower($class)) {
return true;
} else {
return is_subclass_of($object, $class);
}
}
}
?>
@@ -0,0 +1,53 @@
<?php
/**
* Replace function is_callable()
*
* @category PHP
* @package PHP_Compat
* @link http://php.net/function.is_callable
* @author Gaetano Giunta <giunta.gaetano@sea-aeroportimilano.it>
* @version $Id: is_callable.php 2 2009-03-16 20:22:51Z ggiunta $
* @since PHP 4.0.6
* @require PHP 4.0.0 (true, false, etc...)
* @todo add the 3rd parameter syntax...
*/
if (!function_exists('is_callable')) {
function is_callable($var, $syntax_only=false)
{
if ($syntax_only)
{
/* from The Manual:
* If the syntax_only argument is TRUE the function only verifies
* that var might be a function or method. It will only reject simple
* variables that are not strings, or an array that does not have a
* valid structure to be used as a callback. The valid ones are
* supposed to have only 2 entries, the first of which is an object
* or a string, and the second a string
*/
return (is_string($var) || (is_array($var) && count($var) == 2 && is_string(end($var)) && (is_string(reset($var)) || is_object(reset($var)))));
}
else
{
if (is_string($var))
{
return function_exists($var);
}
else if (is_array($var) && count($var) == 2 && is_string($method = end($var)))
{
$obj = reset($var);
if (is_string($obj))
{
$methods = get_class_methods($obj);
return (bool)(is_array($methods) && in_array(strtolower($method), $methods));
}
else if (is_object($obj))
{
return method_exists($obj, $method);
}
}
return false;
}
}
}
?>
@@ -0,0 +1,38 @@
<?php
// +----------------------------------------------------------------------+
// | PHP Version 4 |
// +----------------------------------------------------------------------+
// | Copyright (c) 1997-2004 The PHP Group |
// +----------------------------------------------------------------------+
// | This source file is subject to version 3.0 of the PHP license, |
// | that is bundled with this package in the file LICENSE, and is |
// | available at through the world-wide-web at |
// | http://www.php.net/license/3_0.txt. |
// | If you did not receive a copy of the PHP license and are unable to |
// | obtain it through the world-wide-web, please send a note to |
// | license@php.net so we can mail you a copy immediately. |
// +----------------------------------------------------------------------+
//
// $Id: is_scalar.php 2 2009-03-16 20:22:51Z ggiunta $
/**
* Replace is_scalar()
*
* @category PHP
* @package PHP_Compat
* @link http://php.net/function.is_scalar
* @author Gaetano Giunta
* @version $Revision: 1.2 $
* @since PHP 4.0.5
* @require PHP 4 (is_bool)
*/
if (!function_exists('is_scalar')) {
function is_scalar($val)
{
// Check input
return (is_bool($val) || is_int($val) || is_float($val) || is_string($val));
}
}
?>
@@ -0,0 +1,105 @@
<?php
// +----------------------------------------------------------------------+
// | PHP Version 4 |
// +----------------------------------------------------------------------+
// | Copyright (c) 1997-2004 The PHP Group |
// +----------------------------------------------------------------------+
// | This source file is subject to version 3.0 of the PHP license, |
// | that is bundled with this package in the file LICENSE, and is |
// | available at through the world-wide-web at |
// | http://www.php.net/license/3_0.txt. |
// | If you did not receive a copy of the PHP license and are unable to |
// | obtain it through the world-wide-web, please send a note to |
// | license@php.net so we can mail you a copy immediately. |
// +----------------------------------------------------------------------+
// | Authors: Aidan Lister <aidan@php.net> |
// +----------------------------------------------------------------------+
//
// $Id: var_export.php 2 2009-03-16 20:22:51Z ggiunta $
/**
* Replace var_export()
*
* @category PHP
* @package PHP_Compat
* @link http://php.net/function.var_export
* @author Aidan Lister <aidan@php.net>
* @version $Revision: 1.2 $
* @since PHP 4.2.0
* @require PHP 4.0.0 (user_error)
*/
if (!function_exists('var_export')) {
function var_export($array, $return = false, $lvl=0)
{
// Common output variables
$indent = ' ';
$doublearrow = ' => ';
$lineend = ",\n";
$stringdelim = '\'';
// Check the export isn't a simple string / int
if (is_string($array)) {
$out = $stringdelim . str_replace('\'', '\\\'', str_replace('\\', '\\\\', $array)) . $stringdelim;
} elseif (is_int($array) || is_float($array)) {
$out = (string)$array;
} elseif (is_bool($array)) {
$out = $array ? 'true' : 'false';
} elseif (is_null($array)) {
$out = 'NULL';
} elseif (is_resource($array)) {
$out = 'resource';
} else {
// Begin the array export
// Start the string
$out = "array (\n";
// Loop through each value in array
foreach ($array as $key => $value) {
// If the key is a string, delimit it
if (is_string($key)) {
$key = str_replace('\'', '\\\'', str_replace('\\', '\\\\', $key));
$key = $stringdelim . $key . $stringdelim;
}
$val = var_export($value, true, $lvl+1);
// Delimit value
/*if (is_array($value)) {
// We have an array, so do some recursion
// Do some basic recursion while increasing the indent
$recur_array = explode($newline, var_export($value, true));
$temp_array = array();
foreach ($recur_array as $recur_line) {
$temp_array[] = $indent . $recur_line;
}
$recur_array = implode($newline, $temp_array);
$value = $newline . $recur_array;
} elseif (is_null($value)) {
$value = 'NULL';
} else {
$value = str_replace($find, $replace, $value);
$value = $stringdelim . $value . $stringdelim;
}*/
// Piece together the line
for ($i = 0; $i < $lvl; $i++)
$out .= $indent;
$out .= $key . $doublearrow . $val . $lineend;
}
// End our string
for ($i = 0; $i < $lvl; $i++)
$out .= $indent;
$out .= ")";
}
// Decide method of output
if ($return === true) {
return $out;
} else {
echo $out;
return;
}
}
}
?>
@@ -0,0 +1,179 @@
<?php
// +----------------------------------------------------------------------+
// | PHP Version 4 |
// +----------------------------------------------------------------------+
// | Copyright (c) 1997-2004 The PHP Group |
// +----------------------------------------------------------------------+
// | This source file is subject to version 3.0 of the PHP license, |
// | that is bundled with this package in the file LICENSE, and is |
// | available at through the world-wide-web at |
// | http://www.php.net/license/3_0.txt. |
// | If you did not receive a copy of the PHP license and are unable to |
// | obtain it through the world-wide-web, please send a note to |
// | license@php.net so we can mail you a copy immediately. |
// +----------------------------------------------------------------------+
// | Authors: Philippe Jausions <Philippe.Jausions@11abacus.com> |
// | Aidan Lister <aidan@php.net> |
// +----------------------------------------------------------------------+
//
// $Id: version_compare.php 2 2009-03-16 20:22:51Z ggiunta $
/**
* Replace version_compare()
*
* @category PHP
* @package PHP_Compat
* @link http://php.net/function.version_compare
* @author Philippe Jausions <Philippe.Jausions@11abacus.com>
* @author Aidan Lister <aidan@php.net>
* @version $Revision: 1.1 $
* @since PHP 4.1.0
* @require PHP 4.0.0 (user_error)
*/
if (!function_exists('version_compare')) {
function version_compare($version1, $version2, $operator = '<')
{
// Check input
if (!is_scalar($version1)) {
user_error('version_compare() expects parameter 1 to be string, ' .
gettype($version1) . ' given', E_USER_WARNING);
return;
}
if (!is_scalar($version2)) {
user_error('version_compare() expects parameter 2 to be string, ' .
gettype($version2) . ' given', E_USER_WARNING);
return;
}
if (!is_scalar($operator)) {
user_error('version_compare() expects parameter 3 to be string, ' .
gettype($operator) . ' given', E_USER_WARNING);
return;
}
// Standardise versions
$v1 = explode('.',
str_replace('..', '.',
preg_replace('/([^0-9\.]+)/', '.$1.',
str_replace(array('-', '_', '+'), '.',
trim($version1)))));
$v2 = explode('.',
str_replace('..', '.',
preg_replace('/([^0-9\.]+)/', '.$1.',
str_replace(array('-', '_', '+'), '.',
trim($version2)))));
// Replace empty entries at the start of the array
while (empty($v1[0]) && array_shift($v1)) {}
while (empty($v2[0]) && array_shift($v2)) {}
// Release state order
// '#' stands for any number
$versions = array(
'dev' => 0,
'alpha' => 1,
'a' => 1,
'beta' => 2,
'b' => 2,
'RC' => 3,
'#' => 4,
'p' => 5,
'pl' => 5);
// Loop through each segment in the version string
$compare = 0;
for ($i = 0, $x = min(count($v1), count($v2)); $i < $x; $i++) {
if ($v1[$i] == $v2[$i]) {
continue;
}
$i1 = $v1[$i];
$i2 = $v2[$i];
if (is_numeric($i1) && is_numeric($i2)) {
$compare = ($i1 < $i2) ? -1 : 1;
break;
}
// We use the position of '#' in the versions list
// for numbers... (so take care of # in original string)
if ($i1 == '#') {
$i1 = '';
} elseif (is_numeric($i1)) {
$i1 = '#';
}
if ($i2 == '#') {
$i2 = '';
} elseif (is_numeric($i2)) {
$i2 = '#';
}
if (isset($versions[$i1]) && isset($versions[$i2])) {
$compare = ($versions[$i1] < $versions[$i2]) ? -1 : 1;
} elseif (isset($versions[$i1])) {
$compare = 1;
} elseif (isset($versions[$i2])) {
$compare = -1;
} else {
$compare = 0;
}
break;
}
// If previous loop didn't find anything, compare the "extra" segments
if ($compare == 0) {
if (count($v2) > count($v1)) {
if (isset($versions[$v2[$i]])) {
$compare = ($versions[$v2[$i]] < 4) ? 1 : -1;
} else {
$compare = -1;
}
} elseif (count($v2) < count($v1)) {
if (isset($versions[$v1[$i]])) {
$compare = ($versions[$v1[$i]] < 4) ? -1 : 1;
} else {
$compare = 1;
}
}
}
// Compare the versions
if (func_num_args() > 2) {
switch ($operator) {
case '>':
case 'gt':
return (bool) ($compare > 0);
break;
case '>=':
case 'ge':
return (bool) ($compare >= 0);
break;
case '<=':
case 'le':
return (bool) ($compare <= 0);
break;
case '==':
case '=':
case 'eq':
return (bool) ($compare == 0);
break;
case '<>':
case '!=':
case 'ne':
return (bool) ($compare != 0);
break;
case '':
case '<':
case 'lt':
return (bool) ($compare < 0);
break;
default:
return;
}
}
return $compare;
}
}
?>
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,944 @@
<?php
/**
* PHP-XMLRPC "wrapper" functions
* Generate stubs to transparently access xmlrpc methods as php functions and viceversa
*
* @version $Id: xmlrpc_wrappers.inc,v 1.13 2008/09/20 01:23:47 ggiunta Exp $
* @author Gaetano Giunta
* @copyright (C) 2006-2008 G. Giunta
* @license code licensed under the BSD License: http://phpxmlrpc.sourceforge.net/license.txt
*
* @todo separate introspection from code generation for func-2-method wrapping
* @todo use some better templating system for code generation?
* @todo implement method wrapping with preservation of php objs in calls
* @todo when wrapping methods without obj rebuilding, use return_type = 'phpvals' (faster)
* @todo implement self-parsing of php code for PHP <= 4
*/
// requires: xmlrpc.inc
/**
* Given a string defining a php type or phpxmlrpc type (loosely defined: strings
* accepted come from javadoc blocks), return corresponding phpxmlrpc type.
* NB: for php 'resource' types returns empty string, since resources cannot be serialized;
* for php class names returns 'struct', since php objects can be serialized as xmlrpc structs
* @param string $phptype
* @return string
*/
function php_2_xmlrpc_type($phptype)
{
switch(strtolower($phptype))
{
case 'string':
return $GLOBALS['xmlrpcString'];
case 'integer':
case $GLOBALS['xmlrpcInt']: // 'int'
case $GLOBALS['xmlrpcI4']:
return $GLOBALS['xmlrpcInt'];
case 'double':
return $GLOBALS['xmlrpcDouble'];
case 'boolean':
return $GLOBALS['xmlrpcBoolean'];
case 'array':
return $GLOBALS['xmlrpcArray'];
case 'object':
return $GLOBALS['xmlrpcStruct'];
case $GLOBALS['xmlrpcBase64']:
case $GLOBALS['xmlrpcStruct']:
return strtolower($phptype);
case 'resource':
return '';
default:
if(class_exists($phptype))
{
return $GLOBALS['xmlrpcStruct'];
}
else
{
// unknown: might be any 'extended' xmlrpc type
return $GLOBALS['xmlrpcValue'];
}
}
}
/**
* Given a string defining a phpxmlrpc type return corresponding php type.
* @param string $xmlrpctype
* @return string
*/
function xmlrpc_2_php_type($xmlrpctype)
{
switch(strtolower($xmlrpctype))
{
case 'base64':
case 'datetime.iso8601':
case 'string':
return $GLOBALS['xmlrpcString'];
case 'int':
case 'i4':
return 'integer';
case 'struct':
case 'array':
return 'array';
case 'double':
return 'float';
case 'undefined':
return 'mixed';
case 'boolean':
case 'null':
default:
// unknown: might be any xmlrpc type
return strtolower($xmlrpctype);
}
}
/**
* Given a user-defined PHP function, create a PHP 'wrapper' function that can
* be exposed as xmlrpc method from an xmlrpc_server object and called from remote
* clients (as well as its corresponding signature info).
*
* Since php is a typeless language, to infer types of input and output parameters,
* it relies on parsing the javadoc-style comment block associated with the given
* function. Usage of xmlrpc native types (such as datetime.dateTime.iso8601 and base64)
* in the @param tag is also allowed, if you need the php function to receive/send
* data in that particular format (note that base64 encoding/decoding is transparently
* carried out by the lib, while datetime vals are passed around as strings)
*
* Known limitations:
* - requires PHP 5.0.3 +
* - only works for user-defined functions, not for PHP internal functions
* (reflection does not support retrieving number/type of params for those)
* - functions returning php objects will generate special xmlrpc responses:
* when the xmlrpc decoding of those responses is carried out by this same lib, using
* the appropriate param in php_xmlrpc_decode, the php objects will be rebuilt.
* In short: php objects can be serialized, too (except for their resource members),
* using this function.
* Other libs might choke on the very same xml that will be generated in this case
* (i.e. it has a nonstandard attribute on struct element tags)
* - usage of javadoc @param tags using param names in a different order from the
* function prototype is not considered valid (to be fixed?)
*
* Note that since rel. 2.0RC3 the preferred method to have the server call 'standard'
* php functions (ie. functions not expecting a single xmlrpcmsg obj as parameter)
* is by making use of the functions_parameters_type class member.
*
* @param string $funcname the name of the PHP user function to be exposed as xmlrpc method; array($obj, 'methodname') and array('class', 'methodname') are ok too
* @param string $newfuncname (optional) name for function to be created
* @param array $extra_options (optional) array of options for conversion. valid values include:
* bool return_source when true, php code w. function definition will be returned, not evaluated
* bool encode_php_objs let php objects be sent to server using the 'improved' xmlrpc notation, so server can deserialize them as php objects
* bool decode_php_objs --- WARNING !!! possible security hazard. only use it with trusted servers ---
* bool suppress_warnings remove from produced xml any runtime warnings due to the php function being invoked
* @return false on error, or an array containing the name of the new php function,
* its signature and docs, to be used in the server dispatch map
*
* @todo decide how to deal with params passed by ref: bomb out or allow?
* @todo finish using javadoc info to build method sig if all params are named but out of order
* @todo add a check for params of 'resource' type
* @todo add some trigger_errors / error_log when returning false?
* @todo what to do when the PHP function returns NULL? we are currently returning an empty string value...
* @todo add an option to suppress php warnings in invocation of user function, similar to server debug level 3?
* @todo if $newfuncname is empty, we could use create_user_func instead of eval, as it is possibly faster
* @todo add a verbatim_object_copy parameter to allow avoiding the same obj instance?
*/
function wrap_php_function($funcname, $newfuncname='', $extra_options=array())
{
$buildit = isset($extra_options['return_source']) ? !($extra_options['return_source']) : true;
$prefix = isset($extra_options['prefix']) ? $extra_options['prefix'] : 'xmlrpc';
$encode_php_objects = isset($extra_options['encode_php_objs']) ? (bool)$extra_options['encode_php_objs'] : false;
$decode_php_objects = isset($extra_options['decode_php_objs']) ? (bool)$extra_options['decode_php_objs'] : false;
$catch_warnings = isset($extra_options['suppress_warnings']) && $extra_options['suppress_warnings'] ? '@' : '';
if(version_compare(phpversion(), '5.0.3') == -1)
{
// up to php 5.0.3 some useful reflection methods were missing
error_log('XML-RPC: cannot not wrap php functions unless running php version bigger than 5.0.3');
return false;
}
$exists = false;
if(is_array($funcname))
{
if(count($funcname) < 2 || (!is_string($funcname[0]) && !is_object($funcname[0])))
{
error_log('XML-RPC: syntax for function to be wrapped is wrong');
return false;
}
if(is_string($funcname[0]))
{
$plainfuncname = implode('::', $funcname);
}
elseif(is_object($funcname[0]))
{
$plainfuncname = get_class($funcname[0]) . '->' . $funcname[1];
}
$exists = method_exists($funcname[0], $funcname[1]);
}
else
{
$plainfuncname = $funcname;
$exists = function_exists($funcname);
}
if(!$exists)
{
error_log('XML-RPC: function to be wrapped is not defined: '.$plainfuncname);
return false;
}
else
{
// determine name of new php function
if($newfuncname == '')
{
if(is_array($funcname))
{
if(is_string($funcname[0]))
$xmlrpcfuncname = "{$prefix}_".implode('_', $funcname);
else
$xmlrpcfuncname = "{$prefix}_".get_class($funcname[0]) . '_' . $funcname[1];
}
else
{
$xmlrpcfuncname = "{$prefix}_$funcname";
}
}
else
{
$xmlrpcfuncname = $newfuncname;
}
while($buildit && function_exists($xmlrpcfuncname))
{
$xmlrpcfuncname .= 'x';
}
// start to introspect PHP code
if(is_array($funcname))
{
$func = new ReflectionMethod($funcname[0], $funcname[1]);
if($func->isPrivate())
{
error_log('XML-RPC: method to be wrapped is private: '.$plainfuncname);
return false;
}
if($func->isProtected())
{
error_log('XML-RPC: method to be wrapped is protected: '.$plainfuncname);
return false;
}
if($func->isConstructor())
{
error_log('XML-RPC: method to be wrapped is the constructor: '.$plainfuncname);
return false;
}
if($func->isDestructor())
{
error_log('XML-RPC: method to be wrapped is the destructor: '.$plainfuncname);
return false;
}
if($func->isAbstract())
{
error_log('XML-RPC: method to be wrapped is abstract: '.$plainfuncname);
return false;
}
/// @todo add more checks for static vs. nonstatic?
}
else
{
$func = new ReflectionFunction($funcname);
}
if($func->isInternal())
{
// Note: from PHP 5.1.0 onward, we will possibly be able to use invokeargs
// instead of getparameters to fully reflect internal php functions ?
error_log('XML-RPC: function to be wrapped is internal: '.$plainfuncname);
return false;
}
// retrieve parameter names, types and description from javadoc comments
// function description
$desc = '';
// type of return val: by default 'any'
$returns = $GLOBALS['xmlrpcValue'];
// desc of return val
$returnsDocs = '';
// type + name of function parameters
$paramDocs = array();
$docs = $func->getDocComment();
if($docs != '')
{
$docs = explode("\n", $docs);
$i = 0;
foreach($docs as $doc)
{
$doc = trim($doc, " \r\t/*");
if(strlen($doc) && strpos($doc, '@') !== 0 && !$i)
{
if($desc)
{
$desc .= "\n";
}
$desc .= $doc;
}
elseif(strpos($doc, '@param') === 0)
{
// syntax: @param type [$name] desc
if(preg_match('/@param\s+(\S+)(\s+\$\S+)?\s+(.+)/', $doc, $matches))
{
if(strpos($matches[1], '|'))
{
//$paramDocs[$i]['type'] = explode('|', $matches[1]);
$paramDocs[$i]['type'] = 'mixed';
}
else
{
$paramDocs[$i]['type'] = $matches[1];
}
$paramDocs[$i]['name'] = trim($matches[2]);
$paramDocs[$i]['doc'] = $matches[3];
}
$i++;
}
elseif(strpos($doc, '@return') === 0)
{
// syntax: @return type desc
//$returns = preg_split('/\s+/', $doc);
if(preg_match('/@return\s+(\S+)\s+(.+)/', $doc, $matches))
{
$returns = php_2_xmlrpc_type($matches[1]);
if(isset($matches[2]))
{
$returnsDocs = $matches[2];
}
}
}
}
}
// execute introspection of actual function prototype
$params = array();
$i = 0;
foreach($func->getParameters() as $paramobj)
{
$params[$i] = array();
$params[$i]['name'] = '$'.$paramobj->getName();
$params[$i]['isoptional'] = $paramobj->isOptional();
$i++;
}
// start building of PHP code to be eval'd
$innercode = '';
$i = 0;
$parsvariations = array();
$pars = array();
$pnum = count($params);
foreach($params as $param)
{
if (isset($paramDocs[$i]['name']) && $paramDocs[$i]['name'] && strtolower($paramDocs[$i]['name']) != strtolower($param['name']))
{
// param name from phpdoc info does not match param definition!
$paramDocs[$i]['type'] = 'mixed';
}
if($param['isoptional'])
{
// this particular parameter is optional. save as valid previous list of parameters
$innercode .= "if (\$paramcount > $i) {\n";
$parsvariations[] = $pars;
}
$innercode .= "\$p$i = \$msg->getParam($i);\n";
if ($decode_php_objects)
{
$innercode .= "if (\$p{$i}->kindOf() == 'scalar') \$p$i = \$p{$i}->scalarval(); else \$p$i = php_{$prefix}_decode(\$p$i, array('decode_php_objs'));\n";
}
else
{
$innercode .= "if (\$p{$i}->kindOf() == 'scalar') \$p$i = \$p{$i}->scalarval(); else \$p$i = php_{$prefix}_decode(\$p$i);\n";
}
$pars[] = "\$p$i";
$i++;
if($param['isoptional'])
{
$innercode .= "}\n";
}
if($i == $pnum)
{
// last allowed parameters combination
$parsvariations[] = $pars;
}
}
$sigs = array();
$psigs = array();
if(count($parsvariations) == 0)
{
// only known good synopsis = no parameters
$parsvariations[] = array();
$minpars = 0;
}
else
{
$minpars = count($parsvariations[0]);
}
if($minpars)
{
// add to code the check for min params number
// NB: this check needs to be done BEFORE decoding param values
$innercode = "\$paramcount = \$msg->getNumParams();\n" .
"if (\$paramcount < $minpars) return new {$prefix}resp(0, {$GLOBALS['xmlrpcerr']['incorrect_params']}, '{$GLOBALS['xmlrpcstr']['incorrect_params']}');\n" . $innercode;
}
else
{
$innercode = "\$paramcount = \$msg->getNumParams();\n" . $innercode;
}
$innercode .= "\$np = false;\n";
// since there are no closures in php, if we are given an object instance,
// we store a pointer to it in a global var...
if ( is_array($funcname) && is_object($funcname[0]) )
{
$GLOBALS['xmlrpcWPFObjHolder'][$xmlrpcfuncname] =& $funcname[0];
$innercode .= "\$obj =& \$GLOBALS['xmlrpcWPFObjHolder']['$xmlrpcfuncname'];\n";
$realfuncname = '$obj->'.$funcname[1];
}
else
{
$realfuncname = $plainfuncname;
}
foreach($parsvariations as $pars)
{
$innercode .= "if (\$paramcount == " . count($pars) . ") \$retval = {$catch_warnings}$realfuncname(" . implode(',', $pars) . "); else\n";
// build a 'generic' signature (only use an appropriate return type)
$sig = array($returns);
$psig = array($returnsDocs);
for($i=0; $i < count($pars); $i++)
{
if (isset($paramDocs[$i]['type']))
{
$sig[] = php_2_xmlrpc_type($paramDocs[$i]['type']);
}
else
{
$sig[] = $GLOBALS['xmlrpcValue'];
}
$psig[] = isset($paramDocs[$i]['doc']) ? $paramDocs[$i]['doc'] : '';
}
$sigs[] = $sig;
$psigs[] = $psig;
}
$innercode .= "\$np = true;\n";
$innercode .= "if (\$np) return new {$prefix}resp(0, {$GLOBALS['xmlrpcerr']['incorrect_params']}, '{$GLOBALS['xmlrpcstr']['incorrect_params']}'); else {\n";
//$innercode .= "if (\$_xmlrpcs_error_occurred) return new xmlrpcresp(0, $GLOBALS['xmlrpcerr']user, \$_xmlrpcs_error_occurred); else\n";
$innercode .= "if (is_a(\$retval, '{$prefix}resp')) return \$retval; else\n";
if($returns == $GLOBALS['xmlrpcDateTime'] || $returns == $GLOBALS['xmlrpcBase64'])
{
$innercode .= "return new {$prefix}resp(new {$prefix}val(\$retval, '$returns'));";
}
else
{
if ($encode_php_objects)
$innercode .= "return new {$prefix}resp(php_{$prefix}_encode(\$retval, array('encode_php_objs')));\n";
else
$innercode .= "return new {$prefix}resp(php_{$prefix}_encode(\$retval));\n";
}
// shall we exclude functions returning by ref?
// if($func->returnsReference())
// return false;
$code = "function $xmlrpcfuncname(\$msg) {\n" . $innercode . "}\n}";
//print_r($code);
if ($buildit)
{
$allOK = 0;
eval($code.'$allOK=1;');
// alternative
//$xmlrpcfuncname = create_function('$m', $innercode);
if(!$allOK)
{
error_log('XML-RPC: could not create function '.$xmlrpcfuncname.' to wrap php function '.$plainfuncname);
return false;
}
}
/// @todo examine if $paramDocs matches $parsvariations and build array for
/// usage as method signature, plus put together a nice string for docs
$ret = array('function' => $xmlrpcfuncname, 'signature' => $sigs, 'docstring' => $desc, 'signature_docs' => $psigs, 'source' => $code);
return $ret;
}
}
/**
* Given a user-defined PHP class or php object, map its methods onto a list of
* PHP 'wrapper' functions that can be exposed as xmlrpc methods from an xmlrpc_server
* object and called from remote clients (as well as their corresponding signature info).
*
* @param mixed $classname the name of the class whose methods are to be exposed as xmlrpc methods, or an object instance of that class
* @param array $extra_options see the docs for wrap_php_method for more options
* string method_type 'static', 'nonstatic', 'all' and 'auto' (default); the latter will switch between static and non-static depending on wheter $classname is a class name or object instance
* @return array or false on failure
*
* @todo get_class_methods will return both static and non-static methods.
* we have to differentiate the action, depending on wheter we recived a class name or object
*/
function wrap_php_class($classname, $extra_options=array())
{
$methodfilter = isset($extra_options['method_filter']) ? $extra_options['method_filter'] : '';
$methodtype = isset($extra_options['method_type']) ? $extra_options['method_type'] : 'auto';
if(version_compare(phpversion(), '5.0.3') == -1)
{
// up to php 5.0.3 some useful reflection methods were missing
error_log('XML-RPC: cannot not wrap php functions unless running php version bigger than 5.0.3');
return false;
}
$result = array();
$mlist = get_class_methods($classname);
foreach($mlist as $mname)
{
if ($methodfilter == '' || preg_match($methodfilter, $mname))
{
// echo $mlist."\n";
$func = new ReflectionMethod($classname, $mname);
if(!$func->isPrivate() && !$func->isProtected() && !$func->isConstructor() && !$func->isDestructor() && !$func->isAbstract())
{
if(($func->isStatic && ($methodtype == 'all' || $methodtype == 'static' || ($methodtype == 'auto' && is_string($classname)))) ||
(!$func->isStatic && ($methodtype == 'all' || $methodtype == 'nonstatic' || ($methodtype == 'auto' && is_object($classname)))))
{
$methodwrap = wrap_php_function(array($classname, $mname), '', $extra_options);
if ( $methodwrap )
{
$result[$methodwrap['function']] = $methodwrap['function'];
}
}
}
}
}
return $result;
}
/**
* Given an xmlrpc client and a method name, register a php wrapper function
* that will call it and return results using native php types for both
* params and results. The generated php function will return an xmlrpcresp
* oject for failed xmlrpc calls
*
* Known limitations:
* - server must support system.methodsignature for the wanted xmlrpc method
* - for methods that expose many signatures, only one can be picked (we
* could in priciple check if signatures differ only by number of params
* and not by type, but it would be more complication than we can spare time)
* - nested xmlrpc params: the caller of the generated php function has to
* encode on its own the params passed to the php function if these are structs
* or arrays whose (sub)members include values of type datetime or base64
*
* Notes: the connection properties of the given client will be copied
* and reused for the connection used during the call to the generated
* php function.
* Calling the generated php function 'might' be slow: a new xmlrpc client
* is created on every invocation and an xmlrpc-connection opened+closed.
* An extra 'debug' param is appended to param list of xmlrpc method, useful
* for debugging purposes.
*
* @param xmlrpc_client $client an xmlrpc client set up correctly to communicate with target server
* @param string $methodname the xmlrpc method to be mapped to a php function
* @param array $extra_options array of options that specify conversion details. valid ptions include
* integer signum the index of the method signature to use in mapping (if method exposes many sigs)
* integer timeout timeout (in secs) to be used when executing function/calling remote method
* string protocol 'http' (default), 'http11' or 'https'
* string new_function_name the name of php function to create. If unsepcified, lib will pick an appropriate name
* string return_source if true return php code w. function definition instead fo function name
* bool encode_php_objs let php objects be sent to server using the 'improved' xmlrpc notation, so server can deserialize them as php objects
* bool decode_php_objs --- WARNING !!! possible security hazard. only use it with trusted servers ---
* mixed return_on_fault a php value to be returned when the xmlrpc call fails/returns a fault response (by default the xmlrpcresp object is returned in this case). If a string is used, '%faultCode%' and '%faultString%' tokens will be substituted with actual error values
* bool debug set it to 1 or 2 to see debug results of querying server for method synopsis
* @return string the name of the generated php function (or false) - OR AN ARRAY...
*/
function wrap_xmlrpc_method($client, $methodname, $extra_options=0, $timeout=0, $protocol='', $newfuncname='')
{
// mind numbing: let caller use sane calling convention (as per javadoc, 3 params),
// OR the 2.0 calling convention (no options) - we really love backward compat, don't we?
if (!is_array($extra_options))
{
$signum = $extra_options;
$extra_options = array();
}
else
{
$signum = isset($extra_options['signum']) ? (int)$extra_options['signum'] : 0;
$timeout = isset($extra_options['timeout']) ? (int)$extra_options['timeout'] : 0;
$protocol = isset($extra_options['protocol']) ? $extra_options['protocol'] : '';
$newfuncname = isset($extra_options['new_function_name']) ? $extra_options['new_function_name'] : '';
}
//$encode_php_objects = in_array('encode_php_objects', $extra_options);
//$verbatim_client_copy = in_array('simple_client_copy', $extra_options) ? 1 :
// in_array('build_class_code', $extra_options) ? 2 : 0;
$encode_php_objects = isset($extra_options['encode_php_objs']) ? (bool)$extra_options['encode_php_objs'] : false;
$decode_php_objects = isset($extra_options['decode_php_objs']) ? (bool)$extra_options['decode_php_objs'] : false;
$simple_client_copy = isset($extra_options['simple_client_copy']) ? (int)($extra_options['simple_client_copy']) : 0;
$buildit = isset($extra_options['return_source']) ? !($extra_options['return_source']) : true;
$prefix = isset($extra_options['prefix']) ? $extra_options['prefix'] : 'xmlrpc';
if (isset($extra_options['return_on_fault']))
{
$decode_fault = true;
$fault_response = $extra_options['return_on_fault'];
}
else
{
$decode_fault = false;
$fault_response = '';
}
$debug = isset($extra_options['debug']) ? ($extra_options['debug']) : 0;
$msgclass = $prefix.'msg';
$valclass = $prefix.'val';
$decodefunc = 'php_'.$prefix.'_decode';
$msg = new $msgclass('system.methodSignature');
$msg->addparam(new $valclass($methodname));
$client->setDebug($debug);
$response =& $client->send($msg, $timeout, $protocol);
if($response->faultCode())
{
error_log('XML-RPC: could not retrieve method signature from remote server for method '.$methodname);
return false;
}
else
{
$msig = $response->value();
if ($client->return_type != 'phpvals')
{
$msig = $decodefunc($msig);
}
if(!is_array($msig) || count($msig) <= $signum)
{
error_log('XML-RPC: could not retrieve method signature nr.'.$signum.' from remote server for method '.$methodname);
return false;
}
else
{
// pick a suitable name for the new function, avoiding collisions
if($newfuncname != '')
{
$xmlrpcfuncname = $newfuncname;
}
else
{
// take care to insure that methodname is translated to valid
// php function name
$xmlrpcfuncname = $prefix.'_'.preg_replace(array('/\./', '/[^a-zA-Z0-9_\x7f-\xff]/'),
array('_', ''), $methodname);
}
while($buildit && function_exists($xmlrpcfuncname))
{
$xmlrpcfuncname .= 'x';
}
$msig = $msig[$signum];
$mdesc = '';
// if in 'offline' mode, get method description too.
// in online mode, favour speed of operation
if(!$buildit)
{
$msg = new $msgclass('system.methodHelp');
$msg->addparam(new $valclass($methodname));
$response =& $client->send($msg, $timeout, $protocol);
if (!$response->faultCode())
{
$mdesc = $response->value();
if ($client->return_type != 'phpvals')
{
$mdesc = $mdesc->scalarval();
}
}
}
$results = build_remote_method_wrapper_code($client, $methodname,
$xmlrpcfuncname, $msig, $mdesc, $timeout, $protocol, $simple_client_copy,
$prefix, $decode_php_objects, $encode_php_objects, $decode_fault,
$fault_response);
//print_r($code);
if ($buildit)
{
$allOK = 0;
eval($results['source'].'$allOK=1;');
// alternative
//$xmlrpcfuncname = create_function('$m', $innercode);
if($allOK)
{
return $xmlrpcfuncname;
}
else
{
error_log('XML-RPC: could not create function '.$xmlrpcfuncname.' to wrap remote method '.$methodname);
return false;
}
}
else
{
$results['function'] = $xmlrpcfuncname;
return $results;
}
}
}
}
/**
* Similar to wrap_xmlrpc_method, but will generate a php class that wraps
* all xmlrpc methods exposed by the remote server as own methods.
* For more details see wrap_xmlrpc_method.
* @param xmlrpc_client $client the client obj all set to query the desired server
* @param array $extra_options list of options for wrapped code
* @return mixed false on error, the name of the created class if all ok or an array with code, class name and comments (if the appropriatevoption is set in extra_options)
*/
function wrap_xmlrpc_server($client, $extra_options=array())
{
$methodfilter = isset($extra_options['method_filter']) ? $extra_options['method_filter'] : '';
//$signum = isset($extra_options['signum']) ? (int)$extra_options['signum'] : 0;
$timeout = isset($extra_options['timeout']) ? (int)$extra_options['timeout'] : 0;
$protocol = isset($extra_options['protocol']) ? $extra_options['protocol'] : '';
$newclassname = isset($extra_options['new_class_name']) ? $extra_options['new_class_name'] : '';
$encode_php_objects = isset($extra_options['encode_php_objs']) ? (bool)$extra_options['encode_php_objs'] : false;
$decode_php_objects = isset($extra_options['decode_php_objs']) ? (bool)$extra_options['decode_php_objs'] : false;
$verbatim_client_copy = isset($extra_options['simple_client_copy']) ? !($extra_options['simple_client_copy']) : true;
$buildit = isset($extra_options['return_source']) ? !($extra_options['return_source']) : true;
$prefix = isset($extra_options['prefix']) ? $extra_options['prefix'] : 'xmlrpc';
$msgclass = $prefix.'msg';
//$valclass = $prefix.'val';
$decodefunc = 'php_'.$prefix.'_decode';
$msg = new $msgclass('system.listMethods');
$response =& $client->send($msg, $timeout, $protocol);
if($response->faultCode())
{
error_log('XML-RPC: could not retrieve method list from remote server');
return false;
}
else
{
$mlist = $response->value();
if ($client->return_type != 'phpvals')
{
$mlist = $decodefunc($mlist);
}
if(!is_array($mlist) || !count($mlist))
{
error_log('XML-RPC: could not retrieve meaningful method list from remote server');
return false;
}
else
{
// pick a suitable name for the new function, avoiding collisions
if($newclassname != '')
{
$xmlrpcclassname = $newclassname;
}
else
{
$xmlrpcclassname = $prefix.'_'.preg_replace(array('/\./', '/[^a-zA-Z0-9_\x7f-\xff]/'),
array('_', ''), $client->server).'_client';
}
while($buildit && class_exists($xmlrpcclassname))
{
$xmlrpcclassname .= 'x';
}
/// @todo add function setdebug() to new class, to enable/disable debugging
$source = "class $xmlrpcclassname\n{\nvar \$client;\n\n";
$source .= "function $xmlrpcclassname()\n{\n";
$source .= build_client_wrapper_code($client, $verbatim_client_copy, $prefix);
$source .= "\$this->client =& \$client;\n}\n\n";
$opts = array('simple_client_copy' => 2, 'return_source' => true,
'timeout' => $timeout, 'protocol' => $protocol,
'encode_php_objs' => $encode_php_objects, 'prefix' => $prefix,
'decode_php_objs' => $decode_php_objects
);
/// @todo build javadoc for class definition, too
foreach($mlist as $mname)
{
if ($methodfilter == '' || preg_match($methodfilter, $mname))
{
$opts['new_function_name'] = preg_replace(array('/\./', '/[^a-zA-Z0-9_\x7f-\xff]/'),
array('_', ''), $mname);
$methodwrap = wrap_xmlrpc_method($client, $mname, $opts);
if ($methodwrap)
{
if (!$buildit)
{
$source .= $methodwrap['docstring'];
}
$source .= $methodwrap['source']."\n";
}
else
{
error_log('XML-RPC: will not create class method to wrap remote method '.$mname);
}
}
}
$source .= "}\n";
if ($buildit)
{
$allOK = 0;
eval($source.'$allOK=1;');
// alternative
//$xmlrpcfuncname = create_function('$m', $innercode);
if($allOK)
{
return $xmlrpcclassname;
}
else
{
error_log('XML-RPC: could not create class '.$xmlrpcclassname.' to wrap remote server '.$client->server);
return false;
}
}
else
{
return array('class' => $xmlrpcclassname, 'code' => $source, 'docstring' => '');
}
}
}
}
/**
* Given the necessary info, build php code that creates a new function to
* invoke a remote xmlrpc method.
* Take care that no full checking of input parameters is done to ensure that
* valid php code is emitted.
* Note: real spaghetti code follows...
* @access private
*/
function build_remote_method_wrapper_code($client, $methodname, $xmlrpcfuncname,
$msig, $mdesc='', $timeout=0, $protocol='', $client_copy_mode=0, $prefix='xmlrpc',
$decode_php_objects=false, $encode_php_objects=false, $decode_fault=false,
$fault_response='')
{
$code = "function $xmlrpcfuncname (";
if ($client_copy_mode < 2)
{
// client copy mode 0 or 1 == partial / full client copy in emitted code
$innercode = build_client_wrapper_code($client, $client_copy_mode, $prefix);
$innercode .= "\$client->setDebug(\$debug);\n";
$this_ = '';
}
else
{
// client copy mode 2 == no client copy in emitted code
$innercode = '';
$this_ = 'this->';
}
$innercode .= "\$msg = new {$prefix}msg('$methodname');\n";
if ($mdesc != '')
{
// take care that PHP comment is not terminated unwillingly by method description
$mdesc = "/**\n* ".str_replace('*/', '* /', $mdesc)."\n";
}
else
{
$mdesc = "/**\nFunction $xmlrpcfuncname\n";
}
// param parsing
$plist = array();
$pcount = count($msig);
for($i = 1; $i < $pcount; $i++)
{
$plist[] = "\$p$i";
$ptype = $msig[$i];
if($ptype == 'i4' || $ptype == 'int' || $ptype == 'boolean' || $ptype == 'double' ||
$ptype == 'string' || $ptype == 'dateTime.iso8601' || $ptype == 'base64' || $ptype == 'null')
{
// only build directly xmlrpcvals when type is known and scalar
$innercode .= "\$p$i = new {$prefix}val(\$p$i, '$ptype');\n";
}
else
{
if ($encode_php_objects)
{
$innercode .= "\$p$i =& php_{$prefix}_encode(\$p$i, array('encode_php_objs'));\n";
}
else
{
$innercode .= "\$p$i =& php_{$prefix}_encode(\$p$i);\n";
}
}
$innercode .= "\$msg->addparam(\$p$i);\n";
$mdesc .= '* @param '.xmlrpc_2_php_type($ptype)." \$p$i\n";
}
if ($client_copy_mode < 2)
{
$plist[] = '$debug=0';
$mdesc .= "* @param int \$debug when 1 (or 2) will enable debugging of the underlying {$prefix} call (defaults to 0)\n";
}
$plist = implode(', ', $plist);
$mdesc .= '* @return '.xmlrpc_2_php_type($msig[0])." (or an {$prefix}resp obj instance if call fails)\n*/\n";
$innercode .= "\$res =& \${$this_}client->send(\$msg, $timeout, '$protocol');\n";
if ($decode_fault)
{
if (is_string($fault_response) && ((strpos($fault_response, '%faultCode%') !== false) || (strpos($fault_response, '%faultString%') !== false)))
{
$respcode = "str_replace(array('%faultCode%', '%faultString%'), array(\$res->faultCode(), \$res->faultString()), '".str_replace("'", "''", $fault_response)."')";
}
else
{
$respcode = var_export($fault_response, true);
}
}
else
{
$respcode = '$res';
}
if ($decode_php_objects)
{
$innercode .= "if (\$res->faultcode()) return $respcode; else return php_{$prefix}_decode(\$res->value(), array('decode_php_objs'));";
}
else
{
$innercode .= "if (\$res->faultcode()) return $respcode; else return php_{$prefix}_decode(\$res->value());";
}
$code = $code . $plist. ") {\n" . $innercode . "\n}\n";
return array('source' => $code, 'docstring' => $mdesc);
}
/**
* Given necessary info, generate php code that will rebuild a client object
* Take care that no full checking of input parameters is done to ensure that
* valid php code is emitted.
* @access private
*/
function build_client_wrapper_code($client, $verbatim_client_copy, $prefix='xmlrpc')
{
$code = "\$client = new {$prefix}_client('".str_replace("'", "\'", $client->path).
"', '" . str_replace("'", "\'", $client->server) . "', $client->port);\n";
// copy all client fields to the client that will be generated runtime
// (this provides for future expansion or subclassing of client obj)
if ($verbatim_client_copy)
{
foreach($client as $fld => $val)
{
if($fld != 'debug' && $fld != 'return_type')
{
$val = var_export($val, true);
$code .= "\$client->$fld = $val;\n";
}
}
}
// only make sure that client always returns the correct data type
$code .= "\$client->return_type = '{$prefix}vals';\n";
//$code .= "\$client->setDebug(\$debug);\n";
return $code;
}
?>
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,24 @@
<?php
//
// by Fumi.Iseki '09 5/31
//
if (!defined('ENV_READ_CONFIG')) require_once(realpath(dirname(__FILE__).'/../include/config.php'));
if (!defined('ENV_READ_DEFINE')) require_once(realpath(ENV_HELPER_PATH.'/../include/env_define.php'));
if (!isset($HTTP_RAW_POST_DATA)) $HTTP_RAW_POST_DATA = file_get_contents('php://input');
//$debugXMLRPC = 1;
//$debugXMLRPCFile = 'xmlgroup.log';
//$request_xml = $HTTP_RAW_POST_DATA;
//error_log('xmlgroups.php: '.$request_xml); // see /var/log/php/... or /var/log/httpd/error_log
if ($XMLGRP_DB_MYSQLI) {
include(ENV_HELPER_PATH.'/xmlrpci.php');
}
else {
include(ENV_HELPER_PATH.'/xmlrpc.php');
}
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,78 @@
<?php
//
// Configration file for non Web Interface
// v1.2 2016100500
//
// Please set this hepler script directory
if (!defined('ENV_HELPER_URL')) define('ENV_HELPER_URL', 'http://opensim.tuis.ac.jp/helper_scripts/helper');
if (!defined('ENV_HELPER_PATH')) define('ENV_HELPER_PATH', '/var/www/html/helper_scripts/helper');
//////////////////////////////////////////////////////////////////////////////////i
// Valiables for OpenSim
// Please set MySQL DB access information for OpenSim
define('OPENSIM_DB_HOST', 'localhost');
define('OPENSIM_DB_NAME', 'opensim_db');
define('OPENSIM_DB_USER', 'opensim_user');
define('OPENSIM_DB_PASS', 'opensim_pass');
define('OPENSIM_DB_MYSQLI', 1);
// Please set MySQL DB access information for Helper Scripts
// If it is the same as the DB of OpenSim, you may not set these
define('HELPER_DB_HOST', 'localhost');
define('HELPER_DB_NAME', '');
define('HELPER_DB_USER', '');
define('HELPER_DB_PASS', '');
define('HELPER_DB_MYSQLI', 1);
// DB for External Modules
// Please set 'HELPER' or 'OPENSIM' or 'NONE'
// 'NONE' measns that to use OpenSim standard modules
define('OSPROFILE_DB', 'OPENSIM');
define('OSSEARCH_DB', 'OPENSIM');
define('MESSAGE_DB', 'OPENSIM');
define('XMLGROUP_DB', 'OPENSIM'); // XMLGROUP means Flotsam XmlRpc Group function
// Flotsam XMLRPC Group Module Access Keys
// If you use Flotsam XMLRPC Group Module, please set same keys with at [Groups] section in OpenSim.ini
define('XMLGROUP_RKEY', '1234'); // Read Key
define('XMLGROUP_WKEY', '1234'); // Write key
// for DTL/NSL Money Module
define('USE_CURRENCY_SERVER', 1);
// DTL/NSL Money Server Access Key
// Please set same key with MoneyScriptAccessKey in MoneyServer.ini
define('CURRENCY_SCRIPT_KEY', '123456789');
//
define('OPENSIM_PG_ONLY', 0);
define('USE_UTC_TIME', 0);
define('DATE_FORMAT', 'd.m.Y - H:i');
// Select script. Set 1 or 2 (1: 4 images, 2: 8 images).
// See helper/loginscreen/imageswitch1.js or imageswitch2.js
define('LOGINPAGE_SCRIPT', 1);
//////////////////////////////////////////////////////////////////////////////////
// System
define('SYSURL', ENV_HELPER_URL);
$GLOBALS['xmlrpc_internalencoding'] = 'UTF-8';
if (USE_UTC_TIME) date_default_timezone_set('UTC');
//
if (!defined('ENV_READ_CONFIG')) define('ENV_READ_CONFIG', 'YES');
@@ -0,0 +1,79 @@
<?php
//
// Environment Interface for non Web Interface
// by Fumi.Iseki
//
//
if (!defined('ENV_READ_CONFIG')) require_once(realpath(dirname(__FILE__).'/../include/config.php'));
if ( defined('ENV_READ_DEFINE')) return;
$groups_config = realpath(ENV_HELPER_PATH.'/../include/xmlgroups_config.php');
$profile_config = realpath(ENV_HELPER_PATH.'/../include/profile_config.php');
$search_config = realpath(ENV_HELPER_PATH.'/../include/search_config.php');
$message_config = realpath(ENV_HELPER_PATH.'/../include/message_config.php');
if ($groups_config!='') require_once($groups_config);
if ($profile_config!='') require_once($profile_config);
if ($search_config!='') require_once($search_config);
if ($message_config!='') require_once($message_config);
//////////////////////////////////////////////////////////////////////////////////
// DB Table Name
// Offline Message and MuteList
define ('MUTE_LIST_TBL', MUTE_LIST_TBL_BASE);
define ('OFFLINE_MESSAGE_TBL', OFFLINE_MESSAGE_TBL_BASE);
// XML Group. see also xmlgroups_config.php
define('XMLGROUP_ACTIVE_TBL', XMLGROUP_ACTIVE_TBL_BASE);
define('XMLGROUP_LIST_TBL', XMLGROUP_LIST_TBL_BASE);
define('XMLGROUP_INVITE_TBL', XMLGROUP_INVITE_TBL_BASE);
define('XMLGROUP_MEMBERSHIP_TBL', XMLGROUP_MEMBERSHIP_TBL_BASE);
define('XMLGROUP_NOTICE_TBL', XMLGROUP_NOTICE_TBL_BASE);
define('XMLGROUP_ROLE_MEMBER_TBL', XMLGROUP_ROLE_MEMBER_TBL_BASE);
define('XMLGROUP_ROLE_TBL', XMLGROUP_ROLE_TBL_BASE);
// Avatar Profile. see also profile_config.php
define('PROFILE_CLASSIFIEDS_TBL', PROFILE_CLASSIFIEDS_TBL_BASE);
define('PROFILE_USERNOTES_TBL', PROFILE_USERNOTES_TBL_BASE);
define('PROFILE_USERPICKS_TBL', PROFILE_USERPICKS_TBL_BASE);
define('PROFILE_USERPROFILE_TBL', PROFILE_USERPROFILE_TBL_BASE);
define('PROFILE_USERSETTINGS_TBL', PROFILE_USERSETTINGS_TBL_BASE);
// Search the In World. see also search_config.php
define('SEARCH_ALLPARCELS_TBL', SEARCH_ALLPARCELS_TBL_BASE);
define('SEARCH_EVENTS_TBL', SEARCH_EVENTS_TBL_BASE);
define('SEARCH_HOSTSREGISTER_TBL', SEARCH_HOSTSREGISTER_TBL_BASE);
define('SEARCH_OBJECTS_TBL', SEARCH_OBJECTS_TBL_BASE);
define('SEARCH_PARCELS_TBL', SEARCH_PARCELS_TBL_BASE);
define('SEARCH_PARCELSALES_TBL', SEARCH_PARCELSALES_TBL_BASE);
define('SEARCH_POPULARPLACES_TBL', SEARCH_POPULARPLACES_TBL_BASE);
define('SEARCH_REGIONS_TBL', SEARCH_REGIONS_TBL_BASE);
if (defined('PROFILE_CLASSIFIEDS_TBL')) {
define('SEARCH_CLASSIFIEDS_TBL', PROFILE_CLASSIFIEDS_TBL);
}
//////////////////////////////////////////////////////////////////////////////////
// Event Categories
$Categories = array();
$Categories[0] = 'All Category';
$Categories[18] = 'Discussion';
$Categories[19] = 'Sports';
$Categories[20] = 'Live Music';
$Categories[22] = 'Commercial';
$Categories[23] = 'Entertainment';
$Categories[24] = 'Games/Contests';
$Categories[25] = 'Pageants';
$Categories[26] = 'Education';
$Categories[27] = 'Arts and Culture';
$Categories[28] = 'Charity/Support';
$Categories[29] = 'Miscellaneous';
if (!OPENSIM_PG_ONLY) $Categories[23] = 'Nightlife/'.$Categories[23];
//
if (!defined('ENV_READ_DEFINE')) define('ENV_READ_DEFINE', 'YES');
@@ -0,0 +1,65 @@
<?php
//
// Environment Library for non Web Interface
// by Fumi.Iseki
//
//
if (!defined('ENV_READ_CONFIG')) require_once(realpath(dirname(__FILE__).'/../include/config.php'));
if (!defined('ENV_READ_DEFINE')) require_once(realpath(ENV_HELPER_PATH.'/../include/env_define.php'));
require_once(realpath(ENV_HELPER_PATH.'/../include/tools.func.php'));
require_once(realpath(ENV_HELPER_PATH.'/../include/mysql.func.php'));
require_once(realpath(ENV_HELPER_PATH.'/../include/opensim.mysql.php'));
/////////////////////////////////////////////////////////////////////////////////
// Functions
//
function env_get_user_email($uid)
{
return "";
}
//
// Config Value
//
$env_config["currency_script_key"] = CURRENCY_SCRIPT_KEY;
function env_get_config($name)
{
global $env_config;
return $env_config[$name];
}
////////////////////////////////////////////////////////////
// for Login Page
if (isset($LOGINPAGE) and $LOGINPAGE)
{
$LOGIN_SCREEN_CONTENT = 'Welcome to My Grid';
$BOX_TITLE = 'Attention';
$BOX_COLOR = 'red';
$BOX_INFOTEXT = 'please rewrite env_lib.php';
$GRID_NAME = 'My Grid';
$REGION_TTL = 'My Regions';
$DB_STATUS_TTL = 'DB Status';
$ONLINE = ' ONLINE ';
$OFFLINE = ' OFFLINE ';
$TOTAL_USER_TTL = 'Total Users';
$TOTAL_REGION_TTL = 'Total Regions';
$LAST_USERS_TTL = 'Visitors last 30 days';
$ONLINE_TTL = 'Online Now';
$HG_ONLINE_TTL = 'Online HG';
}
@@ -0,0 +1 @@
<script>history.go(-1);</script>
@@ -0,0 +1,309 @@
<?php
//
// by Fumi.Iseki 2007/03/24
// 2012/04/12
// 2013/04/20
// 2013/09/21
// 2014/11/28
// 2016/05/26
// 2019/08/21
//
$jbxl_tools_ver = 2019082100;
//
if (!defined('JBXL_TOOLS_VER') and !defined('_JBXL_TOOLS')) {
define('JBXL_TOOLS_VER', $jbxl_tools_ver);
/****************************************************************************************
//
// function jbxl_to_subnetformats($strips)
// function jbxl_match_ipaddr($ip, $ipaddr_subnets)
// function jbxl_randstr($len=8, $lowcase=false)
//
// function jbxl_get_ipresolv_url($ip)
//
// function jbxl_get_url_params_array($urlstr)
// function jbxl_get_url_params_str($params, $amp=false)
// function jbxl_make_url($serverURI, $portnum=0)
//
*****************************************************************************************/
//
// IPアドレスを "," または半角空白で区切って記述した文字列から,有効なIPアドレス
// とサブネットを8bitずつ取り出す.CIDER対応
//
// 入力例:" 0.2.1.1/2 222.222.111.222/255., 123.31.6.000 202.26.156.2/20, 202.26.144.0/255.255.255.0 , "
//
// 戻り値:
// $return[index]['ipaddr'][0〜3の数] 8bit区切りの IPアドレス
// $return[index]['subnet'][0〜3の数] 8bit区切りの netmaskアドレス
//
function jbxl_to_subnetformats($strips)
{
$return = array();
$tmpips = preg_split("/[ ,]/ ", $strips);
foreach($tmpips as $value) {
if (!empty($value)) $ipfmts[] = $value;
}
if (empty($ipfmts)) return $return;
unset($tempips);
// omission of subnetmask
foreach($ipfmts as $ipfmt) {
$tempips = explode('/', $ipfmt);
if (empty($tempips[0])) continue;
if (empty($tempips[1])) {
$ips = explode('.', $tempips[0]);
$tempips[1] = '';
for ($i=0; $i<4; $i++) {
if (empty($ips[$i])) $tempips[1].= '0';
else $tempips[1].= '255';
if ($i!=3) $tempips[1].= '.';
}
unset($ips);
}
$ipaddr_subnets[] = $tempips;
}
if (empty($ipaddr_subnets)) return $return;
//
$index = 0;
foreach($ipaddr_subnets as $ipaddr_subnet) {
$ips = explode('.', $ipaddr_subnet[0]);
$sub = explode('.', $ipaddr_subnet[1]);
if (count($sub)==1 and $sub[0]<=32) { // CIDER -> SubnetMask
$cider = $sub[0];
$nbyte = (int)($cider/8);
$nbit = $cider - $nbyte*8;
for ($i=0; $i<$nbyte; $i++) {
$sub[$i] = 255;
}
if ($nbyte!=4) {
$nsub = 0;
$base = 128;
for ($i=0; $i<$nbit; $i++) {
$nsub += $base;
$base = $base/2;
}
$sub[$nbyte] = $nsub;
}
}
for ($i=0; $i<4; $i++) {
if (!empty($ips[$i])) $return[$index]['ipaddr'][$i] = (int)$ips[$i];
else $return[$index]['ipaddr'][$i] = (int)0;
if (!empty($sub[$i])) $return[$index]['subnet'][$i] = (int)$sub[$i];
else $return[$index]['subnet'][$i] = (int)0;
}
$index++;
}
return $return;
}
//
// $ip が $ipaddr_subnetsの中に含まれるか検査する.
// $ipaddr_subnets は jbxl_to_subnetformats()が出力したものを使用すること.
// $ip の内容の形式はチェックしない.これは呼び出し側の責任.
//
function jbxl_match_ipaddr($ip, array $ipaddr_subnets)
{
$ipa = explode('.', $ip);
if (empty($ipa)) return false;
for ($i=1; $i<4; $i++) {
if (empty($ipa[$i])) $ipa[$i] = 0;
}
foreach($ipaddr_subnets as $ipaddr_subnet) {
$ips = $ipaddr_subnet['ipaddr'];
$sub = $ipaddr_subnet['subnet'];
$match_f = true;
for ($i=0; $i<4; $i++) {
$check1 = $ipa[$i] & $sub[$i];
$check2 = $ips[$i] & $sub[$i];
if ($check1 != $check2) {
$match_f = false;
break;
}
}
if ($match_f) {
//print_r($ips);
//print_r($sub);
return true;
}
}
return false;
}
$JBXLBaseChar = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
function jbxl_randstr($len=8, $lowcase=false)
{
global $JBXLBaseChar;
if ($lowcase) $rndmax = 25;
else $rndmax = strlen($JBXLBaseChar) - 1;
$return = "";
for($i=0; $i<$len; $i++) {
$return .= $JBXLBaseChar{mt_rand(0, $rndmax)};
}
return $return;
}
function jbxl_get_ipresolv_url($ip, $region='APNIC')
{
if (!preg_match('/(^\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/', $ip, $match)) return '';
if ($match[1]>255 or $match[2]>255 or $match[3]>255 or $match[4]>255) return '';
if ($match[1]=='127' or $match[1]=='10') return '';
if ($match[1]=='172' and $match[2]>='16' and $match[2]<='31') return '';
if ($match[1]=='192' and $match[2]=='168') return '';
if ($region=='JPNIC') {
$url = 'http://whois.nic.ad.jp/cgi-bin/whois_gw?type=NET&key='.$ip; // JPNIC
}
else {
$url = 'http://wq.apnic.net/apnic-bin/whois.pl?searchtext='.$ip; // APNIC
}
return $url;
}
function jbxl_get_url_params_array($urlstr)
{
$strs = explode('?', $urlstr);
$parmstr = $strs[0];
if (array_key_exists(1, $strs)) $paramstr = $strs[1];
$ret = array();
$params = explode('&', $paramstr);
foreach($params as $param) {
if (substr($param, 0, 4)=='amp;') $param = substr($param, 5);
$temps = explode('=', $param);
$ret[$temps[0]] = '';
if (array_key_exists(1, $temps)) $ret[$temps[0]] = $temps[1];
}
return $ret;
}
//
// $params: パラメータの入っている配列
// $amp: 先頭文字を '&' にするか? false の場合は 先頭文字は '?'
//
function jbxl_get_url_params_str($params, $amp=false)
{
$ret = '';
if (!is_array($params)) return $ret;
$no = 0;
foreach($params as $key => $param) {
if ($no==0 and !$amp) {
$ret .= '?'.$key.'='.$param;
}
else {
$ret .= '&amp;'.$key.'='.$param;
}
$no++;
}
return $ret;
}
//
// 入力された FSDN, URL に対して http(s)://ABC.EFG:#/ の形を生成する
//
function jbxl_make_url($serverURI, $portnum=0)
{
$url = '';
$host = 'localhost';
$port = 80;
$protocol = 'http';
if ($serverURI!=null) {
$uri = preg_split("/[:\/]/", $serverURI);
// with http:// or https://
if (array_key_exists(3, $uri)) {
$protocol = $uri[0];
$host = $uri[3];
//
if (array_key_exists(4, $uri)) {
$port = $uri[4];
}
else {
if ($portnum!=0) {
$port = $portnum;
}
else {
if ($uri[0]=='http') $port = 80;
else if ($uri[0]=='https') $port = 443;
else if ($uri[0]=='ftp') $port = 21;
// else if ....
}
}
}
// with no http:// and https://
else {
$host = $uri[0];
if (array_key_exists(1, $uri)) {
$port = $uri[1];
}
else {
if ($portnum!=0) {
$port = $portnum;
}
else {
$port = 80;
}
}
}
//
if ($port==443) {
$url = 'https://'.$host.':'.$port.'/';
$protocol = 'https';
}
else if ($port==80) {
$url = 'http://'.$host.'/';
$protocol = 'http';
}
else if ($port==21) {
$url = 'ftp://'.$host.'/';
$protocol = 'ftp';
}
else {
$url = $protocol.'://'.$host.':'.$port.'/';
}
}
$server['url'] = $url;
$server['host'] = $host;
$server['port'] = $port;
$server['porotocol'] = $protocol;
return $server;
}
} // !defined('JBXL_TOOLS_VER')
@@ -0,0 +1,382 @@
<?php
class DB
{
var $Host = null; // Hostname of our MySQL server
var $Database = null; // Logical database name on that server
var $User = null; // Database user
var $Password = null; // Database user's password
var $Link_ID = null; // Result of mysql_connect()/mysqli_connect()
var $Query_ID = null; // Result of most recent mysql_query()/mysqli_query()
var $Record = array(); // Current mysql_fetch_array()/mysqli_fetch_array() -result
var $Row; // Current row number
var $Errno = 0; // Error state of query
var $Error = '';
var $UseMySQLi = false;
var $Timeout; // not implement yet
/*
function DB($dbhost=null, $dbname=null, $dbuser=null, $dbpass=null, $usemysqli=true, $timeout=60)
{
__construct($dbhost, $dbname, $dbuser, $dbpass, $usemysqli, $timeout);
}
*/
function __construct($dbhost=null, $dbname=null, $dbuser=null, $dbpass=null, $usemysqli=true, $timeout=60)
{
$this->Host = $dbhost;
$this->Database = $dbname;
$this->User = $dbuser;
$this->Password = $dbpass;
$this->UseMySQLi= $usemysqli;
$this->Timeout = $timeout;
ini_set('mysql.connect_timeout', $timeout);
}
function set_DB($dbhost, $dbname, $dbuser, $dbpass, $usemysqli=false)
{
$this->Host = $dbhost;
$this->Database = $dbname;
$this->User = $dbuser;
$this->Password = $dbpass;
$this->UseMySQLi= $usemysqli;
}
function halt($msg)
{
echo "<strong>DB ERROR :</strong> $msg<br />\n";
echo "<strong>MySQL ERROR:</strong> $this->Error ($this->Errno)<br />\n";
die('Session Halted.');
}
function connect()
{
if ($this->Link_ID==null) {
//
if (!$this->UseMySQLi) {
$this->Link_ID = mysql_connect($this->Host, $this->User, $this->Password);
if (!$this->Link_ID) {
$this->Errno = 999;
//error_log('cannot select database. 1/2');
return false;
}
mysql_set_charset('utf8');
$SelectResult = mysql_select_db($this->Database, $this->Link_ID);
if (!$SelectResult) {
$this->Errno = mysql_errno($this->Link_ID);
$this->Error = mysql_error($this->Link_ID);
$this->Link_ID = null;
//$this->halt('cannot select database <i>'.$this->Database.'</i>');
//error_log('cannot select database. 2/2');
return false;
}
}
//
else {
$this->Link_ID = mysqli_connect($this->Host, $this->User, $this->Password, $this->Database);
if (!$this->Link_ID) {
$this->Errno = 999;
$this->Error = mysqli_connect_error();
//$this->halt('cannot select database <i>'.$this->Database.'</i>');
//error_log('cannot select database.');
return false;
}
mysqli_set_charset($this->Link_ID, 'utf8');
}
}
return true;
}
function escape($String)
{
$this->connect();
if (!$this->UseMySQLi) return mysql_real_escape_string($String);
return mysqli_real_escape_string($this->Link_ID, $String);
}
function query($Query_String)
{
$this->connect();
if ($this->Errno!=0) return 0;
if (!$this->UseMySQLi) {
$this->Query_ID = mysql_query($Query_String, $this->Link_ID);
$this->Errno = mysql_errno($this->Link_ID);
$this->Error = mysql_error($this->Link_ID);
}
else {
$this->Query_ID = mysqli_query($this->Link_ID, $Query_String);
$this->Errno = mysqli_errno($this->Link_ID);
$this->Error = mysqli_error($this->Link_ID);
}
$this->Row = 0;
//
if (!$this->Query_ID) {
$this->halt('Invalid SQL: '.$Query_String);
}
return $this->Query_ID;
}
function next_record()
{
if (!$this->UseMySQLi) {
$this->Record = @mysql_fetch_array($this->Query_ID);
$this->Row += 1;
$this->Errno = mysql_errno($this->Link_ID);
$this->Error = mysql_error($this->Link_ID);
$stat = is_array($this->Record);
if (!$stat) {
@mysql_free_result($this->Query_ID);
$this->Query_ID = null;
}
}
else {
$this->Record = @mysqli_fetch_array($this->Query_ID);
$this->Row += 1;
$this->Errno = mysqli_errno($this->Link_ID);
$this->Error = mysqli_error($this->Link_ID);
$stat = is_array($this->Record);
if (!$stat) {
@mysqli_free_result($this->Query_ID);
$this->Query_ID = null;
}
}
return $this->Record;
}
function insert_record($table, $params)
{
if (!is_array($params)) return false;
$num = 0;
$keys = '';
$vals = '';
foreach ($params as $key => $value) {
if ($num==0) {
$keys = $key;
$vals = "'".$value."'";
}
else {
$keys .= ','.$key;
$vals .= ",'".$value."'";
}
$num++;
}
$this->query('INSERT INTO '.$table.' ('.$keys.') VALUES ('.$vals.')');
if ($this->Errno==0) return true;
return false;
}
// params配列の一番最初の要素が キー
function update_record($table, $params)
{
if (!is_array($params)) return false;
$num = 0;
$where = '';
$setval = '';
foreach ($params as $key => $value) {
if ($num==0) {
$where = $key."='".$value."'";
}
else if ($num==1) {
$setval = $key."='".$value."'";
}
else {
$setval .= ','.$key."='".$value."'";
}
$num++;
}
$this->query('UPDATE '.$table.' SET '.$setval.' WHERE '.$where);
if ($this->Errno==0) return true;
return false;
}
function num_rows()
{
if (!$this->UseMySQLi) return mysql_num_rows($this->Query_ID);
return mysqli_num_rows($this->Query_ID);
}
function affected_rows()
{
if (!$this->UseMySQLi) return mysql_affected_rows($this->Link_ID);
return mysqli_affected_rows($this->Link_ID);
}
function optimize($tbl_name)
{
$this->connect();
if ($this->Errno!=0) return;
if (!$this->UseMySQLi) {
$this->Query_ID = @mysql_query('OPTIMIZE TABLE '.$tbl_name, $this->Link_ID);
}
else {
$this->Query_ID = @mysqli_query($this->Link_ID, 'OPTIMIZE TABLE '.$tbl_name);
}
}
function clean_results()
{
if ($this->Query_ID!=null) {
if (!$this->UseMySQLi) {
mysql_freeresult($this->Query_ID);
}
else {
mysqli_freeresult($this->Query_ID);
}
$this->Query_ID = null;
}
}
function close()
{
/*
if ($this->Link_ID) {
if (!$this->UseMySQLi) mysql_close($this->Link_ID);
mysqli_close($this->Link_ID);
$this->Link_ID = null;
}
*/
}
function exist_table($table, $lower_case=true)
{
$ret = false;
if ($lower_case) $table = strtolower($table);
$this->query('SHOW TABLES');
if ($this->Errno==0) {
while (list($db_tbl) = $this->next_record()) {
if ($lower_case) $db_tbl = strtolower($db_tbl);
if ($db_tbl==$table) {
$ret = true;
break;
}
}
}
return $ret;
}
function exist_field($table, $field, $lower_case=true)
{
$ret1 = false;
$ret2 = false;
if ($lower_case) $cmp_table = strtolower($table);
else $cmp_table = $table;
$this->query('SHOW TABLES');
if ($this->Errno==0) {
while (list($db_tbl) = $this->next_record()) {
if ($lower_case) $db_tbl = strtolower($db_tbl);
if ($db_tbl==$cmp_table) {
$ret1 = true;
break;
}
}
}
if ($ret1) {
$this->query('SHOW COLUMNS FROM '.$table);
if ($this->Errno==0) {
while (list($db_fld) = $this->next_record()) {
if ($db_fld==$field) {
$ret2 = true;
break;
}
}
}
}
return $ret2;
}
//
// InnoDB では Update_time は NULL になる!
//
function get_update_time($table, $unixtime=true)
{
$update = '';
if ($unixtime) $update = 0;
$this->query("SHOW TABLE STATUS WHERE name='$table'");
if ($this->Errno==0) {
$table_status = $this->next_record();
$update = $table_status['Update_time'];
if ($unixtime) {
if ($update!='') $update = strtotime($update);
else $update = 0;
}
}
return $update;
}
//
// Lock
//
function lock_table($table, $mode='write')
{
$this->query("LOCK TABLES ".$table." ".$mode);
}
function unlock_table()
{
$this->query("UNLOCK TABLES");
}
//
// Timeout
//
function set_default_timeout($tm)
{
ini_set('mysql.connect_timeout', $tm);
$this->Timeout = $tm;
}
function set_temp_timeout($tm)
{
ini_set('mysql.connect_timeout', $tm);
}
function reset_timeout()
{
ini_set('mysql.connect_timeout', $this->Timeout);
}
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,224 @@
<?php
/****************************************************************
* tools.func.php v1.0.0
* by Fumi.Iseki (c) 2010 5/13
*
* http://www.nsl.tuis.ac.jp/
*
****************************************************************/
/****************************************************************
* Function List
function isNumeric($str, $nullok=false)
function isAlphabetNumeric($str, $nullok=false)
function isAlphabetNumericSpecial($str, $nullok=false)
function isGUID($uuid, $nullok=false)
function split_key_value($str)
function make_random_hash()
function make_random_guid()
function j2k_to_tga($file, $iscopy=true)
function get_j2k_to_tga_command() // need j2k_to_image (OpenJpeg)
function get_image_size_convert_command($xsize, $ysize)
function find_command_path($command)
****************************************************************/
function isNumeric($str, $nullok=false)
{
if ($str!='0' and $str==null) return $nullok;
if (!preg_match('/^[0-9\.]+$/', $str)) return false;
return true;
}
function isAlphabetNumeric($str, $nullok=false)
{
if ($str!='0' and $str==null) return $nullok;
if (!preg_match('/^\w+$/', $str)) return false;
return true;
}
function isAlphabetNumericSpecial($str, $nullok=false)
{
if ($str!='0' and $str==null) return $nullok;
//if (!preg_match('/^[_a-zA-Z0-9 &@%#\-\.]+$/', $str)) return false;
if (!preg_match('/^[_a-zA-Z0-9 !&@%#\-\.\$]+$/', $str)) return false;
return true;
}
function isGUID($uuid, $nullok=false)
{
if ($uuid==null) return $nullok;
if (!preg_match('/^[0-9A-Fa-f]{8,8}-[0-9A-Fa-f]{4,4}-[0-9A-Fa-f]{4,4}-[0-9A-Fa-f]{4,4}-[0-9A-Fa-f]{12,12}$/', $uuid)) return false;
return true;
}
function make_random_hash()
{
$ret = sprintf('%04x%04x%04x%04x%04x%04x%04x%04x',mt_rand(0,0xffff),mt_rand(0,0xffff),mt_rand(0,0xffff),mt_rand(0,0xffff),
mt_rand(0,0xffff),mt_rand(0,0xffff),mt_rand(0,0xffff),mt_rand(0,0xffff));
return $ret;
}
function make_random_guid()
{
$uuid = sprintf( '%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
mt_rand( 0, 0xffff ), mt_rand( 0, 0xffff ), mt_rand( 0, 0xffff ),
mt_rand( 0, 0x0fff ) | 0x4000,
mt_rand( 0, 0x3fff ) | 0x8000,
mt_rand( 0, 0xffff ), mt_rand( 0, 0xffff ), mt_rand( 0, 0xffff ) );
return $uuid;
}
///////////////////////////////////////////////////////////////////////////////////////////////////
//
// String Tools
//
// parse {"key1":"value1","key2":{"key3":"value3"}}
//
// --> [key1] => value1
// [key2] => Array
// (
// [key3] => value3
// )
//
function split_key_value($str)
{
$info = array();
$str = trim($str);
if (substr($str, 0, 1)=='{' and substr($str, -1)=='}') {
$str = substr($str, 1, -1);
$inbrkt = 0;
$inquot = false;
$inkkko = false;
$isakey = true;
$key = "";
$val = "";
for ($i=0; $i<strlen($str); $i++) {
$cc = substr($str, $i, 1);
if ($inbrkt==0 and !$inquot and ($cc=='"' or $cc=='\'')) {
$inquot = true;
}
else if ($inbrkt==0 and $inquot and ($cc=='"' or $cc=='\'')) {
$inquot = false;
}
else if ($inbrkt==0 and $isakey and !$inquot and !$inkkko and $cc==':') {
$isakey = false;
}
else if ($inbrkt==0 and !$isakey and !$inquot and !$inkkko and $cc==',') {
if (substr($val, 0, 1)=='{' and substr($val, -1)=='}') {
$info[$key] = split_key_value($val);
}
else $info[$key] = $val;
$isakey = true;
$key = "";
$val = "";
}
else {
if ($cc=='{') $inbrkt++;
else if ($cc=='}') $inbrkt--;
else {
if ($inbrkt==0 and !$inkkko and $cc=='[') $inkkko = true;
else if ($inbrkt==0 and $inkkko and $cc==']') $inkkko = false;
}
if ($isakey) $key .= $cc;
else $val .= $cc;
}
}
//
if ($key!="") {
if (substr($val, 0, 1)=='{' and substr($val, -1)=='}') {
$info[$key] = split_key_value($val);
}
else $info[$key] = $val;
}
}
return $info;
}
///////////////////////////////////////////////////////////////////////////////////////////////////
//
// Image
//
//
// Convert Image from JPEG2000 to TGA
// file -> file.tga
//
function j2k_to_tga($file, $iscopy=true)
{
if (!file_exists($file)) return false;
$com_totga = get_j2k_to_tga_command();
if ($com_totga=='') return false;
if ($iscopy) $ret = copy ($file, $file.'.j2k');
else $ret = rename($file, $file.'.j2k');
if (!$ret) return false;
exec("$com_totga -i $file.j2k -o $file.tga 1>/dev/null 2>&1");
unlink($file.'.j2k');
return true;
}
function get_j2k_to_tga_command()
{
$command = find_command_path('j2k_to_image');
return $command;
}
//
// Image Size Convert Command String
//
function get_image_size_convert_command($xsize, $ysize)
{
if (!isNumeric($xsize) or !isNumeric($ysize)) return '';
$command = find_command_path('convert');
if ($command=='') return '';
$prog = $command.' - -geometry '.$xsize.'x'.$ysize.'! -';
return $prog;
}
function find_command_path($command)
{
$path = '';
if (file_exists('/usr/local/bin/'.$command)) $path = '/usr/local/bin/';
else if (file_exists('/usr/bin/'.$command)) $path = '/usr/bin/';
else if (file_exists('/usr/X11R6/bin/'.$command)) $path = '/usr/X11R6/bin/';
else if (file_exists('/bin/'.$command)) $path = '/bin/';
else return '';
return $path.$command;
}
@@ -0,0 +1,54 @@
<?php
//
// Group DB configration by Fumi.Iseki
//
// default
$XMLGRP_DB_HOST = OPENSIM_DB_HOST;
$XMLGRP_DB_NAME = OPENSIM_DB_NAME;
$XMLGRP_DB_USER = OPENSIM_DB_USER;
$XMLGRP_DB_PASS = OPENSIM_DB_PASS;
$XMLGRP_DB_MYSQLI = OPENSIM_DB_MYSQLI;
if (XMLGROUP_DB=='HELPER' and defined('HELPER_DB_NAME')) {
$XMLGRP_DB_HOST = HELPER_DB_HOST;
$XMLGRP_DB_NAME = HELPER_DB_NAME;
$XMLGRP_DB_USER = HELPER_DB_USER;
$XMLGRP_DB_PASS = HELPER_DB_PASS;
$XMLGRP_DB_MYSQLI = HELPER_DB_MYSQLI;
}
// Access Key
if (defined('XMLGROUP_RKEY')) {
$GroupReadKey = XMLGROUP_RKEY;
$GroupWriteKey = XMLGROUP_WKEY;
}
else {
$GroupReadKey = '1234';
$GroupWriteKey = '1234';
}
$GroupRequireAgentAuthForWrite = false;
$GroupEnforceGroupPerms = false;
//
if (XMLGROUP_DB=='HELPER' or XMLGROUP_DB=='OPENSIM') {
define('XMLGROUP_ACTIVE_TBL_BASE', 'group_active');
define('XMLGROUP_INVITE_TBL_BASE', 'group_invite');
define('XMLGROUP_LIST_TBL_BASE', 'group_list');
define('XMLGROUP_MEMBERSHIP_TBL_BASE', 'group_membership');
define('XMLGROUP_NOTICE_TBL_BASE', 'group_notice');
define('XMLGROUP_ROLE_TBL_BASE', 'group_role');
define('XMLGROUP_ROLE_MEMBER_TBL_BASE', 'group_rolemembership');
}
else { // NONE (OpenSim Group V2 Module)
define('XMLGROUP_ACTIVE_TBL_BASE', 'os_groups_principals');
define('XMLGROUP_INVITE_TBL_BASE', 'os_groups_invites');
define('XMLGROUP_LIST_TBL_BASE', 'os_groups_groups');
define('XMLGROUP_MEMBERSHIP_TBL_BASE', 'os_groups_membership');
define('XMLGROUP_NOTICE_TBL_BASE', 'os_groups_notices');
define('XMLGROUP_ROLE_TBL_BASE', 'os_groups_roles');
define('XMLGROUP_ROLE_MEMBER_TBL_BASE', 'os_groups_rolemembership');
}
+7
View File
@@ -0,0 +1,7 @@
### Derzeit sind mir keine funktionierenden helper Dateien bekannt.
Sollten sie welche kennen teilen sie es mir bitte hier als issues mit.
### At the moment I don't know of any working helper files.
If you know any, please tell me here as issues.
+7
View File
@@ -0,0 +1,7 @@
# Building
Copy Directory folder /bin to /opensim
Copy Directory folder /ThirdParty to /opensim
Add money-prebuild.xml to prebuild.xml:
@@ -0,0 +1,71 @@
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSim Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
//using System.Linq;
using System.Text;
using OpenMetaverse;
namespace OpenSim.Data.MySQL.MySQLMoneyDataWrapper
{
public interface IMoneyManager
{
int getBalance(string userID);
//int getBalanceStatus(string userID);
//bool updateBalanceStatus(string userID,int status);
bool withdrawMoney(UUID transactionID,string senderID, int amount);
bool giveMoney(UUID transactionID,string receiverID, int amount);
bool addTransaction(TransactionData transaction);
bool updateTransactionStatus(UUID transactionID, int status,string description);
TransactionData FetchTransaction(UUID transactionID);
TransactionData[] FetchTransaction(string userID, int startTime, int endTime, uint index,uint retNum);
int getTransactionNum(string userID, int startTime, int endTime);
bool addUser(string userID, int balance, int status, int type);
bool SetTransExpired(int deadTime);
bool ValidateTransfer(string secureCode, UUID transactionID);
bool addUserInfo(UserInfo user);
UserInfo fetchUserInfo(string userID);
bool updateUserInfo(UserInfo user);
}
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,52 @@
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Threading;
namespace OpenSim.Data.MySQL.MySQLMoneyDataWrapper
{
// This bit of code is from OpenSim.Data.MySQLSuperManager
public class MySQLSuperManager
{
public bool Locked;
private readonly Mutex m_lock = new Mutex(false);
public MySQLMoneyManager Manager;
public string Running;
public void GetLock()
{
Locked = true;
m_lock.WaitOne();
}
public void Release()
{
m_lock.ReleaseMutex();
Locked = false;
}
}
}
@@ -0,0 +1,36 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("OpenSim.Data.MySQL.MySQLMoneyDataWrapper")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("OpenSim.Data.MySQL.MySQLMoneyDataWrapper")]
[assembly: AssemblyCopyright("Copyright © Microsoft 2009")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("03f4a266-2e30-47e4-b785-ff02cdb4bbb9")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
@@ -0,0 +1,237 @@
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSim Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Text;
using OpenMetaverse;
namespace OpenSim.Data.MySQL.MySQLMoneyDataWrapper
{
public class TransactionData
{
UUID m_uuid;
string m_sender = string.Empty;
string m_receiver = string.Empty;
int m_amount;
int m_senderBalance;
int m_receiverBalance;
int m_type;
int m_time;
int m_status;
string m_objectID = UUID.Zero.ToString();
// string m_objectID = "00000000-0000-0000-0000-000000000000";
string m_objectName = string.Empty;
string m_regionHandle = string.Empty;
string m_regionUUID = string.Empty;
string m_secureCode = string.Empty;
string m_commonName = string.Empty;
string m_description = string.Empty;
/*
public TransactionData(string uuid, string sender, string receiver,
int amount, int time, int status, string description)
{
this.m_uuid = uuid;
this.m_sender = sender;
this.m_receiver = receiver;
this.m_amount = amount;
}
*/
public UUID TransUUID
{
get { return m_uuid; }
set { m_uuid = value; }
}
public string Sender
{
get { return m_sender; }
set { m_sender = value; }
}
public string Receiver
{
get { return m_receiver; }
set { m_receiver = value; }
}
public int Amount
{
get { return m_amount; }
set { m_amount = value; }
}
public int SenderBalance
{
get { return m_senderBalance; }
set { m_senderBalance = value; }
}
public int ReceiverBalance
{
get { return m_receiverBalance; }
set { m_receiverBalance = value; }
}
public int Type
{
get { return m_type; }
set { m_type = value; }
}
public int Time
{
get { return m_time; }
set { m_time = value; }
}
public int Status
{
get { return m_status; }
set { m_status = value; }
}
public string Description
{
get { return m_description; }
set { m_description = value; }
}
public string ObjectUUID
{
get { return m_objectID; }
set { m_objectID = value; }
}
public string ObjectName
{
get { return m_objectName; }
set { m_objectName = value; }
}
public string RegionHandle
{
get { return m_regionHandle; }
set { m_regionHandle = value; }
}
public string RegionUUID
{
get { return m_regionUUID; }
set { m_regionUUID = value; }
}
public string SecureCode
{
get { return m_secureCode; }
set { m_secureCode = value; }
}
public string CommonName
{
get { return m_commonName; }
set { m_commonName = value; }
}
}
public enum Status
{
SUCCESS_STATUS = 0,
PENDING_STATUS = 1,
FAILED_STATUS = 2,
ERROR_STATUS = 9
}
public enum AvatarType
{
LOCAL_AVATAR = 0,
HG_AVATAR = 1,
NPC_AVATAR = 2,
GUEST_AVATAR = 3,
FOREIGN_AVATAR = 8,
UNKNOWN_AVATAR = 9
}
public class UserInfo
{
string m_userID = string.Empty;
string m_simIP = string.Empty;
string m_avatarName = string.Empty;
string m_passwordHash = string.Empty;
int m_avatarType = (int)AvatarType.LOCAL_AVATAR;
int m_avatarClass = (int)AvatarType.LOCAL_AVATAR;
string m_serverURL = string.Empty;
public string UserID
{
get { return m_userID; }
set { m_userID = value; }
}
public string SimIP
{
get { return m_simIP; }
set { m_simIP = value; }
}
public string Avatar
{
get { return m_avatarName; }
set { m_avatarName = value; }
}
public string PswHash
{
get { return m_passwordHash; }
set { m_passwordHash = value; }
}
public int Type
{
get { return m_avatarType; }
set { m_avatarType = value; }
}
public int Class
{
get { return m_avatarClass; }
set { m_avatarClass = value; }
}
public string ServerURL
{
get { return m_serverURL; }
set { m_serverURL = value; }
}
}
}
@@ -0,0 +1,70 @@
/*
* Copyright (c) Contributors, http://opensimulator.org/, http://www.nsl.tuis.ac.jp/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSim Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
//using System.Linq;
using System.Text;
using OpenMetaverse;
using OpenSim.Data.MySQL.MySQLMoneyDataWrapper;
namespace OpenSim.Grid.MoneyServer
{
public interface IMoneyDBService
{
int getBalance(string userID);
bool withdrawMoney(UUID transactionID, string senderID, int amount);
bool giveMoney(UUID transactionID, string receiverID, int amount);
bool addTransaction(TransactionData transaction);
bool addUser(string userID, int balance, int status, int type);
bool updateTransactionStatus(UUID transactionID, int status, string description);
bool SetTransExpired(int deadTime);
bool ValidateTransfer(string secureCode, UUID transactionID);
TransactionData FetchTransaction(UUID transactionID);
TransactionData FetchTransaction(string userID, int startTime, int endTime, int lastIndex);
int getTransactionNum(string userID, int startTime, int endTime);
bool DoTransfer(UUID transactionUUID);
bool DoAddMoney(UUID transactionUUID); // Added by Fumi.Iseki
bool TryAddUserInfo(UserInfo user);
UserInfo FetchUserInfo(string userID);
}
}
@@ -0,0 +1,52 @@
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSim Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
//using System.Linq;
using System.Text;
using OpenSim.Framework.Servers;
using OpenSim.Framework.Servers.HttpServer;
using Nini.Config;
namespace OpenSim.Grid.MoneyServer
{
public interface IMoneyServiceCore
{
BaseHttpServer GetHttpServer();
Dictionary<string, string> GetSessionDic();
Dictionary<string, string> GetSecureSessionDic();
Dictionary<string, string> GetWebSessionDic();
//
IConfig GetServerConfig();
IConfig GetCertConfig();
bool IsCheckClientCert();
}
}
@@ -0,0 +1,574 @@
/*
* Copyright (c) Contributors, http://opensimulator.org/, http://www.nsl.tuis.ac.jp/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSim Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Text;
using OpenSim.Data.MySQL.MySQLMoneyDataWrapper;
using OpenSim.Modules.Currency;
using log4net;
using System.Reflection;
using OpenMetaverse;
namespace OpenSim.Grid.MoneyServer
{
#pragma warning disable 0168
class MoneyDBService : IMoneyDBService
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private string m_connect;
//private MySQLMoneyManager m_moneyManager;
private long TicksToEpoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).Ticks;
// DB manager pool
protected Dictionary<int, MySQLSuperManager> m_dbconnections = new Dictionary<int, MySQLSuperManager>(); // Lock付
private int m_maxConnections;
public int m_lastConnect = 0;
public MoneyDBService(string connect)
{
m_connect = connect;
Initialise(m_connect,10);
}
public MoneyDBService()
{
}
public void Initialise(string connectionString, int maxDBConnections)
{
m_connect = connectionString;
m_maxConnections = maxDBConnections;
if (connectionString != string.Empty) {
//m_moneyManager = new MySQLMoneyManager(connectionString);
//m_log.Info("Creating " + m_maxConnections + " DB connections...");
for (int i=0; i<m_maxConnections; i++) {
//m_log.Info("Connecting to DB... [" + i + "]");
MySQLSuperManager msm = new MySQLSuperManager();
msm.Manager = new MySQLMoneyManager(connectionString);
m_dbconnections.Add(i, msm);
}
}
else {
m_log.Error("[MONEY DB]: Connection string is null, initialise database failed");
throw new Exception("Failed to initialise MySql database");
}
}
public void Reconnect()
{
for (int i=0; i<m_maxConnections; i++) {
MySQLSuperManager msm = m_dbconnections[i];
msm.Manager.Reconnect();
}
}
private MySQLSuperManager GetLockedConnection()
{
int lockedCons = 0;
while (true) {
m_lastConnect++;
// Overflow protection
if (m_lastConnect==int.MaxValue) m_lastConnect = 0;
MySQLSuperManager msm = m_dbconnections[m_lastConnect%m_maxConnections];
if (!msm.Locked) {
msm.GetLock();
return msm;
}
lockedCons++;
if (lockedCons>m_maxConnections) {
lockedCons = 0;
System.Threading.Thread.Sleep(1000); // Wait some time before searching them again.
m_log.Debug("WARNING: All threads are in use. Probable cause: Something didnt release a mutex properly, or high volume of requests inbound.");
}
}
}
public int getBalance(string userID)
{
MySQLSuperManager dbm = GetLockedConnection();
try {
return dbm.Manager.getBalance(userID);
}
catch (MySql.Data.MySqlClient.MySqlException e) {
dbm.Manager.Reconnect();
return dbm.Manager.getBalance(userID);
}
catch(Exception e) {
m_log.Error(e.ToString());
return 0;
}
finally {
dbm.Release();
}
}
public bool withdrawMoney(UUID transactionID, string senderID, int amount)
{
MySQLSuperManager dbm = GetLockedConnection();
try {
return dbm.Manager.withdrawMoney(transactionID, senderID, amount);
}
catch (MySql.Data.MySqlClient.MySqlException e) {
dbm.Manager.Reconnect();
return dbm.Manager.withdrawMoney(transactionID, senderID, amount);
}
catch (Exception e) {
m_log.Error(e.ToString());
return false;
}
finally {
dbm.Release();
}
}
public bool giveMoney(UUID transactionID, string receiverID, int amount)
{
MySQLSuperManager dbm = GetLockedConnection();
try {
return dbm.Manager.giveMoney(transactionID, receiverID, amount);
}
catch (MySql.Data.MySqlClient.MySqlException e) {
dbm.Manager.Reconnect();
return dbm.Manager.giveMoney(transactionID, receiverID, amount);
}
catch (Exception e) {
m_log.Error(e.ToString());
return false;
}
finally {
dbm.Release();
}
}
public bool setTotalSale(TransactionData transaction)
{
if (transaction.Receiver==transaction.Sender) return false;
if (transaction.Sender==UUID.Zero.ToString()) return false;
MySQLSuperManager dbm = GetLockedConnection();
int time = (int)((DateTime.UtcNow.Ticks - TicksToEpoch) / 10000000);
try {
return dbm.Manager.setTotalSale(transaction.Receiver, transaction.ObjectUUID, transaction.Type, 1, transaction.Amount, time);
}
catch (MySql.Data.MySqlClient.MySqlException e) {
dbm.Manager.Reconnect();
return dbm.Manager.setTotalSale(transaction.Receiver, transaction.ObjectUUID, transaction.Type, 1, transaction.Amount, time);
}
catch (Exception e) {
m_log.Error(e.ToString());
return false;
}
finally {
dbm.Release();
}
}
public bool addTransaction(TransactionData transaction)
{
MySQLSuperManager dbm = GetLockedConnection();
try {
return dbm.Manager.addTransaction(transaction);
}
catch (MySql.Data.MySqlClient.MySqlException e) {
dbm.Manager.Reconnect();
return dbm.Manager.addTransaction(transaction);
}
catch (Exception e) {
m_log.Error(e.ToString());
return false;
}
finally {
dbm.Release();
}
}
public bool addUser(string userID, int balance, int status, int type)
{
TransactionData transaction = new TransactionData();
transaction.TransUUID = UUID.Random();
transaction.Sender = UUID.Zero.ToString();
transaction.Receiver = userID;
transaction.Amount = balance;
transaction.ObjectUUID = UUID.Zero.ToString();
transaction.ObjectName = string.Empty;
transaction.RegionHandle = string.Empty;
transaction.Type = (int)TransactionType.BirthGift;
transaction.Time = (int)((DateTime.UtcNow.Ticks - TicksToEpoch) / 10000000);;
transaction.Status = (int)Status.PENDING_STATUS;
transaction.SecureCode = UUID.Random().ToString();
transaction.CommonName = string.Empty;
transaction.Description = "addUser " + DateTime.UtcNow.ToString();
bool ret = addTransaction(transaction);
if (!ret) return false;
//
MySQLSuperManager dbm = GetLockedConnection();
try {
ret = dbm.Manager.addUser(userID, 0, status, type); // make Balance Table
}
catch (MySql.Data.MySqlClient.MySqlException e) {
dbm.Manager.Reconnect();
ret = dbm.Manager.addUser(userID, 0, status, type); // make Balance Table
}
catch (Exception e) {
m_log.Error(e.ToString());
return false;
}
finally {
dbm.Release();
}
//
if (ret) ret = giveMoney(transaction.TransUUID, userID, balance);
return ret;
}
public bool updateTransactionStatus(UUID transactionID, int status, string description)
{
MySQLSuperManager dbm = GetLockedConnection();
try {
return dbm.Manager.updateTransactionStatus(transactionID, status, description);
}
catch (MySql.Data.MySqlClient.MySqlException e) {
dbm.Manager.Reconnect();
return dbm.Manager.updateTransactionStatus(transactionID, status, description);
}
catch (Exception e) {
m_log.Error(e.ToString());
return false;
}
finally {
dbm.Release();
}
}
public bool SetTransExpired(int deadTime)
{
MySQLSuperManager dbm = GetLockedConnection();
try {
return dbm.Manager.SetTransExpired(deadTime);
}
catch (MySql.Data.MySqlClient.MySqlException e) {
dbm.Manager.Reconnect();
return dbm.Manager.SetTransExpired(deadTime);
}
catch (Exception e) {
m_log.Error(e.ToString());
return false;
}
finally {
dbm.Release();
}
}
public bool ValidateTransfer(string secureCode, UUID transactionID)
{
MySQLSuperManager dbm = GetLockedConnection();
try {
return dbm.Manager.ValidateTransfer(secureCode, transactionID);
}
catch (MySql.Data.MySqlClient.MySqlException e) {
dbm.Manager.Reconnect();
return dbm.Manager.ValidateTransfer(secureCode, transactionID);
}
catch (Exception e) {
m_log.Error(e.ToString());
return false;
}
finally {
dbm.Release();
}
}
public TransactionData FetchTransaction(UUID transactionID)
{
MySQLSuperManager dbm = GetLockedConnection();
try {
return dbm.Manager.FetchTransaction(transactionID);
}
catch (MySql.Data.MySqlClient.MySqlException e) {
dbm.Manager.Reconnect();
return dbm.Manager.FetchTransaction(transactionID);
}
catch (Exception e) {
m_log.Error(e.ToString());
return null;
}
finally {
dbm.Release();
}
}
public TransactionData FetchTransaction(string userID, int startTime, int endTime, int lastIndex)
{
MySQLSuperManager dbm = GetLockedConnection();
TransactionData[] arrTransaction;
uint index = 0;
if (lastIndex>=0) index = Convert.ToUInt32(lastIndex) + 1;
try {
arrTransaction = dbm.Manager.FetchTransaction(userID, startTime, endTime, index, 1);
}
catch (MySql.Data.MySqlClient.MySqlException e) {
dbm.Manager.Reconnect();
arrTransaction = dbm.Manager.FetchTransaction(userID, startTime, endTime, index, 1);
}
catch (Exception e) {
m_log.Error(e.ToString());
return null;
}
finally {
dbm.Release();
}
//
if (arrTransaction.Length > 0) {
return arrTransaction[0];
}
else {
return null;
}
}
public bool DoTransfer(UUID transactionUUID)
{
bool do_trans = false;
TransactionData transaction = new TransactionData();
transaction = FetchTransaction(transactionUUID);
if (transaction != null && transaction.Status == (int)Status.PENDING_STATUS) {
int balance = getBalance(transaction.Sender);
//check the amount
if (transaction.Amount >= 0 && balance >= transaction.Amount) {
if (withdrawMoney(transactionUUID, transaction.Sender, transaction.Amount)) {
//If receiver not found, add it to DB.
if (getBalance(transaction.Receiver) == -1) {
m_log.ErrorFormat("[MONEY DB]: DoTransfer: Receiver not found in balances DB. {0}", transaction.Receiver);
return false;
}
if (giveMoney(transactionUUID, transaction.Receiver, transaction.Amount)) {
do_trans = true;
}
else { // give money to receiver failed. 返金処理
m_log.ErrorFormat("[MONEY DB]: Give money to receiver {0} failed", transaction.Receiver);
//Return money to sender
if (giveMoney(transactionUUID, transaction.Sender, transaction.Amount)) {
m_log.ErrorFormat("[MONEY DB]: give money to receiver {0} failed but return it to sender {1} successfully",
transaction.Receiver, transaction.Sender);
updateTransactionStatus(transactionUUID, (int)Status.FAILED_STATUS, "give money to receiver failed but return it to sender successfully");
}
else {
m_log.ErrorFormat("[MONEY DB]: FATAL ERROR: Money withdrawn from sender: {0}, but failed to be given to receiver {1}",
transaction.Sender, transaction.Receiver);
updateTransactionStatus(transactionUUID, (int)Status.ERROR_STATUS, "give money to receiver failed, and return it to sender unsuccessfully!!!");
}
}
}
else { // withdraw money failed
m_log.ErrorFormat("[MONEY DB]: Withdraw money from sender {0} failed", transaction.Sender);
}
}
else { // not enough balance to finish the transaction
m_log.ErrorFormat("[MONEY DB]: Not enough balance for user: {0} to apply the transaction.", transaction.Sender);
}
}
else { // Can not fetch the transaction or it has expired
m_log.ErrorFormat("[MONEY DB]: The transaction:{0} has expired", transactionUUID.ToString());
}
//
if (do_trans) {
setTotalSale(transaction);
}
return do_trans;
}
// by Fumi.Iseki
public bool DoAddMoney(UUID transactionUUID)
{
TransactionData transaction = new TransactionData();
transaction = FetchTransaction(transactionUUID);
if (transaction!=null && transaction.Status==(int)Status.PENDING_STATUS) {
//If receiver not found, add it to DB.
if (getBalance(transaction.Receiver)==-1) {
m_log.ErrorFormat("[MONEY DB]: DoAddMoney: Receiver not found in balances DB. {0}", transaction.Receiver);
return false;
}
//
if (giveMoney(transactionUUID, transaction.Receiver, transaction.Amount)) {
setTotalSale(transaction);
return true;
}
else { // give money to receiver failed.
m_log.ErrorFormat("[MONEY DB]: Add money to receiver {0} failed", transaction.Receiver);
updateTransactionStatus(transactionUUID, (int)Status.FAILED_STATUS, "add money to receiver failed");
}
}
else { // Can not fetch the transaction or it has expired
m_log.ErrorFormat("[MONEY DB]: The transaction:{0} has expired", transactionUUID.ToString());
}
return false;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////
//
// userinfo
//
public bool TryAddUserInfo(UserInfo user)
{
MySQLSuperManager dbm = GetLockedConnection();
UserInfo userInfo = null;
try {
userInfo = dbm.Manager.fetchUserInfo(user.UserID);
}
catch (MySql.Data.MySqlClient.MySqlException e) {
dbm.Manager.Reconnect();
userInfo = dbm.Manager.fetchUserInfo(user.UserID);
}
catch (Exception e) {
m_log.Error(e.ToString());
dbm.Release();
return false;
}
try {
if (userInfo!=null) {
//m_log.InfoFormat("[MONEY DB]: Found user \"{0}\", now update information", user.Avatar);
if (dbm.Manager.updateUserInfo(user)) return true;
}
else if (dbm.Manager.addUserInfo(user)) {
//m_log.InfoFormat("[MONEY DB]: Unable to find user \"{0}\", add it to DB successfully", user.Avatar);
return true;
}
m_log.InfoFormat("[MONEY DB]: WARNNING: TryAddUserInfo: Unable to TryAddUserInfo.");
return false;
}
catch (Exception e) {
m_log.Error(e.ToString());
return false;
}
finally {
dbm.Release();
}
}
public UserInfo FetchUserInfo(string userID)
{
UserInfo userInfo = null;
MySQLSuperManager dbm = GetLockedConnection();
try {
userInfo = dbm.Manager.fetchUserInfo(userID);
return userInfo;
}
catch (MySql.Data.MySqlClient.MySqlException e) {
dbm.Manager.Reconnect();
userInfo = dbm.Manager.fetchUserInfo(userID);
return userInfo;
}
catch (Exception e) {
m_log.Error(e.ToString());
return null;
}
finally {
dbm.Release();
}
}
public int getTransactionNum(string userID, int startTime, int endTime)
{
MySQLSuperManager dbm = GetLockedConnection();
try {
return dbm.Manager.getTransactionNum(userID,startTime,endTime);
}
catch (MySql.Data.MySqlClient.MySqlException e) {
dbm.Manager.Reconnect();
return dbm.Manager.getTransactionNum(userID,startTime,endTime);
}
catch (Exception e) {
m_log.Error(e.ToString());
return -1;
}
finally {
dbm.Release();
}
}
}
#pragma warning restore 0168
}
@@ -0,0 +1,338 @@
/*
* Copyright (c) Contributors, http://opensimulator.org/, http://www.nsl.tuis.ac.jp/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSim Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.IO;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Net.Security;
using System.Reflection;
using System.Timers;
//using System.Security.Authentication;
//using System.Security.Cryptography;
//using System.Security.Cryptography.X509Certificates;
using HttpServer;
using Nini.Config;
using log4net;
using OpenSim.Framework;
using OpenSim.Framework.Console;
using OpenSim.Framework.Servers;
using OpenSim.Framework.Servers.HttpServer;
using OpenSim.Data;
using NSL.Certificate.Tools;
namespace OpenSim.Grid.MoneyServer
{
class MoneyServerBase : BaseOpenSimServer, IMoneyServiceCore
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private string connectionString = string.Empty;
private uint m_moneyServerPort = 8008;
private string m_certFilename = "";
private string m_certPassword = "";
private string m_cacertFilename = "";
private string m_clcrlFilename = "";
private bool m_checkClientCert = false;
private int DEAD_TIME = 120;
private int MAX_DB_CONNECTION = 10;
private MoneyXmlRpcModule m_moneyXmlRpcModule;
private MoneyDBService m_moneyDBService;
private NSLCertificateVerify m_certVerify = new NSLCertificateVerify(); // クライアント認証用
private Dictionary<string, string> m_sessionDic = new Dictionary<string, string>();
private Dictionary<string, string> m_secureSessionDic = new Dictionary<string, string>();
private Dictionary<string, string> m_webSessionDic = new Dictionary<string, string>();
IConfig m_server_config;
IConfig m_cert_config;
public MoneyServerBase()
{
m_console = new LocalConsole("Money ");
// m_console = new CommandConsole("Money ");
MainConsole.Instance = m_console;
}
public void Work()
{
//m_console.Notice("Enter help for a list of commands\n");
//The timer checks the transactions table every 60 seconds
Timer checkTimer = new Timer();
checkTimer.Interval = 60*1000;
checkTimer.Enabled = true;
checkTimer.Elapsed += new ElapsedEventHandler(CheckTransaction);
checkTimer.Start();
while (true) {
m_console.Prompt();
}
}
/// <summary>
/// Check the transactions table, set expired transaction state to failed
/// </summary>
private void CheckTransaction(object sender, ElapsedEventArgs e)
{
long ticksToEpoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).Ticks;
int unixEpochTime =(int) ((DateTime.UtcNow.Ticks - ticksToEpoch )/10000000);
int deadTime = unixEpochTime - DEAD_TIME;
m_moneyDBService.SetTransExpired(deadTime);
}
protected override void StartupSpecific()
{
m_log.Info("[MONEY SERVER]: Setup HTTP Server process");
ReadIniConfig();
try {
if (m_certFilename!="") {
m_httpServer = new BaseHttpServer(m_moneyServerPort, true, m_certFilename, m_certPassword);
if (m_checkClientCert) {
Type typeBaseHttpServer = typeof(BaseHttpServer); // BaseHttpServer.cs にパッチがあたっていない場合のため
PropertyInfo pinfo = typeBaseHttpServer.GetProperty("CertificateValidationCallback");
if (pinfo!=null) {
//m_httpServer.CertificateValidationCallback = (RemoteCertificateValidationCallback)m_certVerify.ValidateClientCertificate;
pinfo.SetValue(m_httpServer, (RemoteCertificateValidationCallback)m_certVerify.ValidateClientCertificate, null);
m_log.Info ("[MONEY SERVER]: Set RemoteCertificateValidationCallback");
}
else {
m_log.Error("[MONEY SERVER]: StartupSpecific: CheckClientCert is true. But this MoneyServer does not support CheckClientCert!!");
}
}
}
else {
m_httpServer = new BaseHttpServer(m_moneyServerPort);
}
SetupMoneyServices();
m_httpServer.Start();
base.StartupSpecific(); // OpenSim/Framework/Servers/BaseOpenSimServer.cs
}
catch (Exception e) {
m_log.ErrorFormat("[MONEY SERVER]: StartupSpecific: Fail to start HTTPS process");
m_log.ErrorFormat("[MONEY SERVER]: StartupSpecific: Please Check Certificate File or Password. Exit");
m_log.ErrorFormat("[MONEY SERVER]: StartupSpecific: {0}", e);
Environment.Exit(1);
}
//TODO : Add some console commands here
}
protected void ReadIniConfig()
{
MoneyServerConfigSource moneyConfig = new MoneyServerConfigSource();
Config = moneyConfig.m_config; // for base.StartupSpecific()
try {
// [Startup]
IConfig st_config = moneyConfig.m_config.Configs["Startup"];
string PIDFile = st_config.GetString("PIDFile", "");
if (PIDFile!="") Create_PIDFile(PIDFile);
// [MySql]
IConfig db_config = moneyConfig.m_config.Configs["MySql"];
string sqlserver = db_config.GetString("hostname", "localhost");
string database = db_config.GetString("database", "OpenSim");
string username = db_config.GetString("username", "root");
string password = db_config.GetString("password", "password");
string pooling = db_config.GetString("pooling", "false");
string port = db_config.GetString("port", "3306");
MAX_DB_CONNECTION = db_config.GetInt ("MaxConnection", MAX_DB_CONNECTION);
connectionString = "Server=" + sqlserver + ";Port=" + port + ";Database=" + database + ";User ID=" +
username + ";Password=" + password + ";Pooling=" + pooling + ";";
// [MoneyServer]
m_server_config = moneyConfig.m_config.Configs["MoneyServer"];
DEAD_TIME = m_server_config.GetInt("ExpiredTime", DEAD_TIME);
//
// [Certificate]
m_cert_config = moneyConfig.m_config.Configs["Certificate"];
if (m_cert_config==null) {
m_log.Info("[MONEY SERVER]: [Certificate] section is not found. Using [MoneyServer] section instead");
m_cert_config = m_server_config;
}
// HTTPS Server Cert (Server Mode)
// サーバ証明書
m_certFilename = m_cert_config.GetString("ServerCertFilename", m_certFilename);
m_certPassword = m_cert_config.GetString("ServerCertPassword", m_certPassword);
if (m_certFilename!="") {
m_log.Info("[MONEY SERVER]: ReadIniConfig: Execute HTTPS comunication. Cert file is " + m_certFilename);
}
// クライアント認証
m_checkClientCert = m_cert_config.GetBoolean("CheckClientCert", m_checkClientCert);
m_cacertFilename = m_cert_config.GetString("CACertFilename", m_cacertFilename);
m_clcrlFilename = m_cert_config.GetString("ClientCrlFilename", m_clcrlFilename);
//
if (m_checkClientCert && m_cacertFilename!="") {
m_certVerify.SetPrivateCA(m_cacertFilename);
m_log.Info("[MONEY SERVER]: ReadIniConfig: Execute Authentication of Clients. CA file is " + m_cacertFilename);
}
else {
m_checkClientCert = false;
}
if (m_checkClientCert) {
if (m_clcrlFilename!="") {
m_certVerify.SetPrivateCRL(m_clcrlFilename);
m_log.Info("[MONEY SERVER]: ReadIniConfig: Execute Authentication of Clients. CRL file is " + m_clcrlFilename);
}
}
}
catch (Exception) {
m_log.Error("[MONEY SERVER]: ReadIniConfig: Fail to setup configure. Please check MoneyServer.ini. Exit");
Environment.Exit(1);
}
}
// added by skidz
protected void Create_PIDFile(string path)
{
try {
string pidstring = System.Diagnostics.Process.GetCurrentProcess().Id.ToString();
FileStream fs = File.Create(path);
System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();
Byte[] buf = enc.GetBytes(pidstring);
fs.Write(buf, 0, buf.Length);
fs.Close();
m_pidFile = path;
}
catch (Exception) {
}
}
protected virtual void SetupMoneyServices()
{
m_log.Info("[MONEY SERVER]: Connecting to Money Storage Server");
m_moneyDBService = new MoneyDBService();
m_moneyDBService.Initialise(connectionString, MAX_DB_CONNECTION);
m_moneyXmlRpcModule = new MoneyXmlRpcModule();
// m_moneyXmlRpcModule.Initialise(m_version, m_server_config, m_cert_config, m_moneyDBService, this);
m_moneyXmlRpcModule.Initialise(m_version, m_moneyDBService, this);
m_moneyXmlRpcModule.PostInitialise();
}
//
public bool IsCheckClientCert()
{
return m_checkClientCert;
}
public IConfig GetServerConfig()
{
return m_server_config;
}
public IConfig GetCertConfig()
{
return m_cert_config;
}
public BaseHttpServer GetHttpServer()
{
return m_httpServer;
}
public Dictionary<string, string> GetSessionDic()
{
return m_sessionDic;
}
public Dictionary<string, string> GetSecureSessionDic()
{
return m_secureSessionDic;
}
public Dictionary<string, string> GetWebSessionDic()
{
return m_webSessionDic;
}
}
//
class MoneyServerConfigSource
{
public IniConfigSource m_config;
public MoneyServerConfigSource()
{
string configPath = Path.Combine(Directory.GetCurrentDirectory(), "MoneyServer.ini");
if (File.Exists(configPath)) {
m_config = new IniConfigSource(configPath);
}
else {
//TODO: create default configuration.
//m_config = DefaultConfig();
}
}
public void Save(string path)
{
m_config.Save(path);
}
}
}
File diff suppressed because it is too large Load Diff
+42
View File
@@ -0,0 +1,42 @@
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSim Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using log4net.Config;
namespace OpenSim.Grid.MoneyServer
{
class Program
{
public static void Main(string[] args)
{
XmlConfigurator.Configure();
MoneyServerBase app = new MoneyServerBase();
app.Startup();
app.Work();
}
}
}
@@ -0,0 +1,36 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("OpenSim.Grid.MoneyServer")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("OpenSim.Grid.MoneyServer")]
[assembly: AssemblyCopyright("Copyright © Microsoft 2009")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("f554c84a-d8c7-41ea-833d-2483cde29e0f")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,226 @@
/*
* Copyright (c) Contributors, http://www.nsl.tuis.ac.jp
*
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Xml;
using System.Net;
using System.Net.Security;
using System.Text;
using System.Reflection;
using System.Security.Cryptography.X509Certificates;
using log4net;
namespace NSL.Certificate.Tools
{
//
public class NSLCertificateVerify
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private X509Chain m_chain = null;
private X509Certificate2 m_cacert = null;
private Mono.Security.X509.X509Crl m_clientcrl = null;
public NSLCertificateVerify()
{
m_chain = null;
m_cacert = null;
m_clientcrl = null;
}
public NSLCertificateVerify(string certfile)
{
SetPrivateCA(certfile);
}
public NSLCertificateVerify(string certfile, string crlfile)
{
SetPrivateCA (certfile);
SetPrivateCRL(crlfile);
}
public void SetPrivateCA(string certfile)
{
try {
m_cacert = new X509Certificate2(certfile);
}
catch (Exception ex)
{
m_cacert = null;
m_log.ErrorFormat("[SET PRIVATE CA]: CA File reading error [{0}]. {1}", certfile, ex);
}
if (m_cacert!=null) {
m_chain = new X509Chain();
m_chain.ChainPolicy.ExtraStore.Add(m_cacert);
m_chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck;
m_chain.ChainPolicy.VerificationFlags = X509VerificationFlags.NoFlag;
}
}
public void SetPrivateCRL(string crlfile)
{
try {
m_clientcrl = Mono.Security.X509.X509Crl.CreateFromFile(crlfile);
}
catch (Exception ex)
{
m_clientcrl = null;
m_log.ErrorFormat("[SET PRIVATE CRL]: CRL File reading error [{0}]. {1}", crlfile, ex);
}
}
//
//
//
public bool CheckPrivateChain(X509Certificate2 cert)
{
if (m_chain==null || m_cacert==null) {
return false;
}
bool ret = m_chain.Build((X509Certificate2)cert);
if (ret) {
return true;
}
for (int i=0; i<m_chain.ChainStatus.Length; i++) {
if (m_chain.ChainStatus[i].Status==X509ChainStatusFlags.UntrustedRoot) return true;
}
//
return false;
}
/*
SslPolicyErrors:
RemoteCertificateNotAvailable = 1, // 証明書が利用できません.
RemoteCertificateNameMismatch = 2, // 証明書名が不一致です.
RemoteCertificateChainErrors = 4, // ChainStatus が空でない配列を返しました.
*/
//
//
//
public bool ValidateServerCertificate(object obj, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
{
m_log.InfoFormat("[NSL CERT VERIFY]: ValidateServerCertificate: Policy is ({0})", sslPolicyErrors);
if (obj is HttpWebRequest) {
//
HttpWebRequest Request = (HttpWebRequest)obj;
string noVerify = Request.Headers.Get("NoVerifyCert");
if (noVerify!=null && noVerify.ToLower()=="true") {
return true;
}
}
X509Certificate2 certificate2 = new X509Certificate2(certificate);
string simplename = certificate2.GetNameInfo(X509NameType.SimpleName, false);
m_log.InfoFormat("[NSL CERT VERIFY]: ValidateServerCertificate: Simple Name is \"{0}\"", simplename);
/*
// RemoteCertificateNotAvailableはエラーとする.
if ((sslPolicyErrors & SslPolicyErrors.RemoteCertificateNotAvailable)==SslPolicyErrors.RemoteCertificateNotAvailable) {
m_log.InfoFormat("[NSL CERT VERIFY]: ValidateServerCertificate: Policy Error! {0}", sslPolicyErrors);
return false;
}
*/
// None, ChainErrors 以外は全てエラーとする.
if (sslPolicyErrors!=SslPolicyErrors.None && sslPolicyErrors!=SslPolicyErrors.RemoteCertificateChainErrors) {
m_log.InfoFormat("[NSL CERT VERIFY]: ValidateServerCertificate: Policy Error! {0}", sslPolicyErrors);
return false;
}
bool valid = CheckPrivateChain(certificate2);
if (valid) {
m_log.InfoFormat("[NSL CERT VERIFY]: Valid Server Certification for \"{0}\"", simplename);
}
else {
m_log.InfoFormat("[NSL CERT VERIFY]: Failed to Verify Server Certification for \"{0}\"", simplename);
}
return valid;
}
//
//
// obj is SslStream
public bool ValidateClientCertificate(object obj, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
{
m_log.InfoFormat("[NSL CERT VERIFY]: ValidateClientCertificate: Policy is ({0})", sslPolicyErrors);
X509Certificate2 certificate2 = new X509Certificate2(certificate);
string simplename = certificate2.GetNameInfo(X509NameType.SimpleName, false);
//m_log.InfoFormat("[NSL CERT VERIFY]: ValidateClientCertificate: Simple Name is \"{0}\"", simplename);
/*
// RemoteCertificateNotAvailableはエラーとする.
if ((sslPolicyErrors & SslPolicyErrors.RemoteCertificateNotAvailable)==SslPolicyErrors.RemoteCertificateNotAvailable) {
m_log.InfoFormat("[NSL CERT VERIFY]: ValidateClientCertificate: Policy Error! {0}", sslPolicyErrors);
return false;
}
*/
// None, ChainErrors 以外は全てエラーとする.
if (sslPolicyErrors!=SslPolicyErrors.None && sslPolicyErrors!=SslPolicyErrors.RemoteCertificateChainErrors) {
m_log.InfoFormat("[NSL CERT VERIFY]: ValidateClientCertificate: Policy Error! {0}", sslPolicyErrors);
return false;
}
// check CRL
if (m_clientcrl!=null) {
Mono.Security.X509.X509Certificate monocert = new Mono.Security.X509.X509Certificate(certificate.GetRawCertData());
Mono.Security.X509.X509Crl.X509CrlEntry entry = m_clientcrl.GetCrlEntry(monocert);
if (entry!=null) {
m_log.InfoFormat("[NSL CERT VERIFY]: Common Name \"{0}\" was revoked at {1}", simplename, entry.RevocationDate.ToString());
return false;
}
}
bool valid = CheckPrivateChain(certificate2);
if (valid) {
m_log.InfoFormat("[NSL CERT VERIFY]: Valid Client Certification for \"{0}\"", simplename);
}
else {
m_log.InfoFormat("[NSL CERT VERIFY]: Failed to Verify Client Certification for \"{0}\"", simplename);
}
return valid;
}
}
//
public class NSLCertificatePolicy : ICertificatePolicy
{
//private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
public bool CheckValidationResult(ServicePoint srvPoint, X509Certificate certificate, WebRequest request, int certificateProblem)
{
if (certificateProblem == 0 || //正常
certificateProblem == -2146762487 || //信頼されてない?
certificateProblem == -2146762495 || //期限切れ
certificateProblem == -2146762481) { //名前不正?
return true;
}
else {
return false;
}
}
}
}
+96
View File
@@ -0,0 +1,96 @@
/*
* Copyright (c) Contributors, http://www.nsl.tuis.ac.jp
*
*/
using System;
using System.Collections;
using System.IO;
using System.Xml;
using System.Net;
using System.Text;
using System.Reflection;
using System.Security.Cryptography.X509Certificates;
using log4net;
using Nwc.XmlRpc;
namespace NSL.Network.XmlRpc
{
public class NSLXmlRpcRequest : XmlRpcRequest
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private Encoding _encoding = new UTF8Encoding();
private XmlRpcRequestSerializer _serializer = new XmlRpcRequestSerializer();
private XmlRpcResponseDeserializer _deserializer = new XmlRpcResponseDeserializer();
public NSLXmlRpcRequest()
{
_params = new ArrayList();
}
public NSLXmlRpcRequest(String methodName, IList parameters)
{
MethodName = methodName;
_params = parameters;
}
public XmlRpcResponse certSend(String url, X509Certificate2 myClientCert, bool checkServerCert, Int32 timeout)
{
m_log.InfoFormat("[MONEY NSL RPC]: XmlRpcResponse certSend: connect to {0}", url);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
if (request==null)
{
throw new XmlRpcException(XmlRpcErrorCodes.TRANSPORT_ERROR, XmlRpcErrorCodes.TRANSPORT_ERROR_MSG +": Could not create request with " + url);
}
request.Method = "POST";
request.ContentType = "text/xml";
request.AllowWriteStreamBuffering = true;
request.Timeout = timeout;
request.UserAgent = "NSLXmlRpcRequest";
if (myClientCert!=null) request.ClientCertificates.Add(myClientCert); // 自身の証明書
if (!checkServerCert) request.Headers.Add("NoVerifyCert", "true"); // 相手の証明書を検証しない
Stream stream = null;
try {
stream = request.GetRequestStream();
}
catch (Exception ex) {
m_log.ErrorFormat("[MONEY NSL RPC]: GetRequestStream Error: {0}", ex);
}
if (stream==null) return null;
//
XmlTextWriter xml = new XmlTextWriter(stream, _encoding);
_serializer.Serialize(xml, this);
xml.Flush();
xml.Close();
HttpWebResponse response = null;
try {
response = (HttpWebResponse)request.GetResponse();
}
catch (Exception ex) {
m_log.ErrorFormat("[MONEY NSL RPC]: XmlRpcResponse certSend: GetResponse Error: {0}", ex.ToString());
}
StreamReader input = new StreamReader(response.GetResponseStream());
string inputXml = input.ReadToEnd();
XmlRpcResponse resp = (XmlRpcResponse)_deserializer.Deserialize(inputXml);
input.Close();
response.Close();
return resp;
}
}
}
@@ -0,0 +1,36 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("OpenSim.Modules.Currency")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("DTL/NSL Group")]
[assembly: AssemblyCopyright("Copyright © Microsoft 2009")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("2363e3c9-7be0-4b9b-84ac-82923d5021f4")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
+29
View File
@@ -0,0 +1,29 @@
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net" />
</configSections>
<appSettings>
</appSettings>
<log4net>
<appender name="Console" type="OpenSim.Framework.Console.OpenSimAppender, OpenSim.Framework.Console">
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date{HH:mm:ss} - %message%newline" />
</layout>
</appender>
<appender name="LogFileAppender" type="log4net.Appender.FileAppender">
<file value="MoneyServer.log" />
<appendToFile value="true" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date %-5level - %logger %message%newline" />
</layout>
</appender>
<root>
<level value="DEBUG" />
<appender-ref ref="Console" />
<appender-ref ref="LogFileAppender" />
</root>
</log4net>
</configuration>
+99
View File
@@ -0,0 +1,99 @@
[Startup]
;
; Place to create a PID file
; PIDFile = "/tmp/money.pid"
[MySql]
;
;Connection parameters of MySQL
hostname = localhost ; Name of MySQL Server
database = opensim_db
username = opensim_user
password = opensim_pass
pooling = false
port = 3306
;
; Max DB connections kept by money server.
MaxConnection = 50
[MoneyServer]
;
; If the user is not found in database,he/she will be created with the default balance.
DefaultBalance = 1000
;
; Is amount==0 transaction enable? Default is false.
EnableAmountZero = true
;
; If "00000000-0000-0000-0000-000000000000" is specified, all avatars can get money from system.
; If "" is specified, nobody can get money.
BankerAvatar = ""
;
; If you want to use llGiveMoney() function normally even when payer doesn't login to OpenSim,
; please set true to this valiable
EnableForceTransfer = true
;
; Send/Move money to/from avatar by Money Script
;EnableScriptSendMoney = false
;MoneyScriptAccessKey = "123456789" ;; Specify same secret key in include/config.php or WI(XoopenSim/Modlos)
;MoneyScriptIPaddress = "202.26.159.139" ;; Not use 127.0.0.1. This is used to generate Script key
;
; for HG/Guest Avatar. Foreign Avatar is always false
EnableHGAvatar = true
EnableGuestAvatar = true
HGAvatarDefaultBalance = 1000
GuestAvatarDefaultBalance = 1000
;
; Message that displayed in blue dialog, when balance is updated.
; If "" is specified, blue dialog is not displayed.
; You can use {0} and {1} in message string.
; {0} means amount and {1} means avatar name or object owner name.
BalanceMessageSendGift = "Sent Gift L${0} to {1}." ;; for send gift to other avatar
BalanceMessageReceiveGift = "Received Gift L${0} from {1}." ;; for receieve gift from other avatar
BalanceMessagePayCharge = "" ;; for upload and group creation charge
BalanceMessageBuyObject = "Bought the Object {2} from {1} by L${0}." ;; for buy the object
BalanceMessageSellObject = "{1} bought the Object {2} by L${0}." ;; for sell the object
BalanceMessageLandSale = "Paid the Money L${0} for Land." ;; for buy the land
BalanceMessageScvLandSale = "" ;; for get the money of the sold land
BalanceMessageGetMoney = "Got the Money L${0} from {1}." ;; for get the money from object by llGiveMoney()
BalanceMessageBuyMoney = "Bought the Money L${0}." ;; for buy the money from system
BalanceMessageRollBack = "RollBack the Transaction: L${0} from/to {1}.";; when roll back ocuurred
BalanceMessageSendMoney = "Paid the Money L${0} to {1}." ;; for sender of sending the money
BalanceMessageReceiveMoney = "Received L${0} from {1}." ;; for receive the money
[Certificate]
;
; Certification Configuration
;
; CA Cert to check Client/Server Cert
;CACertFilename = "cacert.crt"
;
; HTTPS Server Cert (Server Mode)
;ServerCertFilename = "SineWaveCert.pfx"
;ServerCertPassword = "123"
;ServerCertFilename = "server_cert.p12"
;ServerCertPassword = ""
; Client Authentication from Region Server
;CheckClientCert = false ;; check Region Server
;ClientCrlFilename = "clcrl.crt"
;
; XML RPC to Region Server (Client Mode)
;;CheckServerCert = false ;; check Region Server
;;ClientCertFilename = "client_cert.p12"
;;ClientCertPassword = ""
+43
View File
@@ -0,0 +1,43 @@
[Economy]
;; Enables selling things for $0. Default is true.
SellEnabled = true
;CurrencyServer = "" ;; ex.) "https://jogrid.net:8008/" Default is ""
EconomyModule = DTLNSLMoneyModule
;
;; CA
;CheckServerCert = false
;CACertFilename = "cacert.crt"
;
;; Client Cert
;ClientCertFilename = "region_cert.p12"
;ClientCertPassword = ""
;
;; Money Unit fee to upload textures, animations etc. Default is 0.
PriceUpload = 0
;; Mesh upload factors
;MeshModelUploadCostFactor = 0.0
;MeshModelUploadTextureCostFactor = 1.0
;MeshModelMinCostFactor = 0.0
;; Money Unit fee to create groups. Default is 0.
PriceGroupCreate = 0
;
;; Avatar Class for HG Avatar
;; {ForeignAvatar, HGAvatar, GuestAvatar, LocalAvatar} HGAvatar
;; HG Avatar is assumed as a specified avatar class. Default is HGAvatar
;; Processing for each avatar class is dependent on Money Server settings.
;HGAvatarAs = "HGAvatar"
;
;; in development
;SettlementByWeb = false
;SettlementURL = "http://www.jogrid.net"
;SettlementMessage = "Goto the settlement of accounts Web page. (Testing now)"
+1
View File
@@ -0,0 +1 @@
# Copy this to /opensim/bin
Binary file not shown.
Binary file not shown.
+141
View File
@@ -0,0 +1,141 @@
<!-- MoneyServer -->
<Project frameworkVersion="v4_6" name="OpenSim.Data.MySQL.MySQLMoneyDataWrapper" path="ThirdParty/OpenSim.Data.MySQL.MySQLMoneyDataWrapper" type="Library">
<Configuration name="Debug">
<Options>
<OutputPath>../../bin/</OutputPath>
</Options>
</Configuration>
<Configuration name="Release">
<Options>
<OutputPath>../../bin/</OutputPath>
</Options>
</Configuration>
<ReferencePath>../../bin/</ReferencePath>
<Reference name="System"/>
<Reference name="System.Xml"/>
<Reference name="System.Data"/>
<Reference name="System.Drawing"/>
<Reference name="System.Runtime.Remoting"/>
<Reference name="Nini" path="../../bin/"/>
<Reference name="Mono.Addins" path="../../bin/"/>
<Reference name="log4net" path="../../bin/"/>
<Reference name="OpenMetaverse" path="../../bin/"/>
<Reference name="OpenMetaverseTypes" path="../../bin/"/>
<Reference name="XMLRPC" path="../../bin/"/>
<Reference name="MySql.Data" path="../../bin/"/>
<Reference name="OpenSim.Region.Framework"/>
<Reference name="OpenSim.Framework"/>
<Reference name="OpenSim.Framework.Console"/>
<Reference name="OpenSim.Framework.Servers"/>
<Reference name="OpenSim.Framework.Servers.HttpServer"/>
<Reference name="OpenSim.Services.Interfaces"/>
<Reference name="OpenSim.Server.Base"/>
<Reference name="OpenSim.Data"/>
<Files>
<Match pattern="*.cs" recurse="true">
<Exclude name="obj" pattern="obj"/>
</Match>
</Files>
</Project>
<Project frameworkVersion="v4_6" name="OpenSim.Modules.Currency" path="ThirdParty/OpenSim.Modules.Currency" type="Library">
<Configuration name="Debug">
<Options>
<OutputPath>../../bin/</OutputPath>
</Options>
</Configuration>
<Configuration name="Release">
<Options>
<OutputPath>../../bin/</OutputPath>
</Options>
</Configuration>
<ReferencePath>../../bin/</ReferencePath>
<Reference name="System"/>
<Reference name="System.Xml"/>
<Reference name="System.Drawing"/>
<Reference name="System.Runtime.Remoting"/>
<Reference name="Mono.Security.dll"/>
<Reference name="Nini" path="../../bin/"/>
<Reference name="Mono.Addins" path="../../bin/"/>
<Reference name="log4net" path="../../bin/"/>
<Reference name="XMLRPC" path="../../bin/"/>
<Reference name="OpenMetaverseTypes" path="../../bin/"/>
<Reference name="OpenMetaverse" path="../../bin/"/>
<Reference name="HttpServer_OpenSim.dll" path="../../bin/"/>
<Reference name="OpenSim.Region.Framework"/>
<Reference name="OpenSim.Framework"/>
<Reference name="OpenSim.Framework.Console"/>
<Reference name="OpenSim.Framework.Servers"/>
<Reference name="OpenSim.Framework.Servers.HttpServer"/>
<Reference name="OpenSim.Services.Interfaces"/>
<Reference name="OpenSim.Server.Base"/>
<Reference name="OpenSim.Data"/>
<Reference name="OpenSim.Data.MySQL.MySQLMoneyDataWrapper"/>
<Files>
<Match pattern="*.cs" recurse="true">
<Exclude name="obj" pattern="obj"/>
</Match>
</Files>
</Project>
<Project frameworkVersion="v4_6" name="MoneyServer" path="ThirdParty/OpenSim.Grid.MoneyServer" type="Exe">
<Configuration name="Debug">
<Options>
<OutputPath>../../bin/</OutputPath>
</Options>
</Configuration>
<Configuration name="Release">
<Options>
<OutputPath>../../bin/</OutputPath>
</Options>
</Configuration>
<ReferencePath>../../bin/</ReferencePath>
<Reference name="System"/>
<Reference name="System.Core"/>
<Reference name="System.Xml"/>
<Reference name="System.Data"/>
<Reference name="System.Drawing"/>
<Reference name="System.Runtime.Remoting"/>
<Reference name="Mono.Security.dll"/>
<Reference name="Nini" path="../../bin/"/>
<Reference name="Mono.Addins" path="../../bin/"/>
<Reference name="log4net" path="../../bin/"/>
<Reference name="XMLRPC" path="../../bin/"/>
<Reference name="MySql.Data" path="../../bin/"/>
<Reference name="OpenMetaverseTypes" path="../../bin/"/>
<Reference name="OpenMetaverse" path="../../bin/"/>
<Reference name="HttpServer_OpenSim.dll" path="../../bin/"/>
<Reference name="OpenSim.Region.Framework"/>
<Reference name="OpenSim.Framework"/>
<Reference name="OpenSim.Framework.Console"/>
<Reference name="OpenSim.Framework.Servers"/>
<Reference name="OpenSim.Framework.Servers.HttpServer"/>
<Reference name="OpenSim.Services.Interfaces"/>
<Reference name="OpenSim.Server.Base"/>
<Reference name="OpenSim.Data"/>
<Reference name="OpenSim.Data.MySQL.MySQLMoneyDataWrapper"/>
<Reference name="OpenSim.Modules.Currency"/>
<Files>
<Match pattern="*.cs" recurse="true">
<Exclude name="obj" pattern="obj"/>
</Match>
</Files>
</Project>
@@ -0,0 +1,26 @@
---------------------------------------------------------------------
--- DTLNSLMoneyModule.cs.ori 2020-01-16 11:40:31.320753823 +0100
+++ DTLNSLMoneyModule.cs 2020-01-16 11:39:54.717394571 +0100
@@ -1638,8 +1638,10 @@
avatarType = (int)AvatarType.NPC_AVATAR;
}
//
- if ((agent.teleportFlags & (uint)Constants.TeleportFlags.ViaHGLogin)!=0 || String.IsNullOrEmpty(userName)) {
- avatarType = (int)AvatarType.HG_AVATAR;
+ if (!isNpc) {
+ if ((agent.teleportFlags & (uint)Constants.TeleportFlags.ViaHGLogin)!=0 || String.IsNullOrEmpty(userName)) {
+ avatarType = (int)AvatarType.HG_AVATAR;
+ }
}
}
if (String.IsNullOrEmpty(userName)) {
@@ -1648,7 +1650,7 @@
//
avatarClass = avatarType;
- if (avatarType==(int)AvatarType.NPC_AVATAR) return false;
+ if (avatarType==(int)AvatarType.NPC_AVATAR) return true;
if (avatarType==(int)AvatarType.HG_AVATAR) avatarClass = m_hg_avatarClass;
//
---------------------------------------------------------------------
@@ -0,0 +1,46 @@
diff -Nur OpenSim-/Framework/Servers/HttpServer/BaseHttpServer.cs OpenSim/Framework/Servers/HttpServer/BaseHttpServer.cs
--- OpenSim-/Framework/Servers/HttpServer/BaseHttpServer.cs 2018-04-22 14:34:37.642698003 +0900
+++ OpenSim/Framework/Servers/HttpServer/BaseHttpServer.cs 2018-04-22 14:35:35.331826307 +0900
@@ -1094,6 +1094,10 @@
if (gridproxy)
xmlRprcRequest.Params.Add("gridproxy"); // Param[4]
+
+ // by Fumi.Iseki for DTLNSLMoneyServer
+ xmlRprcRequest.Params.Add(request.IHttpClientContext.SSLCommonName); // Param[4] or Param[5]
+
try
{
xmlRpcResponse = method(xmlRprcRequest, request.RemoteIPEndPoint);
diff -Nur OpenSim-/Framework/Servers/Tests/OSHttpTests.cs OpenSim/Framework/Servers/Tests/OSHttpTests.cs
--- OpenSim-/Framework/Servers/Tests/OSHttpTests.cs 2018-04-22 14:34:37.643698006 +0900
+++ OpenSim/Framework/Servers/Tests/OSHttpTests.cs 2018-04-22 14:35:35.331826307 +0900
@@ -62,6 +62,12 @@
_secured = secured;
}
+ // by Fumi.Iseki for DTLNSLMoenyServer
+ public string SSLCommonName
+ {
+ get { return "";}
+ }
+
public void Disconnect(SocketError error) {}
public void Respond(string httpVersion, HttpStatusCode statusCode, string reason, string body) {}
public void Respond(string httpVersion, HttpStatusCode statusCode, string reason) {}
diff -Nur OpenSim-/Tests/Common/Mock/TestHttpClientContext.cs OpenSim/Tests/Common/Mock/TestHttpClientContext.cs
--- OpenSim-/Tests/Common/Mock/TestHttpClientContext.cs 2018-04-22 14:34:37.643698006 +0900
+++ OpenSim/Tests/Common/Mock/TestHttpClientContext.cs 2018-04-22 14:35:35.332826313 +0900
@@ -72,6 +72,12 @@
// Console.WriteLine("TestHttpClientContext.Disconnect Received disconnect with status {0}", error);
}
+ // by Fumi.Iseki for DTLNSLMoenyServer
+ public string SSLCommonName
+ {
+ get { return "";}
+ }
+
public void Respond(string httpVersion, HttpStatusCode statusCode, string reason, string body) {Console.WriteLine("x");}
public void Respond(string httpVersion, HttpStatusCode statusCode, string reason) {Console.WriteLine("xx");}
public void Respond(string body) { Console.WriteLine("xxx");}
@@ -0,0 +1,15 @@
diff -Nur OpenSim-/Framework/Servers/HttpServer/BaseHttpServer.cs OpenSim/Framework/Servers/HttpServer/BaseHttpServer.cs
--- OpenSim-/Framework/Servers/HttpServer/BaseHttpServer.cs 2019-02-13 17:07:00.037657561 +0900
+++ OpenSim/Framework/Servers/HttpServer/BaseHttpServer.cs 2019-02-13 17:29:49.371393303 +0900
@@ -158,6 +158,11 @@
m_port = port;
}
+ public RemoteCertificateValidationCallback CertificateValidationCallback
+ {
+ set { m_certificateValidationCallback = value; }
+ }
+
private void load_cert(string CPath, string CPass)
{
try