This repository has been archived on 2024-04-08. You can view files and clone it, but cannot push or open issues or pull requests.
khosb/modules/account/account.inc.php
2011-05-03 09:49:01 +10:00

2045 lines
57 KiB
PHP

<?php
/**
* AgileBill - Open Billing Software
*
* This body of work is free software; you can redistribute it and/or
* modify it under the terms of the Open AgileBill License
* License as published at http://www.agileco.com/agilebill/license1-4.txt
*
* Originally authored by Tony Landis, AgileBill LLC
*
* Recent modifications by Deon George
*
* @author Deon George <deonATleenooksDOTnet>
* @copyright 2009 Deon George
* @link http://osb.leenooks.net
*
* @link http://www.agileco.com/
* @copyright 2004-2008 Agileco, LLC.
* @license http://www.agileco.com/agilebill/license1-4.txt
* @author Tony Landis <tony@agileco.com>
* @package AgileBill
* @subpackage Modules:Account
*/
/**
* The main AgileBill Account Class
*
* @package AgileBill
* @subpackage Modules:Account
*/
class account extends OSB_module {
private $parent_id;
# Has account passed validation
public $validated = true;
/** SUB ACCOUNTS **/
/**
* Add sub account
*/
public function user_sub_account_add($VAR) {
global $C_debug;
if (! SESS_LOGGED)
return false;
$this->parent_id = SESS_ACCOUNT;
if ($this->add($VAR,$this)) {
# Add any additional groups
if (! empty($VAR['groups']) && is_array($VAR['groups']))
$this->add_account_groups($VAR['groups'],$this->account_id,false);
define('FORCE_PAGE','account:account');
$C_debug->alert('The sub-account has been added');
}
}
/**
* Delete sub account
*
* @uses account_admin
*/
public function user_sub_delete($VAR) {
# Verify perms
if (empty($VAR['id']) || !$this->isParentAccount($VAR['id']))
return false;
# OK, do deletion
include_once(PATH_MODULES.'account_admin/account_admin.inc.php');
$aa = new account_admin;
$VAR['account_admin_id'] = $VAR['id'];
$aa->delete($VAR);
}
/**
* Check if sub account auth
*/
private function isParentAccount($sub_account_id) {
$db = &DB();
$rs = $db->Execute(sqlSelect($db,'account','parent_id',
sprintf("id=%s AND parent_id != 0 AND parent_id IS NOT NULL AND parent_id != '' AND parent_id = %s",$sub_account_id,SESS_ACCOUNT)));
if ($rs && $rs->RecordCount())
return true;
else
return false;
}
/** SMARTY METHODS **/
/**
* Get authorized groups
*/
public function user_get_auth_groups($VAR) {
global $smarty,$C_auth;
$db = &DB();
$groups = array();
# Get groups for this account
$authgrp = array();
if (! empty($VAR['id'])) {
$grs = $db->Execute(sqlSelect($db,'account_group','group_id',sprintf('group_id>2 AND active=1 AND account_id=%s',$VAR['id'])));
if ($grs && $grs->RecordCount()) {
while (! $grs->EOF) {
$authgrp[$grs->fields['group_id']] = true;
$grs->MoveNext();
}
}
}
$rs = $db->Execute(sqlSelect($db,'group','id,name',sprintf('id IN (%s) AND id > 2',implode(',',$C_auth->group))));
if ($rs && $rs->RecordCount()) {
while (! $rs->EOF) {
$gid = $rs->fields['id'];
if ((! empty($VAR['groups']) && is_array($VAR['groups']) && ! empty($VAR['groups'][$gid])) || (! empty($authgrp[$gid])))
$rs->fields['checked'] = true;
array_push($groups,$rs->fields);
$rs->MoveNext();
}
}
$smarty->assign('groups',$groups);
}
/** ACCOUNT MANAGEMENT **/
/**
* Add new accounts
*
* @uses blocked_email
* @uses blocked_ip
* @uses account_password_history
* @uses email_template
* @uses newsletter
* @uses CORE_auth
* @uses affiliate
*/
public function user_add($VAR) {
global $C_list,$C_translate,$C_debug,$smarty;
# Set the hidden values
$VAR[$this->module.'_date_orig'] = time();
$VAR[$this->module.'_date_last'] = time();
if (defined('SESS_LANGUAGE'))
$VAR[$this->module.'_language_id'] = SESS_LANGUAGE;
else
$VAR[$this->module.'_language_id'] = DEFAULT_LANGUAGE;
if (defined('SESS_AFFILIATE'))
$VAR[$this->module.'_affiliate_id']= SESS_AFFILIATE;
else
$VAR[$this->module.'_affiliate_id']= DEFAULT_AFFILIATE;
if (defined('SESS_RESELLER'))
$VAR[$this->module.'_reseller_id'] = SESS_RESELLER;
else
$VAR[$this->module.'_reseller_id'] = DEFAULT_RESELLER;
if (defined('SESS_CURRENCY'))
$VAR[$this->module.'_currency_id'] = SESS_CURRENCY;
else
$VAR[$this->module.'_currency_id'] = DEFAULT_CURRENCY;
if (defined('SESS_THEME'))
$VAR[$this->module.'_theme_id'] = SESS_THEME;
else
$VAR[$this->module.'_theme_id'] = DEFAULT_THEME;
if (defined('SESS_CAMPAIGN'))
$VAR[$this->module.'_campaign_id'] = SESS_CAMPAIGN;
else
$VAR[$this->module.'_campaign_id'] = 0;
if (! isset($VAR[$this->module.'_email_type']))
$VAR[$this->module.'_email_type'] = '0';
# Determine the proper account status
if (! isset($VAR[$this->module.'_status']))
if (defined('DEFAULT_ACCOUNT_STATUS'))
# This constant is negative, ie: when 1 it requires validation
$VAR[$this->module.'_status'] = ! DEFAULT_ACCOUNT_STATUS;
else
$VAR[$this->module.'_status'] = 0;
$VAR[$this->module.'_tax_id'] = $this->validate_tax($VAR);
# Get default invoice options
$db = &DB();
$invopt = $db->Execute(sqlSelect($db,'setup_invoice','*',''));
if ($invopt && $invopt->RecordCount()) {
$VAR[$this->module.'_invoice_delivery'] = $invopt->fields['invoice_delivery'];
$VAR[$this->module.'_invoice_show_itemized'] = $invopt->fields['invoice_show_itemized'];
} else {
$VAR[$this->module.'_invoice_delivery'] = 0;
$VAR[$this->module.'_invoice_show_itemized'] = 0;
}
$VAR[$this->module.'_invoice_grace'] = GRACE_PERIOD;
# If we are called by a child object, then can skip this part
if (get_class($this) == 'account') {
# Validate the password
if (isset($VAR['account_password']) && $VAR['account_password'] != '') {
if (isset($VAR['confirm_password']) && $VAR['account_password'] == $VAR['confirm_password']) {
$password = $VAR['account_password'];
$smarty->assign('confirm_account_password',$VAR['account_password']);
} else {
# ERROR: The passwords provided do not match!
$smarty->assign('confirm_account_password','');
$this->validated = false;
array_push($this->val_error,array(
'field'=>sprintf('%s_%s',$this->module,'_confirm_password'),
'field_trans'=>$C_translate->translate('field_confirm_password',$this->module,''),
'error'=>$C_translate->translate('password_change_match',$this->module,'')
));
}
} else {
$smarty->assign('confirm_account_password','');
}
# Validate that the user's IP & E-mail are not banned!
if ($this->validated) {
if ($C_list->is_installed('blocked_email')) {
require_once(PATH_MODULES.'blocked_email/blocked_email.inc.php');
$blocked_email = new blocked_email;
if ($blocked_email->is_blocked($VAR['account_email']))
array_push($this->val_error,array(
'field'=>sprintf('%s_%s',$this->module,'email'),
'field_trans'=>$C_translate->translate('field_email',$this->module,''),
'error'=>$C_translate->translate('validate_banned_email','','')
));
}
if ($C_list->is_installed('blocked_ip')) {
require_once(PATH_MODULES.'blocked_ip/blocked_ip.inc.php');
$blocked_ip = new blocked_ip;
if ($blocked_ip->is_blocked(USER_IP))
array_push($this->val_error,array(
'field'=>'IP Address',
'field_trans'=>$C_translate->translate('ip_address',$this->module,''),
'error'=>$C_translate->translate('validate_banned_ip','','')
));
}
}
# Dont set the redirect
$VAR['_noredirect'] = true;
}
# Add the record
if (! $this->account_id = parent::user_add($VAR))
return;
# Password logging class
if ($C_list->is_installed('account_password_history')) {
include_once(PATH_MODULES.'account_password_history/account_password_history.inc.php');
$accountHistory = new account_password_history();
$accountHistory->setNewPassword($this->account_id,$VAR[$this->module.'_password']);
}
# OK, if we are called by a child, we can return here
if (get_class($this) != 'account')
return $this->account_id;
# Add the account to the default group
$this->add_account_groups(array(),$this->account_id,false);
# Mail the user the new_account email template
if ($C_list->is_installed('email_template')) {
require_once(PATH_MODULES.'email_template/email_template.inc.php');
$my = new email_template;
if ($VAR['account_status'] == '1')
$my->send('account_registration_active',$this->account_id,$this->account_id,'','');
else
$my->send('account_registration_inactive',$this->account_id,'','',$this->validation_str($this->account_id));
}
# Add the newsletters
if (NEWSLETTER_REGISTRATION == '1') {
$VAR['newsletter_html'] = $VAR['account_email_type'];
$VAR['newsletter_email'] = $VAR['account_email'];
$VAR['newsletter_first_name'] = $VAR['account_first_name'];
$VAR['newsletter_last_name'] = $VAR['account_last_name'];
require_once(PATH_MODULES.'newsletter/newsletter.inc.php');
$newsletter = new newsletter;
$newsletter->subscribe($VAR,$this);
}
# Log in the user & display the welcome message
if ($VAR['account_status'] == '1') {
if ($this->parent_id == $this->account_id || empty($this->parent_id)) {
$C_debug->alert($C_translate->translate('user_add_active_welcome',$this->module,''));
if (SESSION_EXPIRE == 0)
$exp = 99999;
else
$exp = SESSION_EXPIRE;
$date_expire = (time()+(SESSION_EXPIRE*60));
# Update the session
$db = &DB();
$result = $db->Execute(
sqlUpdate($db,'session',array('ip'=>USER_IP,'date_expire'=>$date_expire,'logged'=>1,'account_id'=>$this->account_id),sprintf('id=::%s::',SESS)));
# Constants
define('FORCE_SESS_ACCOUNT',$this->account_id);
define('FORCE_SESS_LOGGED',1);
# Reload the session auth cache
if (CACHE_SESSIONS == '1') {
$force = true;
$C_auth = new CORE_auth($force);
global $C_auth2;
$C_auth2 = $C_auth;
}
if (isset($VAR['_page_next']))
define('REDIRECT_PAGE','?_page='.$VAR['_page_next']);
elseif (isset($VAR['_page']))
define('REDIRECT_PAGE','?_page='.$VAR['_page']);
}
# Affiliate Auto Creation
if (AUTO_AFFILIATE == 1 && $C_list->is_installed('affiliate')) {
$VAR['affiliate_account_id'] = $this->account_id;
$VAR['affiliate_template_id'] = DEFAULT_AFFILIATE_TEMPLATE;
include_once(PATH_MODULES.'affiliate/affiliate.inc.php');
$affiliate = new affiliate;
$affiliate->add($VAR,$affiliate);
}
} else {
$C_debug->alert($C_translate->translate('user_add_inactive_welcome',$this->module,''));
define('FORCE_PAGE','core:blank');
}
}
/**
* View Account Information
*/
public function user_view($VAR) {
# Check that user is logged in
if (SESS_LOGGED != '1') {
echo 'Sorry, you must be logged in!';
return false;
}
# If we are called from a child class, just return the results from the parent
if (get_class($this) != 'account')
return parent::view($VAR);
# Check for sub account
if (! empty($VAR['id']) && $VAR['id'] != SESS_ACCOUNT) {
if ($this->isParentAccount($VAR['id'])) {
global $smarty;
$VAR['account_id'] = $VAR['id'];
$smarty->assign('issubaccount',true);
} else {
return false;
}
} else {
$VAR['id'] = SESS_ACCOUNT;
$VAR['account_id'] = SESS_ACCOUNT;
}
# Retrieve the record
$smart = parent::view($VAR);
# Get child accounts
$child = array();
if (empty($smart['parent_id']) || $smart['parent_id']==$smart['id']) {
$db = &DB();
$rs = $db->Execute(sqlSelect($db,'account','id,first_name,last_name,email,username',sprintf('parent_id=%s',SESS_ACCOUNT)));
if ($rs && $rs->RecordCount()) {
while (! $rs->EOF) {
array_push($child,$rs->fields);
$rs->MoveNext();
}
global $smarty;
$smarty->assign('subaccount',$child);
}
}
return $smart;
}
/**
* Update an account record
*
* @uses account_password_history
* @uses CORE_static_var
*/
public function user_update($VAR) {
global $VAR;
# Check that user is logged in
if (SESS_LOGGED != '1') {
echo 'Sorry, you must be logged in!';
return false;
}
# Some special processing for account object
if (get_class($this) == 'account') {
# Check for sub account
$issubaccount = false;
if (! empty($VAR['account_id']) && $VAR['account_id'] != SESS_ACCOUNT) {
if ($this->isParentAccount($VAR['account_id'])) {
global $smarty;
$VAR['id'] = $VAR['account_id'];
$issubaccount = true;
} else {
return false;
}
} else {
$VAR['id'] = SESS_ACCOUNT;
$VAR['account_id'] = SESS_ACCOUNT;
}
# Change password
$password_changed = false;
if (isset($VAR['account_password']) && $VAR['account_password'] != '') {
if (isset($VAR['confirm_password']) && $VAR['account_password'] == $VAR['confirm_password']) {
# Alert: the password has been changed!
global $C_debug,$C_translate;
$C_debug->alert($C_translate->translate('password_changed',$this->module,''));
$password_changed = true;
# Check if new password is ok
global $C_list;
if ($C_list->is_installed('account_password_history')) {
include_once(PATH_MODULES.'account_password_history/account_password_history.inc.php');
$accountHistory = new account_password_history();
if (! $accountHistory->getIsPasswordOk(SESS_ACCOUNT,$VAR['account_password'],false)) {
$C_debug->alert('The password you have selected has been used recently and cannot be used again at this time for security purposes.');
unset($VAR['account_password']);
$password_changed=false;
}
}
} else {
# ERROR: The passwords provided do not match!
global $C_debug,$C_translate;
$C_debug->alert($C_translate->translate('password_change_match',$this->module,''));
unset($VAR['account_password']);
}
} else {
unset($VAR['account_password']);
}
}
$VAR[$this->module.'_date_last'] = time();
# Get required static_Vars and validate them... return an array w/ ALL errors
require_once(PATH_CORE.'static_var.inc.php');
$static_var = new CORE_static_var;
$all_error = $static_var->validate_form($this->module,$this->val_error);
if (! $this->validated || ($all_error != false && gettype($all_error) == 'array'))
$this->validated = false;
else
$this->validated = true;
/**
* If validation was failed, skip the db insert &
* set the errors & origonal fields as Smarty objects,
* and change the page to be loaded.*/
if (! $this->validated) {
global $smarty;
# set the errors as a Smarty Object
$smarty->assign('form_validation',$all_error);
# set the page to be loaded
if (! defined('FORCE_PAGE'))
define('FORCE_PAGE',$VAR['_page_current']);
return;
}
# Change theme
if (isset($VAR['tid']) && $VAR['tid'] != '')
$VAR[$this->module.'_theme_id'] = $VAR['tid'];
# Change Language
if (isset($VAR['lid']) && $VAR['lid'] != '')
$VAR[$this->module.'_language_id'] = $VAR['lid'];
# Change country
if (isset($VAR['cid']) && $VAR['cid'] != '')
$VAR[$this->module.'_country_id'] = $VAR['cid'];
# Change currency
if (isset($VAR['cyid']) && $VAR['cyid'] != '')
$VAR[$this->module.'_currency_id'] = $VAR['cyid'];
$VAR[$this->module.'_tax_id'] = $this->validate_tax($VAR);
# Update the record
$update = parent::update($VAR);
# Password logging class
if ($password_changed && is_object($accountHistory))
$accountHistory->setNewPassword(SESS_ACCOUNT,$VAR[$this->module.'_password'],false);
# Update the static vars
$static_var->update($VAR,$this->module,SESS_ACCOUNT);
# If we were called from a child class, we can return now
if (get_class($this) != 'account')
return $update;
# Update groups for subaccount
if ($issubaccount) {
$db = &DB();
$db->Execute(sqlDelete($db,'account_group',sprintf("group_id>2 AND (service_id IS NULL OR service_id=0 OR service_id='') AND account_id=%s",$VAR['account_id'])));
if (! empty($VAR['groups'])) {
global $C_auth;
foreach ($VAR['groups'] as $gid => $val)
if ($gid==$val && $C_auth->auth_group_by_id($gid))
$db->Execute(sqlInsert($db,'account_group',array('account_id'=>$VAR['account_id'],'group_id'=>$gid,'active'=>1,'date_orig'=>time())));
}
}
}
/**
* Password Reset
*
* @uses email_template
*/
public function user_password($VAR) {
global $C_translate,$C_debug;
# Set the max time between password requests
$LIMIT_SECONDS = 120; //2 minutes
$EXPIRE_TIME = 60*15; //15 minutes
# Is the username & email both set?
if ((! isset($VAR['account_email']) && ! isset($VAR['account_username'])) ||
((trim($VAR['account_email']) == '' && trim($VAR['account_username']) == '')) ||
(($VAR['account_email'] && $VAR['account_username']))) {
# ERROR: You must enter either your username or e-mail address!
$C_debug->alert($C_translate->translate('password_reset_req',$this->module,''));
return;
}
$db = &DB();
if ($VAR['account_email'])
$sql = sqlSelect($db,'account','id,email,first_name,last_name',sprintf('email=::%s::',$VAR['account_email']));
elseif ($VAR['account_username'])
$sql = sqlSelect($db,'account','id,email,first_name,last_name',sprintf('username=::%s::',$VAR['account_username']));
else
$sql = '';
$result = $db->Execute($sql);
if (! $result || $result->RecordCount() == 0) {
# ERROR: No matches found!
$C_debug->alert($C_translate->translate('password_reset_no_match',$this->module,''));
return;
}
$account = $result->fields['id'];
# Check that this email has not been requested already in the last LIMIT_SECONDS seconds
$result = $db->Execute(sqlSelect($db,'temporary_data','*',sprintf('field1=::%s::',$account)));
if ($result->RecordCount() > 0) {
$limit = $result->fields['date_orig']+$LIMIT_SECONDS;
if ($limit>time()) {
$error1 = $C_translate->translate('password_reset_spam_limit',$this->module,'');
$error = str_replace('%limit%',$LIMIT_SECONDS,$error1);
$C_debug->alert($error);
return;
} else {
# Delete the old request
$db->Execute(sqlDelete($db,'temporary_data',sprintf('field1=::%s::',$account)));
}
}
# Ok to continue
$now = md5(microtime());
$expire = time()+$EXPIRE_TIME;
# Create the temporary DB Record
$result = $db->Execute(sqlInsert($db,'temporary_data',array(
'date_orig'=>time(),
'date_expire'=>$expire,
'field1'=>$account,
'field2'=>$now
)));
# Send the password reset email template
require_once(PATH_MODULES.'email_template/email_template.inc.php');
$my = new email_template;
$my->send('account_reset_password',$account,'','',$now,false);
# ALERT: we have sent an email to you....
$C_debug->alert($C_translate->translate('password_reset_sent',$this->module,''));
}
/**
* Password Reset
*
* @uses account_password_history
*/
public function user_password_reset($VAR) {
global $C_translate,$C_debug,$smarty;
# Validate that the password && confirm password is set
if (! isset($VAR['account_password']) || ! isset($VAR['confirm_password']) || $VAR['account_password'] == '') {
# ERROR
$message = $C_translate->translate('password_reset_reqq',$this->module,'');
$C_debug->alert($message);
return;
} else if ($VAR['account_password'] != $VAR['confirm_password']) {
# ERROR
$message = $C_translate->translate('password_change_match',$this->module,'');
$C_debug->alert($message);
return;
} else {
# Hash the password
if (defined('PASSWORD_ENCODING_SHA'))
$password = sha1($VAR['account_password']);
else
$password = md5($VAR['account_password']);
}
if (! isset($VAR['validate']) || $VAR['validate'] == '') {
# ERROR: bad link....
$url = sprintf('<br><a href="%s?_page=account:user_password">%s</a>',URL,$C_translate->translate('submit','CORE',''));
$message = $C_translate->translate('password_reset_bad_url',$this->module,'');
$C_debug->alert($message.$url);
return;
}
# Get the temporary record from the database
$db = &DB();
$result = $db->Execute(sqlSelect($db,'temporary_data','field1,field2',sprintf('date_expire>=%s AND field2=::%s::',time(),$VAR['validate'])));
if ($result->RecordCount() == 0) {
# ERROR: no match for submitted link, invalid or expired.
$url = sprintf('<br><a href="%s?_page=account:user_password">%s</a>',URL,$C_translate->translate('submit','CORE',''));
$message = $C_translate->translate('password_reset_bad_url',$this->module,'');
$C_debug->alert($message.$url);
return;
}
$account_id = $result->fields['field1'];
# Check if new password is ok
global $C_list;
if ($C_list->is_installed('account_password_history')) {
include_once(PATH_MODULES.'account_password_history/account_password_history.inc.php');
$accountHistory = new account_password_history();
if (! $accountHistory->getIsPasswordOk($account_id,$password)) {
$C_debug->alert('The password you have selected has been used recently and cannot be used again at this time for security purposes.');
return;
}
}
# Delete the temporary record
$db->Execute(sqlDelete($db,'temporary_data',sprintf('field2=::%s::',$VAR['validate'])));
# Update the password record
$db->Execute(sqlUpdate($db,'account',array('date_last'=>time(),'password'=>$password),sprintf('id=%s',$account_id)));
# Password logging class
if (! empty($accountHistory) && is_object($accountHistory))
$accountHistory->setNewPassword($account_id,$password);
# Return the success message
$C_debug->alert($C_translate->translate('password_update_success',$this->module,''));
$smarty->assign('pw_changed',true);
}
/**
* Verify and activate an account
*/
public function user_verify($VAR) {
global $C_debug,$C_translate,$smarty;
# Validate $verify is set
if (! isset($VAR['verify']) || $VAR['verify'] == '') {
# Error: please use the form below ...
$smarty->assign('verify_results',false);
$C_debug->alert($C_translate->translate('validate_fail',$this->module));
return;
}
$verify = explode(':',$VAR['verify']);
# Validate the $verify string.
$db = &DB();
$result = $db->Execute(sqlSelect($db,'account','id,username,status',array('id'=>$verify[1],'date_orig'=>$verify[0])));
if ($result->RecordCount() == 0) {
# Error: please use the form below ...
$smarty->assign('verify_results',false);
$C_debug->alert($C_translate->translate('validate_fail',$this->module,''));
return;
}
# Check the status
$status = $result->fields['status'];
$username = $result->fields['username'];
if ($status == '1') {
# Account already active!
$smarty->assign('verify_results',true);
return;
}
# Update the account status
$db->Execute(sqlUpdate($db,'account',array('status'=>1),array('id'=>$verify[1])));
# Account now active!
$smarty->assign('verify_results',true);
# Return the success message
$C_debug->alert($C_translate->translate('password_update_success',$this->module,''));
}
/**
* Resend Verify Code
*
* @uses email_template
*/
public function user_verify_resend($VAR) {
global $C_translate,$C_debug;
# Is the username & email both set?
if ((! isset($VAR['account_email']) && ! isset($VAR['account_username'])) ||
((trim($VAR['account_email']) == '' && trim($VAR['account_username']) == '')) ||
(($VAR['account_email'] && $VAR['account_username']))) {
# ERROR: You must enter either your username or e-mail address!
$C_debug->alert($C_translate->translate('verify_resend_req',$this->module,''));
return;
}
$db = &DB();
if ($VAR['account_email'])
$sql = sqlSelect($db,'account','id,date_orig,status,email,first_name,last_name',array('email'=>$VAR['account_email']));
elseif ($VAR['account_username'])
$sql = sqlSelect($db,'account','id,date_orig,status,email,first_name,last_name',array('username'=>$VAR['account_username']));
else
$sql = '';
$result = $db->Execute($sql);
if (! $result || $result->RecordCount() == 0) {
# ERROR: No matches found!
$C_debug->alert($C_translate->translate('password_reset_no_match',$this->module,''));
return;
}
$account = $result->fields['id'];
if ($result->fields['status'] == '1') {
# ERROR: This account is already active!
$C_debug->alert($C_translate->translate('verify_resend_active',$this->module,''));
return;
}
# Resend the pending email
require_once(PATH_MODULES.'email_template/email_template.inc.php');
$my = new email_template;
$my->send('account_registration_inactive',$account,$account,'',$this->validation_str($account));
# Notice that the email is sent
$C_debug->alert($C_translate->translate('user_add_inactive_welcome',$this->module,''));
}
/**
* Validate the Tax ID
*
* @uses tax
*/
private function validate_tax($VAR) {
# Validate the tax_id
require_once(PATH_MODULES.'tax/tax.inc.php');
$taxObj = new tax;
$tif = $this->module.'_tax_id';
$tef = $this->module.'_tax_id_exempt';
$cid = $this->module.'_country_id';
if (isset($VAR[$tif]) && isset($VAR[$cid]) && is_array($VAR[$tif])) {
foreach ($VAR[$tif] as $country_id => $tax_id) {
if ($country_id == $VAR[$cid]) {
$exempt = @$VAR[$tef][$country_id];
if (! $txRs = $taxObj->TaxIdsValidate($country_id,$tax_id,$exempt)) {
$this->validated = false;
global $C_translate;
array_push($this->val_error,array(
'field'=>$tif,
'field_trans'=>$taxObj->errField,
'error'=>$C_translate->translate('validate_general','','')
));
}
if ($exempt)
return false;
else
return $tax_id;
}
}
}
return false;
}
/**
* Return validation string
*/
private function validation_str($id) {
$db = &DB();
$rs = $db->Execute(sqlSelect($db,'account','date_orig',array('id'=>$id)));
if ($rs && $rs->RecordCount())
return sprintf('%s:%s',$rs->fields['date_orig'],$id);
else
return false;
}
protected function add_account_groups($groups,$account,$expire) {
global $C_auth,$C_debug;
$db = &DB();
$addDefault = true;
# Loop through the array to add each account_group record
for ($i=0; $i<count($groups); $i++) {
# Verify the admin adding this account is authorized for this group themselves, otherwise skip
if ($C_auth->auth_group_by_id($groups[$i])) {
$result = $db->Execute(sqlInsert($db,'account_group',array('date_orig'=>time(),'date_expire'=>$expire,'group_id'=>$groups[$i],'account_id'=>$account,'active'=>1)));
$addDefault = false;
# Error reporting
if ($result === false)
$C_debug->error(__FILE__,__METHOD__,$db->ErrorMsg());
}
}
# Add default group
if ($addDefault) {
$result = $db->Execute(sqlInsert($db,'account_group',array('date_orig'=>time(),'date_expire'=>$expire,'group_id'=>DEFAULT_GROUP,'account_id'=>$account,'active'=>1)));
# Error reporting
if ($result === false)
$C_debug->error(__FILE__,__METHOD__,$db->ErrorMsg());
}
}
public function __construct() {
if (! defined('AJAX'))
parent::__construct();
}
/**
* Account Custom Group Search
*/
public function group_search($VAR) {
# Get date ranges
$sql = $this->sql_search_date($VAR,'A');
# Get group(s)
$sql2 = $this->sql_build($VAR,'groups','group_id');
if (! empty($sql2)) {
if (! empty($sql))
$sql .= ' AND ';
$sql .= sprintf('(%s) AND (A.id=B.account_id AND B.active=1)',$sql2);
}
# Assemble SQL
$q = sprintf('SELECT DISTINCT A.* FROM %saccount AS A, %saccount_group AS B WHERE (A.site_id=%s AND B.site_id =%s)',
AGILE_DB_PREFIX,AGILE_DB_PREFIX,DEFAULT_SITE,DEFAULT_SITE);
if (! empty($sql))
$q .= sprintf(' AND %s',$sql);
$db = &DB();
$rs = $db->Execute($q);
echo '<pre>';
# Print results in text format
if ($rs && $rs->RecordCount() > 0) {
while (! $rs->EOF) {
printf("%s %s, %s, %s\r\n",$rs->fields['first_name'],$rs->fields['last_name'],$rs->fields['email'],$rs->fields['company']);
$rs->MoveNext();
}
} else {
echo '<B>No matches</B>!';
}
echo '</pre>';
}
/**
* Account Custom Product Search
*/
public function product_search($VAR) {
# Get date ranges
$sql = $this->sql_search_date($VAR,'B');
# Get group(s)
$sql2 = $this->sql_build($VAR,'products','product_id');
if (! empty($sql2)) {
if (! empty($sql))
$sql .= ' AND ';
$sql .= sprintf('(%s) AND (A.id=C.account_id AND C.id=B.invoice_id) ',$sql2);
}
# Assemble SQL
$q = sprintf('SELECT DISTINCT A.* FROM %saccount as A, %sinvoice_item as B, %sinvoice as C WHERE (A.site_id=%s AND C.site_id=%s AND B.site_id=%s)',
AGILE_DB_PREFIX,AGILE_DB_PREFIX,AGILE_DB_PREFIX,DEFAULT_SITE,DEFAULT_SITE,DEFAULT_SITE);
if (! empty($sql))
$q .= sprintf(' AND %s',$sql);
$db = &DB();
$rs = $db->Execute($q);
echo '<pre>';
# Print results in text format
if ($rs && $rs->RecordCount() > 0) {
while (! $rs->EOF) {
printf("%s %s, %s, %s\r\n",$rs->fields['first_name'],$rs->fields['last_name'],$rs->fields['email'],$rs->fields['company']);
$rs->MoveNext();
}
} else {
echo '<B>No matches</B>!';
}
echo '</pre>';
}
/**
* Return the SQL that create the search dates for a custom search
*
* @uses CORE_validate
*/
private function sql_search_date($VAR,$table) {
include_once(PATH_CORE.'validate.inc.php');
$validate = new CORE_validate;
$sql = '';
# Get date ranges
if (isset($VAR['dates']['val']) && is_array($VAR['dates']['val']))
foreach($VAR['dates']['val'] as $cond => $val) {
if ($val > 0) {
$exp = $VAR['dates']['expr'][$cond];
if (! empty($sql))
$sql .= ' AND ';
$sql .= sprintf('%s.date_orig %s %s',$table,$exp,$validate->convert_date($val));
}
}
if (! empty($sql))
$sql = sprintf('(%s)',$sql);
return $sql;
}
/**
* SQL query builder
*/
private function sql_build($VAR,$index,$field) {
$sql = '';
if (! empty($VAR[$index])) {
foreach($VAR[$index] as $a) {
if ($a != 0) {
if (! empty($sql))
$sql .= ' OR ';
$sql .= sprintf('B.%s=%s',$field,$a);
}
}
}
return $sql;
}
/**
* AJAX selector
* Renders the account details in field before submit
*/
public function autoselect($VAR) {
if (! isset($VAR['return']) || ! isset($VAR['field']))
return;
$return = $VAR['return'];
$field = sprintf('autosearch_%s',$VAR['field']);
$fieldlist = 'email,first_name,last_name,username';
$sort = 'first_name,last_name';
if (empty($VAR[$field]))
$where = 'id > 0';
elseif (is_numeric($VAR[$field]))
$where = sprintf('id LIKE "%s%%"',$VAR[$field]);
elseif (preg_match('/ /',$VAR[$field])) {
$arr = explode(' ',$VAR[$field]);
$where = sprintf('(first_name LIKE "%s%%" AND last_name LIKE "%s%%") OR (company LIKE "%s%%")',$arr[0],$arr[1],$VAR[$field]);
} elseif (preg_match('/@/',$VAR[$field]))
$where = sprintf('email LIKE "%%%s%%"',$VAR[$field]);
else
$where = sprintf('(username LIKE "%s%%" OR first_name LIKE "%s%%" OR last_name LIKE "%s%%" OR company LIKE "%s%%")',
$VAR[$field],$VAR[$field],$VAR[$field],$VAR[$field]);
if (! preg_match("/{$return}/",$fieldlist))
$fieldlist .= ','.$return;
$db = &DB();
$result = $db->SelectLimit(sqlSelect($db,'account',$fieldlist,$where,$sort),10);
# Render the results
echo '<ul>';
if ($result->RecordCount() > 0) {
while (! $result->EOF) {
printf('<li><div class="name"><b>%s %s</b></div><div class="email"><span class="informal">%s</span></div><div class="index" style="display:none">%s</div></li>',
$result->fields['first_name'],$result->fields['last_name'],$result->fields['email'],$result->fields[$return]);
$result->MoveNext();
}
}
echo '</ul>';
}
/**
* Login as user
* Called by "Become User"
*
* @uses CORE_login_handler
*/
public function login($VAR) {
global $C_auth;
$db = &DB();
# Check for target user
$display_this = false;
if (! empty($VAR['account_id'])) {
# Get any authorized groups of the target account
$groups = $db->Execute(sqlSelect($db,'account_group','group_id',sprintf('account_id=%s AND active=1',$VAR['account_id']),'group_id'));
$group = array();
while (! $groups->EOF) {
array_push($group,$groups->fields['group_id']);
$groups->MoveNext();
}
# Verify the user has access to view this account
if (SESS_ACCOUNT != $VAR['account_id']) {
$display_this = true;
for ($ix=0; $ix<count($group); $ix++)
if (! $C_auth->auth_group_by_id($group[$ix]))
$display_this = false;
} else {
return false;
}
} else {
return false;
}
# Logout current user and login as the target user
if ($display_this) {
$acct = $db->Execute(sqlSelect($db,'account','username,password',sprintf('id=%s',$VAR['account_id'])));
$arr['_username'] = $acct->fields['username'];
$arr['_password'] = $acct->fields['password'];
include_once(PATH_CORE.'login.inc.php');
$login = new CORE_login_handler;
$login->logout($VAR);
$login->login($arr,$md5=false);
define('REDIRECT_PAGE',sprintf('?_page=account:account&tid=%s',DEFAULT_THEME));
}
}
#@todo appears to be unused
private function popup_search($VAR)
{
$db = &DB();
if (empty($VAR['search'])) {
$where = '';
} elseif (eregi(" ", $VAR['search'])) {
$arr = explode(" ", $VAR['search']);
$where = "first_name = ".$db->qstr($arr[0])." AND ".
"last_name LIKE ".$db->qstr('%'.$arr[1].'%')." AND ";
} else {
$where = "username LIKE ".$db->qstr('%'.$VAR['search'].'%')." OR ".
"first_name LIKE ".$db->qstr('%'.$VAR['search'].'%')." OR ".
"first_name LIKE ".$db->qstr('%'.$VAR['search'].'%')." OR ".
"company LIKE ". $db->qstr('%'.$VAR['search'].'%')." AND ";
}
$q = "SELECT id,first_name,last_name
FROM ".AGILE_DB_PREFIX."account
WHERE $where
site_id = '" . DEFAULT_SITE . "'";
$q_save = "SELECT * FROM ".AGILE_DB_PREFIX."account WHERE $where %%whereList%% ";
$result = $db->Execute($q);
/// DEBUG ////
// echo "<PRE>$q</PRE>";
# get the result count
$results = $result->RecordCount();
# Create the alert for no records found
if ($results == 0)
{
$id = $result->fields['id'];
$name = $result->fields['first_name'].' '.$result->fields['last_name'];
$val = $id.'|'.$name;
$res = '
<script language=\'javascript\'>
window.parent.popup_clear_'.$VAR['field'].'(true);
alert("No matches found");
window.close();
</script> ';
echo $res;
}
else if ($results == 1)
{
$id = $result->fields['id'];
$name = $result->fields['first_name'].' '.$result->fields['last_name'];
$val = $id.'|'.$name;
$res = '
<script language=\'javascript\'>
window.parent.popup_fill_'.$VAR['field'].'("'.$val.'");
window.close();
</script> ';
echo $res;
}
else
{
# create the search record
include_once(PATH_CORE . 'search.inc.php');
$search = new CORE_search;
$arr['module'] = $this->module;
$arr['sql'] = $q_save;
$arr['limit'] = '30';
$arr['order_by'] = 'last_name';
$arr['results'] = $results;
$search->add($arr);
global $smarty;
$smarty->assign('search_id', $search->id);
$smarty->assign('page', '1');
$smarty->assign('limit', $limit);
$smarty->assign('order_by', $order_by);
$smarty->assign('results', $results);
$res = '
<script language=\'javascript\'>
function popup_fill(val) {
window.parent.popup_fill_'.$VAR['field'].'(val);
}
window.open("?_page=account:iframe_search_show&_escape=1&search_id='.$search->id.'&page=1","account_select_popup","toolbar=no,status=no,width=400,height=500");
</script> ';
echo $res;
}
}
###########################################
### Top Accounts Graph
###########################################
#@todo appears to be redundant ?page=core:graphview
private function top($VAR)
{
global $smarty, $C_translate, $C_auth;
# Get the period type, default to month
if (empty($VAR['period']))
$p = 'm';
else
$p = $VAR['period'];
# Load the jpgraph class
include(PATH_GRAPH."jpgraph.php");
include(PATH_GRAPH."jpgraph_bar.php");
# check the validation for this function
if(!$C_auth->auth_method_by_name($this->module,'search')) {
$error = $C_translate->translate('module_non_auth','','');
include(PATH_GRAPH."jpgraph_canvas.php");
$graph = new CanvasGraph(460,55,"auto");
$t1 = new Text($error);
$t1->Pos(0.2,0.5);
$t1->SetOrientation("h");
$t1->SetBox("white","black",'gray');
$t1->SetFont(FF_FONT1,FS_NORMAL);
$t1->SetColor("black");
$graph->AddText($t1);
$graph->Stroke();
exit;
}
# Get the period start & end
switch ($p)
{
# By Weeks
case 'w':
$interval = "1";
$width = ".9";
$title = 'Top Accounts for Last Last Week';
$dow = date('w');
$start_str = mktime(0,0,0,date('m'), date('d')-$dow, date('y'));
$end_str = mktime(23,59,59,date('m'), date('d'), date('y'));
break;
# By Months
case 'm':
$interval = "3";
$width = ".6";
$title = 'Top Accounts for Last Last Month';
$start_str = mktime(0,0,0,date('m'), 1, date('y'));
$end_str = mktime(23,59,59,date('m'), date('d'), date('y'));
break;
# By Years
case 'y':
$interval = "1";
$width = ".8";
$title = 'Top Accounts for Last Last Year';
$start_str = mktime(0,0,0,1,1, date('y'));
$end_str = mktime(23,59,59, date('m'), date('d'), date('y'));
break;
}
##############################@@@@@@@@
# Get accounts & sales for this period
##############################@@@@@@@@
$db = &DB();
$sql = 'SELECT account_id,total_amt FROM ' . AGILE_DB_PREFIX . 'invoice WHERE
date_orig >= ' . $db->qstr( $start_str ) . ' AND date_orig <= ' . $db->qstr( $end_str ) . ' AND
site_id = ' . $db->qstr(DEFAULT_SITE);
$result = $db->Execute($sql);
if(@$result->RecordCount() == 0) {
$file = fopen( PATH_THEMES.'default_admin/images/invisible.gif', 'r');
fpassthru($file);
exit;
}
while(!$result->EOF)
{
$amt = $result->fields['total_amt'];
$acct = $result->fields['account_id'];
if(!isset( $arr[$acct] )) $arr[$acct] = 0;
$arr[$acct] += $amt;
$result->MoveNext();
}
$i = 0;
while(list($key, $var) = each(@$arr)) {
# Get the user name
$sql = 'SELECT first_name,last_name FROM ' . AGILE_DB_PREFIX . 'account WHERE
id = ' . $db->qstr( $key ) . ' AND
site_id = ' . $db->qstr(DEFAULT_SITE);
$rs = $db->Execute($sql);
$_lbl[] = strtoupper(substr($rs->fields['first_name'],0,1)) . ". " . $rs->fields['last_name'];
$_datay[] = $var;
$i++;
}
### Sort the arrays
array_multisort($_datay,SORT_DESC, SORT_NUMERIC, $_lbl);
### Limit the results to 10 or less
for($i=0; $i<count($_lbl); $i++) {
$lbl[$i] = $_lbl[$i];
$datay[$i] = $_datay[$i];
if($i>=9) $i = count($_lbl);
}
$i = count($lbl);
# Get the Currency
$sql = 'SELECT symbol FROM ' . AGILE_DB_PREFIX . 'currency WHERE
id = ' . $db->qstr( DEFAULT_CURRENCY ) . ' AND
site_id = ' . $db->qstr(DEFAULT_SITE);
$rs = $db->Execute($sql);
$currency_iso = $rs->fields['symbol'];
// Size of graph
$width=265;
$height=75 + ($i*15);
// Set the basic parameters of the graph
$graph = new Graph($width,$height,'auto');
$graph->SetScale("textlin");
$graph->yaxis->scale->SetGrace(50);
$graph->SetMarginColor('#F9F9F9');
$graph->SetFrame(true,'#CCCCCC',1);
$graph->SetColor('#FFFFFF');
$top = 45;
$bottom = 10;
$left = 95;
$right = 15;
$graph->Set90AndMargin($left,$right,$top,$bottom);
// Label align for X-axis
$graph->xaxis->SetLabelAlign('right','center','right');
// Label align for Y-axis
$graph->yaxis->SetLabelAlign('center','bottom');
$graph->xaxis->SetTickLabels($lbl);
// Titles
$graph->title->SetFont(FF_FONT1,FS_BOLD,9.5);
$title = $C_translate->translate('graph_top','account_admin','');
$graph->title->Set($title);
// Create a bar pot
$bplot = new BarPlot($datay);
$bplot->SetFillColor("#506DC7");
$bplot->SetWidth(0.2);
// Show the values
$bplot->value->Show();
$bplot->value->SetFont(FF_FONT1,FS_NORMAL,8);
$bplot->value->SetAlign('center','center');
$bplot->value->SetColor("black","darkred");
$bplot->value->SetFormat($currency_iso.'%.2f');
$graph->Add($bplot);
$graph->Stroke();
return;
}
/**
* Send an email to an account
*
* @uses CORE_email
*/
public function mail_one($VAR) {
global $C_translate,$C_debug;
# Validate the required vars (account_id, message, subject)
if (@$VAR['mail_account_id'] != '' && @$VAR['mail_subject'] != '' && @$VAR['mail_message'] != '') {
# Verify the specified account
$db = &DB();
$account = $db->Execute(sqlSelect($db,'account','email,first_name,last_name',sprintf('id=%s',$VAR['mail_account_id'])));
if ($account->RecordCount() == 0) {
# Error message
$C_debug->alert($C_translate->translate('account_non_exist',$this->module,''));
return;
}
# OK to send the email
$db = &DB();
$setup_email = $db->Execute(sqlSelect($db,'setup_email','*',sprintf('id=%s',$VAR['mail_email_id'])));
$E['priority'] = $VAR['mail_priority'];
$E['html'] = '0';
$E['subject'] = $VAR['mail_subject'];
$E['body_text'] = $VAR['mail_message'];
$E['to_email'] = $account->fields['email'];
$E['to_name'] = sprintf('%s %s',$account->fields['first_name'],$account->fields['last_name']);
if ($setup_email->fields['type'] == 0) {
$type = 0;
} else {
$type = 1;
$E['server'] = $setup_email->fields['server'];
$E['account'] = $setup_email->fields['username'];
$E['password'] = $setup_email->fields['password'];
}
$E['from_name'] = $setup_email->fields['from_name'];
$E['from_email'] = $setup_email->fields['from_email'];
if ($setup_email->fields['cc_list'] != '')
$E['cc_list'] = explode(',',$setup_email->fields['cc_list']);
if ($setup_email->fields['bcc_list'] != '')
$E['bcc_list'] = explode(',',$setup_email->fields['bcc_list']);
# Call the mail class
require_once(PATH_CORE.'email.inc.php');
$email = new CORE_email;
if ($type == 0)
$email->PHP_Mail($E);
else
$email->SMTP_Mail($E);
} else {
global $C_vars;
# Error message
$C_debug->alert($C_translate->translate('validate_any','',''));
$C_vars->strip_slashes_all();
return;
}
global $C_vars;
# Success message
$C_debug->alert($C_translate->translate('mail_sent',$this->module,''));
$C_vars->strip_slashes_all();
}
/**
* Send a mail to multiple recipients
* Send email to the receipients found from a search
*
* @uses CORE_email
* @uses CORE_search
*/
public function mail_multi($VAR) {
global $C_translate, $C_debug;
# Validate the required vars (account_id, message, subject)
if (@$VAR['search_id'] != '' && @$VAR['mail_subject'] != '' && @$VAR['mail_message'] != '') {
# Get the search details
if (isset($VAR['search_id'])) {
include_once(PATH_CORE.'search.inc.php');
$search = new CORE_search;
$search->get($VAR['search_id']);
} else {
# Invalid search!
# @todo Translate
echo '<BR> The search terms submitted were invalid!';
return;
}
# Generate the full query
$field_list = sprintf('%saccount.email,%saccount.first_name,%saccount.last_name',AGILE_DB_PREFIX,AGILE_DB_PREFIX,AGILE_DB_PREFIX);
$q = str_replace('%%fieldList%%',$field_list,$search->sql);
$q = str_replace('%%tableList%%',AGILE_DB_PREFIX.'account',$q);
$q = str_replace('%%whereList%%','',$q);
$q .= sprintf('%saccount.site_id=%s',AGILE_DB_PREFIX,DEFAULT_SITE);
$db = &DB();
$account = $db->Execute($q);
# Check results
if ($account->RecordCount() == 0) {
$C_debug->alert($C_translate->translate('account_non_exist',$this->module,''));
return;
}
# Get the selected email setup details
$db = &DB();
$setup_email = $db->Execute(sqlSelect($db,'setup_email','*',sprintf('id=%s',$VAR['mail_email_id'])));
if ($setup_email->fields['type'] == 0) {
$type = 0;
} else {
$type = 1;
$E['server'] = $setup_email->fields['server'];
$E['account'] = $setup_email->fields['username'];
$E['password'] = $setup_email->fields['password'];
}
$E['priority'] = $VAR['mail_priority'];
$E['html'] = '0';
$E['subject'] = $VAR['mail_subject'];
$E['body_text'] = $VAR['mail_message'];
$E['from_name'] = $setup_email->fields['from_name'];
$E['from_email'] = $setup_email->fields['from_email'];
# Loop to send each e-mail
while (! $account->EOF) {
$E['to_email'] = $account->fields['email'];
$E['to_name'] = sprintf('%s %s',$account->fields['first_name'],$account->fields['last_name']);
# Call the mail class
require_once(PATH_CORE.'email.inc.php');
$email = new CORE_email;
if ($type == 0)
$email->PHP_Mail($E);
else
$email->SMTP_Mail($E);
# Next record
$account->MoveNext();
}
} else {
global $C_vars;
# Error message
$C_debug->alert($C_translate->translate('validate_any','',''));
$C_vars->strip_slashes_all();
return;
}
global $C_vars;
# Success message
$C_debug->alert($C_translate->translate('mail_sent',$this->module,''));
$C_vars->strip_slashes_all();
}
/**
* Send Password Reminder
*
* @uses email_template
*/
public function send_password_email($VAR) {
global $C_translate,$C_debug;
require_once(PATH_MODULES.'email_template/email_template.inc.php');
$my = new email_template;
$my->send('password_change_instructions',@$VAR['id'],'','','');
echo $C_translate->translate('password_change_instructions',$this->module,'');
}
/**
* Send users verification email
*
* @uses email_template
*/
public function send_verify_email($VAR) {
global $C_translate,$C_debug;
require_once(PATH_MODULES.'email_template/email_template.inc.php');
$my = new email_template;
$db = &DB();
$result = $db->Execute(sqlSelect($db,'account','date_orig',sprintf('id=%s',$VAR['id'])));
$my->send('account_registration_inactive',$VAR['id'],$VAR['id'],'',$this->validation_str($VAR['id']));
echo $C_translate->translate('account_verify_instructions',$this->module,'');
}
/**
* Add new accounts
*
* @uses CORE_validate
* @uses email_template
* @uses affiliate
*/
public function add($VAR) {
global $C_list,$C_translate,$C_debug,$smarty;
if (! empty($VAR['account_date_expire'])) {
include_once(PATH_CORE.'validate.inc.php');
$val = new CORE_validate($VAR);
$VAR['account_date_expire'] = $val->convert_date($VAR['account_date_expire']);
} else {
$VAR['account_date_expire'] = 0;
}
# If the username is blank, auto generate one
if (empty($VAR['account_username'])) {
$VAR['account_username'] = '';
$length = 4;
srand((double)microtime()*1000000);
$vowels = array('a','e','i','o','u');
$cons = array('b','c','d','g','h','j','k','l','m','n','p','r','s','t','u','v','w','tr','cr','br','fr','th','dr','ch','ph','wr','st','sp','sw','pr','sl','cl');
$num_vowels = count($vowels);
$num_cons = count($cons);
for ($i=0; $i<$length; $i++)
$VAR['account_username'] .= $cons[rand(0,$num_cons-1)].$vowels[rand(0,$num_vowels-1)];
}
# If the password is blank, auto generate one
if (empty($VAR['account_password'])) {
$passwd = '********';
srand((double)microtime() * 1000000);
$UniqID = md5(uniqid(rand()));
$VAR['account_password'] = substr(md5(uniqid(rand())),0,10);
} else {
$passwd = $VAR['account_password'];
}
# Add the record
if (! $this->account_id = parent::add($VAR))
return;
# Add the account to the groups
$this->add_account_groups($VAR['groups'],$this->account_id,$VAR['account_date_expire']);
# Mail the new user
if (! empty($VAR['welcome_email'])) {
require_once(PATH_MODULES.'email_template/email_template.inc.php');
$my = new email_template;
if ($VAR['account_status'] == '1')
$my->send('account_add_staff_active',$this->account_id,'','',$passwd);
else
$my->send('account_add_staff_inactive',$this->account_id,$this->account_id,'',$this->validation_str($this->account_id));
}
# Display the welcome message
if ($VAR['account_status'] == '1')
$C_debug->alert($C_translate->translate('staff_add_active',$this->module,''));
else
$C_debug->alert($C_translate->translate('staff_add_inactive',$this->module,''));
# Affiliate Auto Creation
if (AUTO_AFFILIATE == 1 && $C_list->is_installed('affiliate')) {
$VAR['affiliate_account_id'] = $this->account_id;
$VAR['affiliate_template_id'] = DEFAULT_AFFILIATE_TEMPLATE;
$VAR['affiliate_parent_affiliate_id'] = $VAR['account_affiliate_id'];
include_once(PATH_MODULES.'affiliate/affiliate.inc.php');
$affiliate = new affiliate;
$affiliate->add($VAR,$affiliate);
}
return;
}
/**
* View an Account
*/
public function view($VAR) {
global $C_auth;
$db = &DB();
# Get our results
$smart = parent::view($VAR);
if ($smart) {
# Get any authorized groups
$view = $db->Execute(sqlSelect($db,'account_group','service_id,group_id',array('account_id'=>$VAR['id'],'active'=>1),'group_id'));
while (! $view->EOF) {
$smart['groups'] = array();
if ($view->fields['service_id'] == '')
array_push($smart['groups'],$view->fields['group_id']);
$view->MoveNext();
}
# Verify the user has access to view this account
if (SESS_ACCOUNT != $VAR['id']) {
$smart['own_account'] = false;
$display_this = true;
for ($ix=0; $ix<count($group); $ix++)
if (!$C_auth->auth_group_by_id($group[$ix]))
$display_this = false;
} else {
$display_this = true;
$smart['own_account'] = true;
}
# define the results
if (! $display_this) {
unset($smart);
echo 'You have selected an account for which you are not authorized, your permission settings are to low!<br/><br/>';
continue;
}
# Get the last activity date/IP
$view = $db->SelectLimit(sqlSelect($db,'login_log','*',array('account_id'=>$VAR['id']),'date_orig DESC'),1);
if ($view && $view->RecordCount() == 1) {
$smart['last_activity'] = $view->fields['date_orig'];
$smart['last_ip'] = $view->fields['ip'];
} else {
$smart['last_activity'] = '';
$smart['last_ip'] = '';
}
# Get invoice details for this account
$view = $db->SelectLimit(sqlSelect($db,'invoice','id,date_orig,total_amt,billed_amt,process_status',array('account_id'=>$VAR['id']),'id DESC'),10);
if ($view && $view->RecordCount() > 0) {
$smart['invoice'] = array();
while (! $view->EOF) {
if ($view->fields['total_amt'] > $view->fields['billed_amt'] && $view->fields['suspend_billing'] != 1)
$view->fields['due'] = $view->fields['total_amt']-$view->fields['billed_amt'];
array_push($smart['invoice'],$view->fields);
$view->MoveNext();
}
}
# Get service details for this account
$view = $db->SelectLimit(sqlSelect($db,'service','id,sku,price,active,type,domain_name,domain_tld',array('account_id'=>$VAR['id']),'id DESC'),10);
if ($view && $view->RecordCount() > 0) {
$smart['service'] = array();
while (! $view->EOF) {
array_push($smart['service'],$view->fields);
$view->MoveNext();
}
}
# Get invoices to be generated for this account
include_once(PATH_MODULES.'invoice/invoice.inc.php');
$invoice = new invoice;
$view = $db->Execute($invoice->sql_invoice_soon(null,null,$VAR['id']));
if ($view && $view->RecordCount() > 0) {
$smart['duesoon'] = array();
while (! $view->EOF) {
array_push($smart['duesoon'],$view->fields);
$view->MoveNext();
}
}
# No results
} else {
global $C_debug;
$C_debug->error(__FILE__,__METHOD__,'The selected record does not exist any longer, or your account is not authorized to view it');
return;
}
global $smarty;
$smarty->assign('record',$smart);
}
/**
* Update an account
*/
public function update($VAR) {
if (isset($VAR['process_account_password']) && $VAR['process_account_password'])
$VAR['account_password'] = $VAR['process_account_password'];
$ok = parent::update($VAR);
if ($ok) {
# Remove login lock
if ($VAR['account_status']) {
$db = &DB();
$delrs = $db->Execute(sqlDelete($db,'login_lock',sprintf('account_id=%s',$VAR['account_id'])));
$delrs = $db->Execute(sqlDelete($db,'login_log',sprintf('account_id=%s AND status=0',$VAR['account_id'])));
}
return true;
}
}
/**
* Merge two accounts together
*
* @uses CORE_auth
*/
public function merge($VAR) {
global $C_auth,$C_list,$C_translate,$C_debug;
$db = &DB();
if (empty($VAR['id']) || empty($VAR['merge_acct_id'])) {
$C_debug->alert($C_translate->translate('merge_err',$this->module,''));
return false;
}
$acct_id = $VAR['id'];
$merge_acct_id = $VAR['merge_acct_id'];
# Get merged account_group
$rs = $db->Execute(sqlSelect($db,'account_group','*',sprintf("(service_id = '' OR service_id = 0 OR service_id IS NULL) AND account_id=%s",$acct_id)));
if ($rs === false) {
$C_debug->error(__FILE__,__METHOD__,$db->ErrorMsg());
} else {
while (! $rs->EOF) {
$Cauth = new CORE_auth(true);
if ($Cauth->auth_group_by_account_id($merge_acct_id,$rs->fields['group_id']))
# Duplicate group, delete
$db->Execute(sqlDelete($db,'account_group',sprintf('id=%s',$rs->fields['id'])));
$rs->MoveNext();
}
}
# Default table
$merge = array(
'account_group'=>'account_id',
'account_billing'=>'account_id',
'cart'=>'account_id',
'charge'=>'account_id',
'discount'=>'avail_account_id',
'invoice'=>'account_id',
'log_error'=>'account_id',
'login_lock'=>'account_id',
'login_log'=>'account_id',
'search'=>'account_id',
'service'=>'account_id',
'session'=>'account_id',
'staff'=>'account_id'
);
# Affiliate
if ($C_list->is_installed('affiliate'))
$merge['affiliate'] = 'account_id';
foreach ($merge as $table => $field) {
$rs = $db->Execute(sqlUpdate($db,$table,array($field=>$acct_id),sprintf('%s=%s',$field,$merge_acct_id)));
if ($rs === false)
$C_debug->error(__FILE__,sprintf('%s::%s',__METHOD__,$table),$db->ErrorMsg());
}
# Delete account
$rs = $db->Execute(sqlDelete($db,'account',sprintf('id=%s',$merge_acct_id)));
if ($rs === false)
$C_debug->error(__FILE__,__METHOD__,$db->ErrorMsg());
$C_debug->alert($C_translate->translate('merge_ok',$this->module,''));
return;
}
/**
* Delete an account
*
* @uses invoice
*/
public function delete($VAR) {
global $C_list;
$db = &DB();
# Generate the list of ID's
$id_list = '';
$account_id_list = '';
$discount_id_list = '';
if (isset($VAR['delete_id']))
$ids = explode(',',preg_replace('/,$/','',$VAR['delete_id']));
elseif (isset($VAR['id']))
$ids = explode(',',preg_replace('/,$/','',$VAR['id']));
# Verify this is not the admin account or the current user's account
if (($i = array_search(SESS_ACCOUNT,$ids)) || ($i = array_search(1,$ids)))
unset($ids[$i]);
$this->associated_DELETE = array();
array_push($this->associated_DELETE,array('table'=>'session','field'=>'account_id'));
array_push($this->associated_DELETE,array('table'=>'account_billing','field'=>'account_id'));
array_push($this->associated_DELETE,array('table'=>'account_group','field'=>'account_id'));
array_push($this->associated_DELETE,array('table'=>'cart','field'=>'account_id'));
array_push($this->associated_DELETE,array('table'=>'search','field'=>'account_id'));
array_push($this->associated_DELETE,array('table'=>'staff','field'=>'account_id'));
array_push($this->associated_DELETE,array('table'=>'discount','field'=>'account_id'));
if ($C_list->is_installed('affiliate'))
array_push($this->associated_DELETE,array('table'=>'affiliate','field'=>'account_id'));
$result = parent::delete($VAR);
if ($result) {
# Generate the full query (invoice)
$invoice = $db->Execute(sqlSelect($db,'invoice','id',array('account_id'=>$ids)));
if ($invoice && $invoice->RecordCount() > 0 ) {
while (! $invoice->EOF) {
include_once(PATH_MODULES.'invoice/invoice.inc.php');
$inv = new invoice;
$arr['id'] = $invoice->fields['id'];
$inv->delete($arr,$inv);
$invoice->MoveNext();
}
}
# Error reporting
if ($result === false) {
global $C_debug;
$C_debug->error('account_admin.inc.php','delete', $db->ErrorMsg());
} else {
# Alert delete message
global $C_debug, $C_translate;
$C_translate->value['CORE']['module_name'] = $C_translate->translate('name',$this->table,'');
$message = $C_translate->translate('alert_delete_ids','CORE','');
$C_debug->alert($message);
}
}
}
/**
* Update account groups
*
* This method is a trigger, called when an account is added from account()
*
* @uses CORE_validate
*/
public function update_account_groups($VAR) {
global $C_auth;
$db = &DB();
@$account = $VAR['account_id'];
# If there are no groups to modify, just return
if (! is_array($VAR['groups']) || ! count($VAR['groups']))
return false;
$groups = $VAR['groups'];
# Admin accounts groups cannot be altered user cannot modify their own groups
if ($account == '1' || SESS_ACCOUNT == $account)
return false;
# Drop the current groups for this account
$result = $db->Execute(sqlDelete($db,'account_group',sprintf('service_id IS NULL AND account_id=%s',$account)));
# Verify the admin adding this account is authorized for this group themselves, otherwise skip
foreach ($groups as $i => $group)
if (! $C_auth->auth_group_by_id($groups[$i]))
unset($groups[$i]);
if (! count($group))
return false;
# Determine the expiration
if (! empty($VAR['account_date_expire'])) {
include_once(PATH_CORE.'validate.inc.php');
$validate = new CORE_validate;
$expire = $validate->convert_date($VAR['account_date_expire'],DEFAULT_DATE_FORMAT);
} else {
$expire = 0;
}
$this->add_account_groups($groups,$account,$expire);
# Remove the user's session_auth_cache so it is regenerated on user's next pageview
$rss = $db->Execute(sqlSelect($db,'session','id',array('account_id'=>$account)));
while (! $rss->EOF) {
$db->Execute(sqlDelete($db,'session_auth_cache',sprintf('session_id=::%s::',$rss->fields['id'])));
$rss->MoveNext();
}
}
}
?>