Merge pull request #628 from timothygwebb/master

PHP 7.4.9 Update with Composer
This commit is contained in:
Andrius Putna authored and GitHub committed 2020-09-02 22:56:54 +03:00
commit f39feab68c
9692 files changed
+1358790 -55

No files matched your search

+8 -2
View File
@@ -4,13 +4,19 @@
.vagrant*
tmp
src/.htaccess
.htaccess
src/bb-config*
bb-config*
!src/bb-config-sample.php
bb-config-sample.php
src/bb-data/log/*
bb-data/log/*
src/bb-data/cache/*
bb-data/cache/*
src/bb-data/tmp.txt
src/bb-vendor
bb-data/tmp.txt
src/bb-test.php
bb-test.php
build
composer.phar
public
@@ -24,4 +30,4 @@ puphpet/files/dot/ssh/*
### node_moduels ###
node_modules
npm-debug.log
.history/
.history/
+4 -4
View File
@@ -7,7 +7,7 @@ Open Source billing software
Requirements
================================================================================
* PHP 7.2
* PHP 7.4.8
* Linux Operating System (64-bit) | Does not support Windows Operating Systems.
* PHP extensions:
* openssl
@@ -20,7 +20,7 @@ Requirements
Recommended
================================================================================
* PHP 7.2
* PHP 7.4.8
* CentOS 64-bit Operating System
* PHP Extensions
* openssl
@@ -48,8 +48,8 @@ Contributing
Roadmap
================================================================================
* [ ] Support latest PHP version 7.3
* [ ] Add support for composer package manager
* [*] Support latest PHP version 7.3
* [*] Add support for composer package manager
Using Vagrant
================================================================================
+118
View File
@@ -0,0 +1,118 @@
<?php
/**
* BoxBilling configuration file example
*
* If you are not using the web-installer, you can rename this file
* to "bb-config.php" and fill in the values.
* Import /install/structure.sql to your database
* Import /install/content.sql to your database
* Open browser http://www.youdomain.com/index.php?_url=/bb-admin to create new admin account.
* Remove /install directory
*/
return array(
/**
* Set BoxBilling license key. Get license key at http://www.boxbilling.com
*/
'license' => getenv('BB_LICENSE'),
'salt' => getenv('BB_SALT'),
/**
* Full URL where BoxBilling is installed with trailing slash
*/
'url' => getenv('BB_URL'),
'admin_area_prefix' => '/bb-admin',
/**
* Enable or Disable the display of notices
*/
'debug' => getenv('BB_DEBUG'),
/**
* Enable or Disable search engine friendly urls.
* Configure .htaccess file before enabling this feature
* Set to TRUE if using nginx
*/
'sef_urls' => getenv('BB_SEF_URLS'),
/**
* Application timezone
*/
'timezone' => 'UTC',
/**
* Set BoxBilling locale
*/
'locale' => 'en_US',
/**
* Set default date format for localized strings
* Format information: http://php.net/manual/en/function.strftime.php
*/
'locale_date_format' => '%A, %d %B %G',
/**
* Set default time format for localized strings
* Format information: http://php.net/manual/en/function.strftime.php
*/
'locale_time_format' => ' %T',
/**
* Set location to store sensitive data
*/
'path_data' => dirname(__FILE__) . '/bb-data',
'path_logs' => dirname(__FILE__) . '/bb-data/log/application.log',
'log_to_db' => true,
'db' => array(
/**
* Database type. Don't change this if in doubt.
*/
'type' =>getenv('BB_DB_TYPE'),
/**
* Database hostname. Don't change this if in doubt.
*/
'host' => getenv('BB_DB_HOST'),
/**
* The name of the database for BoxBilling
*/
'name' =>getenv('BB_DB_NAME'),
/**
* Database username
*/
'user' =>getenv('BB_DB_USER'),
/**
* Database password
*/
'password' =>getenv('BB_DB_PASSWORD'),
),
'twig' => array(
'debug' => false,
'auto_reload' => false,
'cache' => dirname(__FILE__) . '/bb-data/cache',
),
'api' => array(
// all requests made to API must have referrer request header with the same url as BoxBilling installation
'require_referrer_header' => false,
// empty array will allow all IPs to access API
'allowed_ips' => array(),
// Time span for limit in seconds
'rate_span' => 60 * 60,
// How many requests allowed per time span
'rate_limit' => 1000,
),
);
+118
View File
@@ -0,0 +1,118 @@
<?php
/**
* BoxBilling configuration file example
*
* If you are not using the web-installer, you can rename this file
* to "bb-config.php" and fill in the values.
* Import /install/structure.sql to your database
* Import /install/content.sql to your database
* Open browser http://www.youdomain.com/index.php?_url=/bb-admin to create new admin account.
* Remove /install directory
*/
return array(
/**
* Set BoxBilling license key. Get license key at http://www.boxbilling.com
*/
'license' => 'PRO-wfe1RJ6aqG1wurwlocc9lwouNeTcUtklsp9ujy33clb8c57fdV',
'salt' => '',
/**
* Full URL where BoxBilling is installed with trailing slash
*/
'url' => 'http://www.boxbilling.test/',
'admin_area_prefix' => '/bb-admin',
/**
* Enable or Disable the display of notices
*/
'debug' => false,
/**
* Enable or Disable search engine friendly urls.
* Configure .htaccess file before enabling this feature
* Set to TRUE if using nginx
*/
'sef_urls' => false,
/**
* Application timezone
*/
'timezone' => 'UTC',
/**
* Set BoxBilling locale
*/
'locale' => 'en_US',
/**
* Set default date format for localized strings
* Format information: http://php.net/manual/en/function.strftime.php
*/
'locale_date_format' => '%A, %d %B %G',
/**
* Set default time format for localized strings
* Format information: http://php.net/manual/en/function.strftime.php
*/
'locale_time_format' => ' %T',
/**
* Set location to store sensitive data
*/
'path_data' => dirname(__FILE__) . '/bb-data',
'path_logs' => dirname(__FILE__) . '/bb-data/log/application.log',
'log_to_db' => true,
'db' => array(
/**
* Database type. Don't change this if in doubt.
*/
'type' =>'mysql',
/**
* Database hostname. Don't change this if in doubt.
*/
'host' =>'127.0.0.1',
/**
* The name of the database for BoxBilling
*/
'name' =>'boxbilling',
/**
* Database username
*/
'user' =>'foo',
/**
* Database password
*/
'password' =>'foo',
),
'twig' => array(
'debug' => false,
'auto_reload' => false,
'cache' => dirname(__FILE__) . '/bb-data/cache',
),
'api' => array(
// all requests made to API must have referrer request header with the same url as BoxBilling installation
'require_referrer_header' => false,
// empty array will allow all IPs to access API
'allowed_ips' => array(),
// Time span for limit in seconds
'rate_span' => 60 * 60,
// How many requests allowed per time span
'rate_limit' => 1000,
),
);
+22
View File
@@ -0,0 +1,22 @@
<?php
/**
* BoxBilling
*
* @copyright BoxBilling, Inc (http://www.boxbilling.com)
* @license Apache-2.0
*
* Copyright BoxBilling, Inc
* This source file is subject to the Apache-2.0 License that is bundled
* with this source code in the file LICENSE
*/
require_once dirname(__FILE__) . '/bb-load.php';
$di = include dirname(__FILE__) . '/bb-di.php';
$di['translate']();
$interval = isset($argv[1]) ? $argv[1] : null;
$service = $di['mod_service']('cron');
$service->runCrons($interval);
unset($service, $interval, $di);
+347
View File
@@ -0,0 +1,347 @@
<?php
/**
* BoxBilling
*
* @copyright BoxBilling, Inc (http://www.boxbilling.com)
* @license Apache-2.0
*
* Copyright BoxBilling, Inc
* This source file is subject to the Apache-2.0 License that is bundled
* with this source code in the file LICENSE
*/
$di = new Box_Di();
$di['config'] = function() {
$array = include BB_PATH_ROOT . '/bb-config.php';
return new Box_Config($array);
};
$di['logger'] = function () use ($di) {
$logFile = $di['config']['path_logs'];
$writer = new Box_LogStream($logFile);
$log = new Box_Log();
$log->addWriter($writer);
$log_to_db = isset($di['config']['log_to_db']) && $di['config']['log_to_db'];
if ($log_to_db) {
$activity_service = $di['mod_service']('activity');
$writer2 = new Box_LogDb($activity_service);
if ($di['auth']->isAdminLoggedIn()){
$admin = $di['loggedin_admin'];
$log->setEventItem('admin_id', $admin->id);
}
elseif ($di['auth']->isClientLoggedIn()) {
$client = $di['loggedin_client'];
$log->setEventItem('client_id', $client->id);
}
$log->addWriter($writer2);
}
return $log;
};
$di['crypt'] = function() use ($di) {
$crypt = new Box_Crypt();
$crypt->setDi($di);
return $crypt;
};
$di['pdo'] = function() use ($di) {
$c = $di['config']['db'];
$pdo = new PDO($c['type'].':host='.$c['host'].';dbname='.$c['name'],
$c['user'],
$c['password'],
array(
PDO::MYSQL_ATTR_USE_BUFFERED_QUERY => true,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
)
);
if(isset($c['debug']) && $c['debug']) {
$pdo->setAttribute(PDO::ATTR_STATEMENT_CLASS, array ('Box_DbLoggedPDOStatement'));
}
if($c['type'] == 'mysql') {
$pdo->exec( 'SET NAMES "utf8"' );
$pdo->exec( 'SET CHARACTER SET utf8' );
$pdo->exec( 'SET CHARACTER_SET_CONNECTION = utf8' );
$pdo->exec( 'SET CHARACTER_SET_DATABASE = utf8' );
$pdo->exec( 'SET character_set_results = utf8' );
$pdo->exec( 'SET character_set_server = utf8' );
$pdo->exec( 'SET SESSION interactive_timeout = 28800' );
$pdo->exec( 'SET SESSION wait_timeout = 28800' );
}
return $pdo;
};
$di['db'] = function() use ($di) {
require_once dirname(__FILE__) . DIRECTORY_SEPARATOR . 'rb.php';
R::setup($di['pdo']);
$helper = new Box_BeanHelper();
$helper->setDi($di);
$mapper = new \RedBeanPHP\Facade();
$mapper->getRedBean()->setBeanHelper($helper);
$freeze = isset($di['config']['db']['freeze']) ? (bool)$di['config']['db']['freeze'] : true;
$mapper->freeze($freeze);
$db = new Box_Database();
$db->setDi($di);
$db->setDataMapper($mapper);
return $db;
};
$di['pager'] = function() use($di) {
$service = new Box_Pagination();
$service->setDi($di);
return $service;
};
$di['url'] = function() use ($di) {
$url = new Box_Url();
$url->setDi($di);
$url->setBaseUri(BB_URL);
return $url;
};
$di['mod'] = $di->protect(function ($name) use($di) {
$mod = new Box_Mod($name);
$mod->setDi($di);
return $mod;
});
$di['mod_service'] = $di->protect(function ($mod, $sub = '') use($di) {
return $di['mod']($mod)->getService($sub);
});
$di['mod_config'] = $di->protect(function ($name) use($di) {
return $di['mod']($name)->getConfig();
});
$di['events_manager'] = function() use ($di) {
$service = new Box_EventManager();
$service->setDi($di);
return $service;
};
$di['session'] = function () use ($di) {
$handler = new PdoSessionHandler($di['pdo']);
return new Box_Session($handler);
};
$di['cookie'] = function () use ($di) {
$service = new Box_Cookie();
$service->setDi($di);
return $service;
};
$di['request'] = function () use ($di) {
$service = new Box_Request();
$service->setDi($di);
return $service;
};
$di['cache'] = function () use ($di) { return new FileCache();};
$di['auth'] = function () use ($di) { return new Box_Authorization($di);};
$di['twig'] = $di->factory(function () use ($di) {
$config = $di['config'];
$options = $config['twig'];
$loader = new Twig\Loader\ArrayLoader();
$twig = new Twig\Environment($loader, $options);
$box_extensions = new Box_TwigExtensions();
$box_extensions->setDi($di);
//$twig->addExtension(new Twig\Extension\OptimizerExtension());
$twig->addExtension(new \Twig\Extension\StringLoaderExtension());
$twig->addExtension(new Twig\Extension\DebugExtension());
$twig->addExtension(new Twig\Extensions\I18nExtension());
$twig->addExtension($box_extensions);
$twig->getExtension(Twig\Extension\CoreExtension::class)->setDateFormat($config['locale_date_format']);
$twig->getExtension(Twig\Extension\CoreExtension::class)->setTimezone($config['timezone']);
// add globals
if(isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest') {
$_GET['ajax'] = TRUE;
}
$twig->addGlobal('request', $_GET);
$twig->addGlobal('guest', $di['api_guest']);
return $twig;
});
$di['is_client_logged'] = function() use($di) {
if(!$di['auth']->isClientLoggedIn()) {
$url = $di['url']->link('login');
header("Location: $url");
throw new Exception('Client is not logged in');
}
return true;
};
$di['is_admin_logged'] = function() use($di) {
if(!$di['auth']->isAdminLoggedIn()) {
throw new Exception('Admin is not logged in');
}
return true;
};
$di['loggedin_client'] = function() use ($di) {
$di['is_client_logged'];
$client_id = $di['session']->get('client_id');
return $di['db']->getExistingModelById('Client', $client_id);
};
$di['loggedin_admin'] = function() use ($di) {
if(php_sapi_name() == 'cli' || substr(php_sapi_name(), 0, 3) == 'cgi') {
return $di['mod_service']('staff')->getCronAdmin();
}
$di['is_admin_logged'];
$admin = $di['session']->get('admin');
return $di['db']->getExistingModelById('Admin', $admin['id']);
};
$di['api'] = $di->protect(function($role) use($di) {
switch ($role) {
case 'guest':
$identity = new \Model_Guest();
break;
case 'client':
$identity = $di['loggedin_client'];
break;
case 'admin':
$identity = $di['loggedin_admin'];
break;
case 'system':
$identity = $di['mod_service']('staff')->getCronAdmin();
break;
default:
throw new Exception('Unrecognized Handler type: '.$role);
}
$api = new Api_Handler($identity);
$api->setDi($di);
return $api;
});
$di['api_guest'] = function() use ($di) { return $di['api']('guest'); };
$di['api_client'] = function() use ($di) { return $di['api']('client');};
$di['api_admin'] = function() use ($di) { return $di['api']('admin'); };
$di['api_system'] = function() use ($di) { return $di['api']('system'); };
$di['license'] = function () use ($di) {
$service = new Box_License();
$service->setDi($di);
return $service;
};
$di['tools'] = function () use ($di){
$service = new Box_Tools();
$service->setDi($di);
return $service;
};
$di['validator'] = function () use ($di){
$validator = new Box_Validate();
$validator->setDi($di);
return $validator;
};
$di['guzzle_client'] = function () {
return new \Guzzle\Http\Client();
};
$di['mail'] = function () {
return new Box_Mail();
};
$di['extension'] = function () use ($di) {
$extension = new \Box_Extension();
$extension->setDi($di);
return $extension;
};
$di['updater'] = function () use ($di) {
$updater = new \Box_Update();
$updater->setDi($di);
return $updater;
};
$di['curl'] = function ($url) use ($di) {
$curl = new \Box_Curl($url);
$curl->setDi($di);
return $curl;
};
$di['zip_archive'] = function () use ($di) {return new ZipArchive();};
$di['server_package'] = function () use ($di) {return new Server_Package();};
$di['server_client'] = function () use ($di) {return new Server_Client();};
$di['server_account'] = function () use ($di) {return new Server_Account();};
$di['server_manager'] = $di->protect(function ($manager, $config) use($di) {
$class = sprintf('Server_Manager_%s', ucfirst($manager));
return new $class($config);
});
$di['requirements'] = function () use ($di) {
$r = new Box_Requirements();
$r->setDi($di);
return $r;
};
$di['period'] = $di->protect(function($code) use($di){ return new \Box_Period($code); });
$di['theme'] = function() use($di) {
$service = $di['mod_service']('theme');
return $service->getCurrentClientAreaTheme();
};
$di['cart'] = function() use($di) {
$service = $di['mod_service']('cart');
return $service->getSessionCart();
};
$di['table'] = $di->protect(function ($name) use($di) {
$tools = new Box_Tools();
$tools->setDi($di);
$table = $tools->getTable($name);
$table->setDi($di);
return $table;
});
$di['license_server'] = function () use ($di) {
$server = new \Box\Mod\Servicelicense\Server($di['logger']);
$server->setDi($di);
return $server;
};
$di['solusvm'] = $di->protect(function ($config) use($di) {
$solusVM = new \Box\Mod\Servicesolusvm\SolusVM();
$solusVM->setDi($di);
$solusVM->setConfig($config);
return $solusVM;
});
$di['service_boxbilling'] = $di->protect(function ($config) use($di) {
$service = new \Box\Mod\Serviceboxbillinglicense\ServiceBoxbilling($config);
return $service;
});
$di['ftp'] = $di->protect(function($params) use($di){ return new \Box_Ftp($params); });
$di['pdf'] = function () use ($di) {
include BB_PATH_LIBRARY . '/PDF_ImageAlpha.php';
return new \PDF_ImageAlpha();
};
$di['geoip'] = function () use ($di) { return new \GeoIp2\Database\Reader(BB_PATH_LIBRARY . '/GeoLite2-Country.mmdb'); };
$di['password'] = function() use ($di) { return new Box_Password();};
$di['translate'] = $di->protect(function($textDomain = '') use ($di) {
$tr = new Box_Translate();
if (!empty($textDomain)){
$tr->setDomain($textDomain);
}
$cookieBBlang = $di['cookie']->get('BBLANG');
$locale = !empty($cookieBBlang) ? $cookieBBlang : $di['config']['locale'];
$tr->setDi($di);
$tr->setLocale($locale);
$tr->setup();
return $tr;
});
$di['array_get'] = $di->protect(function (array $array, $key, $default = null) use ($di) {
return array_key_exists($key, $array) ? $array[$key] : $default;
});
return $di;
+63
View File
@@ -0,0 +1,63 @@
<?php
/**
* BoxBilling
*
* @copyright BoxBilling, Inc (http://www.boxbilling.com)
* @license Apache-2.0
*
* Copyright BoxBilling, Inc
* This source file is subject to the Apache-2.0 License that is bundled
* with this source code in the file LICENSE
*/
require_once dirname(__FILE__) . '/bb-load.php';
$di = include dirname(__FILE__) . '/bb-di.php';
$di['translate']();
$bb_invoice_id = null;
if(isset($_GET['bb_invoice_id'])) {
$bb_invoice_id = $_GET['bb_invoice_id'];
}
if(isset($_POST['bb_invoice_id'])) {
$bb_invoice_id = $_POST['bb_invoice_id'];
}
$bb_gateway_id = null;
if(isset($_GET['bb_gateway_id'])) {
$bb_gateway_id = $_GET['bb_gateway_id'];
}
if(isset($_POST['bb_gateway_id'])) {
$bb_gateway_id = $_POST['bb_gateway_id'];
}
$ipn = array(
'skip_validation' => true,
'bb_invoice_id' => $bb_invoice_id,
'bb_gateway_id' => $bb_gateway_id,
'get' => $_GET,
'post' => $_POST,
'server' => $_SERVER,
'http_raw_post_data' => file_get_contents("php://input"),
);
try {
$service = $di['mod_service']('invoice', 'transaction');
$output = $service->createAndProcess($ipn);
$res = array('result'=>$output, 'error'=>null);
} catch(Exception $e) {
$res = array('result'=>null, 'error'=> array('message' => $e->getMessage()));
$output = false;
}
// redirect to invoice if gateways requires
if(isset($_GET['bb_redirect']) && isset($_GET['bb_invoice_hash'])) {
$url = $di['url']->link('invoice/'.$_GET['bb_invoice_hash']);
header("Location: $url");
exit;
} else {
header('Cache-Control: no-cache, must-revalidate');
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Content-type: application/json; charset=utf-8');
print json_encode($res);
exit;
}
+151
View File
@@ -0,0 +1,151 @@
<?php
/**
* BoxBilling
*
* @copyright BoxBilling, Inc (http://www.boxbilling.com)
* @license Apache-2.0
*
* Copyright BoxBilling, Inc
* This source file is subject to the Apache-2.0 License that is bundled
* with this source code in the file LICENSE
*/
use Box\InjectionAwareInterface;
class Api_Abstract implements InjectionAwareInterface
{
/**
* @var string - request ip
*/
protected $ip = null;
/**
* @var \Box_Mod
*/
protected $mod = null;
/**
* @var \Box\Mod\X\Service
*/
protected $service = null;
/**
* @var Model_Admin | Model_Client | Model_Guest
*/
protected $identity = null;
/**
* @var \Box_Di
*/
protected $di = null;
/**
* @param \Box_Di $di
*/
public function setDi($di)
{
$this->di = $di;
}
/**
* @return \Box_Di
*/
public function getDi()
{
return $this->di;
}
/**
* @param null $mod
*/
public function setMod($mod)
{
$this->mod = $mod;
}
/**
* @return Box_Mod
*/
public function getMod()
{
if(!$this->mod) {
throw new Box_Exception('Mod object is not set for the service');
}
return $this->mod;
}
/**
* @param null $identity
*/
public function setIdentity($identity)
{
$this->identity = $identity;
}
/**
* @return Model_Admin
*/
public function getIdentity()
{
return $this->identity;
}
/**
* @param null $service
*/
public function setService($service)
{
$this->service = $service;
}
/**
* @return null
*/
public function getService()
{
return $this->service;
}
/**
* @param null $ip
*/
public function setIp($ip)
{
$this->ip = $ip;
}
/**
* @return string
*/
public function getIp()
{
return $this->ip;
}
/**
* @deprecated use DI
*/
public function getApiAdmin()
{
if($this->identity instanceof \Model_Admin) {
return $this->di['api_admin'];
}
return $this->di['api_system'];
}
/**
* @deprecated use DI
*/
public function getApiGuest()
{
return $this->di['api_guest'];
}
/**
* @deprecated use DI
*/
public function getApiClient()
{
return $this->di['api_client'];
}
}
+116
View File
@@ -0,0 +1,116 @@
<?php
/**
* BoxBilling
*
* @copyright BoxBilling, Inc (http://www.boxbilling.com)
* @license Apache-2.0
*
* Copyright BoxBilling, Inc
* This source file is subject to the Apache-2.0 License that is bundled
* with this source code in the file LICENSE
*/
use Box\InjectionAwareInterface;
final class Api_Handler implements InjectionAwareInterface
{
protected $type = NULL;
protected $identity = NULL;
protected $ip = NULL;
protected $di = NULL;
private $_enable_cache = FALSE;
private $_cache = array();
private $_acl_exception = FALSE;
public function __construct($identity)
{
$this->identity = $identity;
$role = str_replace('model_', '', strtolower(get_class($identity)));
$this->type = $role;
}
public function setDi($di)
{
$this->di = $di;
}
public function getDi()
{
return $this->di;
}
public function __call($method, $arguments)
{
if(strpos($method, '_') === FALSE) {
throw new \Box_Exception("Method :method must contain underscore", array(':method'=>$method), 710);
}
if(isset($arguments[0])) {
$arguments = $arguments[0];
}
$e = explode('_', $method);
$mod = strtolower($e[0]);
unset($e[0]);
$method_name = implode('_', $e);
if(empty($mod)) {
throw new \Box_Exception('Invalid module name', null, 714);
}
//cache
$cache_key = md5($this->type.$mod.$method_name.serialize($arguments));
if($this->_enable_cache && isset($this->_cache[$cache_key])) {
return $this->_cache[$cache_key];
}
$service = $this->di['mod']('extension')->getService();
if(!$service->isExtensionActive('mod',$mod)) {
throw new \Box_Exception('BoxBilling module :mod is not installed/activated',array(':mod'=>$mod), 715);
}
// permissions check
if($this->type == 'admin') {
$staff_service = $this->di['mod_service']('Staff');
if(!$staff_service->hasPermission($this->identity, $mod, $method_name)) {
if($this->_acl_exception) {
throw new \Box_Exception('You do not have access to :mod module', array(':mod'=>$mod), 725);
} else {
if(BB_DEBUG) error_log('You do not have access to '.$mod. ' module');
return null;
}
}
}
$api_class = '\Box\Mod\\'.ucfirst($mod).'\\Api\\'.ucfirst($this->type);
$api = new $api_class();
if(!$api instanceof Api_Abstract ) {
throw new \Box_Exception('Api class must be instance of Api_Abstract', null, 730);
}
$bb_mod = $this->di['mod']($mod);
$api->setDi($this->di);
$api->setMod($bb_mod);
$api->setIdentity($this->identity);
$api->setIp($this->di['request']->getClientAddress());
if($bb_mod->hasService()) {
$api->setService($this->di['mod_service']($mod));
}
if(!method_exists($api, $method_name) || !is_callable(array($api, $method_name))) {
$reflector = new ReflectionClass($api);
if(!$reflector->hasMethod('__call')) {
throw new \Box_Exception(':type API call :method does not exist in module :module', array(':type'=>ucfirst($this->type), ':method'=>$method_name,':module'=>$mod), 740);
}
}
$res = $api->{$method_name}($arguments);
if($this->_enable_cache) $this->_cache[$cache_key] = $res;
return $res;
}
}
+290
View File
@@ -0,0 +1,290 @@
<?php
/**
* BoxBilling
*
* @copyright BoxBilling, Inc (http://www.boxbilling.com)
* @license Apache-2.0
*
* Copyright BoxBilling, Inc
* This source file is subject to the Apache-2.0 License that is bundled
* with this source code in the file LICENSE
*/
use Box\InjectionAwareInterface;
class Box_App {
protected $mappings = array();
protected $before_filters = array();
protected $after_filters = array();
protected $shared = array();
protected $options;
protected $di = NULL;
protected $ext = 'phtml';
protected $mod = 'index';
protected $url = '/';
public $uri = NULL;
public function __construct($options=array())
{
$this->options = new ArrayObject($options);
}
public function setDi($di)
{
$this->di = $di;
}
public function setUrl($url)
{
$this->url = $url;
}
protected function registerModule()
{
//bind module urls and process
//determine module and bind urls
$requestUri = $this->url;
if(empty($requestUri)) {
$requestUri = '/';
}
if($requestUri == '/') {
$mod = 'index';
} else {
$requestUri = trim($requestUri, '/');
if(strpos($requestUri, '/') === false) {
$mod = $requestUri;
} else {
list($mod) = explode('/',$requestUri);
}
}
$mod = filter_var($mod, FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_HIGH);
$this->mod = $mod;
$this->uri = $requestUri;
}
protected function init(){}
public function show404(Exception $e) {
error_log($e->getMessage());
header("HTTP/1.0 404 Not Found");
return $this->render('404', array('exception'=>$e));
}
/**
* @param string $url
* @param string $methodName
* @param string $class
*/
public function get($url, $methodName, $conditions = array(), $class = null) {
$this->event('get', $url, $methodName, $conditions, $class);
}
/**
* @param string $url
* @param string $methodName
* @param string $class
*/
public function post($url, $methodName, $conditions = array(), $class = null) {
$this->event('post', $url, $methodName, $conditions, $class);
}
public function put($url, $methodName, $conditions = array(), $class = null) {
$this->event('put', $url, $methodName, $conditions, $class);
}
public function delete($url, $methodName, $conditions = array(), $class = null) {
$this->event('delete', $url, $methodName, $conditions, $class);
}
public function before($methodName, $filterName) {
$this->push_filter($this->before_filters, $methodName, $filterName);
}
public function after($methodName, $filterName) {
$this->push_filter($this->after_filters, $methodName, $filterName);
}
protected function push_filter(&$arr_filter, $methodName, $filterName) {
if (!is_array($methodName)) {
$methodName = explode('|', $methodName);
}
$counted = count($methodName);
for ($i = 0; $i < $counted; $i++) {
$method = $methodName[$i];
if (!isset($arr_filter[$method])) {
$arr_filter[$method] = array();
}
array_push($arr_filter[$method], $filterName);
}
}
protected function run_filter($arr_filter, $methodName) {
if(isset($arr_filter[$methodName])) {
$counted = count($arr_filter[$methodName]);
for ($i=0; $i < $counted; $i++) {
$return = call_user_func(array($this, $arr_filter[$methodName][$i]));
if(!is_null($return)) {
return $return;
}
}
}
}
public function run()
{
$this->registerModule();
$this->init();
return $this->processRequest();
}
/**
* @param string $path
*/
public function redirect($path)
{
$location = $this->di['url']->link($path);
header("Location: $location");
exit;
}
/**
* @param string $fileName
*/
public function render($fileName, $variableArray = array())
{
print 'Rendering '.$fileName;
}
public function sendFile($filename, $contentType, $path) {
header("Content-type: $contentType");
header("Content-Disposition: attachment; filename=$filename");
return readfile($path);
}
public function sendDownload($filename, $path) {
header("Content-Type: application/force-download");
header("Content-Type: application/octet-stream");
header("Content-Type: application/download");
header("Content-Description: File Transfer");
header("Content-Disposition: attachment; filename=$filename".";");
header("Content-Transfer-Encoding: binary");
return readfile($path);
}
protected function executeShared($classname, $methodName, $params)
{
$class = new $classname();
if($class instanceof InjectionAwareInterface) {
$class->setDi($this->di);
}
$reflection = new ReflectionMethod(get_class($class), $methodName);
$args = array();
$args[] = $this; // first param always app instance
foreach($reflection->getParameters() as $param) {
if(isset($params[$param->name])) {
$args[$param->name] = $params[$param->name];
}
else if($param->isDefaultValueAvailable()) {
$args[$param->name] = $param->getDefaultValue();
}
}
return $reflection->invokeArgs($class, $args);
}
protected function execute($methodName, $params, $classname = null) {
$return = $this->run_filter($this->before_filters, $methodName);
if (!is_null($return)) {
return $return;
}
$reflection = new ReflectionMethod(get_class($this), $methodName);
$args = array();
foreach($reflection->getParameters() as $param) {
if(isset($params[$param->name])) {
$args[$param->name] = $params[$param->name];
}
else if($param->isDefaultValueAvailable()) {
$args[$param->name] = $param->getDefaultValue();
}
}
$response = $reflection->invokeArgs($this, $args);
$return = $this->run_filter($this->after_filters, $methodName);
if (!is_null($return)) {
return $return;
}
return $response;
}
/**
* @param string $httpMethod
*/
protected function event($httpMethod, $url, $methodName, $conditions=array(), $classname = null) {
if (method_exists($this, $methodName)) {
array_push($this->mappings, array($httpMethod, $url, $methodName, $conditions));
}
if (null !== $classname) {
array_push($this->shared, array($httpMethod, $url, $methodName, $conditions, $classname));
}
}
protected function processRequest()
{
$sharedCount = count($this->shared);
for($i = 0; $i < $sharedCount; $i++) {
$mapping = $this->shared[$i];
$url = new Box_UrlHelper($mapping[0], $mapping[1], $mapping[3], $this->url);
if($url->match) {
return $this->executeShared($mapping[4], $mapping[2], $url->params);
}
}
// this class mappings
$mappingsCount = count($this->mappings);
for($i = 0; $i < $mappingsCount; $i++) {
$mapping = $this->mappings[$i];
$url = new Box_UrlHelper($mapping[0], $mapping[1], $mapping[3], $this->url);
if($url->match) {
return $this->execute($mapping[2], $url->params);
}
}
$e = new \Box_Exception('Page :url not found', array(':url'=>$this->url), 404);
return $this->show404($e);
}
/**
* @deprecated
*/
public function getApiAdmin()
{
return $this->di['api_admin'];
}
/**
* @deprecated
*/
public function getApiClient()
{
return $this->di['api_client'];
}
/**
* @deprecated
*/
public function getApiGuest()
{
return $this->di['api_guest'];
}
}
+59
View File
@@ -0,0 +1,59 @@
<?php
/**
* BoxBilling
*
* @copyright BoxBilling, Inc (http://www.boxbilling.com)
* @license Apache-2.0
*
* Copyright BoxBilling, Inc
* This source file is subject to the Apache-2.0 License that is bundled
* with this source code in the file LICENSE
*/
class Box_AppAdmin extends Box_App
{
public function init()
{
$m = $this->di['mod']($this->mod);
$controller = $m->getAdminController();
$controller->register($this);
}
public function render($fileName, $variableArray = array())
{
$template = $this->getTwig()->load($fileName.'.phtml');
return $template->render($variableArray);
}
public function redirect($path)
{
$location = $this->di['url']->adminLink($path);
header("Location: $location");
exit;
}
protected function getTwig()
{
$service = $this->di['mod_service']('theme');
$theme = $service->getCurrentAdminAreaTheme();
$loader = new Box_TwigLoader(array(
"mods" => BB_PATH_MODS,
"theme" => BB_PATH_THEMES . DIRECTORY_SEPARATOR . $theme['code'],
"type" => "admin"
)
);
$twig = $this->di['twig'];
$twig->setLoader($loader);
$twig->addGlobal('theme', $theme);
if($this->di['auth']->isAdminLoggedIn()) {
$twig->addGlobal('admin', $this->di['api_admin']);
}
return $twig;
}
}
+112
View File
@@ -0,0 +1,112 @@
<?php
/**
* BoxBilling
*
* @copyright BoxBilling, Inc (http://www.boxbilling.com)
* @license Apache-2.0
*
* Copyright BoxBilling, Inc
* This source file is subject to the Apache-2.0 License that is bundled
* with this source code in the file LICENSE
*/
class Box_AppClient extends Box_App
{
protected function init()
{
$m = $this->di['mod']($this->mod);
$m->registerClientRoutes($this);
if($this->mod == 'api') {
define ('BB_MODE_API', TRUE);
} else {
$extensionService = $this->di['mod_service']('extension');
if ($extensionService->isExtensionActive('mod', 'redirect')) {
$m = $this->di['mod']('redirect');
$m->registerClientRoutes($this);
}
//init index module manually
$this->get('', 'get_index');
$this->get('/', 'get_index');
//init custom methods for undefined pages
$this->get('/:page', 'get_custom_page', array('page' => '[a-z0-9-/.//]+'));
$this->post('/:page', 'get_custom_page', array('page' => '[a-z0-9-/.//]+'));
}
}
public function get_index()
{
return $this->render('mod_index_dashboard');
}
public function get_custom_page($page)
{
$ext = $this->ext;
if(strpos($page, '.') !== false) {
$ext = substr($page, strpos($page, '.')+1);
$page = substr($page, 0, strpos($page, '.'));
}
$page = str_replace('/', '_', $page);
$tpl = 'mod_page_'.$page;
try {
return $this->render($tpl, array('post'=>$_POST), $ext);
} catch(Exception $e) {
if(BB_DEBUG) error_log($e);
}
// throw new \Box_Exception('Page :url not found', array(':url'=>$page), 404);
$e = new \Box_Exception('Page :url not found', array(':url'=>$this->url), 404);
error_log($e->getMessage());
header("HTTP/1.0 404 Not Found");
return $this->render('404', array('exception'=>$e));
}
/**
* @param string $fileName
*/
public function render($fileName, $variableArray = array(), $ext = 'phtml')
{
try {
$template = $this->getTwig()->load($fileName.'.'.$ext);
} catch (Twig\Error\LoaderError $e) {
error_log($e->getMessage());
throw new \Box_Exception('Page not found', null, 404);
}
return $template->render($variableArray);
}
protected function getTwig()
{
$service = $this->di['mod_service']('theme');
$code = $service->getCurrentClientAreaThemeCode();
$theme = $service->getTheme($code);
$settings = $service->getThemeSettings($theme);
$loader = new Box_TwigLoader(array(
"mods" => BB_PATH_MODS,
"theme" => BB_PATH_THEMES.DIRECTORY_SEPARATOR.$code,
"type" => "client"
)
);
$twig = $this->di['twig'];
$twig->setLoader($loader);
$twig->addGlobal('current_theme', $code);
$twig->addGlobal('settings', $settings);
if($this->di['auth']->isClientLoggedIn()) {
$twig->addGlobal('client', $this->di['api_client']);
}
if($this->di['auth']->isAdminLoggedIn()) {
$twig->addGlobal('admin', $this->di['api_admin']);
}
return $twig;
}
}
+57
View File
@@ -0,0 +1,57 @@
<?php
/**
* BoxBilling
*
* @copyright BoxBilling, Inc (http://www.boxbilling.com)
* @license Apache-2.0
*
* Copyright BoxBilling, Inc
* This source file is subject to the Apache-2.0 License that is bundled
* with this source code in the file LICENSE
*/
class Box_Authorization
{
private $di = null;
private $session = null;
public function __construct(Box_Di $di)
{
$this->di = $di;
$this->session = $di['session'];
}
public function isClientLoggedIn()
{
return (bool)($this->session->get('client_id'));
}
public function isAdminLoggedIn()
{
return (bool)($this->session->get('admin'));
}
public function authorizeUser($user, $plainTextPassword)
{
$user = $this->passwordBackwardCompatibility($user, $plainTextPassword);
if ($this->di['password']->verify($plainTextPassword, $user->pass)){
if ($this->di['password']->needsRehash($user->pass)){
$user->pass = $this->di['password']->hashIt($plainTextPassword);
$this->di['db']->store($user);
}
return $user;
}
return null;
}
public function passwordBackwardCompatibility($user, $plainTextPassword)
{
if (sha1($plainTextPassword) == $user->pass){
$user->pass = $this->di['password']->hashIt($plainTextPassword);
$this->di['db']->store($user);
}
return $user;
}
}
+63
View File
@@ -0,0 +1,63 @@
<?php
/**
* BoxBilling
*
* @copyright BoxBilling, Inc (http://www.boxbilling.com)
* @license Apache-2.0
*
* Copyright BoxBilling, Inc
* This source file is subject to the Apache-2.0 License that is bundled
* with this source code in the file LICENSE
*/
class Box_BeanHelper extends \RedBeanPHP\BeanHelper\SimpleFacadeBeanHelper implements \Box\InjectionAwareInterface
{
protected $di;
/**
* @param mixed $di
*/
public function setDi($di)
{
$this->di = $di;
}
/**
* @return mixed
*/
public function getDi()
{
return $this->di;
}
public function getModelForBean( \RedBeanPHP\OODBBean $bean )
{
$prefix = '\\Model_';
$model = $bean->getMeta( 'type' );
$modelName = $prefix.$this->underscoreToCamelCase($model);
if ( !class_exists( $modelName ) ) {
return null;
}
$model = new $modelName();
if($model instanceof \Box\InjectionAwareInterface) {
$model->setDi( $this->di );
}
$model->loadBean( $bean );
return $model;
}
private function underscoreToCamelCase( $string, $first_char_caps = true)
{
if( $first_char_caps === true )
{
$string[0] = strtoupper($string[0]);
}
$func = function($c){ return strtoupper($c[1]); };
return preg_replace_callback('/_([a-z])/', $func, $string);
}
}
+17
View File
@@ -0,0 +1,17 @@
<?php
/**
* BoxBilling
*
* @copyright BoxBilling, Inc (http://www.boxbilling.com)
* @license Apache-2.0
*
* Copyright BoxBilling, Inc
* This source file is subject to the Apache-2.0 License that is bundled
* with this source code in the file LICENSE
*/
/**
* Class Box_Config
*/
class Box_Config extends Pimple\Container {}
+58
View File
@@ -0,0 +1,58 @@
<?php
/**
* BoxBilling
*
* @copyright BoxBilling, Inc (http://www.boxbilling.com)
* @license Apache-2.0
*
* Copyright BoxBilling, Inc
* This source file is subject to the Apache-2.0 License that is bundled
* with this source code in the file LICENSE
*/
class Box_Cookie implements \Box\InjectionAwareInterface
{
protected $di;
/**
* @param mixed $di
*/
public function setDi($di)
{
$this->di = $di;
}
/**
* @return mixed
*/
public function getDi()
{
return $this->di;
}
public function delete($key)
{
unset($_COOKIE[$key]);
}
public function has($key)
{
return isset($_COOKIE[$key]);
}
public function get($key)
{
return isset($_COOKIE[$key]) ? $_COOKIE[$key] : null;
}
public function set($key, $value)
{
$_COOKIE[$key] = $value;
}
public function reset()
{
$_COOKIE = null;
}
}
+88
View File
@@ -0,0 +1,88 @@
<?php
/**
* BoxBilling
*
* @copyright BoxBilling, Inc (http://www.boxbilling.com)
* @license Apache-2.0
*
* Copyright BoxBilling, Inc
* This source file is subject to the Apache-2.0 License that is bundled
* with this source code in the file LICENSE
*/
class Box_Crypt implements \Box\InjectionAwareInterface
{
protected $di = NULL;
const METHOD = 'aes-256-cbc';
public function __construct()
{
if (!extension_loaded('openssl')) {
throw new Box_Exception('php openssl extension must be enabled on your server');
}
}
public function setDi($di)
{
$this->di = $di;
}
public function getDi()
{
return $this->di;
}
public function encrypt($text, $pass = null)
{
$key = $this->_getSalt($pass);
$ivsize = openssl_cipher_iv_length(self::METHOD);
$iv = openssl_random_pseudo_bytes($ivsize);
$ciphertext = openssl_encrypt(
$text,
self::METHOD,
$key,
OPENSSL_RAW_DATA,
$iv
);
return base64_encode($iv . $ciphertext);
}
public function decrypt($text, $pass = null)
{
if (is_null($text)){
return false;
}
$key = $this->_getSalt($pass);
$text = base64_decode($text);
$ivsize = openssl_cipher_iv_length(self::METHOD);
$iv = mb_substr($text, 0, $ivsize, '8bit');
$ciphertext = mb_substr($text, $ivsize, null, '8bit');
$result = openssl_decrypt(
$ciphertext,
self::METHOD,
$key,
OPENSSL_RAW_DATA,
$iv
);
$result = trim($result);
return $result;
}
private function _getSalt($pass = null)
{
if (null == $pass) {
$pass = $this->di['config']['salt'];
}
return pack('H*', hash('md5', $pass));
}
}
+186
View File
@@ -0,0 +1,186 @@
<?php
/**
* BoxBilling
*
* @copyright BoxBilling, Inc (http://www.boxbilling.com)
* @license Apache-2.0
*
* Copyright BoxBilling, Inc
* This source file is subject to the Apache-2.0 License that is bundled
* with this source code in the file LICENSE
*/
class Box_Curl {
protected $_useragent = 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1';
protected $_url;
protected $_followlocation;
protected $_timeout;
protected $_maxRedirects;
protected $_cookieFileLocation = './cookie.txt';
protected $_post;
protected $_postFields;
protected $_referer = "http://www.google.com";
protected $_session;
protected $_webpage;
protected $_includeHeader;
protected $_noBody;
protected $_status;
protected $_binaryTransfer;
public $authentication = 0;
public $auth_name = '';
public $auth_pass = '';
/**
* @var \Box_Di
*/
protected $di = null;
/**
* @param \Box_Di $di
*/
public function setDi($di)
{
$this->di = $di;
}
/**
* @return \Box_Di
*/
public function getDi()
{
return $this->di;
}
/**
* @param string $url
*/
public function __construct($url, $timeOut = 30, $followlocation = true, $maxRedirecs = 4, $binaryTransfer = false, $includeHeader = false, $noBody = false) {
if (!extension_loaded('curl')) {
throw new \Box_Exception('CURL extension is not enabled');
}
$this->_url = $url;
$this->_followlocation = (bool)$followlocation;
$this->_timeout = $timeOut;
$this->_maxRedirects = $maxRedirecs;
$this->_noBody = $noBody;
$this->_includeHeader = $includeHeader;
$this->_binaryTransfer = $binaryTransfer;
$this->_cookieFileLocation = BB_PATH_CACHE . '/c.txt';
}
public function useAuth($use) {
$this->authentication = 0;
if ($use == true)
$this->authentication = 1;
}
public function setName($name) {
$this->auth_name = $name;
}
public function setPass($pass) {
$this->auth_pass = $pass;
}
public function setReferer($referer) {
$this->_referer = $referer;
}
public function setCookiFileLocation($path) {
$this->_cookieFileLocation = $path;
}
public function setPost($postFields) {
$this->_post = true;
$this->_postFields = $postFields;
}
public function setUserAgent($userAgent) {
$this->_useragent = $userAgent;
}
public function request($url = null) {
if (null !== $url) {
$this->_url = $url;
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $this->_url);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Expect:'));
curl_setopt($ch, CURLOPT_TIMEOUT, $this->_timeout);
curl_setopt($ch, CURLOPT_MAXREDIRS, $this->_maxRedirects);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_COOKIEJAR, $this->_cookieFileLocation);
curl_setopt($ch, CURLOPT_COOKIEFILE, $this->_cookieFileLocation);
if (ini_get('open_basedir') == '' && ini_get('safe_mode') == 'Off'){
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, $this->_followlocation);
}
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
if ($this->authentication == 1) {
curl_setopt($ch, CURLOPT_USERPWD, $this->auth_name . ':' . $this->auth_pass);
}
if ($this->_post) {
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $this->_postFields);
}
if ($this->_includeHeader) {
curl_setopt($ch, CURLOPT_HEADER, true);
}
if ($this->_noBody) {
curl_setopt($ch, CURLOPT_NOBODY, true);
}
curl_setopt($ch, CURLOPT_USERAGENT, $this->_useragent);
curl_setopt($ch, CURLOPT_REFERER, $this->_referer);
$this->_webpage = curl_exec($ch);
$this->_status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
return $this;
}
public function getBody()
{
return $this->_webpage;
}
public function getHttpStatus() {
return $this->_status;
}
public function downloadTo($path)
{
if(!file_exists($path)) {
touch($path);
}
set_time_limit(0); // unlimited max execution time
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $this->_url);
curl_setopt($ch, CURLOPT_TIMEOUT, $this->_timeout);
curl_setopt($ch, CURLOPT_FILE, fopen($path, 'w'));
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_exec($ch);
if(curl_errno($ch)) {
throw new Exception(sprintf("curl Error %s: %s", curl_errno($ch), curl_error($ch)));
}
}
public function __tostring() {
return $this->_webpage;
}
}
+191
View File
@@ -0,0 +1,191 @@
<?php
/**
* BoxBilling
*
* @copyright BoxBilling, Inc (http://www.boxbilling.com)
* @license Apache-2.0
*
* Copyright BoxBilling, Inc
* This source file is subject to the Apache-2.0 License that is bundled
* with this source code in the file LICENSE
*/
use Box\InjectionAwareInterface;
class Box_Database implements InjectionAwareInterface
{
protected $di = null;
protected $orm = null;
public function setDataMapper($orm)
{
$this->orm = $orm;
}
public function setDi($di)
{
$this->di = $di;
}
public function getDi()
{
return $this->di;
}
public function dispense($modelName)
{
$type = $this->_getTypeFromModelName($modelName);
$bean = $this->orm->dispense($type);
if($type == $modelName) return $bean;
return $bean->box();
}
public function store($modelOrBean)
{
if($modelOrBean instanceof \RedBean_SimpleModel) {
$bean = $modelOrBean->unbox();
} else {
$bean = $modelOrBean;
}
return $this->orm->store($bean);
}
public function getAll($sql, $values=array() )
{
return $this->orm->getAll($sql, $values);
}
public function getCell($sql, $values=array() )
{
return $this->orm->getCell($sql, $values);
}
public function getRow($sql, $values=array() )
{
return $this->orm->getRow($sql, $values);
}
public function getAssoc( $sql, $values = array())
{
return $this->orm->getAssoc($sql, $values);
}
public function findOne($modelName, $sql=null, $values=array())
{
$type = $this->_getTypeFromModelName($modelName);
$bean = $this->orm->findOne($type, $sql, $values);
if($type == $modelName) return $bean;
if($bean && $bean->id) {
return $bean->box();
}
return null;
}
public function find($modelName, $sql = null, $values = array())
{
$type = $this->_getTypeFromModelName($modelName);
$beans = $this->orm->find($type, $sql, $values);
if($type == $modelName) return $beans;
foreach ($beans as &$bean) {
$bean = $bean->box();
}
return $beans;
}
/**
* @param string $modelName
* @param integer $id
*/
public function load($modelName, $id)
{
/* If RedBean finds the bean it will return
* the OODB Bean object; if it cannot find the bean
* RedBean will return a new bean of type $modelName and with
* primary key ID 0. In the latter case it acts basically the
* same as dispense().
*/
$type = $this->_getTypeFromModelName($modelName);
$bean = $this->orm->load($type, $id);
if ($type == $modelName) return $bean;
if ($bean && $bean->id) {
return $bean->box();
}
return null;
}
/**
* @param string $sql
* @param array $values
* @return int - affected rows
*/
public function exec($sql, $values=array())
{
return $this->orm->exec($sql, $values);
}
public function trash($modelOrBean)
{
if($modelOrBean instanceof \RedBean_SimpleModel) {
$bean = $modelOrBean->unbox();
} else {
$bean = $modelOrBean;
}
return $this->orm->trash($bean);
}
public function getInsertID()
{
return $this->di['pdo']->lastInsertId();
}
public function getColumns($table)
{
return $this->orm->getColumns($table);
}
public function toArray($modelOrBean)
{
if($modelOrBean instanceof \RedBean_SimpleModel) {
$bean = $modelOrBean->unbox();
} else {
$bean = $modelOrBean;
}
return $bean->export();
}
/**
* @param string $modelName
* @param int $id
* @param string $message
* @return \RedBean_SimpleModel
* @throws Box_Exception
*/
public function getExistingModelById($modelName, $id, $message = "Model not found")
{
$model = $this->load($modelName, (int)$id);
if (null === $model) {
throw new \Box_Exception($message);
}
return $model;
}
private function _getTypeFromModelName($modelName)
{
if($modelName == strtolower($modelName)) {
return $modelName;
}
preg_match_all('!([A-Z][A-Z0-9]*(?=$|[A-Z][a-z0-9])|[A-Za-z][a-z0-9]+)!', $modelName, $matches);
$ret = $matches[0];
foreach ($ret as &$match) {
$match = $match == strtoupper($match) ? strtolower($match) : lcfirst($match);
}
return implode('_', $ret);
}
}
+21
View File
@@ -0,0 +1,21 @@
<?php
/**
* BoxBilling
*
* @copyright BoxBilling, Inc (http://www.boxbilling.com)
* @license Apache-2.0
*
* Copyright BoxBilling, Inc
* This source file is subject to the Apache-2.0 License that is bundled
* with this source code in the file LICENSE
*/
class Box_DbLoggedPDOStatement extends PDOStatement
{
public function execute ($input_parameters = null)
{
error_log($this->queryString);
parent::execute($input_parameters);
}
}
+14
View File
@@ -0,0 +1,14 @@
<?php
/**
* BoxBilling
*
* @copyright BoxBilling, Inc (http://www.boxbilling.com)
* @license Apache-2.0
*
* Copyright BoxBilling, Inc
* This source file is subject to the Apache-2.0 License that is bundled
* with this source code in the file LICENSE
*/
class Box_Di extends Pimple\Container {}
+188
View File
@@ -0,0 +1,188 @@
<?php
/**
* BoxBilling
*
* @copyright BoxBilling, Inc (http://www.boxbilling.com)
* @license Apache-2.0
*
* Copyright BoxBilling, Inc
* This source file is subject to the Apache-2.0 License that is bundled
* with this source code in the file LICENSE
*/
class Box_Event implements ArrayAccess, \Box\InjectionAwareInterface
{
protected $di = null;
protected $value = null;
protected $processed = false;
protected $subject = null;
protected $name = '';
protected $parameters = null;
protected $api_guest = null;
protected $api_admin = null;
/**
* Constructs a new sfEvent.
*
* @param mixed $subject The subject
* @param string $name The event name
* @param array $parameters An array of parameters
*/
public function __construct($subject, $name, $parameters = array(), $api_admin = null, $api_guest = null)
{
$this->subject = $subject;
$this->name = $name;
$this->parameters = $parameters;
$this->api_admin = $api_admin;
$this->api_guest = $api_guest;
}
/**
* @param Box_Di|null $di
*/
public function setDi($di)
{
$this->di = $di;
}
/**
* @return Box_Di|null
*/
public function getDi()
{
return $this->di;
}
/**
* Returns the subject.
*
* @return mixed The subject
*/
public function getSubject()
{
return $this->subject;
}
public function getApiAdmin()
{
return $this->api_admin;
}
public function getApiGuest()
{
return $this->api_guest;
}
/**
* Returns the event name.
*
* @return string The event name
*/
public function getName()
{
return $this->name;
}
/**
* Sets the return value for this event.
*
* @param mixed $value The return value
*/
public function setReturnValue($value)
{
$this->value = $value;
}
/**
* Returns the return value.
*
* @return mixed The return value
*/
public function getReturnValue()
{
return $this->value;
}
/**
* Sets the processed flag.
*
* @param Boolean $processed The processed flag value
*/
public function setProcessed($processed)
{
$this->processed = (boolean) $processed;
}
/**
* Returns whether the event has been processed by a listener or not.
*
* @return Boolean true if the event has been processed, false otherwise
*/
public function isProcessed()
{
return $this->processed;
}
/**
* Returns the event parameters.
*
* @return array The event parameters
*/
public function getParameters()
{
return $this->parameters;
}
/**
* Returns true if the parameter exists (implements the ArrayAccess interface).
*
* @param string $name The parameter name
*
* @return Boolean true if the parameter exists, false otherwise
*/
public function offsetExists($name)
{
return array_key_exists($name, $this->parameters);
}
/**
* Returns a parameter value (implements the ArrayAccess interface).
*
* @param string $name The parameter name
*
* @return mixed The parameter value
*/
public function offsetGet($name)
{
if (!array_key_exists($name, $this->parameters))
{
throw new InvalidArgumentException(sprintf('The event "%s" has no "%s" parameter.', $this->name, $name));
}
return $this->parameters[$name];
}
/**
* Sets a parameter (implements the ArrayAccess interface).
*
* @param string $name The parameter name
* @param mixed $value The parameter value
*/
public function offsetSet($name, $value)
{
$this->parameters[$name] = $value;
}
/**
* Removes a parameter (implements the ArrayAccess interface).
*
* @param string $name The parameter name
*/
public function offsetUnset($name)
{
unset($this->parameters[$name]);
}
}
+169
View File
@@ -0,0 +1,169 @@
<?php
/**
* BoxBilling
*
* @copyright BoxBilling, Inc (http://www.boxbilling.com)
* @license Apache-2.0
*
* Copyright BoxBilling, Inc
* This source file is subject to the Apache-2.0 License that is bundled
* with this source code in the file LICENSE
*/
class Box_EventDispatcher
{
protected $listeners = array();
/**
* Connects a listener to a given event name.
*
* @param string $name An event name
* @param mixed $listener A PHP callable
*/
public function connect($name, $listener)
{
if (!isset($this->listeners[$name]))
{
$this->listeners[$name] = array();
}
$this->listeners[$name][] = $listener;
}
/**
* Disconnects a listener for a given event name.
*
* @param string $name An event name
* @param mixed $listener A PHP callable
*
* @return false|null false if listener does not exist, null otherwise
*/
public function disconnect($name, $listener)
{
if (!isset($this->listeners[$name]))
{
return false;
}
foreach ($this->listeners[$name] as $i => $callable)
{
if ($listener === $callable)
{
unset($this->listeners[$name][$i]);
}
}
}
/**
* Disconnects all listeners for a given event name.
*
* @param string $name An event name
*
* @return false|null false if listener does not exist, null otherwise
*/
public function disconnectAll($name)
{
if (!isset($this->listeners[$name]))
{
return false;
}
foreach ($this->listeners[$name] as $i => $callable)
{
unset($this->listeners[$name][$i]);
}
}
/**
* Notifies all listeners of a given event.
*
* @param Box_Event $event A Box_Event instance
*
* @return Box_Event The Box_Event instance
*/
public function notify(Box_Event $event)
{
foreach ($this->getListeners($event->getName()) as $listener)
{
call_user_func($listener, $event);
}
return $event;
}
/**
* Notifies all listeners of a given event until one returns a non null value.
*
* @param Box_Event $event A Box_Event instance
*
* @return Box_Event The Box_Event instance
*/
public function notifyUntil(Box_Event $event)
{
foreach ($this->getListeners($event->getName()) as $listener)
{
if (call_user_func($listener, $event))
{
$event->setProcessed(true);
break;
}
}
return $event;
}
/**
* Filters a value by calling all listeners of a given event.
*
* @param Box_Event $event A Box_Event instance
* @param mixed $value The value to be filtered
*
* @return Box_Event The Box_Event instance
*/
public function filter(Box_Event $event, $value)
{
foreach ($this->getListeners($event->getName()) as $listener)
{
$value = call_user_func_array($listener, array($event, $value));
}
$event->setReturnValue($value);
return $event;
}
/**
* Returns true if the given event name has some listeners.
*
* @param string $name The event name
*
* @return Boolean true if some listeners are connected, false otherwise
*/
public function hasListeners($name)
{
if (!isset($this->listeners[$name]))
{
$this->listeners[$name] = array();
}
return (boolean) count($this->listeners[$name]);
}
/**
* Returns all listeners associated with a given event name.
*
* @param string $name The event name
*
* @return array An array of listeners
*/
public function getListeners($name)
{
if (!isset($this->listeners[$name]))
{
return array();
}
return $this->listeners[$name];
}
}
+92
View File
@@ -0,0 +1,92 @@
<?php
/**
* BoxBilling
*
* @copyright BoxBilling, Inc (http://www.boxbilling.com)
* @license Apache-2.0
*
* Copyright BoxBilling, Inc
* This source file is subject to the Apache-2.0 License that is bundled
* with this source code in the file LICENSE
*/
class Box_EventManager implements \Box\InjectionAwareInterface
{
protected $di;
/**
* @param mixed $di
*/
public function setDi($di)
{
$this->di = $di;
}
/**
* @return mixed
*/
public function getDi()
{
return $this->di;
}
public function fire($data)
{
if(!isset($data['event']) || empty($data['event'])) {
error_log('Invoked event call without providing event name');
return false;
}
$event = $data['event'];
$subject = isset($data['subject']) ? $data['subject'] : null;
$params = isset($data['params']) ? $data['params'] : null;
if(BB_DEBUG) {
$this->di['logger']->debug($event. ': '. var_export($params, 1));
}
$e = new Box_Event($subject, $event, $params);
$e->setDi($this->di);
$disp = new Box_EventDispatcher();
$this->_connectDatabaseHooks($disp, $e->getName());
$disp->notify($e);
return $e->getReturnValue();
}
/**
* @param Box_EventDispatcher $disp
* @param string $event
*/
private function _connectDatabaseHooks(&$disp, $event)
{
$sql="SELECT id, rel_id, meta_value
FROM extension_meta
WHERE extension = 'mod_hook'
AND rel_type = 'mod'
AND meta_key = 'listener'
AND meta_value = :event
";
$list = $this->di['db']->getAll($sql, array('event'=>$event));
// no need to connect listeners
if(empty($list)) {
return ;
}
foreach($list as $listener) {
$mod = $listener['rel_id'];
$event = $listener['meta_value'];
try {
$s = $this->di['mod_service']($mod);
if(method_exists($s, $event)) {
$disp->connect($event, array(get_class($s), $event));
}
} catch(Exception $e) {
error_log($e->getMessage());
}
}
}
}
+29
View File
@@ -0,0 +1,29 @@
<?php
/**
* BoxBilling
*
* @copyright BoxBilling, Inc (http://www.boxbilling.com)
* @license Apache-2.0
*
* Copyright BoxBilling, Inc
* This source file is subject to the Apache-2.0 License that is bundled
* with this source code in the file LICENSE
*/
class Box_Exception extends Exception
{
/**
* Creates a new translated exception.
*
* @param string error message
* @param array translation variables
*/
public function __construct($message, array $variables = NULL, $code = 0)
{
// Set the message
$message = __($message, $variables);
// Pass the message to the parent
parent::__construct($message, $code);
}
}
+19
View File
@@ -0,0 +1,19 @@
<?php
/**
* BoxBilling
*
* @copyright BoxBilling, Inc (http://www.boxbilling.com)
* @license Apache-2.0
*
* Copyright BoxBilling, Inc
* This source file is subject to the Apache-2.0 License that is bundled
* with this source code in the file LICENSE
*/
class Box_ExceptionAuth extends Box_Exception
{
public function __construct($uri = "", $code = 0)
{
parent::__construct('You need to login in order to view this :url page', array(':url'=>$uri), $code);
}
}
+98
View File
@@ -0,0 +1,98 @@
<?php
/**
* BoxBilling
*
* @copyright BoxBilling, Inc (http://www.boxbilling.com)
* @license Apache-2.0
*
* Copyright BoxBilling, Inc
* This source file is subject to the Apache-2.0 License that is bundled
* with this source code in the file LICENSE
*/
/**
* BoxBilling extensions API wrapper
*/
class Box_Extension
{
/**
* @var \Box_Ii
*/
protected $di = null;
/**
* @param \Box_Ii $di
*/
public function setDi($di)
{
$this->di = $di;
}
/**
* @return \Box_Ii
*/
public function getDi()
{
return $this->di;
}
const TYPE_MOD = 'mod';
const TYPE_THEME = 'theme';
const TYPE_PG = 'payment-gateway';
const TYPE_SM = 'server-manager';
const TYPE_DR = 'domain-registrar';
const TYPE_HOOK = 'hook';
const TYPE_TRANSLATION = 'translation';
private $_url = 'https://extensions.boxbilling.com/api/';
public function getExtension($id, $type = Box_Extension::TYPE_MOD)
{
$params = array();
$params['return'] = 'manifest';
$params['type'] = $type;
$params['id'] = $id;
return $this->_request('guest/extension/get', $params);
}
public function getLatestExtensionVersion($id, $type = Box_Extension::TYPE_MOD)
{
$params = array();
$params['type'] = $type;
$params['id'] = $id;
return $this->_request('guest/extension/version', $params);
}
public function getLatest($type = null)
{
$params = array();
$params['return'] = 'manifest';
if(!empty($type)) {
$params['type'] = $type;
}
return $this->_request('guest/extension/search', $params);
}
/**
* @param string $call
*/
private function _request($call, array $params)
{
$params['bb_version'] = Box_Version::VERSION;
$url = $this->_url.$call.'?'.http_build_query($params);
$curl = new Box_Curl($url, 5);
$curl->request();
$response = $curl->getBody();
$json = json_decode($response, 1);
if(is_null($json)) {
throw new \Box_Exception('Unable to connect to BoxBilling extensions site.', null, 1545);
}
if(isset($json['error']) && is_array($json['error'])) {
throw new Exception($json['error']['message'], 746);
}
return $json['result'];
}
}
+3
View File
@@ -0,0 +1,3 @@
<?php
class FileCacheException extends Exception{}
+548
View File
@@ -0,0 +1,548 @@
<?php
/**
* BoxBilling
*
* @copyright BoxBilling, Inc (http://www.boxbilling.com)
* @license Apache-2.0
*
* Copyright BoxBilling, Inc
* This source file is subject to the Apache-2.0 License that is bundled
* with this source code in the file LICENSE
*/
class Box_Ftp
{
protected $link;
protected $timeout = 5;
protected $options = array();
protected $bb_root = NULL; // initial dir
protected $permission = NULL;
protected $method;
public function __construct($opt=array())
{
//Check if possible to use ftp functions.
if ( ! extension_loaded('ftp')) {
throw new \Box_Exception('FTP extension is not enabled in PHP. You will not be able to use automatic updates and other automation.');
}
$this->method = 'ftpext';
//Check if possible to use ftp functions.
if (!extension_loaded('ftp')) {
throw new \Box_Exception('The ftp PHP extension is not available');
}
// Set defaults:
if ( empty($opt['port']) )
$this->options['port'] = 21;
else
$this->options['port'] = $opt['port'];
if ( empty($opt['hostname']) )
throw new \Box_Exception('FTP hostname is required');
else
$this->options['hostname'] = $opt['hostname'];
if ( isset($opt['root']) && ! empty($opt['root']) )
$this->bb_root = $opt['root'];
// Check if the options provided are OK.
if ( empty($opt['username']) )
throw new \Box_Exception('FTP username is required');
else
$this->options['username'] = $opt['username'];
if ( empty($opt['password']) )
throw new \Box_Exception('FTP password is required');
else
$this->options['password'] = $opt['password'];
$this->options['ssl'] = false;
if ( isset($opt['connection_type']) && 'ftps' == $opt['connection_type'] )
$this->options['ssl'] = true;
}
public function connect()
{
if ( isset($this->options['ssl']) && $this->options['ssl'] && function_exists('ftp_ssl_connect') )
$this->link = @ftp_ssl_connect($this->options['hostname'], $this->options['port'], $this->timeout);
else
$this->link = @ftp_connect($this->options['hostname'], $this->options['port'], $this->timeout);
if ( ! $this->link ) {
throw new \Box_Exception('Failed to connect to FTP Server :host : :port',array(':host'=>$this->options['hostname'], ':port'=>$this->options['port']));
}
if ( ! @ftp_login($this->link,$this->options['username'], $this->options['password']) ) {
throw new \Box_Exception('FTP Username/Password incorrect for :usernmae', array(':username'=>$this->options['username']));
}
//Set the Connection to use Passive FTP
@ftp_pasv( $this->link, true );
if($this->bb_root) {
$this->chdir($this->bb_root);
}
return true;
}
public function setDefaultPermissions($perm)
{
$this->permission = $perm;
return $this;
}
public function get_contents($file, $type = '', $resumepos = 0 )
{
if( empty($type) )
$type = FTP_BINARY;
$temp = tmpfile();
if ( ! $temp )
return false;
if( ! @ftp_fget($this->link, $temp, $file, $type, $resumepos) )
return false;
fseek($temp, 0); //Skip back to the start of the file being written to
$contents = '';
while ( ! feof($temp) )
$contents .= fread($temp, 8192);
fclose($temp);
return $contents;
}
public function get_contents_array($file)
{
return explode("\n", $this->get_contents($file));
}
/**
* @param string $contents
*/
public function put_contents($file, $contents, $type = '' )
{
if( empty($type) )
$type = $this->is_binary($contents) ? FTP_BINARY : FTP_ASCII;
$temp = tmpfile();
if ( ! $temp )
return false;
fwrite($temp, $contents);
fseek($temp, 0); //Skip back to the start of the file being written to
$ret = @ftp_fput($this->link, $file, $temp, $type);
fclose($temp);
return $ret;
}
/**
* Put directory to ftp
* @param string $src_dir
* @param string $dst_dir
*/
public function put_dir($src_dir, $dst_dir = null)
{
if ($dst_dir == null) {
$dst_dir = $this->cwd();
}
$src_dir = rtrim($src_dir, '/');
$conn_id = $this->link;
$d = dir($src_dir);
while($file = $d->read()) { // do this for each file in the directory
if ($file != "." && $file != "..") { // to prevent an infinite loop
if (is_dir($src_dir."/".$file)) { // do the following if it is a directory
if (!@ftp_chdir($conn_id, $dst_dir."/".$file)) {
ftp_mkdir($conn_id, $dst_dir."/".$file); // create directories that do not yet exist
}
$this->put_dir($src_dir."/".$file, $dst_dir."/".$file); // recursive part
} else {
@ftp_delete($conn_id, $dst_dir."/".$file);
$upload = ftp_put($conn_id, $dst_dir."/".$file, $src_dir."/".$file, FTP_BINARY); // put the files
}
}
}
$d->close();
return true;
}
public function cwd()
{
$cwd = ftp_pwd($this->link);
if( $cwd ) {
$cwd = $this->trailingslashit($cwd);
}
return $cwd;
}
public function chdir($dir)
{
return @ftp_chdir($this->link, $dir);
}
/**
* @param boolean $group
*/
private function chgrp($file, $group, $recursive = false )
{
return false;
}
public function chmod($file, $mode = false, $recursive = false)
{
if( ! $mode )
$mode = $this->permission;
if( ! $mode )
return false;
if ( ! $this->exists($file) && ! $this->is_dir($file) )
return false;
if ( ! $recursive || ! $this->is_dir($file) ) {
if ( ! function_exists('ftp_chmod') )
return @ftp_site($this->link, sprintf('CHMOD %o %s', $mode, $file));
return @ftp_chmod($this->link, $mode, $file);
}
//Is a directory, and we want recursive
$filelist = $this->dirlist($file);
foreach($filelist as $filename){
$this->chmod($file . '/' . $filename, $mode, $recursive);
}
return true;
}
/**
* @param boolean $owner
*/
private function chown($file, $owner, $recursive = false )
{
return false;
}
public function owner($file)
{
$dir = $this->dirlist($file);
return $dir[$file]['owner'];
}
public function getchmod($file)
{
$dir = $this->dirlist($file);
return $dir[$file]['permsn'];
}
public function group($file)
{
$dir = $this->dirlist($file);
return $dir[$file]['group'];
}
/**
* Performs recursive directory copy with content
* @todo check for unlimited recurse if source folder is hghr than destination
*
* @param string $source
* @param string $destination
* @param bool $overwrite
* @return bool
*/
public function copyDir($source, $destination, $overwrite = false )
{
if( ! $overwrite && !$this->is_dir($destination) )
return false;
if( $overwrite && !$this->is_dir($destination) ) {
if(!$this->mkdir($destination)) {
return false;
}
}
if (!$this->is_dir($source) || !$this->is_dir($destination)) {
return false;
}
$res = false;
$this->chdir($source);
$dir_contents = $this->dirlist($source, false, true);
if (empty($dir_contents)) { return true; }
foreach($dir_contents as $name=>$params) {
if ($params['isdir']) {
$res = $this->copyDir($source."/".$name, $destination."/".$name, $overwrite);
} else {
$res = $this->copy($source."/".$name, $destination."/".$name, $overwrite);
}
}
return $res;
}
/**
* @param string $source
* @param string $destination
*/
public function copy($source, $destination, $overwrite = false )
{
if( ! $overwrite && $this->exists($destination) )
return false;
$content = $this->get_contents($source);
if( false === $content)
return false;
return $this->put_contents($destination, $content);
}
public function move($source, $destination, $overwrite = false)
{
return ftp_rename($this->link, $source, $destination);
}
public function delete($file, $recursive = false )
{
if ( empty($file) )
return false;
if ( $this->is_file($file) )
return @ftp_delete($this->link, $file);
if ( !$recursive )
return @ftp_rmdir($this->link, $file);
$filelist = $this->dirlist( $this->trailingslashit($file) );
if ( !empty($filelist) )
foreach ( $filelist as $delete_file )
$this->delete( $this->trailingslashit($file) . $delete_file['name'], $recursive);
return @ftp_rmdir($this->link, $file);
}
public function exists($file)
{
$list = ftp_rawlist($this->link, $file, false);
return !empty($list); //empty list = no file, so invert.
}
public function is_file($file) {
return $this->exists($file) && !$this->is_dir($file);
}
public function is_dir($path)
{
$cwd = $this->cwd();
$result = @ftp_chdir($this->link, $this->trailingslashit($path) );
if( $result && $path == $this->cwd() || $this->cwd() != $cwd ) {
ftp_chdir($this->link, $cwd);
return true;
}
return false;
}
private function is_readable($file)
{
//Get dir list, Check if the file is readable by the current user??
return true;
}
private function is_writable($file)
{
//Get dir list, Check if the file is writable by the current user??
return true;
}
private function atime($file)
{
return false;
}
public function mtime($file)
{
return ftp_mdtm($this->link, $file);
}
public function size($file)
{
return ftp_size($this->link, $file);
}
private function touch($file, $time = 0, $atime = 0)
{
return false;
}
/**
* @param string $path
*/
public function mkdir($path, $chmod = false, $chown = false, $chgrp = false)
{
if( !ftp_mkdir($this->link, $path) )
return false;
if( $chmod )
$this->chmod($path, $chmod);
if( $chown )
$this->chown($path, $chown);
if( $chgrp )
$this->chgrp($path, $chgrp);
return true;
}
public function rmdir($path, $recursive = false)
{
return $this->delete($path, $recursive);
}
private function parselisting($line)
{
static $is_windows;
$b = array();
if ( is_null($is_windows) )
$is_windows = strpos( strtolower(ftp_systype($this->link)), 'win') !== false;
if ($is_windows && preg_match("/([0-9]{2})-([0-9]{2})-([0-9]{2}) +([0-9]{2}):([0-9]{2})(AM|PM) +([0-9]+|<DIR>) +(.+)/", $line, $lucifer)) {
if ($lucifer[3]<70) { $lucifer[3] +=2000; } else { $lucifer[3]+=1900; } // 4digit year fix
$b['isdir'] = ($lucifer[7]=="<DIR>");
if ( $b['isdir'] )
$b['type'] = 'd';
else
$b['type'] = 'f';
$b['size'] = $lucifer[7];
$b['month'] = $lucifer[1];
$b['day'] = $lucifer[2];
$b['year'] = $lucifer[3];
$b['hour'] = $lucifer[4];
$b['minute'] = $lucifer[5];
$b['time'] = @mktime($lucifer[4]+(strcasecmp($lucifer[6],"PM")==0?12:0),$lucifer[5],0,$lucifer[1],$lucifer[2],$lucifer[3]);
$b['am/pm'] = $lucifer[6];
$b['name'] = $lucifer[8];
} else if (!$is_windows && $lucifer=preg_split("/[ ]/",$line,9,PREG_SPLIT_NO_EMPTY)) {
//echo $line."\n";
$lcount=count($lucifer);
if ($lcount<8) return '';
$b = array();
$b['isdir'] = $lucifer[0]{0} === "d";
$b['islink'] = $lucifer[0]{0} === "l";
if ( $b['isdir'] )
$b['type'] = 'd';
elseif ( $b['islink'] )
$b['type'] = 'l';
else
$b['type'] = 'f';
$b['perms'] = $lucifer[0];
$b['number'] = $lucifer[1];
$b['owner'] = $lucifer[2];
$b['group'] = $lucifer[3];
$b['size'] = $lucifer[4];
if ($lcount==8) {
sscanf($lucifer[5],"%d-%d-%d",$b['year'],$b['month'],$b['day']);
sscanf($lucifer[6],"%d:%d",$b['hour'],$b['minute']);
$b['time'] = @mktime($b['hour'],$b['minute'],0,$b['month'],$b['day'],$b['year']);
$b['name'] = $lucifer[7];
} else {
$b['month'] = $lucifer[5];
$b['day'] = $lucifer[6];
if (preg_match("/([0-9]{2}):([0-9]{2})/",$lucifer[7],$l2)) {
$b['year'] = date("Y");
$b['hour'] = $l2[1];
$b['minute'] = $l2[2];
} else {
$b['year'] = $lucifer[7];
$b['hour'] = 0;
$b['minute'] = 0;
}
$b['time'] = strtotime(sprintf("%d %s %d %02d:%02d",$b['day'],$b['month'],$b['year'],$b['hour'],$b['minute']));
$b['name'] = $lucifer[8];
}
}
return $b;
}
public function dirlist($path = '.', $incdot = false, $recursive = false)
{
if( $this->is_file($path) ) {
$limitFile = basename($path);
$path = dirname($path) . '/';
} else {
$limitFile = false;
}
$list = ftp_rawlist($this->link, '-a ' . $path, false);
if ( $list === false )
return false;
$dirlist = array();
foreach ( $list as $k => $v ) {
$entry = $this->parselisting($v);
if ( empty($entry) )
continue;
if ( '.' == $entry["name"] || '..' == $entry["name"] )
continue;
$dirlist[ $entry['name'] ] = $entry;
}
if ( ! $dirlist )
return false;
if ( empty($dirlist) )
return array();
$ret = array();
foreach ( $dirlist as $struc ) {
if ( 'd' == $struc['type'] ) {
$struc['files'] = array();
if ( $incdot ){
//We're including the doted starts
if( '.' != $struc['name'] && '..' != $struc['name'] ){ //Ok, It isnt a special folder
if ($recursive)
$struc['files'] = $this->dirlist($path . '/' . $struc['name'], $incdot, $recursive);
}
} else { //No dots
if ($recursive)
$struc['files'] = $this->dirlist($path . '/' . $struc['name'], $incdot, $recursive);
}
}
//File
$ret[$struc['name']] = $struc;
}
return $ret;
}
/**
* Return current directory contents
* @return array
*/
public function dirContents()
{
$contents = ftp_nlist($this->link, ".");
return $contents;
}
protected function trailingslashit($string)
{
$string = rtrim($string, '/');
return $string . '/';
}
protected function is_binary( $text )
{
return (bool) preg_match('|[^\x20-\x7E]|', $text); //chr(32)..chr(127)
}
public function disconnect()
{
if( $this->link )
ftp_close($this->link);
}
public function __destruct()
{
$this->disconnect();
}
}
@@ -0,0 +1,27 @@
<?php
/**
* BoxBilling
*
* @copyright BoxBilling, Inc (http://www.boxbilling.com)
* @license Apache-2.0
*
* Copyright BoxBilling, Inc
* This source file is subject to the Apache-2.0 License that is bundled
* with this source code in the file LICENSE
*/
namespace Box;
interface InjectionAwareInterface
{
/**
* @param \Box_Di $di
* @return void
*/
public function setDi($di);
/**
* @return \Box_Di
*/
public function getDi ();
}
+204
View File
@@ -0,0 +1,204 @@
<?php
/**
* BoxBilling
*
* @copyright BoxBilling, Inc (http://www.boxbilling.com)
* @license Apache-2.0
*
* Copyright BoxBilling, Inc
* This source file is subject to the Apache-2.0 License that is bundled
* with this source code in the file LICENSE
*/
class Box_License implements \Box\InjectionAwareInterface
{
protected $di;
public function setDi($di)
{
$this->di = $di;
}
public function getDi()
{
return $this->di;
}
/**
* @return string
*/
public function getKey()
{
$license = $this->di['config']['license'];
if(!$license || $license == '') {
throw new \Box_Exception('BoxBilling license key must be defined in bb-config.php file.', null, 315);
}
return $license;
}
public function check()
{
if(!$this->isValid()) {
throw new \Box_Exception('License is not valid');
}
}
public function isValid()
{
try {
$this->getDetails();
return true;
} catch(\Exception $e) {
return false;
}
}
public function isPro()
{
return ($this->getBBType() == \Box_Version::TYPE_PRO);
}
private function getBBType()
{
$prefixes = array(
'PRO-',
'HOSTING24-',
);
$bb_license = $this->getKey();
foreach($prefixes as $prefix){
if(substr($bb_license, 0, strlen($prefix)) == $prefix) {
return \Box_Version::TYPE_PRO;
}
}
return \Box_Version::TYPE_FREE;
}
public function getDetails($from_server = false)
{
$license = $this->getKey();
$systemService = $this->di['mod_service']('system');
$salt = 'IJ2bspsxk1U1INr';
$key = md5('_lc_'.$license);
$cache = $systemService->getParamValue($key);
//set when last time was license checked
$check_key = md5('_last_check_'.$license);
$v = $systemService->getParamValue($check_key);
$last_check = time();
if(!$v) {
$from_server = true;
} else {
$checkd = $this->di['crypt']->decrypt($v, $salt);
if(is_numeric($checkd)) {
$last_check = $checkd;
}
}
if((time() - $last_check) > 60 * 60 * 1) {
$from_server = true;
}
if($cache && !$from_server) {
$data = @unserialize($this->di['crypt']->decrypt($cache, $salt));
if ($data === false) {
$from_server = true;
}
}
if(!$cache || $from_server) {
try {
$servers = array(
'http://www.boxbilling.com/api/guest/servicelicense/check',
);
$l = $this->_getLicenseDetailsFromServer($servers);
} catch(\LogicException $e) {
error_log($e->getMessage());
return array();
}
$data = $l;
$systemService->setParamValue($key, $this->di['crypt']->encrypt(serialize($l), $salt), true);
$systemService->setParamValue($check_key, $this->di['crypt']->encrypt(time(), $salt), true);
} else {
$data = @unserialize($this->di['crypt']->decrypt($cache, $salt));
if (!is_array($data)) {
error_log('Invalid response from licensing server. 9115');
$systemService->setParamValue($key, $this->di['crypt']->encrypt(serialize(false), $salt), true);
}
}
return $data;
}
public function _getLicenseDetailsFromServer(array $servers)
{
$params = array();
$params['license'] = $this->di['config']['license'];
$params['host'] = BB_URL;
$params['path'] = BB_PATH_ROOT;
$params['version'] = \Box_Version::VERSION;
$params['os'] = PHP_OS;
$params['format'] = 2;
foreach($servers as $server) {
$response = $this->_tryLicensingServer($server, $params);
// check empty response
if(!$response) {
error_log($response);
continue;
}
// check invalid json
$r = json_decode($response, 1);
if(!is_array($r) || !isset($r['result'])) {
error_log('Invalid json result '. $response);
continue;
}
// check server error
if(isset($r['error']) && is_array($r['error'])) {
error_log(print_r($r['error'], 1));
continue;
}
if(!is_array($r['result']) || !isset($r['result']['valid'])) {
error_log('Strange response from licensing server');
continue;
}
if(!$r['result']['valid']) {
$code = $r['result']['error_code'] ? (int)$r['result']['error_code'] : 9019;
$msg = (string)$r['result']['error'];
throw new \Exception($msg, $code);
}
return $r['result'];
}
return array();
}
private function _tryLicensingServer($url, $params)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_VERBOSE, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 20);
curl_setopt($ch, CURLOPT_TIMEOUT, 20);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
}
+167
View File
@@ -0,0 +1,167 @@
<?php
/**
* BoxBilling
*
* @copyright BoxBilling, Inc (http://www.boxbilling.com)
* @license Apache-2.0
*
* Copyright BoxBilling, Inc
* This source file is subject to the Apache-2.0 License that is bundled
* with this source code in the file LICENSE
*/
/**
* @method void emerg(string $message)
* @method void alert(string $message)
* @method void crit(string $message)
* @method void err(string $message)
* @method void warn(string $message)
* @method void notice(string $message)
* @method void info(string $message)
* @method void debug(string $message)
*/
class Box_Log
{
const EMERG = 0; // Emergency: system is unusable
const ALERT = 1; // Alert: action must be taken immediately
const CRIT = 2; // Critical: critical conditions
const ERR = 3; // Error: error conditions
const WARN = 4; // Warning: warning conditions
const NOTICE = 5; // Notice: normal but significant condition
const INFO = 6; // Informational: informational messages
const DEBUG = 7; // Debug: debug messages
protected $_priorities = array(
self::EMERG => 'EMERG',
self::ALERT => 'ALERT',
self::CRIT => 'CRIT',
self::ERR => 'ERR',
self::WARN => 'WARN',
self::NOTICE => 'NOTICE',
self::INFO => 'INFO',
self::DEBUG => 'DEBUG',
);
protected $_min_priority = 'NULL';
protected $_writers = array();
protected $_extras = array();
protected $di;
/**
* @param mixed $di
*/
public function setDi($di)
{
$this->di = $di;
}
public function __call($method, $params)
{
$priority = strtoupper($method);
if (($priority = array_search($priority, $this->_priorities)) !== false) {
switch (count($params)) {
case 0:
throw new \Box_Exception('Missing log message');
case 1:
$message = array_shift($params);
$extras = null;
break;
default:
$message = array_shift($params);
$message = vsprintf($message, array_values($params));
if (!$message) {
throw new LogicException('Number of placeholders does not match number of variables');
}
break;
}
$this->log($message, $priority);
} else {
throw new \Box_Exception('Bad log priority');
}
}
public function log($message, $priority, $extras = null)
{
// sanity checks
if (empty($this->_writers)) {
return;
}
if (! isset($this->_priorities[$priority])) {
throw new \Box_Exception('Bad log priority');
}
if($this->_min_priority && $priority > $this->_min_priority) {
return;
}
$event = $this->_packEvent($message, $priority);
// Check to see if any extra information was passed
if (!empty($extras)) {
$info = array();
if (is_array($extras)) {
foreach ($extras as $key => $value) {
if (is_string($key)) {
$event[$key] = $value;
} else {
$info[] = $value;
}
}
} else {
$info = $extras;
}
if (!empty($info)) {
$event['info'] = $info;
}
}
if($this->di('config')('debug') === FALSE && $event('priority') > self::INFO) {
//do not log debug level messages if debug is OFF
// if($this->_min_priority && $priority > self::INFO) {
return ;
}
// send to each writer
foreach ($this->_writers as $writer) {
$writer->write($event);
}
}
protected function _packEvent($message, $priority)
{
return array_merge(array(
'timestamp' => date('Y-m-d H:i:s'),
'message' => $message,
'priority' => $priority,
'priorityName' => $this->_priorities[$priority]
),
$this->_extras
);
}
/**
* @param Box_LogDb|Box_LogStream $writer
*/
public function addWriter($writer)
{
$this->_writers[] = $writer;
return $this;
}
public function setEventItem($name, $value)
{
$this->_extras = array_merge($this->_extras, array($name => $value));
return $this;
}
public function setMinPriority($priority)
{
$this->_min_priority = $priority;
return $this;
}
}
+50
View File
@@ -0,0 +1,50 @@
<?php
/**
* BoxBilling
*
* @copyright BoxBilling, Inc (http://www.boxbilling.com)
* @license Apache-2.0
*
* Copyright BoxBilling, Inc
* This source file is subject to the Apache-2.0 License that is bundled
* with this source code in the file LICENSE
*/
class Box_LogDb
{
/**
* $service - module service class
*
* @var object $service
*/
protected $service = null;
/**
* Class constructor
*
* @param object $service - module service class object
*/
public function __construct($service)
{
$this->service = $service;
}
/**
* Write a message to the log.
*
* @param array $event event data
* @return void
*/
public function write($event)
{
try {
if(method_exists($this->service, 'logEvent')) {
$this->service->logEvent($event);
}
} catch(Exception $e) {
error_log($e);
}
}
}
+69
View File
@@ -0,0 +1,69 @@
<?php
/**
* BoxBilling
*
* @copyright BoxBilling, Inc (http://www.boxbilling.com)
* @license Apache-2.0
*
* Copyright BoxBilling, Inc
* This source file is subject to the Apache-2.0 License that is bundled
* with this source code in the file LICENSE
*/
class Box_LogStream
{
private $_stream = NULL;
/**
* @param string $streamOrUrl
*/
public function __construct($streamOrUrl, $mode = null)
{
// Setting the default
if (null === $mode) {
$mode = 'a';
}
if (is_resource($streamOrUrl)) {
if (get_resource_type($streamOrUrl) != 'stream') {
throw new \Box_Exception('Resource is not a stream');
}
if ($mode != 'a') {
throw new \Box_Exception('Mode cannot be changed on existing streams');
}
$this->_stream = $streamOrUrl;
} else {
if (is_array($streamOrUrl) && isset($streamOrUrl['stream'])) {
$streamOrUrl = $streamOrUrl['stream'];
}
if(!file_exists($streamOrUrl)) {
@touch($streamOrUrl);
}
if (! $this->_stream = @fopen($streamOrUrl, $mode, false)) {
throw new \Box_Exception(":stream cannot be opened with mode :mode", array(':stream'=>$streamOrUrl, ':mode'=>$mode));
}
}
}
public function write($event)
{
$output = '%timestamp% %priorityName% (%priority%): %message%'.PHP_EOL;
foreach ($event as $name => $value) {
if ((is_object($value) && !method_exists($value,'__toString'))
|| is_array($value)
) {
$value = gettype($value);
}
$output = str_replace("%$name%", $value, $output);
}
if (false === @fwrite($this->_stream, $output)) {
throw new \Box_Exception("Unable to write to stream");
}
}
}
+285
View File
@@ -0,0 +1,285 @@
<?php
/**
* BoxBilling
*
* @copyright BoxBilling, Inc (http://www.boxbilling.com)
* @license Apache-2.0
*
* Copyright BoxBilling, Inc
* This source file is subject to the Apache-2.0 License that is bundled
* with this source code in the file LICENSE
*/
/**
* BoxBilling
*
* LICENSE
*
* This source file is subject to the license that is bundled
* with this package in the file LICENSE.txt
* It is also available through the world-wide-web at this URL:
* http://www.boxbilling.com/LICENSE.txt
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@boxbilling.com so we can send you a copy immediately.
*
* @copyright Copyright (c) 2010-2012 BoxBilling (http://www.boxbilling.com)
* @license http://www.boxbilling.com/LICENSE.txt
* @version $Id$
*/
class Box_Mail
{
private $_bodyHtml = NULL;
private $_from = NULL;
private $_from_name = NULL;
private $_subject = NULL;
private $_replyTo = NULL;
private $_replyTo_name = NULL;
private $_to = NULL;
private $_headers = '';
public function send($transport = 'sendmail', $options = array())
{
if($transport == 'sendmail') {
$this->_sendMail($options);
} else if($transport == 'smtp') {
$this->_sendSmtpMail($options);
} else if($transport == 'sendgrid') {
$this->_sendSendgrid($options);
} else {
throw new \Box_Exception('Unknown mail transport: :transport', array(':transport'=>$transport));
}
}
public function setBodyHtml($param)
{
$this->_bodyHtml = $param;
return $this;
}
public function setFrom($email, $name = null)
{
$this->_from = $this->_filterEmail($email);
$this->_from_name = $this->_filterName($name);
return $this;
}
public function getSubject()
{
return $this->_subject;
}
public function getBody()
{
return $this->_bodyHtml;
}
public function setSubject($subject)
{
$this->_subject = $this->_filterOther($subject);
return $this;
}
public function setReplyTo($email, $name = null)
{
$this->_replyTo = $this->_filterEmail($email);
$this->_replyTo_name = $this->_filterName($name);
return $this;
}
public function addTo($email, $name='')
{
$this->_to = $this->_filterEmail($email);
return $this;
}
protected function _sendSendgrid($options)
{
if(!isset($options['sendgrid_username']) || !isset($options['sendgrid_password'])) {
throw new \Box_Exception('Sendgrid is not configured');
}
$user = isset($options['sendgrid_username']) ? $options['sendgrid_username'] : NULL;
$pass = isset($options['sendgrid_password']) ? $options['sendgrid_password'] : NULL;
// Create JSON array
$params = array(
'api_user' => $user,
'api_key' => $pass,
'to' => $this->_to,
'subject' => $this->_subject,
'html' => $this->_bodyHtml . 'Reply Address: ' . $this->_from,
'text' => $this->_bodyHtml . 'Reply Address: ' . $this->_from,
'from' => $replyaddy,
);
// create the request URL
$request = 'https://api.sendgrid.com/api/mail.send.json';
$session = curl_init($request);
// Tell curl to use HTTP POST
curl_setopt ($session, CURLOPT_POST, true);
// Tell curl that this is the body of the POST
curl_setopt ($session, CURLOPT_POSTFIELDS, $params);
// Tell curl not to return headers, but do return the response
curl_setopt($session, CURLOPT_HEADER, false);
// Tell PHP not to use SSLv3 (instead opting for TLS)
curl_setopt($session, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1_2);
curl_setopt($session, CURLOPT_RETURNTRANSFER, true);
// obtain response
$response = curl_exec($session);
curl_close($session);
$dat = json_decode($response);
if ($dat->message != "success") {
error_log("ERROR: Sendgrid email was not successful");
}
}
protected function _sendSmtpMail($options)
{
if(!isset($options['smtp_host'])) {
throw new \Box_Exception('SMTP host not configured');
}
if(!isset($options['smtp_port'])) {
throw new \Box_Exception('SMTP port not configured');
}
$user = isset($options['smtp_username']) ? $options['smtp_username'] : NULL;
$pass = isset($options['smtp_password']) ? $options['smtp_password'] : NULL;
$port = isset($options['smtp_port']) ? $options['smtp_port'] : NULL;
$host = isset($options['smtp_host']) ? $options['smtp_host'] : NULL;
$security = isset($options['smtp_security']) ? $options['smtp_security'] : NULL;
if(empty($host)) {
throw new \Box_Exception('SMTP hostname is not configured.');
}
$mail = new PHPMailer(true);
$mail->CharSet = 'utf-8';
$mail->IsSMTP();
$mail->Host = $host;
$mail->SMTPDebug = 0;
if($port)
$mail->Port = (int)$port;
if($user) {
$mail->SMTPAuth = true;
$mail->SMTPSecure = $security;
$mail->Username = $user;
$mail->Password = $pass;
}
$mail->SetFrom($this->_from, $this->_from_name);
$mail->AddReplyTo($this->_from);
$mail->AddAddress($this->_to);
$mail->Subject = $this->_subject;
$mail->MsgHTML($this->_bodyHtml);
$mail->send();
}
protected function _sendMail()
{
try {
$mail = new PHPMailer(true);
$mail->CharSet = 'utf-8';
$mail->AddReplyTo($this->_from, $this->_from_name);
$mail->SetFrom($this->_from, $this->_from_name);
$mail->AddAddress($this->_to);
$mail->Subject = $this->_subject;
$mail->AltBody = "To view the message, please use an HTML compatible email viewer!"; // optional, comment out and test
$mail->MsgHTML($this->_bodyHtml);
$mail->Send();
} catch(Exception $e) {
error_log($e->getMessage());
//simple mail sending
$subject = "=?utf-8?B?".base64_encode($this->_subject)."?=";
$this->addHeader('From', $this->_from);
$this->addHeader('Reply-To', $this->_replyTo);
$this->addHeader('Return-Path', $this->_from);
$this->addHeader('Content-type', 'text/html;charset=utf-8');
$this->addHeader('Content-Transfer-Encoding', '8bit');
$this->addHeader('X-mailer', 'BoxBilling/'.Box_Version::VERSION);
mail($this->_to,$subject,$this->_bodyHtml,$this->_headers);
}
}
private function addHeader($name, $value)
{
$this->_headers .= $name.": ".$value."\r\n";
}
/**
* Temporary error handler for PHP native mail().
*
* @param int $errno
* @param string $errstr
* @param string $errfile
* @param string $errline
* @param array $errcontext
* @return true
*/
public function _handleMailErrors($errno, $errstr, $errfile = null, $errline = null, array $errcontext = null)
{
throw new \Box_Exception($errstr);
}
/**
* Filter of email data
*
* @param string $email
* @return string
*/
private function _filterEmail($email)
{
$rule = array("\r" => '',
"\n" => '',
"\t" => '',
'"' => '',
',' => '',
'<' => '',
'>' => '',
);
return strtr($email, $rule);
}
/**
* Filter of name data
*
* @param string $name
* @return string
*/
private function _filterName($name)
{
$rule = array("\r" => '',
"\n" => '',
"\t" => '',
'"' => "'",
'<' => '[',
'>' => ']',
);
return trim(strtr($name, $rule));
}
/**
* Filter of other data
*
* @param string $data
* @return string
*/
private function _filterOther($data)
{
$rule = array("\r" => '',
"\n" => '',
"\t" => '',
);
return strtr($data, $rule);
}
}
+273
View File
@@ -0,0 +1,273 @@
<?php
/**
* BoxBilling
*
* @copyright BoxBilling, Inc (http://www.boxbilling.com)
* @license Apache-2.0
*
* Copyright BoxBilling, Inc
* This source file is subject to the Apache-2.0 License that is bundled
* with this source code in the file LICENSE
*/
class Box_Mod
{
private $mod = null;
/**
* @var Box_Di
*/
private $di = null;
private $core = array(
'api',
'activity',
'cart',
'client',
'cron',
'currency',
'email',
'extension',
'filemanager',
'hook',
'index',
'invoice',
'order',
'page',
'product',
'profile',
'servicecustom',
'servicedomain',
'servicedownloadable',
'servicehosting',
'servicelicense',
'staff',
'stats',
'support',
'system',
'theme',
'orderbutton',
'formbuilder',
);
/**
* @param string $mod
*/
public function __construct($mod)
{
if(!preg_match('#[a-zA-Z]#', $mod)) {
throw new \Box_Exception('Invalid module name');
}
$this->mod = strtolower($mod);
}
public function setDi($di)
{
$this->di = $di;
}
public function hasManifest()
{
return file_exists($this->_getModPath() . 'manifest.json');
}
public function getManifest()
{
if(!$this->hasManifest()) {
throw new \Box_Exception('Module :mod manifest file is missing', array(':mod'=>$this->mod), 5897);
}
$file = $this->_getModPath() . 'manifest.json';
$json = json_decode(file_get_contents($file), true);
if(empty ($json)) {
throw new \Box_Exception('Module :mod manifest file is not valid. Check file syntax and permissions.', array(':mod'=>$this->mod));
}
//default module info if some fields are missing
$info = array(
'id' => $this->mod,
'type' => 'mod',
'name' => $this->mod,
'description' => NULL,
'homepage_url' => 'https://github.com/boxbilling/',
'author' => 'BoxBilling',
'author_url' => 'https://extensions.boxbilling.com/',
'license' => 'GPL version 2 or later - http://www.gnu.org/licenses/old-licenses/gpl-2.0.html',
'version' => '1.0',
'icon_url' => NULL,
'download_url' => NULL,
'project_url' => 'https://extensions.boxbilling.com/',
"minimum_boxbilling_version" => NULL,
"maximum_boxbilling_version" => NULL,
);
$info = array_merge($info, $json);
$info['id'] = $this->mod;
$info['type'] = 'mod';
if(!empty($info['icon_url'])) {
$info['icon_url'] = '/bb-modules/'.ucfirst($this->mod).'/'.$info['icon_url'];
}
return $info;
}
public function hasService($sub = '')
{
$filename = sprintf('Service%s.php', ucfirst($sub));
return file_exists($this->_getModPath() . $filename);
}
public function getService($sub = '')
{
if(!$this->hasService($sub)) {
throw new \Box_Exception('Module :mod does not have service class', array(':mod'=>$this->mod), 5898);
}
$class = 'Box\\Mod\\'.ucfirst($this->mod).'\\Service'.ucfirst($sub);
$service = new $class();
if(method_exists($service, 'setDi')) {
$service->setDi($this->di);
}
return $service;
}
public function hasClientController()
{
return file_exists($this->_getModPath() . 'Controller/Client.php');
}
public function getClientController()
{
if(!$this->hasClientController()) {
throw new \Box_Exception('Module :mod Client controller class was not found', array(':mod'=>$this->mod));
}
$class = 'Box\\Mod\\'.ucfirst($this->mod).'\\Controller\\Client';
$service = new $class();
if(method_exists($service, 'setDi')) {
$service->setDi($this->di);
}
return $service;
}
public function hasSettingsPage()
{
return file_exists($this->_getModPath() . 'html_admin/mod_'.$this->mod.'_settings.phtml');
}
public function hasAdminController()
{
return file_exists($this->_getModPath() . 'Controller/Admin.php');
}
public function getAdminController()
{
if(!$this->hasAdminController()) {
throw new \Box_Exception('Module :mod Admin controller class was not found', array(':mod'=>$this->mod));
}
$class = 'Box\\Mod\\'.ucfirst($this->mod).'\\Controller\\Admin';
$service = new $class();
if(method_exists($service, 'setDi')) {
$service->setDi($this->di);
}
return $service;
}
public function install()
{
if($this->isCore()) {
return true;
}
if($this->hasService()) {
$s = $this->getService();
if(method_exists($s, 'install')) {
$s->install();
return true;
}
}
return false;
}
public function uninstall()
{
if($this->isCore()) {
return true;
}
if($this->hasService()) {
$s = $this->getService();
if(method_exists($s, 'uninstall')) {
$s->uninstall();
return true;
}
}
return false;
}
public function update()
{
if($this->isCore()) {
throw new \Box_Exception('Core module can not be updated');
}
if($this->hasService()) {
$s = $this->getService();
if(method_exists($s, 'update')) {
$manifest = $this->getManifest();
$s->update($manifest);
return true;
}
}
return false;
}
public function getCoreModules()
{
return $this->core;
}
public function isCore()
{
return in_array($this->mod, $this->core);
}
public function getConfig()
{
$db = $this->di['db'];
$bb_config = $this->di['config'];
$config = array();
$modName = 'mod_'.strtolower($this->mod);
$c = $db->findOne('extension_meta', 'extension = :ext AND meta_key = :key', array(':ext'=>$modName, ':key'=>'config'));
if($c) {
$config = $this->di['crypt']->decrypt($c->meta_value, $bb_config['salt']);
$config = $this->di['tools']->decodeJ($config);
}
return $config;
}
public function getName()
{
return $this->mod;
}
public function registerClientRoutes(Box_App &$app)
{
if($this->hasClientController()) {
$cc = $this->getClientController();
if(method_exists($cc, 'register')) {
$cc->register($app);
return true;
}
}
return false;
}
private function _getModPath()
{
return BB_PATH_MODS . DIRECTORY_SEPARATOR . ucfirst($this->mod) . DIRECTORY_SEPARATOR;
}
}
+86
View File
@@ -0,0 +1,86 @@
<?php
/**
* BoxBilling
*
* @copyright BoxBilling, Inc (http://www.boxbilling.com)
* @license Apache-2.0
*
* Copyright BoxBilling, Inc
* This source file is subject to the Apache-2.0 License that is bundled
* with this source code in the file LICENSE
*/
use Box\InjectionAwareInterface;
class Box_Pagination implements InjectionAwareInterface
{
protected $di = null;
protected $per_page = 100;
public function setDi($di)
{
$this->di = $di;
}
public function getDi()
{
return $this->di;
}
/**
* @return int
*/
public function getPer_page()
{
return $this->per_page;
}
public function getSimpleResultSet($q, $values, $per_page = 100, $page = null)
{
if (is_null($page)){
$page = $this->di['request']->getQuery('page', "int", 1);
}
$per_page = $this->di['request']->getQuery('per_page', "int", $per_page);
$offset = ($page - 1) * $per_page;
$sql = $q;
$sql .= sprintf(' LIMIT %s,%s', $offset, $per_page);
$result = $this->di['db']->getAll($sql, $values);
$exploded = explode('FROM', $q);
$sql = 'SELECT count(1) FROM ' . $exploded[1];
$total = $this->di['db']->getCell($sql , $values);
$pages = ($per_page > 1) ? (int)ceil($total / $per_page) : 1;
return array(
"pages" => $pages,
"page" => $page,
"per_page" => $per_page,
"total" => $total,
"list" => $result,
);
}
public function getAdvancedResultSet($q, $values, $per_page = 100)
{
$page = $this->di['request']->getQuery('page', "int", 1);
$per_page = $this->di['request']->getQuery('per_page', "int", $per_page);
$offset = ($page - 1) * $per_page;
$q = str_replace('SELECT ', 'SELECT SQL_CALC_FOUND_ROWS ', $q);
$q .= sprintf(' LIMIT %s,%s', $offset, $per_page);
$result = $this->di['db']->getAll($q, $values);
$total = $this->di['db']->getCell('SELECT FOUND_ROWS();');
$pages = ($per_page > 1) ? (int)ceil($total / $per_page) : 1;
return array(
"pages" => $pages,
"page" => $page,
"per_page" => $per_page,
"total" => $total,
"list" => $result,
);
}
}
+231
View File
@@ -0,0 +1,231 @@
<?php
/**
* BoxBilling
*
* @copyright BoxBilling, Inc (http://www.boxbilling.com)
* @license Apache-2.0
*
* Copyright BoxBilling, Inc
* This source file is subject to the Apache-2.0 License that is bundled
* with this source code in the file LICENSE
*/
/**
* Class to paginate a list of items in a old digg style
*
* @see https://github.com/gigo6000/Symfony2-Pagination-Class
* @author Darko Goleš
* @author Carlos Mafla <gigo6000@hotmail.com>
* @www.inchoo.net
*/
class Box_Paginator {
/**
* @var int current displayed page
*/
protected $currentPage;
/**
* @var int items limit (items per page)
*/
protected $limit;
/**
* @var int total number of pages
*/
protected $numPages;
/**
* @var int items limit (items per page)
*/
protected $itemsCount;
/**
* @var int offset
*/
protected $offset;
/**
* @var int pages to show at left and right of current page
*/
protected $midRange;
/**
* @var array range
*/
protected $range;
/**
* @var string currentUrl
*/
protected $currentUrl;
/**
* @param int $itemsCount
* @param int $currentPage
* @param int $limit
* @param int $midRange
*/
public function __construct($itemsCount = 0, $currentPage = 1, $limit = 20, $midRange = 7)
{
//set total items count from controller
$this->itemsCount = $itemsCount;
$this->currentPage = $currentPage;
$this->limit = $limit;
$this->midRange= $midRange;
//Set defaults
$this->setDefaults();
//Calculate number of pages total
$this->getInternalNumPages();
//Calculate first shown item on current page
$this->calculateOffset();
$this->calculateRange();
}
private function calculateRange()
{
$startRange = $this->currentPage - floor($this->midRange / 2);
$endRange = $this->currentPage + floor($this->midRange / 2);
if ($startRange <= 0) {
$endRange += abs($startRange) + 1;
$startRange = 1;
}
if ($endRange > $this->numPages) {
$endRange = $this->numPages;
$startRange = $endRange - $this->numPages + 1;
}
$this->range = range($startRange, $endRange);
}
private function setDefaults()
{
//If currentPage is set to null or is set to 0 or less
//set it to default (1)
if ($this->currentPage == null || $this->currentPage < 1)
{
$this->currentPage = 1;
}
//if limit is set to null set it to default (20)
if ($this->limit == null)
{
$this->limit = 20;
//if limit is any number less than 1 then set it to 0 for displaying
//items without limit
}
else if ($this->limit < 1)
{
$this->limit = 0;
}
}
private function getInternalNumPages()
{
//If limit is set to 0 or set to number bigger then total items count
//display all in one page
if ($this->limit < 1 || $this->limit > $this->itemsCount)
{
$this->numPages = 1;
}
else
{
//Calculate rest numbers from dividing operation so we can add one
//more page for this items
$restItemsNum = $this->itemsCount % $this->limit;
//if rest items > 0 then add one more page else just divide items
//by limit
$this->numPages = $restItemsNum > 0 ? intval($this->itemsCount / $this->limit) + 1 : intval($this->itemsCount / $this->limit);
}
}
private function calculateOffset()
{
//Calculet offset for items based on current page number
$this->offset = ($this->currentPage - 1) * $this->limit;
}
/**
* @return int number of pages
*/
public function getNumPages()
{
return $this->numPages;
}
/**
* @return int current page
*/
public function getCurrentPage()
{
return $this->currentPage;
}
/**
* @return string current url
*/
public function getCurrentUrl()
{
return $this->currentUrl;
}
/**
* @return int limit items per page
*/
public function getLimit()
{
return $this->limit;
}
/**
* @return int offset
*/
public function getOffset()
{
return $this->offset;
}
/**
* @return array range
*/
public function getRange()
{
return $this->range;
}
/**
* @return int mid range
*/
public function getMidRange()
{
return $this->midRange;
}
public function getStartingPoint()
{
$arr = $this->getRange();
return reset($arr);
}
public function getEndingPoint()
{
$arr = $this->getRange();
return end($arr);
}
public function toArray()
{
return array(
'currentpage' => $this->getCurrentPage(),
'numpages' => $this->getNumPages(),
'midrange' => $this->getMidRange(),
'range' => $this->getRange(),
'start' => $this->getStartingPoint(),
'end' => $this->getEndingPoint(),
);
}
}
+55
View File
@@ -0,0 +1,55 @@
<?php
/**
* BoxBilling
*
* @copyright BoxBilling, Inc (http://www.boxbilling.com)
* @license Apache-2.0
*
* Copyright BoxBilling, Inc
* This source file is subject to the Apache-2.0 License that is bundled
* with this source code in the file LICENSE
*/
class Box_Password {
private $algo = PASSWORD_DEFAULT;
private $options = array();
public function setAlgo ($algo)
{
$this->algo = $algo;
}
public function getAlgo()
{
return $this->algo;
}
public function setOptions($options = array())
{
$this->options = $options;
}
public function getOptions()
{
return $this->options;
}
/**
* @return string
*/
public function hashIt($password)
{
return password_hash($password, $this->algo, $this->options);
}
public function verify ($password, $hash)
{
return password_verify((string) $password, $hash);
}
public function needsRehash($hash)
{
return password_needs_rehash($hash, $this->algo, $this->options);
}
}
+199
View File
@@ -0,0 +1,199 @@
<?php
/**
* BoxBilling
*
* @copyright BoxBilling, Inc (http://www.boxbilling.com)
* @license Apache-2.0
*
* Copyright BoxBilling, Inc
* This source file is subject to the Apache-2.0 License that is bundled
* with this source code in the file LICENSE
*/
class Box_Period
{
const UNIT_DAY = 'D';
const UNIT_WEEK = 'W';
const UNIT_MONTH = 'M';
const UNIT_YEAR = 'Y';
const PERIOD_WEEK = '1W';
const PERIOD_MONTH = '1M';
const PERIOD_QUARTER = '3M';
const PERIOD_BIANNUAL = '6M';
const PERIOD_ANNUAL = '1Y';
const PERIOD_BIENNIAL = '2Y';
const PERIOD_TRIENNIAL = '3Y';
/**
* Predefined periods
*/
protected $_multiplier = array(
self::PERIOD_MONTH => 1,
self::PERIOD_QUARTER => 3,
self::PERIOD_BIANNUAL => 6,
self::PERIOD_ANNUAL => 12,
self::PERIOD_BIENNIAL => 24,
self::PERIOD_TRIENNIAL => 36,
);
private $unit;
private $qty;
public function __construct($code)
{
if(strlen($code) != 2) {
throw new \Box_Exception("Invalid period code. Period definition must be 2 chars length");
}
list($qty, $unit) = str_split($code);
$units = $this->getUnits();
$qty = (int)$qty;
$unit = strtoupper($unit);
if(!array_key_exists($unit, $units)) {
throw new \Box_Exception("Period Error. Unit :unit is not defined", array(':unit'=>$unit));
}
if($qty < $units[$unit][0] || $qty > $units[$unit][1]) {
$d = array(
':qty' => $qty,
':unit' => $unit,
':from' => $units[$unit][0],
':to' => $units[$unit][1],
);
throw new \Box_Exception("Invalid period quantity :qty for unit :unit. Allowed range is from :from to :to", $d);
}
$this->unit = $unit;
$this->qty = $qty;
}
private function getUnits()
{
return array(
self::UNIT_DAY => array(1, 90),
self::UNIT_WEEK => array(1, 52),
self::UNIT_MONTH => array(1, 24),
self::UNIT_YEAR => array(1, 5),
);
}
public static function getPredefined($simple = true)
{
$periods = array(
self::PERIOD_WEEK => array('rec_qty'=>1, 'title'=>__('Every week'), 'code'=>self::PERIOD_WEEK, 'rec_unit'=>self::UNIT_WEEK),
self::PERIOD_MONTH => array('rec_qty'=>1, 'title'=>__('Every month'), 'code'=>self::PERIOD_MONTH, 'rec_unit'=>self::UNIT_MONTH),
self::PERIOD_QUARTER => array('rec_qty'=>3, 'title'=>__('Every 3 months'), 'code'=>self::PERIOD_QUARTER, 'rec_unit'=>self::UNIT_MONTH),
self::PERIOD_BIANNUAL => array('rec_qty'=>6, 'title'=>__('Every 6 months'), 'code'=>self::PERIOD_BIANNUAL, 'rec_unit'=>self::UNIT_MONTH),
self::PERIOD_ANNUAL => array('rec_qty'=>1, 'title'=>__('Every year'), 'code'=>self::PERIOD_ANNUAL, 'rec_unit'=>self::UNIT_YEAR),
self::PERIOD_BIENNIAL => array('rec_qty'=>2, 'title'=>__('Every 2 years'), 'code'=>self::PERIOD_BIENNIAL, 'rec_unit'=>self::UNIT_YEAR),
self::PERIOD_TRIENNIAL => array('rec_qty'=>3, 'title'=>__('Every 3 years'), 'code'=>self::PERIOD_TRIENNIAL, 'rec_unit'=>self::UNIT_YEAR),
);
if($simple) {
$new = array();
foreach($periods as $pp) {
$new[$pp['code']] = $pp['title'];
}
$periods = $new;
}
return $periods;
}
public function getUnit()
{
return $this->unit;
}
public function getQty()
{
return $this->qty;
}
public function getCode()
{
return $this->qty.$this->unit;
}
public function getTitle()
{
switch ($this->unit) {
case self::UNIT_DAY:
$shift = __('Every :number day', array(':number'=>$this->qty));
break;
case self::UNIT_WEEK:
$shift = __('Every :number week(s)', array(':number'=>$this->qty));
break;
case self::UNIT_MONTH:
$shift = __('Every :number months', array(':number'=>$this->qty));
break;
case self::UNIT_YEAR:
$shift = __('Every :number years', array(':number'=>$this->qty));
break;
default:
throw new \Box_Exception('Unit not defined');
}
return $shift;
}
public function getDays()
{
return $this->getMonths() * 30;
}
/**
* How many months $this->unit consists of
* @return int
*/
public function getMonths()
{
$qty = 0;
switch ($this->unit) {
case self::UNIT_DAY:
$qty = $this->qty / 30;
break;
case self::UNIT_WEEK:
$qty = $this->qty / 4;
break;
case self::UNIT_MONTH:
$qty = $this->qty;
break;
case self::UNIT_YEAR:
$qty = $this->qty * 12;
break;
default:
throw new \Box_Exception('Can not determine months amount from unit');
}
return $qty;
}
public function getExpirationTime($now = NULL)
{
if(NULL === $now) {
$now = time();
}
switch ($this->unit) {
case self::UNIT_DAY:
$shift = 'days';
break;
case self::UNIT_WEEK:
$shift = 'weeks';
break;
case self::UNIT_MONTH:
$shift = 'months';
break;
case self::UNIT_YEAR:
$shift = 'years';
break;
default:
throw new \Box_Exception('Unit not defined');
}
return strtotime("+$this->qty $shift", $now);
}
}
+598
View File
@@ -0,0 +1,598 @@
<?php
/**
* BoxBilling
*
* @copyright BoxBilling, Inc (http://www.boxbilling.com)
* @license Apache-2.0
*
* Copyright BoxBilling, Inc
* This source file is subject to the Apache-2.0 License that is bundled
* with this source code in the file LICENSE
*/
class Box_Request implements \Box\InjectionAwareInterface
{
protected $di;
protected $_data = array();
protected $_header = array();
protected $_server = array();
protected $_request = array();
protected $_post = array();
protected $_get = array();
protected $_cookie = array();
protected $_method = 'post';
public function __construct()
{
$this->_get = $_GET;
$this->_post = $_POST;
$this->_request = $_REQUEST;
$this->_server = $_SERVER;
}
public function setDi($di)
{
$this->di = $di;
}
public function getDi()
{
return $this->di;
}
public function get($name = null, $filters = null, $defaultValue = null)
{
if (empty($name)) {
return $this->_request;
}
$value = isset($this->_request[$name]) ? $this->_request[$name] : $defaultValue;
return $this->_filterValue($value, $filters);
}
public function getPost($name = null, $filters = null, $defaultValue = null)
{
if (empty($name)) {
return $this->_post;
}
$value = isset($this->_post[$name]) ? $this->_post[$name] : $defaultValue;
return $this->_filterValue($value, $filters);
}
public function getQuery($name = null, $filters = null, $defaultValue = null)
{
if (empty($name)) {
return $this->_get;
}
$value = isset($this->_get[$name]) ? $this->_get[$name] : $defaultValue;
return $this->_filterValue($value, $filters);
}
/**
* Returns the available headers in the request
* @return array
*/
public function getHeaders()
{
$list = getallheaders();
return is_array($list) ? $list : array();
}
public function getPut($name = null, $filters = null, $defaultValue = null)
{
parse_str($this->getRawBody(), $put);
if(empty($name)) {
return $put;
}
$value = isset($put[$name]) ? $put[$name] : $defaultValue;
return $this->_filterValue($value, $filters);
}
/**
* @param string $name
*/
public function getServer($name)
{
return isset($this->_server[$name]) ? $this->_server[$name] : null;
}
public function has($name)
{
return isset($this->_request[$name]);
}
public function hasPost($name)
{
return isset($this->_post[$name]);
}
public function hasPut($name)
{
parse_str($this->getRawBody(), $put);
if(is_array($put) && isset($put[$name])) {
return true;
}
return false;
}
public function hasQuery($name)
{
return isset($this->_get[$name]);
}
/**
* @param string $name
*/
public function hasServer($name)
{
return isset($this->_server[$name]);
}
/**
* Gets HTTP header from request data
* @param string $header
* @return string
*/
public function getHeader($header)
{
$headers = $this->getHeaders();
return isset($headers[$header]) ? $headers[$header] : null;
}
/**
* Gets HTTP schema (http/https)
* @return string
*/
public function getScheme()
{
return $this->getServer('HTTPS') ? 'https' : 'http';
}
/**
* Checks whether request has been made using ajax. Checks if $_SERVER[‘HTTP_X_REQUESTED_WITH’]==’XMLHttpRequest’
* @return bool
*/
public function isAjax()
{
return ($this->getServer('HTTP_X_REQUESTED_WITH') == 'XMLHttpRequest');
}
/**
* Checks whether request has been made using SOAP
* @return bool
*/
public function isSoapRequested()
{
if($this->hasServer('HTTP_SOAPACTION')) {
return true;
}
if($this->getServer('CONTENT_TYPE') == 'application/soap+xml') {
return true;
}
return false;
}
/**
* Checks whether request has been made using any secure layer
* @return bool
*/
public function isSecureRequest()
{
return ($this->getScheme() == 'https');
}
/**
* Gets HTTP raw request body
* @return string
*/
public function getRawBody()
{
return file_get_contents('php://input');
}
/**
* Gets decoded JSON HTTP raw request body
* @return string
*/
public function getJsonRawBody()
{
$result = json_decode($this->getRawBody(), 1);
if($result) {
return $result;
}
$_messages = array(
JSON_ERROR_NONE => 'No error has occurred',
JSON_ERROR_DEPTH => 'The maximum stack depth has been exceeded',
JSON_ERROR_STATE_MISMATCH => 'Invalid or malformed JSON',
JSON_ERROR_CTRL_CHAR => 'Control character error, possibly incorrectly encoded',
JSON_ERROR_SYNTAX => 'Syntax error',
JSON_ERROR_UTF8 => 'Malformed UTF-8 characters, possibly incorrectly encoded'
);
$error = json_last_error();
$msg = isset($_messages[$error]) ? $_messages[$error] : 'Error decoding json';
throw new RuntimeException($msg);
}
/**
* Gets active server address IP
* @return string
*/
public function getServerAddress()
{
$address = $this->getServer('SERVER_ADDR');
return ($address) ? $address : '127.0.0.1';
}
/**
* Gets active server name
* @return string
*/
public function getServerName()
{
$address = $this->getServer('SERVER_NAME');
return ($address) ? $address : 'localhost';
}
/**
* Gets information about schema, host and port used by the request
* @return string
*/
public function getHttpHost()
{
return $this->getServer('HTTP_HOST');
}
/**
* Gets most possible client IPv4 Address. This method search in $_SERVER[‘REMOTE_ADDR’] and optionally in $_SERVER[‘HTTP_X_FORWARDED_FOR’]
* @param bool $trustForwardedHeader - should we trust forwarded header?
* return string
*/
public function getClientAddress($trustForwardedHeader = true)
{
$address = null;
if($trustForwardedHeader) {
$address = $this->getServer('HTTP_X_FORWARDED_FOR');
}
if(is_null($address)) {
$address = $this->getServer('REMOTE_ADDR');
}
if(is_string($address)) {
if(strpos($address, ',') !== false) {
list($address) = explode(',', $address);
}
}
return $address;
}
/**
* Gets HTTP method which request has been made
* @return string
*/
public function getMethod()
{
return $this->getServer('REQUEST_METHOD');
}
/**
* Gets HTTP URI which request has been made
* @return string
*/
public function getURI()
{
return $this->getServer('REQUEST_URI');
}
/**
* Gets HTTP user agent used to made the request
* @return string
*/
public function getUserAgent()
{
return $this->getServer('HTTP_USER_AGENT');
}
/**
* Check if HTTP method match any of the passed methods
* @param string | array
* @return bool
*/
public function isMethod($methods)
{
$current = $this->getMethod();
if(is_array($methods)) {
foreach($methods as $method) {
if($current == $method) {
return true;
}
}
return false;
}
return ($current == $methods);
}
/**
* Checks whether HTTP method is POST. if $_SERVER[‘REQUEST_METHOD’]==’POST’
* @return bool
*/
public function isPost()
{
return ($this->getMethod() == 'POST');
}
/**
* Checks whether HTTP method is GET. if $_SERVER[‘REQUEST_METHOD’]==’GET’
* @return bool
*/
public function isGet()
{
return ($this->getMethod() == 'GET');
}
/**
* Checks whether HTTP method is PUT. if $_SERVER[‘REQUEST_METHOD’]==’PUT’
* @return bool
*/
public function isPut()
{
return ($this->getMethod() == 'PUT');
}
/**
* Checks whether HTTP method is PATCH. if $_SERVER[‘REQUEST_METHOD’]==’PATCH’
* @return bool
*/
public function isPatch()
{
return ($this->getMethod() == 'PATCH');
}
/**
* Checks whether HTTP method is HEAD. if $_SERVER[‘REQUEST_METHOD’]==’HEAD’
* @return bool
*/
public function isHead()
{
return ($this->getMethod() == 'HEAD');
}
/**
* Checks whether HTTP method is DELETE. if $_SERVER[‘REQUEST_METHOD’]==’DELETE’
* @return bool
*/
public function isDelete()
{
return ($this->getMethod() == 'DELETE');
}
/**
* Checks whether HTTP method is OPTIONS. if $_SERVER[‘REQUEST_METHOD’]==’OPTIONS’
* @return bool
*/
public function isOptions()
{
return ($this->getMethod() == 'OPTIONS');
}
/**
* Checks whether request includes attached files
* @return int - number of files
*/
public function hasFiles($onlySuccessful = true)
{
$number_of_files = 0;
$number_of_successful_files = 0;
foreach($_FILES as $file) {
$number_of_files++;
if(isset($file['error']) && $file['error'] == 0) {
$number_of_successful_files++;
}
}
return ($onlySuccessful) ? $number_of_successful_files : $number_of_files;
}
/**
* Gets attached files as SplFileInfo collection
* @return array
*/
public function getUploadedFiles($onlySuccessful = true)
{
$files = array();
foreach($_FILES as $file) {
$f = new Box_RequestFile($file);
if($onlySuccessful) {
if($file['error'] == 0) {
$files[] = $f;
}
} else {
$files[] = $f;
}
}
return $files;
}
/**
* Gets web page that refers active request. ie: http://www.google.com
* @return string
*/
public function getHTTPReferer()
{
return $this->getServer('HTTP_REFERER');
}
/**
* Gets array with mime/types and their quality accepted by the browser/client from $_SERVER[‘HTTP_ACCEPT’]
* @return array
*/
public function getAcceptableContent()
{
return $this->getServer('HTTP_ACCEPT');
}
/**
* Gets best mime/type accepted by the browser/client from $_SERVER[‘HTTP_ACCEPT’]
* @return array
*/
public function getBestAccept()
{
//@todo
}
/**
* Gets charsets array and their quality accepted by the browser/client from $_SERVER[‘HTTP_ACCEPT_CHARSET’]
* @return array
*/
public function getClientCharsets()
{
//@todo
}
/**
* Gets best charset accepted by the browser/client from $_SERVER[‘HTTP_ACCEPT_CHARSET’]
* @return string
*/
public function getBestCharset()
{
//@todo
}
/**
* Gets languages array and their quality accepted by the browser/client from $_SERVER[‘HTTP_ACCEPT_LANGUAGE’]
* @return array
*/
public function getLanguages()
{
$language_header = $this->getServer('HTTP_ACCEPT_LANGUAGE');
return $this->_getQualityHeader($language_header, 'language');
}
/**
* Gets best language accepted by the browser/client from $_SERVER[‘HTTP_ACCEPT_LANGUAGE’]
* @return string
*/
public function getBestLanguage()
{
//@todo
}
/**
* Gets auth info accepted by the browser/client from $_SERVER[‘PHP_AUTH_USER’]
* @return array
*/
public function getBasicAuth()
{
$username = null;
$password = null;
if ($this->hasServer('PHP_AUTH_USER')) {
$username = $_SERVER['PHP_AUTH_USER'];
$password = $_SERVER['PHP_AUTH_PW'];
} elseif ($this->hasServer('HTTP_AUTHENTICATION')) {
$auth = $this->getServer('HTTP_AUTHENTICATION');
if (strpos(strtolower($auth), 'basic') === 0) {
list($username,$password) = explode(':',base64_decode(substr($auth, 6)));
}
}
return array(
'username' => $username,
'password' => $password,
);
}
/**
* Gets auth info accepted by the browser/client from $_SERVER[‘PHP_AUTH_DIGEST’]
* @return array
*/
public function getDigestAuth()
{
// mod_php
if ($this->hasServer('PHP_AUTH_DIGEST')) {
$digest = $this->getServer('PHP_AUTH_DIGEST');
// most other servers
} elseif ($this->hasServer('HTTP_AUTHENTICATION')) {
$auth = $this->getServer('HTTP_AUTHENTICATION');
if (strpos(strtolower($auth),'digest')===0) {
$digest = substr($auth, 7);
}
}
// protect against missing data
$needed_parts = array('nonce'=>1, 'nc'=>1, 'cnonce'=>1, 'qop'=>1, 'username'=>1, 'uri'=>1, 'response'=>1);
$data = array();
$keys = implode('|', array_keys($needed_parts));
preg_match_all('@(' . $keys . ')=(?:([\'"])([^\2]+?)\2|([^\s,]+))@', $digest, $matches, PREG_SET_ORDER);
foreach ((array) $matches as $m) {
$data[$m[1]] = $m[3] ? $m[3] : $m[4];
unset($needed_parts[$m[1]]);
}
return $needed_parts ? false : $data;
}
/**
* Process a request header and return an array of values with their qualities
* @param string $q
* @return array
*/
protected function _getQualityHeader($header, $q)
{
$return = array();
$parts = preg_split('/,\\s*/', $header);
foreach($parts as $part) {
$headerParts = explode(';', $part);
if(isset($headerParts[1]) === true) {
$quality = substr($headerParts[1], 2);
} else {
$quality = 1;
}
$return[] = array($q => $headerParts[0], 'quality' => $quality);
}
return $return;
}
/**
* Process a request header and return the one with best quality
* @return string
*/
protected function _getBestQuality($header)
{
//@todo
}
/**
* @todo implement filtering
* @param $value - value to filter
* @param string|array $filters - list of filter to apply on value
*/
private function _filterValue($value, $filters)
{
return $value;
}
}
if (!function_exists('getallheaders'))
{
function getallheaders()
{
$headers = '';
foreach ($_SERVER as $name => $value)
{
if (substr($name, 0, 5) == 'HTTP_')
{
$headers[str_replace(' ', '-', ucwords(strtolower(str_replace('_', ' ', substr($name, 5)))))] = $value;
}
}
return $headers;
}
}
+30
View File
@@ -0,0 +1,30 @@
<?php
/**
* BoxBilling
*
* @copyright BoxBilling, Inc (http://www.boxbilling.com)
* @license Apache-2.0
*
* Copyright BoxBilling, Inc
* This source file is subject to the Apache-2.0 License that is bundled
* with this source code in the file LICENSE
*/
class Box_RequestFile extends SplFileInfo
{
protected $name;
public function __construct(array $file)
{
$this->name = $file['name'];
parent::__construct($file['tmp_name']);
}
public function getName()
{
return $this->name;
}
}
+203
View File
@@ -0,0 +1,203 @@
<?php
/**
* BoxBilling
*
* @copyright BoxBilling, Inc (http://www.boxbilling.com)
* @license Apache-2.0
*
* Copyright BoxBilling, Inc
* This source file is subject to the Apache-2.0 License that is bundled
* with this source code in the file LICENSE
*/
class Box_Requirements implements \Box\InjectionAwareInterface
{
protected $di;
public function setDi($di)
{
$this->di = $di;
}
public function getDi()
{
return $this->di;
}
private $_all_ok = true;
private $_app_path = BB_PATH_ROOT;
private $_options = array();
public function __construct()
{
$this->_options = array(
'php' => array(
'extensions' => array(
'pdo_mysql',
'curl',
'zlib',
'gettext',
'openssl',
),
'version' => PHP_VERSION,
'min_version' => '7.2',
'safe_mode' => ini_get('safe_mode'),
),
'writable_folders' => array(
$this->_app_path . '/bb-data/cache',
$this->_app_path . '/bb-data/log',
$this->_app_path . '/bb-data/uploads',
),
'writable_files' => array(
$this->_app_path . '/bb-config.php',
),
);
}
public function getOptions()
{
return $this->_options;
}
public function getInfo()
{
$data = array();
$data['ip'] = isset($_SERVER['SERVER_ADDR']) ? $_SERVER['SERVER_ADDR'] : null;
$data['PHP_OS'] = PHP_OS;
$data['PHP_VERSION'] = PHP_VERSION;
$data['bb'] = array(
'BB_LOCALE' => $this->di['config']['locale'],
'BB_SEF_URLS' => BB_SEF_URLS,
'version' => Box_Version::VERSION,
);
$data['ini'] = array(
'allow_url_fopen' => ini_get('allow_url_fopen'),
'safe_mode' => ini_get('safe_mode'),
'memory_limit' => ini_get('memory_limit'),
'magic_quotes' => (function_exists('get_magic_quotes_gpc') && get_magic_quotes_gpc()),
);
$data['permissions'] = array(
BB_PATH_UPLOADS => substr(sprintf('%o', fileperms(BB_PATH_UPLOADS)), -4),
BB_PATH_DATA => substr(sprintf('%o', fileperms(BB_PATH_DATA)), -4),
BB_PATH_CACHE => substr(sprintf('%o', fileperms(BB_PATH_CACHE)), -4),
BB_PATH_LOG => substr(sprintf('%o', fileperms(BB_PATH_LOG)), -4),
);
$data['extensions'] = array(
'apc' => extension_loaded('apc'),
'curl' => extension_loaded('curl'),
'pdo_mysql' => extension_loaded('pdo_mysql'),
'zlib' => extension_loaded('zlib'),
'mbstring' => extension_loaded('mbstring'),
'openssl' => extension_loaded('openssl'),
'gettext' => extension_loaded('gettext'),
);
//determine php username
if(function_exists('posix_getpwuid') && function_exists('posix_geteuid')) {
$data['posix_getpwuid'] = posix_getpwuid(posix_geteuid());
}
return $data;
}
public function isPhpVersionOk()
{
$current = $this->_options['php']['version'];
$required = $this->_options['php']['min_version'];
return version_compare($current, $required, '>=');
}
/**
* What extensions must be loaded for BoxBilling o function correctly
*/
public function extensions()
{
$exts = $this->_options['php']['extensions'];
$result = array();
foreach($exts as $ext) {
if(extension_loaded($ext)) {
$result[$ext] = true;
} else {
$result[$ext] = false;
$this->_all_ok = false;
}
}
return $result;
}
/**
* Files that must be writable
*/
public function files()
{
$files = $this->_options['writable_files'];
$result = array();
foreach($files as $file) {
if ($this->checkPerms($file)) {
$result[$file] = true;
} else if (is_writable($file)) {
$result[$file] = true;
} else {
$result[$file] = false;
$this->_all_ok = false;
}
}
return $result;
}
/**
* Folders that must be writable
*/
public function folders()
{
$folders = $this->_options['writable_folders'];
$result = array();
foreach($folders as $folder) {
if($this->checkPerms($folder)) {
$result[$folder] = true;
} else if (is_writable($folder)) {
$result[$folder] = true;
} else {
$result[$folder] = false;
$this->_all_ok = false;
}
}
return $result;
}
/**
* Check if we can continue with installation
* @return bool
*/
public function canInstall()
{
$this->extensions();
$this->folders();
$this->files();
return $this->_all_ok;
}
/**
* Check permissions
* @param string $path
* @param string $perm
* @return bool
*/
public function checkPerms($path, $perm = '0777')
{
clearstatcache();
$configmod = substr(sprintf('%o', @fileperms($path)), -4);
return ($configmod == $perm);
}
}
+128
View File
@@ -0,0 +1,128 @@
<?php
/**
* BoxBilling
*
* @copyright BoxBilling, Inc (http://www.boxbilling.com)
* @license Apache-2.0
*
* Copyright BoxBilling, Inc
* This source file is subject to the Apache-2.0 License that is bundled
* with this source code in the file LICENSE
*/
class Box_Response implements \Box\InjectionAwareInterface
{
protected $content = '';
protected $content_type;
protected $json_content;
protected $is_sent;
protected $code;
protected $etag;
protected $status;
protected $headers;
protected $cookies;
protected $di;
public function __construct ($content = null, $code = null, $status = null)
{
}
/**
* @param mixed $di
*/
public function setDi($di)
{
$this->di = $di;
}
/**
* @return mixed
*/
public function getDi()
{
return $this->di;
}
/**
* @param mixed $etag
*/
public function setEtag($etag)
{
$this->etag = $etag;
}
/**
* @param mixed $contentType
*/
public function setContentType($contentType, $charset = null)
{
$this->content_type = $contentType;
}
public function redirect($location, $externalRedirect = false, $statusCode = null)
{
}
/**
* @param mixed $content
*/
public function setContent($content)
{
$this->content = $content;
}
/**
* @return string
*/
public function getContent()
{
return $this->content;
}
public function appendContent($content)
{
$this->content .= $content;
}
/**
* @param mixed $json_content
*/
public function setJsonContent($json_content)
{
$this->json_content = $json_content;
}
/**
* @return bool
*/
public function isSent()
{
return (bool)$this->is_sent;
}
public function sendHeaders()
{
}
public function sendCookies()
{
}
public function send()
{
$this->is_sent = true;
}
public function setFileToSend($filePath, $attachmentName = null)
{
}
}
+65
View File
@@ -0,0 +1,65 @@
<?php
/**
* BoxBilling
*
* @copyright BoxBilling, Inc (http://www.boxbilling.com)
* @license Apache-2.0
*
* Copyright BoxBilling, Inc
* This source file is subject to the Apache-2.0 License that is bundled
* with this source code in the file LICENSE
*/
class Box_Session
{
public function __construct($handler)
{
session_set_save_handler(
array($handler, 'open'),
array($handler, 'close'),
array($handler, 'read'),
array($handler, 'write'),
array($handler, 'destroy'),
array($handler, 'gc')
);
if(php_sapi_name() !== 'cli'){
$currentCookieParams = session_get_cookie_params();
$currentCookieParams["httponly"] = true;
session_set_cookie_params(
$currentCookieParams["lifetime"],
$currentCookieParams["path"],
$currentCookieParams["domain"],
$currentCookieParams["secure"],
$currentCookieParams["httponly"]
);
session_start();
}
}
public function getId()
{
return session_id();
}
public function delete($key)
{
unset($_SESSION[$key]);
}
public function get($key)
{
return isset($_SESSION[$key]) ? $_SESSION[$key] : null;
}
public function set($key, $value)
{
$_SESSION[$key] = $value;
}
public function destroy()
{
session_destroy();
}
}
+480
View File
@@ -0,0 +1,480 @@
<?php
/**
* BoxBilling
*
* @copyright BoxBilling, Inc (http://www.boxbilling.com)
* @license Apache-2.0
*
* Copyright BoxBilling, Inc
* This source file is subject to the Apache-2.0 License that is bundled
* with this source code in the file LICENSE
*/
class Box_Tools
{
protected $di = null;
/**
* @param Box_Di|null $di
*/
public function setDi($di)
{
$this->di = $di;
}
/**
* @return Box_Di|null
*/
public function getDi()
{
return $this->di;
}
public function file_put_contents($content, $target, $mode = 'wt')
{
$fp = @fopen($target, $mode);
if ($fp) {
$bytes = fwrite($fp, $content);
fclose($fp);
return $bytes;
} else {
$error = error_get_last();
throw new RuntimeException(
sprintf(
'Could not write to %s: %s',
$target,
substr(
$error['message'],
strpos($error['message'], ':') + 2
)
)
);
}
}
public function file_get_contents($filename, $use_include_path = false, $context = null, $offset = -1)
{
return file_get_contents($filename, $use_include_path, $context, $offset);
}
public function get_url($url, $timeout = 10)
{
$ch = curl_init();
$userAgent = 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; .NET CLR 1.1.4322)';
curl_setopt($ch, CURLOPT_USERAGENT, $userAgent);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
curl_setopt($ch, CURLOPT_FAILONERROR, true);
curl_setopt($ch, CURLOPT_AUTOREFERER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
$data = curl_exec($ch);
if($data === false) {
throw new Exception(curl_error($ch), curl_errno($ch));
}
curl_close($ch);
return $data;
}
/**
* Return site url
* @return string
*/
public function url($link = null)
{
$link = trim($link, '/');
if(BB_SEF_URLS) {
return BB_URL . $link;
}
return BB_URL .'index.php?_url=/' . $link;
}
public function hasService($type)
{
$file = BB_PATH_MODS . '/mod_'.$type.'/Service.php';
return file_exists($file);
}
public function getService($type)
{
$class = 'Box_Mod_'.ucfirst($type).'_Service';
$file = BB_PATH_MODS . '/mod_'.$type.'/Service.php';
if(!file_exists($file)){
throw new \Box_Exception('Service class :class was not found in :path', array(':class'=>$class,':path'=>$file));
}
require_once $file;
return new $class();
}
/**
* Get client IP
* @return string
*/
public function getIpv4()
{
$ip = NULL;
if (isset($_SERVER) ) {
if (isset($_SERVER['REMOTE_ADDR']) ) {
$ip = $_SERVER['REMOTE_ADDR'];
} elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
$ip = $_SERVER['HTTP_CLIENT_IP'];
} elseif (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
$ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
$iplist = explode(',', $ip);
if(is_array($iplist)) {
$ip = trim(array_pop($iplist));
}
}
}
return $ip;
}
public function checkPerms($path, $perm = '0777')
{
clearstatcache();
$configmod = substr(sprintf('%o', fileperms($path)), -4);
$int = (int)$configmod;
if($configmod == $perm) {
return true;
}
if((int)$configmod < (int)$perm) {
return true;
}
return false;
}
public function emptyFolder($folder)
{
if(!is_dir($folder)) {
return;
}
$d = dir($folder);
while (false !== ($entry = $d->read())) {
$isdir = is_dir($folder."/".$entry);
if (!$isdir && $entry!="." && $entry!="..") {
unlink($folder."/".$entry);
} elseif ($isdir && $entry!="." && $entry!="..") {
$this->emptyFolder($folder."/".$entry);
rmdir($folder."/".$entry);
}
}
$d->close();
}
/**
* Returns referer url
* @return string
*/
public function getReferer($default = '/')
{
$r = empty($_SERVER['HTTP_REFERER']) ? $default : $_SERVER['HTTP_REFERER'];
return $r;
}
/**
* Generates random password
* @param int $length
* @param int $strength
* @return string
*/
public function generatePassword($length=8, $strength=3) {
$upper = 0;
$lower = 0;
$numeric = 0;
$other = 0;
$upper_letters = 'QWERTYUIOPASDFGHJKLZXCVBNM';
$lower_letters = 'qwertyuiopasdfghjklzxccvbnm';
$numbers = '1234567890';
$symbols = '!@#$%&?()+-_';
switch ($strength) {
//lowercase
case 1:
$lower = $length;
break;
//lowercase + numeric
case 2:
$lower = rand(1, $length - 1);
$numeric = $length - $lower;
break;
//lowercase + uppsercase + numeric
case 3:
$lower = rand(1, $length - 2);
$upper = rand(1, $length - $lower - 1);
$numeric = $length - $lower - $upper;
break;
//lowercase + uppercase + numeric + symbols
case 4:
default:
$lower = rand(1, $length - 3);
$upper = rand(1, $length - $lower - 2);
$numeric = rand(1, $length - $lower - $upper - 1);
$other = $length - $lower - $upper - $numeric;
break;
}
$passOrder = array();
for ($i = 0; $i < $upper; $i++) {
$passOrder[] = $upper_letters[rand() % strlen($upper_letters)];
}
for ($i = 0; $i < $lower; $i++) {
$passOrder[] = $lower_letters[rand() % strlen($lower_letters)];
}
for ($i = 0; $i < $numeric; $i++) {
$passOrder[] = $numbers[rand() % strlen($numbers)];
}
for ($i = 0; $i < $other; $i++) {
$passOrder[] = $symbols[rand() % strlen($symbols)];
}
shuffle($passOrder);
$password = implode('', $passOrder);
return $password;
}
public function autoLinkText($text)
{
$pattern = '#\b(([\w-]+://?|www[.])[^\s()<>]+(?:\([\w\d]+\)|([^[:punct:]\s]|/)))#';
$callback = function($matches){
$url = array_shift($matches);
$url_parts = parse_url($url);
if(!isset($url_parts["scheme"])) {
$url = "http://".$url;
}
return sprintf('<a target="_blank" href="%s">%s</a>', $url, $url);
};
return preg_replace_callback($pattern, $callback, $text);
}
public function getResponseCode($theURL)
{
$headers = get_headers($theURL);
return substr($headers[0], 9, 3);
}
public function slug($str)
{
$str = strtolower(trim($str));
$str = preg_replace('/[^a-z0-9-]/', '-', $str);
$str = preg_replace('/-+/', "-", $str);
$str = trim($str, '-');
return $str;
}
public function escape($string)
{
$string = htmlspecialchars($string, ENT_QUOTES, 'UTF-8');
return stripslashes($string);
}
/**
* @Deprecated not used anywhere
* @param $filename
* @return mixed|string
*/
public function get_mime_content_type($filename)
{
$mime_types = array(
'txt' => 'text/plain',
'htm' => 'text/html',
'html' => 'text/html',
'php' => 'text/html',
'css' => 'text/css',
'js' => 'application/javascript',
'json' => 'application/json',
'xml' => 'application/xml',
'swf' => 'application/x-shockwave-flash',
'flv' => 'video/x-flv',
// images
'png' => 'image/png',
'jpe' => 'image/jpeg',
'jpeg' => 'image/jpeg',
'jpg' => 'image/jpeg',
'gif' => 'image/gif',
'bmp' => 'image/bmp',
'ico' => 'image/vnd.microsoft.icon',
'tiff' => 'image/tiff',
'tif' => 'image/tiff',
'svg' => 'image/svg+xml',
'svgz' => 'image/svg+xml',
// archives
'zip' => 'application/zip',
'rar' => 'application/x-rar-compressed',
'exe' => 'application/x-msdownload',
'msi' => 'application/x-msdownload',
'cab' => 'application/vnd.ms-cab-compressed',
// audio/video
'mp3' => 'audio/mpeg',
'qt' => 'video/quicktime',
'mov' => 'video/quicktime',
// adobe
'pdf' => 'application/pdf',
'psd' => 'image/vnd.adobe.photoshop',
'ai' => 'application/postscript',
'eps' => 'application/postscript',
'ps' => 'application/postscript',
// ms office
'doc' => 'application/msword',
'rtf' => 'application/rtf',
'xls' => 'application/vnd.ms-excel',
'ppt' => 'application/vnd.ms-powerpoint',
// open office
'odt' => 'application/vnd.oasis.opendocument.text',
'ods' => 'application/vnd.oasis.opendocument.spreadsheet',
);
$ext = explode('.',$filename);
$ext = array_pop($ext);
$ext = strtolower($ext);
if (array_key_exists($ext, $mime_types)) {
return $mime_types[$ext];
}
elseif (function_exists('finfo_open')) {
$finfo = finfo_open(FILEINFO_MIME);
$mimetype = finfo_file($finfo, $filename);
finfo_close($finfo);
return $mimetype;
}
else {
return 'application/octet-stream';
}
}
public function to_camel_case($str, $capitalise_first_char = false) {
if($capitalise_first_char) {
$str[0] = strtoupper($str[0]);
}
$func = function($c){ return strtoupper($c[1]); };
return preg_replace_callback('/-([a-z])/', $func, $str);
}
public function from_camel_case($str) {
$str[0] = strtolower($str[0]);
$func = function($c){ return "-" . strtolower($c[1]); };
return preg_replace_callback('/([A-Z])/', $func, $str);
}
public function decodeJ($json_str)
{
$config = json_decode($json_str, true);
return is_array($config) ? $config : array();
}
public function sortByOneKey(array $array, $key, $asc = true) {
$result = array();
$values = array();
foreach ($array as $id => $value) {
$values[$id] = isset($value[$key]) ? $value[$key] : '';
}
if ($asc) {
asort($values);
}
else {
arsort($values);
}
foreach ($values as $key => $value) {
$result[$key] = $array[$key];
}
return $result;
}
public function cache_function($buildCallback, array $args = array(), $timeoutSeconds = 3600)
{
// Set up the filename for the cache file
if(is_array($buildCallback)){
$cacheKey = get_class($buildCallback[0]) .'::'. $buildCallback[1];
}else{
$cacheKey = $buildCallback . ':' . implode(':', $args);
}
$cacheKey .= ':' . implode(':', $args);
$file_path = BB_PATH_CACHE .DIRECTORY_SEPARATOR. md5($cacheKey);
// If the file hasn't yet been created or is out of date then call the require function and store it's result.
if(!file_exists($file_path) || filemtime($file_path) < (time() - $timeoutSeconds)){
$result = call_user_func_array($buildCallback, $args);
file_put_contents($file_path, serialize($result), LOCK_EX);
// Else, grab the result from the cache.
}else{
$result = unserialize(file_get_contents($file_path));
}
return $result;
}
public function fileExists($file)
{
return file_exists($file);
}
public function rename($old, $new)
{
return rename($old, $new);
}
public function unlink($file)
{
return unlink($file);
}
public function mkdir($destination, $perm, $recursive = false)
{
return mkdir($destination, $perm, $recursive);
}
public function glob($pattern, $flag = 0)
{
return glob($pattern, $flag);
}
public function getTable($type)
{
$class = 'Model_'.ucfirst($type).'Table';
$file = BB_PATH_LIBRARY . '/Model/'.$type.'Table.php';
if(!file_exists($file)){
throw new \Box_Exception('Service class :class was not found in :path', array(':class'=>$class,':path'=>$file));
}
require_once $file;
return new $class();
}
public function getPairsForTableByIds($table, $ids)
{
if (empty ($ids)) {
return array();
}
$slots = (count($ids)) ? implode(',', array_fill(0, count($ids), '?')) : ''; //same as RedBean genSlots() method
$rows = $this->di['db']->getAll('SELECT id, title FROM ' . $table . ' WHERE id in (' . $slots . ')', $ids);
$result = array();
foreach ($rows as $record) {
$result[$record['id']] = $record['title'];
}
return $result;
}
}
+115
View File
@@ -0,0 +1,115 @@
<?php
/**
* BoxBilling
*
* @copyright BoxBilling, Inc (http://www.boxbilling.com)
* @license Apache-2.0
*
* Copyright BoxBilling, Inc
* This source file is subject to the Apache-2.0 License that is bundled
* with this source code in the file LICENSE
*/
class Box_Translate implements \Box\InjectionAwareInterface
{
/**
* @var \Box_Di
*/
protected $di = NULL;
protected $domain = 'messages';
protected $locale = 'en_US';
/**
* @return string
*/
public function getLocale()
{
return $this->locale;
}
/**
* @param string $locale
* @return Box_Translate
*/
public function setLocale($locale)
{
$this->locale = $locale;
return $this;
}
/**
* @param Box_Di $di
*/
public function setDi($di)
{
$this->di = $di;
}
/**
* @return Box_Di
*/
public function getDi()
{
return $this->di;
}
public function setup()
{
$locale = $this->getLocale();
$codeset = "UTF-8";
if(!function_exists('gettext')) {
require_once BB_PATH_LIBRARY . '/php-gettext/gettext.inc';
T_setlocale(LC_MESSAGES, $locale.'.'.$codeset);
T_setlocale(LC_TIME, $locale.'.'.$codeset);
T_bindtextdomain($this->domain, BB_PATH_LANGS);
T_bind_textdomain_codeset($this->domain, $codeset);
T_textdomain($this->domain);
} else {
@putenv('LANG='.$locale.'.'.$codeset);
@putenv('LANGUAGE='.$locale.'.'.$codeset);
// set locale
if (!defined('LC_MESSAGES')) define('LC_MESSAGES', 5);
if (!defined('LC_TIME')) define('LC_TIME', 2);
setlocale(LC_MESSAGES, $locale.'.'.$codeset);
setlocale(LC_TIME, $locale.'.'.$codeset);
bindtextdomain($this->domain, BB_PATH_LANGS);
if(function_exists('bind_textdomain_codeset')) bind_textdomain_codeset($this->domain, $codeset);
textdomain($this->domain);
if (!function_exists('__')) {
function __($msgid, array $values = NULL)
{
if (empty($msgid)) return null;
$string = gettext($msgid);
return empty($values) ? $string : strtr($string, $values);
}
}
}
}
/**
* @return string
*/
public function getDomain()
{
return $this->domain;
}
/**
* @param $domain
* @return Box_Translate
*/
public function setDomain($domain)
{
$this->domain = $domain;
return $this;
}
public function __($msgid, array $values = NULL)
{
return __($msgid, $values);
}
}
+293
View File
@@ -0,0 +1,293 @@
<?php
/**
* BoxBilling
*
* @copyright BoxBilling, Inc (http://www.boxbilling.com)
* @license Apache-2.0
*
* Copyright BoxBilling, Inc
* This source file is subject to the Apache-2.0 License that is bundled
* with this source code in the file LICENSE
*/
class Box_TwigExtensions extends Twig\Extension\AbstractExtension implements \Box\InjectionAwareInterface
{
protected $di;
/**
* @param mixed $di
*/
public function setDi($di)
{
$this->di = $di;
}
/**
* @return mixed
*/
public function getDi()
{
return $this->di;
}
/**
* Returns a list of filters to add to the existing list.
*
* @return array An array of filters
*/
public function getFilters()
{
return array(
'alink' => new Twig\TwigFilter('alink', array($this, 'twig_bb_admin_link_filter'), array('is_safe' => array('html'))),
'link' => new Twig\TwigFilter('link', array($this, 'twig_bb_client_link_filter'), array('is_safe' => array('html'))),
'gravatar' => new Twig\TwigFilter('gravatar','twig_gravatar_filter'),
'markdown' => new Twig\TwigFilter('markdown','twig_markdown_filter', array('needs_environment' => true, 'is_safe' => array('html'))),
'truncate' => new Twig\TwigFilter('truncate','twig_truncate_filter', array('needs_environment' => true)),
'timeago' => new Twig\TwigFilter('timeago','twig_timeago_filter'),
'daysleft' => new Twig\TwigFilter('daysleft','twig_daysleft_filter'),
'size' => new Twig\TwigFilter('size', 'twig_size_filter'),
'ipcountryname' => new Twig\TwigFilter('ipcountryname', array($this, 'twig_ipcountryname_filter')),
'number' => new Twig\TwigFilter('number', 'twig_number_filter'),
'period_title' => new Twig\TwigFilter('period_title', 'twig_period_title', array('needs_environment' => true, 'is_safe' => array('html'))),
'autolink' => new Twig\TwigFilter('autolink', 'twig_autolink_filter'),
'bbmd' => new Twig\TwigFilter('bbmd', 'twig_bbmd_filter', array('needs_environment' => true, 'is_safe' => array('html'))),
'bb_date' => new Twig\TwigFilter('bb_date', array($this, 'twig_bb_date')),
'bb_datetime' => new Twig\TwigFilter('bb_datetime', array($this, 'twig_bb_datetime')),
'img_tag' => new Twig\TwigFilter('img_tag', 'twig_img_tag', array('needs_environment' => false, 'is_safe' => array('html'))),
'script_tag' => new Twig\TwigFilter('script_tag', 'twig_script_tag', array('needs_environment' => false, 'is_safe' => array('html'))),
'stylesheet_tag' => new Twig\TwigFilter('stylesheet_tag', 'twig_stylesheet_tag', array('needs_environment' => false, 'is_safe' => array('html'))),
'mod_asset_url' => new Twig\TwigFilter('mod_asset_url', 'twig_mod_asset_url'),
'asset_url' => new Twig\TwigFilter('asset_url', 'twig_asset_url', array('needs_environment' => true, 'is_safe' => array('html'))),
'money' => new Twig\TwigFilter('money', 'twig_money', array('needs_environment' => true, 'is_safe' => array('html'))),
'money_without_currency' => new Twig\TwigFilter('money_without_currency','twig_money_without_currency', array('needs_environment' => true, 'is_safe' => array('html'))),
'money_convert' => new Twig\TwigFilter('money_convert', 'twig_money_convert', array('needs_environment' => true, 'is_safe' => array('html'))),
'money_convert_without_currency' => new Twig\TwigFilter('money_convert_without_currency', array('needs_environment' => true, 'is_safe' => array('html'))),
);
}
/**
* Returns the name of the extension.
*
* @return string The extension name
*/
public function getName()
{
return 'bb';
}
public function twig_bb_date($time, $format = null)
{
$locale_date_format = $this->di['config']['locale_date_format'];
$format = is_null($format) ? $locale_date_format : $format;
return strftime($format, strtotime($time));
}
public function twig_bb_datetime($time, $format = null)
{
$locale_date_format = $this->di['config']['locale_date_format'];
$locale_time_format = $this->di['config']['locale_time_format'];
$format = is_null($format) ? $locale_date_format . $locale_time_format : $format;
return strftime($format, strtotime($time));
}
function twig_ipcountryname_filter($value)
{
if (empty($value)) {
return '';
}
try {
$record = $this->di['geoip']->country($value);
return $record->country->name;
} catch (Exception $e) {
return '';
}
}
function twig_bb_client_link_filter($link, $params = null)
{
if($this->di['url'] === null) {
return null;
}
return $this->di['url']->link($link, $params);
}
function twig_bb_admin_link_filter($link, $params = null)
{
return $this->di['url']->adminLink($link, $params);
}
}
function twig_period_title(Twig\Environment $env, $period)
{
$globals = $env->getGlobals();
$api_guest = $globals['guest'];
return $api_guest->system_period_title(array('code'=>$period));
}
function twig_money_convert(Twig\Environment $env, $price, $currency = null)
{
$globals = $env->getGlobals();
$api_guest = $globals['guest'];
if(is_null($currency)) {
$c = $api_guest->cart_get_currency();
$currency = $c['code'];
}
return $api_guest->currency_format(array("price" => $price, 'code'=>$currency, 'convert'=>true));
}
function money_convert_without_currency(Twig\Environment $env, $price, $currency = null, $without_currency = false)
{
$globals = $env->getGlobals();
$api_guest = $globals['guest'];
if(is_null($currency)) {
$c = $api_guest->cart_get_currency();
$currency = $c['code'];
}
return $api_guest->currency_format(array("price" => $price, 'code'=>$currency, 'convert'=>true, 'without_currency'=>true));
}
function twig_money(Twig\Environment $env, $price, $currency = null)
{
$globals = $env->getGlobals();
$api_guest = $globals['guest'];
return $api_guest->currency_format(array("price" => $price, 'code'=>$currency, 'convert'=>false));
}
function twig_money_without_currency(Twig\Environment $env, $price, $currency = null)
{
$globals = $env->getGlobals();
$api_guest = $globals['guest'];
return $api_guest->currency_format(array("price" => $price, 'code'=>$currency, 'convert'=>false, 'without_currency'=>true));
}
function twig_mod_asset_url($asset, $mod)
{
return BB_URL . 'bb-modules/'.ucfirst($mod).'/assets/'.$asset;
}
function twig_asset_url(Twig\Environment $env, $asset)
{
$globals = $env->getGlobals();
return BB_URL . 'bb-themes/'.$globals['current_theme'].'/assets/'.$asset;
}
function twig_img_tag($path, $alt = null)
{
$alt = is_null($alt) ? pathinfo($path, PATHINFO_BASENAME) : $alt;
return sprintf('<img src="%s" alt="%s" title="%s"/>', $path, $alt, $alt);
}
function twig_script_tag($path)
{
return sprintf('<script type="text/javascript" src="%s?%s"></script>', $path, Box_Version::VERSION);
}
function twig_stylesheet_tag($path, $media = 'screen')
{
return sprintf('<link rel="stylesheet" type="text/css" href="%s?v=%s" media="%s" />', $path, Box_Version::VERSION, $media);
}
function twig_gravatar_filter($email, $size = null)
{
$protocol = BB_SSL ? 'https' : 'http';
$link = $protocol . '://gravatar.com/avatar/' . md5($email);
if ($size) {
$link .= '/?s=' . $size;
}
return $link;
}
function twig_autolink_filter($text)
{
$pattern = '#\b(([\w-]+://?|www[.])[^\s()<>]+(?:\([\w\d]+\)|([^[:punct:]\s]|/)))#';
$callback = function($matches)
{
$url = array_shift($matches);
$url_parts = parse_url($url);
if(!isset($url_parts["scheme"])) {
$url = 'http://' . $url;
}
return sprintf('<a target="_blank" href="%s">%s</a>', $url, $url);
};
return preg_replace_callback($pattern, $callback, $text);
}
function twig_number_filter($number, $decimals = 2, $dec_point = '.', $thousands_sep = '')
{
return number_format($number, $decimals, $dec_point, $thousands_sep);
}
function twig_daysleft_filter($iso8601)
{
$timediff = strtotime($iso8601) - time();
return intval($timediff/86400);
}
function twig_timeago_filter($iso8601)
{
$cur_tm = time(); $dif = $cur_tm-strtotime($iso8601);
$pds = array(__('second'),__('minute'),__('hour'),__('day'),__('week'),__('month'),__('year'),__('decade'));
$lngh = array(1,60,3600,86400,604800,2630880,31570560,315705600);
for($v = sizeof($lngh)-1; ($v >= 0)&&(($no = $dif/$lngh[$v])<=1); $v--); if($v < 0) $v = 0; $_tm = $cur_tm-($dif%$lngh[$v]);
$no = floor($no); if($no <> 1) $pds[$v] .='s'; $x=sprintf("%d %s ",$no,$pds[$v]);
return $x;
}
function twig_size_filter($value)
{
$precision = 2;
$units = array('B', 'KB', 'MB', 'GB', 'TB');
$bytes = max($value, 0);
$pow = floor(($bytes ? log($bytes) : 0) / log(1024));
$pow = min($pow, count($units) - 1);
$bytes /= pow(1024, $pow);
return round($bytes, $precision) . ' ' . $units[$pow];
}
function twig_markdown_filter(Twig\Environment $env, $value)
{
$markdownParser = new \Michelf\MarkdownExtra;
// Michelf Markdown version 1.7.0 and up
$markdownParser->hard_wrap = true;
return $markdownParser->transform($value); //htmlspecialchars($value, ENT_NOQUOTES)
}
function twig_truncate_filter(Twig\Environment $env, $value, $length = 30, $preserve = false, $separator = '...')
{
mb_internal_encoding("UTF-8");
if (mb_strlen($value) > $length) {
if ($preserve) {
if (false !== ($breakpoint = mb_strpos($value, ' ', $length))) {
$length = $breakpoint;
}
}
return mb_substr($value, 0, $length) . $separator;
}
return $value;
}
/**
* BoxBilling markdown
*/
function twig_bbmd_filter(Twig\Environment $env, $value)
{
$value = twig_markdown_filter($env, $value);
return $value;
}
+68
View File
@@ -0,0 +1,68 @@
<?php
/**
* BoxBilling
*
* @copyright BoxBilling, Inc (http://www.boxbilling.com)
* @license Apache-2.0
*
* Copyright BoxBilling, Inc
* This source file is subject to the Apache-2.0 License that is bundled
* with this source code in the file LICENSE
*/
class Box_TwigLoader extends Twig\Loader\FilesystemLoader
{
protected $options = array();
/**
* Constructor.
*
* @param string|array $options A path or an array of options and paths
*/
public function __construct(array $options)
{
if(!isset($options['mods'])) {
throw new \Box_Exception('Missing mods param for Box_TwigLoader');
}
if(!isset($options['theme'])) {
throw new \Box_Exception('Missing theme param for Box_TwigLoader');
}
if(!isset($options['type'])) {
throw new \Box_Exception('Missing type param for Box_TwigLoader');
}
$this->options = $options;
$paths_arr = array($options['mods'], $options['theme']);
$this->setPaths($paths_arr);
}
protected function findTemplate($name, $throw = true)
{
// normalize name
$name = preg_replace('#/{2,}#', '/', strtr($name, '\\', '/'));
if (isset($this->cache[$name])) {
return $this->cache[$name];
}
$name_split = explode("_", $name);
$paths = array();
$paths[] = $this->options["theme"] . DIRECTORY_SEPARATOR . "html";
if(isset($name_split[1])) {
$paths[] = $this->options["mods"] . DIRECTORY_SEPARATOR . ucfirst($name_split[1]). DIRECTORY_SEPARATOR . "html_" . $this->options["type"];
}
foreach($paths as $path) {
if(file_exists($path . DIRECTORY_SEPARATOR . $name)) {
return $this->cache[$name] = $path . '/' . $name;
}
}
throw new \Twig\Error\LoaderError(sprintf('Unable to find template "%s" (looked into: %s).', $name, implode(', ', $paths)));
}
}
+153
View File
@@ -0,0 +1,153 @@
<?php
/**
* BoxBilling
*
* @copyright BoxBilling, Inc (http://www.boxbilling.com)
* @license Apache-2.0
*
* Copyright BoxBilling, Inc
* This source file is subject to the Apache-2.0 License that is bundled
* with this source code in the file LICENSE
*/
class Box_Update
{
/**
* @var \Box_Di
*/
protected $di = null;
/**
* @param \Box_Di $di
*/
public function setDi($di)
{
$this->di = $di;
}
/**
* @return \Box_Di
*/
public function getDi()
{
return $this->di;
}
private $_url = 'http://api.boxbilling.com/compare-version.php';
public function __construct()
{
if(defined('BB_VERSION_URL') && BB_VERSION_URL) {
$this->_url = BB_VERSION_URL;
}
}
/**
* Returns latest information
*/
private function _getLatestVersionInfo()
{
return $this->di['tools']->cache_function(array($this, 'getJson'), array(), 86400);
}
/**
* Return latest version number
* @return string
*/
public function getLatestVersion()
{
$response = $this->_getLatestVersionInfo();
if(!is_object($response)) {
return Box_Version::VERSION;
}
return $response->version;
}
/**
* Latest version link
* @return string
*/
public function getLatestVersionDownloadLink()
{
$response = $this->_getLatestVersionInfo();
if(isset($response->update)) {
return $response->update;
}
return $response->link;
}
/**
* Check if we need to update current BoxBilling version
* @return bool
*/
public function getCanUpdate()
{
$version = $this->getLatestVersion();
$result = Box_Version::compareVersion($version);
return ($result > 0);
}
/**
* Check if given file is same as original
* @param string $file - filepath
* @return bool
*/
private function isHashValid($file)
{
if(!file_exists($file)) {
return false;
}
$response = $this->_getLatestVersionInfo();
$hash = md5($response->version.filesize($file));
return ($hash == $response->hash);
}
public function getJson()
{
$url = $this->_url . '?current=' . Box_Version::VERSION;
$curl = new Box_Curl($url);
$curl->request();
$response = $curl->getBody();
return json_decode($response);
}
/**
* Perform update
*
* @throws Exception
*/
public function performUpdate()
{
if(!$this->getCanUpdate()) {
throw new LogicException('You have latest version of BoxBilling. You do not need to update.');
}
error_log('Started BoxBilling auto-update script');
$latest_version = $this->getLatestVersion();
$latest_version_archive = BB_PATH_CACHE.DIRECTORY_SEPARATOR.$latest_version.'.zip';
// download latest archive from link
$content = $this->di['tools']->file_get_contents($this->getLatestVersionDownloadLink());
$f = fopen($latest_version_archive,'wb');
fwrite($f,$content,strlen($content));
fclose($f);
//@todo validate downloaded file hash
// Extract latest archive on top of current version
$ff = new Box_Zip($latest_version_archive);
$ff->decompress(BB_PATH_ROOT);
if(file_exists(BB_PATH_ROOT.'/bb-update.php')) {
error_log('Calling bb-update.php script from auto-updater');
$this->di['tools']->file_get_contents(BB_URL.'bb-update.php');
}
// clean up things
$this->di['tools']->emptyFolder(BB_PATH_CACHE);
$this->di['tools']->emptyFolder(BB_PATH_ROOT.'/install');
rmdir(BB_PATH_ROOT.'/install');
return true;
}
}
+69
View File
@@ -0,0 +1,69 @@
<?php
/**
* BoxBilling
*
* @copyright BoxBilling, Inc (http://www.boxbilling.com)
* @license Apache-2.0
*
* Copyright BoxBilling, Inc
* This source file is subject to the Apache-2.0 License that is bundled
* with this source code in the file LICENSE
*/
class Box_Url implements Box\InjectionAwareInterface
{
protected $di;
protected $baseUri;
public function setDi($di)
{
$this->di = $di;
}
public function getDi()
{
return $this->di;
}
public function setBaseUri($baseUri)
{
$this->baseUri = $baseUri;
}
/**
* Generates a URL
*/
public function get ($uri)
{
return $this->baseUri . $uri;
}
/**
* @param string $uri
*/
public function link($uri = null, $params = array())
{
$uri = trim($uri, '/');
$link =$this->baseUri .'index.php?_url=/' . $uri;
if(BB_SEF_URLS) {
$link = $this->baseUri . $uri;
if (!empty($params)){
$link .= '?';
}
}
if(!empty($params)) {
$link .= '&' . http_build_query($params);
}
return $link;
}
public function adminLink($uri, $params = array())
{
$uri = trim($uri, '/');
$prefix = $this->di['config']['admin_area_prefix'];
$uri = $prefix . '/' . $uri;
return $this->link($uri, $params);
}
}
+58
View File
@@ -0,0 +1,58 @@
<?php
/**
* BoxBilling
*
* @copyright BoxBilling, Inc (http://www.boxbilling.com)
* @license Apache-2.0
*
* Copyright BoxBilling, Inc
* This source file is subject to the Apache-2.0 License that is bundled
* with this source code in the file LICENSE
*/
class Box_UrlHelper {
private $method;
private $conditions;
public $params = array();
public $match = false;
/**
* @param string $requestUri
*/
public function __construct($httpMethod, $url, $conditions=array(), $requestUri) {
$requestMethod = $_SERVER['REQUEST_METHOD'];
$this->method = $httpMethod;
$this->conditions = $conditions;
if (strtoupper($httpMethod) == $requestMethod) {
$paramNames = array();
$paramValues = array();
preg_match_all('@:([a-zA-Z]+)@', $url, $paramNames, PREG_PATTERN_ORDER); // get param names
$paramNames = $paramNames[1]; // we want the set of matches
$regexedUrl = preg_replace_callback('@:[a-zA-Z_\-]+@', array($this, 'regexValue'), $url); // replace param with regex capture
if (preg_match('@^' . $regexedUrl . '$@', $requestUri, $paramValues)) { // determine match and get param values
array_shift($paramValues); // remove the complete text match
$counted = count($paramNames);
for ($i=0; $i < $counted; $i++) {
$this->params[$paramNames[$i]] = $paramValues[$i];
}
$this->match = true;
}
}
}
private function regexValue($matches) {
$key = str_replace(':', '', $matches[0]);
if (array_key_exists($key, $this->conditions)) {
return '(' . $this->conditions[$key] . ')';
} else {
return '([a-zA-Z0-9_\-]+)';
}
}
}
+117
View File
@@ -0,0 +1,117 @@
<?php
/**
* BoxBilling
*
* @copyright BoxBilling, Inc (http://www.boxbilling.com)
* @license Apache-2.0
*
* Copyright BoxBilling, Inc
* This source file is subject to the Apache-2.0 License that is bundled
* with this source code in the file LICENSE
*/
class Box_Validate
{
protected $di = null;
/**
* @param Box_Di|null $di
*/
public function setDi($di)
{
$this->di = $di;
}
/**
* @return Box_Di|null
*/
public function getDi()
{
return $this->di;
}
public function isSldValid($sld)
{
// allow punnycode
if(substr($sld, 0, 4) == 'xn--') {
return true;
}
if(preg_match('/^[a-z0-9]+[a-z0-9\-]*[a-z0-9]+$/i', $sld) && strlen($sld) < 64 && substr($sld, 2, 2) != '--') {
return true;
} else {
return false;
}
}
public function isEmailValid($email, $throw = true)
{
$valid = (preg_match("/[-a-zA-Z0-9_.+]+@[a-zA-Z0-9-]{2,}\.[a-zA-Z]{2,}/", $email) > 0) ? true : false;
if(!$valid && $throw) {
throw new \Box_Exception('Email is not valid');
}
return $valid;
}
public function isPasswordStrong($pwd)
{
if( strlen($pwd) < 7 ) {
throw new \Box_Exception("Password too short!");
}
if( !preg_match("#[0-9]+#", $pwd) ) {
throw new \Box_Exception("Password must include at least one number!");
}
if( !preg_match("#[a-z]+#", $pwd) ) {
throw new \Box_Exception("Password must include at least one letter!");
}
/*
if( !preg_match("#[A-Z]+#", $pwd) ) {
throw new \Box_Exception("Password must include at least one CAPS!");
}
if( !preg_match("#\W+#", $pwd) ) {
throw new \Box_Exception("Password must include at least one symbol!");
}
*/
return true;
}
/**
* @param array $required - Array with required keys and messages to show if the key is not found
* @param array $data - Array to search for keys
* @param array $variables - Array of variables for message placeholders (:placeholder)
* @param integer $code - Exception code
* @throws Box_Exception
*/
public function checkRequiredParamsForArray(array $required, array $data, array $variables = NULL, $code = 0)
{
foreach ($required as $key => $msg) {
if(!isset($data[$key])){
throw new \Box_Exception($msg, $variables, $code);
}
if (is_string($data[$key]) && strlen(trim($data[$key])) === 0){
throw new \Box_Exception($msg, $variables, $code);
}
if (!is_numeric($data[$key]) && empty($data[$key])){
throw new \Box_Exception($msg, $variables, $code);
}
}
}
public function isBirthdayValid($birthday = '')
{
if (strlen(trim($birthday)) > 0 && strtotime($birthday) === false) {
throw new \Box_Exception('Invalid birth date value');
}
return true;
}
}
+37
View File
@@ -0,0 +1,37 @@
<?php
/**
* BoxBilling
*
* @copyright BoxBilling, Inc (http://www.boxbilling.com)
* @license Apache-2.0
*
* Copyright BoxBilling, Inc
* This source file is subject to the Apache-2.0 License that is bundled
* with this source code in the file LICENSE
*/
final class Box_Version
{
const VERSION = '0.0.1';
const TYPE_FREE = 'free';
const TYPE_PRO = 'pro';
/**
* Compare the specified BoxBilling version string $version
* with the current Box_Version::VERSION of BoxBilling.
*
* @param string $version A version string (e.g. "0.7.1").
* @return integer -1 if the $version is older,
* 0 if they are the same,
* and +1 if $version is newer.
*
*/
public static function compareVersion($version)
{
$version = strtolower($version);
$version = preg_replace('/(\d)pr(\d?)/', '$1a$2', $version);
return version_compare($version, strtolower(self::VERSION));
}
}
File diff suppressed because it is too large. Load diff
+102
View File
@@ -0,0 +1,102 @@
<?php
/**
* BoxBilling
*
* @copyright BoxBilling, Inc (http://www.boxbilling.com)
* @license Apache-2.0
*
* Copyright BoxBilling, Inc
* This source file is subject to the Apache-2.0 License that is bundled
* with this source code in the file LICENSE
*/
class FileCache
{
protected $_cacheDir = '';
/**
* Constructor
*/
public function __construct($cacheDir = null)
{
if(is_null($cacheDir)) {
$cacheDir = BB_PATH_CACHE;
}
if ($cacheDir) {
if (!is_dir($cacheDir)) {
throw new FileCacheException('The specified cache directory is invalid.');
}
$this->_cacheDir = $cacheDir;
}
}
/**
* Save data to the specified cache file
*/
public function set($key, $data)
{
$cacheFile = $this->getCacheFile($key);
if (!file_put_contents($cacheFile, json_encode($data))) {
throw new FileCacheException('Error saving data with the key ' . $key . ' to the cache file.');
}
return $this;
}
/**
* Get data from the specified cache file
*/
public function get($key)
{
if ($this->exists($key)) {
$cacheFile = $this->getCacheFile($key);
if (!$data = json_decode(file_get_contents($cacheFile), true)) {
throw new FileCacheException('Error reading data with the key ' . $key . ' from the cache file.');
}
return $data;
}
return null;
}
/**
* Delete the specified cache file
*/
public function delete($key)
{
if ($this->exists($key)) {
$cacheFile = $this->getCacheFile($key);
if (!unlink($cacheFile)) {
throw new FileCacheException('Error deleting the file cache with key ' . $key);
}
return true;
}
return false;
}
/**
* Check if the specified cache file exists
*/
public function exists($key)
{
$cacheFile = $this->getCacheFile($key);
return file_exists($cacheFile);
}
/**
* Get the specified cache file
*/
protected function getCacheFile($key)
{
$key = $this->getCacheKey($key);
return $this->_cacheDir . DIRECTORY_SEPARATOR . $key . '.cache';
}
/**
* Convert cache key to unreadable value
*/
protected function getCacheKey($raw)
{
return strtolower(md5($raw . 'Iip6tPwfNi95gugl0e6'));
}
}
Binary file not shown.
+17
View File
@@ -0,0 +1,17 @@
<?php
/**
* BoxBilling
*
* @copyright BoxBilling, Inc (http://www.boxbilling.com)
* @license Apache-2.0
*
* Copyright BoxBilling, Inc
* This source file is subject to the Apache-2.0 License that is bundled
* with this source code in the file LICENSE
*/
class Model_ActivityAdminHistory extends RedBean_SimpleModel
{
}
+16
View File
@@ -0,0 +1,16 @@
<?php
/**
* BoxBilling
*
* @copyright BoxBilling, Inc (http://www.boxbilling.com)
* @license Apache-2.0
*
* Copyright BoxBilling, Inc
* This source file is subject to the Apache-2.0 License that is bundled
* with this source code in the file LICENSE
*/
class Model_ActivityClientEmail extends \RedBean_SimpleModel
{
}
@@ -0,0 +1,17 @@
<?php
/**
* BoxBilling
*
* @copyright BoxBilling, Inc (http://www.boxbilling.com)
* @license Apache-2.0
*
* Copyright BoxBilling, Inc
* This source file is subject to the Apache-2.0 License that is bundled
* with this source code in the file LICENSE
*/
class Model_ActivityClientHistory extends RedBean_SimpleModel
{
}
@@ -0,0 +1,62 @@
<?php
/**
* BoxBilling
*
* @copyright BoxBilling, Inc (http://www.boxbilling.com)
* @license Apache-2.0
*
* Copyright BoxBilling, Inc
* This source file is subject to the Apache-2.0 License that is bundled
* with this source code in the file LICENSE
*/
class Model_ActivityClientHistoryTable implements \Box\InjectionAwareInterface
{
/**
* @var \Box_Di
*/
protected $di;
/**
* @param Box_Di $di
*/
public function setDi($di)
{
$this->di = $di;
}
/**
* @return Box_Di
*/
public function getDi()
{
return $this->di;
}
/**
* @param array $data
*/
public function logEvent($data)
{
if(!isset($data['client_id']) || !isset($data['ip'])) {
return ;
}
$entry = $this->di['db']->dispense('ActivityClientHistory');
$entry->client_id = $data['client_id'];
$entry->ip = $data['ip'];
$entry->created_at = date('Y-m-d H:i:s');
$entry->updated_at = date('Y-m-d H:i:s');
$this->di['db']->store($entry);
}
public function rmByClient(Model_Client $client)
{
$models = $this->di['db']->find('ActivityClientHistory', 'client_id = ?', array($client->id));
foreach($models as $model){
$this->di['db']->trash($model);
}
}
}
+17
View File
@@ -0,0 +1,17 @@
<?php
/**
* BoxBilling
*
* @copyright BoxBilling, Inc (http://www.boxbilling.com)
* @license Apache-2.0
*
* Copyright BoxBilling, Inc
* This source file is subject to the Apache-2.0 License that is bundled
* with this source code in the file LICENSE
*/
class Model_ActivitySystem extends RedBean_SimpleModel
{
}
+39
View File
@@ -0,0 +1,39 @@
<?php
/**
* BoxBilling
*
* @copyright BoxBilling, Inc (http://www.boxbilling.com)
* @license Apache-2.0
*
* Copyright BoxBilling, Inc
* This source file is subject to the Apache-2.0 License that is bundled
* with this source code in the file LICENSE
*/
class Model_Admin extends \RedBean_SimpleModel
{
const ROLE_ADMIN = 'admin';
const ROLE_STAFF = 'staff';
const ROLE_CRON = 'cron';
const STATUS_ACTIVE = 'active';
const STATUS_INACTIVE = 'inactive';
public function getFullName()
{
return $this->name;
}
public function getStatus($status = '')
{
$statusArray = array(
self::STATUS_ACTIVE,
self::STATUS_INACTIVE
);
if (in_array($status, $statusArray)){
return strtolower($status);
}
return self::STATUS_INACTIVE;
}
}
+17
View File
@@ -0,0 +1,17 @@
<?php
/**
* BoxBilling
*
* @copyright BoxBilling, Inc (http://www.boxbilling.com)
* @license Apache-2.0
*
* Copyright BoxBilling, Inc
* This source file is subject to the Apache-2.0 License that is bundled
* with this source code in the file LICENSE
*/
class Model_AdminGroup extends RedBean_SimpleModel
{
}
+17
View File
@@ -0,0 +1,17 @@
<?php
/**
* BoxBilling
*
* @copyright BoxBilling, Inc (http://www.boxbilling.com)
* @license Apache-2.0
*
* Copyright BoxBilling, Inc
* This source file is subject to the Apache-2.0 License that is bundled
* with this source code in the file LICENSE
*/
class Model_ApiRequest extends \RedBean_SimpleModel
{
}
+65
View File
@@ -0,0 +1,65 @@
<?php
/**
* BoxBilling
*
* @copyright BoxBilling, Inc (http://www.boxbilling.com)
* @license Apache-2.0
*
* Copyright BoxBilling, Inc
* This source file is subject to the Apache-2.0 License that is bundled
* with this source code in the file LICENSE
*/
class Model_ApiRequestTable implements \Box\InjectionAwareInterface
{
/**
* @var \Box_Di
*/
protected $di;
/**
* @param Box_Di $di
*/
public function setDi($di)
{
$this->di = $di;
}
/**
* @return Box_Di
*/
public function getDi()
{
return $this->di;
}
public function logRequest($request, $ip)
{
$r = $this->di['db']->dispense('ApiRequest');
$r->ip = $ip;
$r->request = $request;
$r->created_at = date('Y-m-d H:i:s');
$this->di['db']->store($r);
}
public function getRequestCount($since, $ip = null)
{
$sinceIso = date('Y-m-d H:i:s', $since);
$sql = 'SELECT count(id) as cc
WHERE created_at > :since';
$params = array(':since' => $sinceIso);
if(NULL !== $ip) {
$sql .= ' AND ip = :ip';
$params[':ip'] = $ip;
}
$stmt = $this->di['pdo']->prepare($sql);
$stmt->execute($params);
return $stmt->fetchColumn($stmt);
}
}
+17
View File
@@ -0,0 +1,17 @@
<?php
/**
* BoxBilling
*
* @copyright BoxBilling, Inc (http://www.boxbilling.com)
* @license Apache-2.0
*
* Copyright BoxBilling, Inc
* This source file is subject to the Apache-2.0 License that is bundled
* with this source code in the file LICENSE
*/
class Model_Cart extends \RedBean_SimpleModel
{
}
+17
View File
@@ -0,0 +1,17 @@
<?php
/**
* BoxBilling
*
* @copyright BoxBilling, Inc (http://www.boxbilling.com)
* @license Apache-2.0
*
* Copyright BoxBilling, Inc
* This source file is subject to the Apache-2.0 License that is bundled
* with this source code in the file LICENSE
*/
class Model_CartProduct extends \RedBean_SimpleModel
{
}
+24
View File
@@ -0,0 +1,24 @@
<?php
/**
* BoxBilling
*
* @copyright BoxBilling, Inc (http://www.boxbilling.com)
* @license Apache-2.0
*
* Copyright BoxBilling, Inc
* This source file is subject to the Apache-2.0 License that is bundled
* with this source code in the file LICENSE
*/
class Model_Client extends RedBean_SimpleModel
{
const ACTIVE = 'active';
const SUSPENDED = 'suspended';
const CANCELED = 'canceled';
public function getFullName()
{
return $this->first_name .' '.$this->last_name;
}
}
+17
View File
@@ -0,0 +1,17 @@
<?php
/**
* BoxBilling
*
* @copyright BoxBilling, Inc (http://www.boxbilling.com)
* @license Apache-2.0
*
* Copyright BoxBilling, Inc
* This source file is subject to the Apache-2.0 License that is bundled
* with this source code in the file LICENSE
*/
class Model_ClientBalance extends RedBean_SimpleModel
{
}
+17
View File
@@ -0,0 +1,17 @@
<?php
/**
* BoxBilling
*
* @copyright BoxBilling, Inc (http://www.boxbilling.com)
* @license Apache-2.0
*
* Copyright BoxBilling, Inc
* This source file is subject to the Apache-2.0 License that is bundled
* with this source code in the file LICENSE
*/
class Model_ClientGroup extends RedBean_SimpleModel
{
}
+30
View File
@@ -0,0 +1,30 @@
<?php
/**
* BoxBilling
*
* @copyright BoxBilling, Inc (http://www.boxbilling.com)
* @license Apache-2.0
*
* Copyright BoxBilling, Inc
* This source file is subject to the Apache-2.0 License that is bundled
* with this source code in the file LICENSE
*/
class Model_ClientOrder extends RedBean_SimpleModel
{
const STATUS_PENDING_SETUP = "pending_setup";
const STATUS_FAILED_SETUP = "failed_setup";
const STATUS_ACTIVE = "active";
const STATUS_CANCELED = "canceled";
const STATUS_SUSPENDED = "suspended";
const ACTION_CREATE = 'create';
const ACTION_ACTIVATE = 'activate';
const ACTION_RENEW = 'renew';
const ACTION_SUSPEND = 'suspend';
const ACTION_UNSUSPEND = 'unsuspend';
const ACTION_CANCEL = 'cancel';
const ACTION_UNCANCEL = 'uncancel';
const ACTION_DELETE = 'delete';
}
+17
View File
@@ -0,0 +1,17 @@
<?php
/**
* BoxBilling
*
* @copyright BoxBilling, Inc (http://www.boxbilling.com)
* @license Apache-2.0
*
* Copyright BoxBilling, Inc
* This source file is subject to the Apache-2.0 License that is bundled
* with this source code in the file LICENSE
*/
class Model_ClientOrderMeta extends RedBean_SimpleModel
{
}
+17
View File
@@ -0,0 +1,17 @@
<?php
/**
* BoxBilling
*
* @copyright BoxBilling, Inc (http://www.boxbilling.com)
* @license Apache-2.0
*
* Copyright BoxBilling, Inc
* This source file is subject to the Apache-2.0 License that is bundled
* with this source code in the file LICENSE
*/
class Model_ClientOrderStatus extends RedBean_SimpleModel
{
}
+17
View File
@@ -0,0 +1,17 @@
<?php
/**
* BoxBilling
*
* @copyright BoxBilling, Inc (http://www.boxbilling.com)
* @license Apache-2.0
*
* Copyright BoxBilling, Inc
* This source file is subject to the Apache-2.0 License that is bundled
* with this source code in the file LICENSE
*/
class Model_ClientPasswordReset extends RedBean_SimpleModel
{
}
@@ -0,0 +1,62 @@
<?php
/**
* BoxBilling
*
* @copyright BoxBilling, Inc (http://www.boxbilling.com)
* @license Apache-2.0
*
* Copyright BoxBilling, Inc
* This source file is subject to the Apache-2.0 License that is bundled
* with this source code in the file LICENSE
*/
class Model_ClientPasswordResetTable implements \Box\InjectionAwareInterface
{
/**
* @var \Box_Di
*/
protected $di;
/**
* @param Box_Di $di
*/
public function setDi($di)
{
$this->di = $di;
}
/**
* @return Box_Di
*/
public function getDi()
{
return $this->di;
}
public function generate(Model_Client $client, $ip)
{
$r = $this->di['db']->findOne('ClientPasswordReset', 'client_id', $client->id);
if(!$r instanceof Model_ClientPasswordReset) {
$r = $this->di['db']->dispense('ClientPasswordReset');
$r->created_at = date('Y-m-d H:i:s');
$r->client_id = $client->id;
}
$r->ip = $ip;
$r->hash = sha1(rand(50, rand(10, 99)));
$r->updated_at = date('Y-m-d H:i:s');
$this->di['db']->store($r);
return $r;
}
public function rmByClient(Model_Client $client)
{
$models = $this->di['db']->find('ClientPasswordReset', 'client_id = ?', array($client->id));
foreach($models as $model){
$this->di['db']->trash($model);
}
}
}
+17
View File
@@ -0,0 +1,17 @@
<?php
/**
* BoxBilling
*
* @copyright BoxBilling, Inc (http://www.boxbilling.com)
* @license Apache-2.0
*
* Copyright BoxBilling, Inc
* This source file is subject to the Apache-2.0 License that is bundled
* with this source code in the file LICENSE
*/
class Model_Currency extends \RedBean_SimpleModel
{
}
+16
View File
@@ -0,0 +1,16 @@
<?php
/**
* BoxBilling
*
* @copyright BoxBilling, Inc (http://www.boxbilling.com)
* @license Apache-2.0
*
* Copyright BoxBilling, Inc
* This source file is subject to the Apache-2.0 License that is bundled
* with this source code in the file LICENSE
*/
class Model_EmailTemplate extends \RedBean_SimpleModel
{
}
+17
View File
@@ -0,0 +1,17 @@
<?php
/**
* BoxBilling
*
* @copyright BoxBilling, Inc (http://www.boxbilling.com)
* @license Apache-2.0
*
* Copyright BoxBilling, Inc
* This source file is subject to the Apache-2.0 License that is bundled
* with this source code in the file LICENSE
*/
class Model_Extension extends RedBean_SimpleModel
{
}
+17
View File
@@ -0,0 +1,17 @@
<?php
/**
* BoxBilling
*
* @copyright BoxBilling, Inc (http://www.boxbilling.com)
* @license Apache-2.0
*
* Copyright BoxBilling, Inc
* This source file is subject to the Apache-2.0 License that is bundled
* with this source code in the file LICENSE
*/
class Model_ExtensionMeta extends \RedBean_SimpleModel
{
}
+17
View File
@@ -0,0 +1,17 @@
<?php
/**
* BoxBilling
*
* @copyright BoxBilling, Inc (http://www.boxbilling.com)
* @license Apache-2.0
*
* Copyright BoxBilling, Inc
* This source file is subject to the Apache-2.0 License that is bundled
* with this source code in the file LICENSE
*/
class Model_Form extends RedBean_SimpleModel
{
}
+17
View File
@@ -0,0 +1,17 @@
<?php
/**
* BoxBilling
*
* @copyright BoxBilling, Inc (http://www.boxbilling.com)
* @license Apache-2.0
*
* Copyright BoxBilling, Inc
* This source file is subject to the Apache-2.0 License that is bundled
* with this source code in the file LICENSE
*/
class Model_FormField extends RedBean_SimpleModel
{
}
+18
View File
@@ -0,0 +1,18 @@
<?php
/**
* BoxBilling
*
* @copyright BoxBilling, Inc (http://www.boxbilling.com)
* @license Apache-2.0
*
* Copyright BoxBilling, Inc
* This source file is subject to the Apache-2.0 License that is bundled
* with this source code in the file LICENSE
*/
class Model_Forum extends RedBean_SimpleModel
{
const STATUS_ACTIVE = 'active';
const STATUS_LOCKED = 'locked';
}
+163
View File
@@ -0,0 +1,163 @@
<?php
/**
* BoxBilling
*
* @copyright BoxBilling, Inc (http://www.boxbilling.com)
* @license Apache-2.0
*
* Copyright BoxBilling, Inc
* This source file is subject to the Apache-2.0 License that is bundled
* with this source code in the file LICENSE
*/
class Model_ForumTable implements \Box\InjectionAwareInterface
{
/**
* @var \Box_Di
*/
protected $di;
/**
* @param Box_Di $di
*/
public function setDi($di)
{
$this->di = $di;
}
/**
* @return Box_Di
*/
public function getDi()
{
return $this->di;
}
public function getSearchQuery($data)
{
$query = "SELECT * FROM forum ORDER BY priority ASC, category ASC";
$bindingss = array();
return array($query, $bindingss);
}
public function findAll($hydrationMode = null)
{
$query = "SELECT f.*, ft.* FROM forum f
LEFT JOIN forum_topic ft ON ft.forum_id = f.id
ORDER BY f.priority ASC, ft.id DESC";
return $this->di['db']->getAll($query);
}
public function findAllActive()
{
$query = "SELECT f.*, ft.* FROM forum f
LEFT JOIN forum_topic ft ON ft.forum_id = f.id
WHERE f.status IN ('active', 'locked')
ORDER BY f.priority ASC, ft.id DESC";
return $this->di['db']->getAll($query);
}
public function findOneActiveById($id)
{
$bindings = array(
':forum_id' => $id
);
return $this->di['db']->findOne('Forum', "id = :forum_id AND status IN ('active', 'locked')", $bindings);
}
public function findOneActiveBySlug($slug)
{
$bindings = array(
':slug' => $slug
);
return $this->di['db']->findOne('Forum', "slug = :slug AND status IN ('active', 'locked')", $bindings);
}
public function findAllActiveWithTopics()
{
$query = "SELECT f.*, ft.* FROM forum f
LEFT JOIN forum_topic ft ON ft.forum_id = f.id
WHERE f.status IN ('active', 'locked')
ORDER BY f.priority ASC, ft.id DESC";
return $this->di['db']->getAll($query);
}
public function getNextPriority()
{
$query = "SELECT priority FROM forum ORDER BY priority ASC LIMIT 1";
$priority = $this->di['db']->getCell($query);
return $priority + 1;
}
public function moveForum(Model_Forum $forum, $dir = 'up')
{
$current = $forum->priority;
$near = ($dir == 'up') ? $current - 1 : $current + 1;
if ($near == 0) {
return true;
}
$fn = $this->di['db']->findOne('Forum', 'priority = :priority', array(':priority' => $near));
$fn->priority = $current;
$this->di['db']->store($fn);
$forum->priority = $near;
$this->di['db']->store($forum);
return true;
}
public function getViewsCount(Model_Forum $forum)
{
$table = $this->di['table']('ForumTopic');
return $table->getViewsCountForForum($forum);
}
public function getMessagesCount(Model_Forum $forum)
{
$table = $this->di['table']('ForumTopicMessage');
return $table->getMessagesCountForForum($forum);
}
public function getPairs()
{
$query = "SELECT id, title FROM forum ORDER BY priority ASC";
return $this->di['db']->getAssoc($query);
}
public function rm(Model_Forum $forum)
{
$table = $this->di['table']('ForumTopic');
$forumTopic = $this->di['db']->find('ForumTopic', 'forum_id = :forum_id', array(':forum_id' => $forum->id));
foreach ($forumTopic as $topic) {
$table->rm($topic);
}
$this->di['db']->trash($forum);
}
public function toApiArray(\Model_Forum $forum, $deep = false, $identity = null)
{
$data = $this->di['db']->toArray($forum);
$forumTopic = $this->di['db']->find('ForumTopic', 'forum_id = :forum_id', array(':forum_id' => $forum->id));
$data['stats']['topics_count'] = count($forumTopic);
$data['stats']['posts_count'] = $this->getMessagesCount($forum);
$data['stats']['views_count'] = $this->getViewsCount($forum);
return $data;
}
}
+18
View File
@@ -0,0 +1,18 @@
<?php
/**
* BoxBilling
*
* @copyright BoxBilling, Inc (http://www.boxbilling.com)
* @license Apache-2.0
*
* Copyright BoxBilling, Inc
* This source file is subject to the Apache-2.0 License that is bundled
* with this source code in the file LICENSE
*/
class Model_ForumTopic extends RedBean_SimpleModel
{
const STATUS_ACTIVE = 'active';
const STATUS_LOCKED = 'locked';
}
+17
View File
@@ -0,0 +1,17 @@
<?php
/**
* BoxBilling
*
* @copyright BoxBilling, Inc (http://www.boxbilling.com)
* @license Apache-2.0
*
* Copyright BoxBilling, Inc
* This source file is subject to the Apache-2.0 License that is bundled
* with this source code in the file LICENSE
*/
class Model_ForumTopicMessage extends RedBean_SimpleModel
{
}
+279
View File
@@ -0,0 +1,279 @@
<?php
/**
* BoxBilling
*
* @copyright BoxBilling, Inc (http://www.boxbilling.com)
* @license Apache-2.0
*
* Copyright BoxBilling, Inc
* This source file is subject to the Apache-2.0 License that is bundled
* with this source code in the file LICENSE
*/
/**
* Model_ForumTopicMessageTable
*
*/
class Model_ForumTopicMessageTable implements \Box\InjectionAwareInterface
{
protected $di;
public function setDi($di)
{
$this->di = $di;
}
public function getDi()
{
return $this->di;
}
public function getSearchQuery($data)
{
$query = "SELECT ftm.*
FROM forum_topic_message ftm
LEFT JOIN forum_topic ft ON ft.id = ftm.forum_topic_id
LEFT JOIN forum f ON f.id = ft.forum_id
LEFT JOIN admin a ON a.id = ftm.admin_id
LEFT JOIN client c ON c.id = ftm.client_id";
$search = (isset($data['q']) && !empty($data['q'])) ? $data['q'] : NULL;
$search2 = (isset($data['search']) && !empty($data['search'])) ? $data['search'] : NULL;
$forum_topic_id = (isset($data['forum_topic_id']) && !empty($data['forum_topic_id'])) ? $data['forum_topic_id'] : NULL;
$forum_id = $this->di['array_get']($data, 'forum_id', NULL);
$client_id = $this->di['array_get']($data, 'client_id', NULL);
$where = $bindings = array();
if ($forum_topic_id) {
$where[] = "ftm.forum_topic_id = :forum_topic_id";
$bindings[':forum_topic_id'] = $forum_topic_id;
}
if ($forum_id) {
$where[] = "ft.forum_id = :forum_id";
$bindings[':forum_id'] = $forum_id;
}
if ($client_id) {
$where[] = "ftm.client_id = :client_id";
$bindings[':client_id'] = $client_id;
}
if ($search) {
$where[] = "ftm.message LIKE :message";
$bindings[':message'] = "%$search%";
}
if ($search2) {
$where[] = "ftm.message LIKE :message2";
$bindings[':message2'] = "%$search%";
}
if (!empty($where)) {
$query = $query . ' WHERE ' . implode(' AND ', $where);
}
if (isset($data['orderby'])) {
if (in_array(strtolower($data['orderby']), array('id', 'created_at'))) {
$sortorder = (isset($data['sortorder']) && in_array(strtolower($data['sortorder']), array('asc', 'desc'))) ? $data['sortorder'] : 'asc';
$query .= " ORDER BY ftm." . $data['orderby'] . " " . strtoupper($sortorder);
}
} else {
$query .= " ORDER BY ftm.id ASC";
}
return array($query, $bindings);
}
public function search(array $filter = null)
{
if (!isset($filter['q'])) {
return array();
}
$searchQuery = $filter['q'];
$query = "SELECT ftm.*, ft.id, ft.slug, f.id, f.slug
FROM forum_topic_message ftm
LEFT JOIN client c ON c.id = ftm.client_id
LEFT JOIN forum_topic ft ON ft.id = ftm.forum_topic_id
LEFT JOIN forum f ON f.id = ft.forum_id
WHERE ft.status IN ('active', 'locked')";
$where = $bindings = array();
if (isset($filter['match_date']) && $filter['match_date'] !== "0") {
$seconds = (int)$filter['match_date'] * 24 * 60 * 60;
$where[] = "(UNIX_TIMESTAMP() - ftm.created_at) < :created_at";
$bindings[':created_at'] = $seconds;
}
$where[] = "ftm.message LIKE :message";
$bindings[':message'] = "%$searchQuery%";
if (!empty($where)) {
$query = $query . ' WHERE ' . implode(' AND ', $where);
}
$query .= " ORDER BY ftm.id DESC";
return $this->di['db']->getAssoc($query, $bindings);
}
public function searchForum(Model_Forum $forum, array $filter = null)
{
if (!isset($filter['q'])) {
return array();
}
$searchQuery = $filter['q'];
$query = "SELECT ftm.*, ft.id, ft.slug
FROM forum_topic_message ftm
LEFT JOIN client c ON c.id = ftm.client_id
LEFT JOIN forum_topic ft ON ft.id = ftm.forum_topic_id
WHERE ft.status IN ('active', 'locked')
AND ft.forum_id = :forum_id";
$where = $bindings = array();
$bindings[':forum_id'] = $forum->id;
if (isset($filter['match_date']) && $filter['match_date'] !== "0") {
$seconds = (int)$filter['match_date'] * 24 * 60 * 60;
$where[] = "(UNIX_TIMESTAMP() - ftm.created_at) < :created_at";
$bindings[':created_at'] = $seconds;
}
$where[] = "ftm.message LIKE :message";
$bindings[':message'] = "%$searchQuery%";
if (!empty($where)) {
$query = $query . ' WHERE ' . implode(' AND ', $where);
}
$query .= " ORDER BY ftm.id DESC";
return $this->di['db']->getAssoc($query, $bindings);
}
public function findTopicMessages(Model_ForumTopic $topic)
{
$query = "SELECT ftm.*, ft.id, ft.slug
FROM forum_topic_message ftm
LEFT JOIN client c ON c.id = ftm.client_id
WHERE ftm.forum_topic_id = :forum_topic_id
ORDER BY ftm.id ASC";
$bindings = array(
':forum_topic_id' => $topic->id
);
return $this->di['db']->getAssoc($query, $bindings);
}
public function getMessagesCountForTopic(Model_ForumTopic $topic)
{
$query = 'SELECT COUNT(id) as posts
FROM forum_topic_message
WHERE forum_topic_id = :forum_topic_id
GROUP BY forum_topic_id';
$bindings = array(
':forum_topic_id' => $topic->id
);
return $this->di['db']->getCell($query, $bindings);
}
public function getMessagesCountForForum(Model_Forum $forum)
{
$query = 'SELECT COUNT(ftm.id) as posts
FROM forum_topic_message ftm
LEFT JOIN forum_topic ft ON ftm.forum_topic_id = ft.id
WHERE ft.forum_id = :forum_id
GROUP BY ft.forum_id';
$bindings = array(
':forum_id' => $forum->id
);
return $this->di['db']->getCell($query, $bindings);
}
public function getAuthorDetails(Model_ForumTopicMessage $model)
{
$author = false;
if ($model->admin_id) {
$author = $this->di['db']->getExistingModelById('Admin', $model->admin_id, 'Admin not found');
}
if ($model->client_id) {
$author = $this->di['db']->getExistingModelById('Client', $model->client_id, 'Client not found');
}
if ($author) {
return array(
'id' => $author->id,
'name' => $author->getFullName(),
'email' => $author->email,
);
}
return array(
'id' => null,
'name' => 'Anonymous',
'email' => 'anonymous@anonymous.com',
);
}
/**
* Do not remove client messages but mark them as null
* @param Model_Client $client
*/
public function rmByClient(Model_Client $client)
{
$query = "UPDATE forum_topic_message
SET client_id = NULL
WHERE client_id = :client_id";
$bindings = array(
':client_id' => $client->id
);
$this->di['db']->exec($query, $bindings);
}
public function rm(Model_ForumTopicMessage $model)
{
$messages = $this->di['db']->find('ForumTopicMessage', 'forum_topic_id = :forum_topic_id', array(':forum_topic_id' => $model->forum_topic_id));
if (count($messages) == 1) {
throw new \Box_Exception('This is a last message in topic. Remove topic in order to remove this message.');
}
$this->di['db']->trash($model);
}
public function toApiArray(Model_ForumTopicMessage $model, $deep = false, $identity = null)
{
$topic = $this->di['db']->load('ForumTopic', $model->forum_topic_id);
$forum = $this->di['db']->load('Forum', $topic->forum_id);
$data = array(
'id' => $model->id,
'forum_topic_id' => $model->forum_topic_id,
'message' => $model->message,
'created_at' => $model->created_at,
'updated_at' => $model->updated_at,
'author' => $this->getAuthorDetails($model),
);
$data['forum_slug'] = ($forum) ? $forum->slug : null;
$data['forum_topic_slug'] = ($topic) ? $topic->slug : null;
if ($identity instanceof Model_Admin) {
$data['ip'] = $model->ip;
}
return $data;
}
}
+218
View File
@@ -0,0 +1,218 @@
<?php
/**
* BoxBilling
*
* @copyright BoxBilling, Inc (http://www.boxbilling.com)
* @license Apache-2.0
*
* Copyright BoxBilling, Inc
* This source file is subject to the Apache-2.0 License that is bundled
* with this source code in the file LICENSE
*/
/**
* Model_ForumTopicTable
*
*/
class Model_ForumTopicTable implements \Box\InjectionAwareInterface
{
protected $di;
public function setDi($di)
{
$this->di = $di;
}
public function getDi()
{
return $this->di;
}
public function getActiveForumTopics(Model_Forum $forum)
{
$query = "SELECT * FROM forum_topic ft
LEFT JOIN forum_topic_message ftm ON ftm.forum_topic_id = ft.id
WHERE ft.forum_id = :forum_id
AND ft.status IN ('active', 'locked')
ORDER BY ftm.created_at DESC";
$bindings = array(
':forum_id' => $forum->id
);
return $this->di['db']->exec($query, $bindings);
}
public function getSearchQuery($data)
{
$query = "SELECT ft.* FROM forum_topic ft
LEFT JOIN forum_topic_message ftm ON ftm.forum_topic_id = ft.id";
$search = isset($data['search']) ? $data['search'] : NULL;
$where = $bindings = array();
if (isset($data['forum_id']) && !empty($data['forum_id'])) {
$where[] = "ft.forum_id = :forum_id";
$bindings[':forum_id'] = $data['forum_id'];
}
if ($search) {
$where[] = "ft.title LIKE :title OR ftm.message LIKE :message";
$bindings[':title'] = "%$search%";
$bindings[':message'] = "%$search%";
}
if (!empty($where)) {
$query = $query . ' WHERE ' . implode(' AND ', $where);
}
$query .= " GROUP BY ft.id ORDER BY ft.sticky DESC, ftm.id DESC";
return array($query, $bindings);
}
public function getTopicsByIds(array $ids)
{
if(empty($ids)) {
return array();
}
$bindings = array(
':ids' => implode(',', $ids)
);
return $this->di['db']->find('ForumTopic', "id IN (:ids) AND status IN ('active', 'locked')", $bindings);
}
public function findTopic($slug)
{
$query = "SELECT ft.*, f.* FROM forum_topic ft
LEFT JOIN forum f ON ft.forum_id = f.id
WHERE ft.slug = :slug
AND ft.status IN ('active', 'locked')";
$bindings = array(
':slug' => $slug
);
return $this->di['db']->getAssoc($query, $bindings);
}
public function findForumTopic($forum, $topic)
{
$query = "SELECT ft.*, f.*, ftm.*
FROM forum_topic ft
LEFT JOIN forum f ON ft.forum_id = f.id
LEFT JOIN forum_topic_message ftm ON ftm.forum_topic_id = ft.id
WHERE ft.slug = :topic
AND f.slug = :forum";
$bindings = array(
':topic' => $topic,
':forum' => $forum
);
return $this->di['db']->getAssoc($query, $bindings);
}
public function getViewsCountForForum(Model_Forum $forum)
{
$query = "SELECT SUM(views) as views
FROM forum_topic
WHERE forum_id = :forum_id
GROUP BY id
";
$bindings = array(
':forum_id' => $forum->id
);
return $this->di['db']->getCell($query, $bindings);
}
public function hitView(Model_ForumTopic $topic)
{
$topic->views = $topic->views + 1;
$this->di['db']->store($topic);
}
public function getAuthorClient(Model_ForumTopic $topic)
{
$bindings = array(
':forum_topic_id' => $topic->id
);
$forumTopicMessage = $this->di['db']->findOne('ForumTopicMessage', 'forum_topic_id = :forum_topic_id ORDER BY id ASC LIMIT 1', $bindings);
if($forumTopicMessage instanceof Model_ForumTopicMessage) {
return $this->di['db']->getExistingModelById('Client', $forumTopicMessage->client_id, 'Client not found');
}
return null;
}
public function getParticipants(Model_ForumTopic $topic)
{
$q="SELECT DISTINCT(client_id) as id FROM `forum_topic_message`
WHERE forum_topic_id = :id
AND client_id IS NOT NULL";
$pdo = $this->di['pdo'];
$stmt = $pdo->prepare($q);
$stmt->execute(array('id'=>$topic->id));
return $stmt->fetchAll(PDO::FETCH_COLUMN);
}
public function rm(Model_ForumTopic $topic)
{
$bindings = array(
':forum_topic_id' => $topic->id
);
$forumTopicMessage = $this->di['db']->find('ForumTopicMessage', 'forum_topic_id = :forum_topic_id', $bindings);
foreach ($forumTopicMessage as $msg) {
$this->di['db']->trash($msg);
}
$this->di['db']->trash($topic);
}
public function toApiArray(Model_ForumTopic $topic, $deep = false, $identity = null)
{
$table = $this->di['table']('ForumTopicMessage');
$bindings = array(
':forum_topic_id' => $topic->id
);
$forum = $this->di['db']->getExistingModelById('Forum', $topic->forum_id);;
$first = $this->di['db']->findOne('ForumTopicMessage', 'forum_topic_id = :forum_topic_id ORDER BY id ASC LIMIT 1', $bindings);;
$last = $this->di['db']->findOne('ForumTopicMessage', 'forum_topic_id = :forum_topic_id ORDER BY id DESC LIMIT 1', $bindings);;
$data = array(
'id' => $topic->id,
'title' => $topic->title,
'slug' => $topic->slug,
'status' => $topic->status,
'sticky' => $topic->sticky,
'created_at' => $topic->created_at,
'updated_at' => $topic->updated_at,
);
$data['forum'] = array(
'id' => $forum->id,
'slug' => $forum->slug,
'title' => $forum->title,
'category' => $forum->category,
);
if($first instanceof Model_ForumTopicMessage) {
$data['first'] = $table->toApiArray($first, $deep, $identity);
}
if($last instanceof Model_ForumTopicMessage) {
$data['last'] = $table->toApiArray($last, $deep, $identity);
}
$data['stats']['posts_count'] = $table->getMessagesCountForTopic($topic);
$data['stats']['views_count'] = $topic->views;
return $data;
}
}
+16
View File
@@ -0,0 +1,16 @@
<?php
/**
* BoxBilling
*
* @copyright BoxBilling, Inc (http://www.boxbilling.com)
* @license Apache-2.0
*
* Copyright BoxBilling, Inc
* This source file is subject to the Apache-2.0 License that is bundled
* with this source code in the file LICENSE
*/
class Model_Guest
{
}
+20
View File
@@ -0,0 +1,20 @@
<?php
/**
* BoxBilling
*
* @copyright BoxBilling, Inc (http://www.boxbilling.com)
* @license Apache-2.0
*
* Copyright BoxBilling, Inc
* This source file is subject to the Apache-2.0 License that is bundled
* with this source code in the file LICENSE
*/
class Model_Invoice extends RedBean_SimpleModel
{
const STATUS_PAID = 'paid';
const STATUS_UNPAID = 'unpaid';
const STATUS_REFUNDED = 'refunded';
const STATUS_CANCELED = 'canceled';
}
+27
View File
@@ -0,0 +1,27 @@
<?php
/**
* BoxBilling
*
* @copyright BoxBilling, Inc (http://www.boxbilling.com)
* @license Apache-2.0
*
* Copyright BoxBilling, Inc
* This source file is subject to the Apache-2.0 License that is bundled
* with this source code in the file LICENSE
*/
class Model_InvoiceItem extends RedBean_SimpleModel
{
const TYPE_DEPOSIT = 'deposit'; // this type of item can not be charged with credits
const TYPE_CUSTOM = 'custom';
const TYPE_ORDER = 'order';
const TYPE_HOOK_CALL= 'hook_call';
const TASK_VOID = 'void';
const TASK_ACTIVATE = 'activate';
const TASK_RENEW = 'renew';
const STATUS_PENDING_PAYMENT = 'pending_payment';
const STATUS_PENDING_SETUP = 'pending_setup';
const STATUS_EXECUTED = 'executed';
}
+17
View File
@@ -0,0 +1,17 @@
<?php
/**
* BoxBilling
*
* @copyright BoxBilling, Inc (http://www.boxbilling.com)
* @license Apache-2.0
*
* Copyright BoxBilling, Inc
* This source file is subject to the Apache-2.0 License that is bundled
* with this source code in the file LICENSE
*/
class Model_KbArticle extends \RedBean_SimpleModel
{
const ACTIVE = 'active';
const DRAFT = 'draft';
}
+16
View File
@@ -0,0 +1,16 @@
<?php
/**
* BoxBilling
*
* @copyright BoxBilling, Inc (http://www.boxbilling.com)
* @license Apache-2.0
*
* Copyright BoxBilling, Inc
* This source file is subject to the Apache-2.0 License that is bundled
* with this source code in the file LICENSE
*/
class Model_KbArticleCategory extends \RedBean_SimpleModel
{
}
+20
View File
@@ -0,0 +1,20 @@
<?php
/**
* BoxBilling
*
* @copyright BoxBilling, Inc (http://www.boxbilling.com)
* @license Apache-2.0
*
* Copyright BoxBilling, Inc
* This source file is subject to the Apache-2.0 License that is bundled
* with this source code in the file LICENSE
*/
/**
* Class Model_ModEmailQueue
*/
class Model_ModEmailQueue extends \RedBean_SimpleModel
{
}
+17
View File
@@ -0,0 +1,17 @@
<?php
/**
* BoxBilling
*
* @copyright BoxBilling, Inc (http://www.boxbilling.com)
* @license Apache-2.0
*
* Copyright BoxBilling, Inc
* This source file is subject to the Apache-2.0 License that is bundled
* with this source code in the file LICENSE
*/
class Model_PayGateway extends RedBean_SimpleModel
{
}
+17
View File
@@ -0,0 +1,17 @@
<?php
/**
* BoxBilling
*
* @copyright BoxBilling, Inc (http://www.boxbilling.com)
* @license Apache-2.0
*
* Copyright BoxBilling, Inc
* This source file is subject to the Apache-2.0 License that is bundled
* with this source code in the file LICENSE
*/
class Model_Post extends \RedBean_SimpleModel
{
}
+65
View File
@@ -0,0 +1,65 @@
<?php
/**
* BoxBilling
*
* @copyright BoxBilling, Inc (http://www.boxbilling.com)
* @license Apache-2.0
*
* Copyright BoxBilling, Inc
* This source file is subject to the Apache-2.0 License that is bundled
* with this source code in the file LICENSE
*/
class Model_Product extends \RedBean_SimpleModel implements \Box\InjectionAwareInterface
{
const STATUS_ENABLED = 'enabled';
const STATUS_DISABLED = 'disabled';
const CUSTOM = 'custom';
const LICENSE = 'license';
const ADDON = 'addon';
const DOMAIN = 'domain';
const DOWNLOADABLE = 'downloadable';
const HOSTING = 'hosting';
const MEMBERSHIP = 'membership';
const VPS = 'vps';
const SETUP_AFTER_ORDER = 'after_order';
const SETUP_AFTER_PAYMENT = 'after_payment';
const SETUP_MANUAL = 'manual';
protected $di;
/**
* @param mixed $di
*/
public function setDi($di)
{
$this->di = $di;
}
/**
* @return mixed
*/
public function getDi()
{
return $this->di;
}
public function getTable()
{
$tableName = 'Model_Product'. ucfirst($this->type). 'Table';
if(!class_exists($tableName)) {
$tableName = 'Model_ProductTable';
}
$productTable = new $tableName;
$productTable->setDi($this->di);
return $productTable;
}
public function getService()
{
return $this->di['mod_service']('service'.$this->type);
}
}
+16
View File
@@ -0,0 +1,16 @@
<?php
/**
* BoxBilling
*
* @copyright BoxBilling, Inc (http://www.boxbilling.com)
* @license Apache-2.0
*
* Copyright BoxBilling, Inc
* This source file is subject to the Apache-2.0 License that is bundled
* with this source code in the file LICENSE
*/
class Model_ProductCategory extends RedBean_SimpleModel
{
}
+17
View File
@@ -0,0 +1,17 @@
<?php
/**
* BoxBilling
*
* @copyright BoxBilling, Inc (http://www.boxbilling.com)
* @license Apache-2.0
*
* Copyright BoxBilling, Inc
* This source file is subject to the Apache-2.0 License that is bundled
* with this source code in the file LICENSE
*/
class Model_ProductCustom extends \RedBean_SimpleModel
{
}
+17
View File
@@ -0,0 +1,17 @@
<?php
/**
* BoxBilling
*
* @copyright BoxBilling, Inc (http://www.boxbilling.com)
* @license Apache-2.0
*
* Copyright BoxBilling, Inc
* This source file is subject to the Apache-2.0 License that is bundled
* with this source code in the file LICENSE
*/
class Model_ProductDomain extends Model_Product
{
}
Loaded 100 of 9692 files, more files were not shown because too many files have changed in this diff. Show more