Exemple #1
0
 public function process()
 {
     switch ($_REQUEST['_process']) {
         case 'quick_save_finance':
             if (isset($_REQUEST['link_go']) && $_REQUEST['link_go'] == 'go') {
                 module_finance::handle_link_transactions();
             } else {
                 // check for date / name at least.
                 $date = trim($_REQUEST['transaction_date']);
                 $name = trim($_REQUEST['name']);
                 if (!$date || !$name) {
                     redirect_browser(module_finance::link_open(false));
                 }
                 $credit = trim($_REQUEST['credit']);
                 $debit = trim($_REQUEST['debit']);
                 if ($credit > 0) {
                     $_POST['type'] = 'i';
                     $_POST['amount'] = $credit;
                 } else {
                     $_POST['type'] = 'e';
                     $_POST['amount'] = $debit;
                 }
             }
         case 'save_finance':
             if (isset($_REQUEST['butt_del'])) {
                 $this->delete($_REQUEST['finance_id']);
                 redirect_browser(self::link_open(false));
             }
             if (isset($_REQUEST['butt_unlink'])) {
                 // unlink this finance_id from other finance_ids.
                 $sql = "UPDATE `" . _DB_PREFIX . "finance` SET parent_finance_id = 0 WHERE parent_finance_id = '" . (int) $_REQUEST['finance_id'] . "'";
                 query($sql);
                 $sql = "UPDATE `" . _DB_PREFIX . "invoice_payment` SET parent_finance_id = 0 WHERE parent_finance_id = '" . (int) $_REQUEST['finance_id'] . "'";
                 query($sql);
                 redirect_browser(self::link_open(false));
             }
             $temp_data = $this->get_finance($_REQUEST['finance_id']);
             $data = $_POST + $temp_data;
             // save the finance categories and account.
             $account_id = $_REQUEST['finance_account_id'];
             if ((string) (int) $account_id != (string) $account_id && strlen($account_id) > 2) {
                 // we have a new account to create.
                 $account_id = update_insert('finance_account_id', 'new', 'finance_account', array('name' => $account_id));
             }
             $data['finance_account_id'] = $account_id;
             $finance_id = update_insert('finance_id', isset($_REQUEST['finance_id']) ? $_REQUEST['finance_id'] : 'new', 'finance', $data);
             module_extra::save_extras('finance', 'finance_id', $finance_id);
             if (!isset($data['tax_ids']) && isset($data['taxes']) && is_array($data['taxes'])) {
                 // default data when saving a new invoice payment to finance area
                 $data['tax_ids'] = array();
                 $data['tax_names'] = array();
                 $data['tax_percents'] = array();
                 $data['tax_increment_checkbox'] = 0;
                 foreach ($data['taxes'] as $tax) {
                     $data['tax_ids'][] = false;
                     $data['tax_names'][] = $tax['name'];
                     $data['tax_percents'][] = $tax['percent'];
                     $data['tax_amount'][] = $tax['amount'];
                     if ($tax['increment']) {
                         $data['tax_increment_checkbox'] = 1;
                     }
                 }
             }
             // save the finance tax rates (copied from invoice.php)
             if (isset($data['tax_ids']) && isset($data['tax_names']) && $data['tax_percents']) {
                 $existing_taxes = get_multiple('finance_tax', array('finance_id' => $finance_id), 'finance_tax_id', 'exact', 'order');
                 $order = 1;
                 foreach ($data['tax_ids'] as $key => $val) {
                     if ((int) $val > 0 && isset($existing_taxes[$val])) {
                         // this means we are trying to update an existing record on the finance_tax table, we confirm this id matches this finance.
                         $finance_tax_id = $val;
                         unset($existing_taxes[$finance_tax_id]);
                         // so we know which ones to remove from the end.
                     } else {
                         $finance_tax_id = false;
                         // create new record
                     }
                     $finance_tax_data = array('finance_id' => $finance_id, 'percent' => isset($data['tax_percents'][$key]) ? $data['tax_percents'][$key] : 0, 'amount' => isset($data['tax_amount'][$key]) ? $data['tax_amount'][$key] : 0, 'name' => isset($data['tax_names'][$key]) ? $data['tax_names'][$key] : 'TAX', 'order' => $order++, 'increment' => isset($data['tax_increment_checkbox']) && $data['tax_increment_checkbox'] ? 1 : 0);
                     $finance_tax_id = update_insert('finance_tax_id', $finance_tax_id, 'finance_tax', $finance_tax_data);
                 }
                 foreach ($existing_taxes as $existing_tax) {
                     delete_from_db('finance_tax', array('finance_id', 'finance_tax_id'), array($finance_id, $existing_tax['finance_tax_id']));
                 }
             }
             $category_ids = isset($_REQUEST['finance_category_id']) && is_array($_REQUEST['finance_category_id']) ? $_REQUEST['finance_category_id'] : array();
             $sql = "DELETE FROM `" . _DB_PREFIX . "finance_category_rel` WHERE finance_id = {$finance_id}";
             query($sql);
             foreach ($category_ids as $category_id) {
                 $category_id = (int) $category_id;
                 if ($category_id <= 0) {
                     continue;
                 }
                 $sql = "REPLACE INTO `" . _DB_PREFIX . "finance_category_rel` SET finance_id = {$finance_id}, finance_category_id = {$category_id}";
                 query($sql);
             }
             if (isset($_REQUEST['finance_category_new']) && strlen(trim($_REQUEST['finance_category_new'])) > 0) {
                 $category_name = trim($_REQUEST['finance_category_new']);
                 $category_id = update_insert('finance_category_id', 'new', 'finance_category', array('name' => $category_name));
                 if (isset($_REQUEST['finance_category_new_checked'])) {
                     $sql = "REPLACE INTO `" . _DB_PREFIX . "finance_category_rel` SET finance_id = {$finance_id}, finance_category_id = {$category_id}";
                     query($sql);
                 }
             }
             if (isset($_REQUEST['invoice_payment_id']) && (int) $_REQUEST['invoice_payment_id'] > 0) {
                 // link this as a child invoice payment to this one.
                 update_insert('invoice_payment_id', $_REQUEST['invoice_payment_id'], 'invoice_payment', array('parent_finance_id' => $finance_id));
             }
             if (isset($_REQUEST['finance_recurring_id']) && (int) $_REQUEST['finance_recurring_id'] > 0) {
                 // if we have set a custom "next recurring date" then we don't recalculate this date unless we are saving a new finance id.
                 $recurring = self::get_recurring($_REQUEST['finance_recurring_id']);
                 if (!(int) $_REQUEST['finance_id'] || !$recurring['next_due_date_custom']) {
                     self::calculate_recurring_date((int) $_REQUEST['finance_recurring_id'], true);
                 }
                 // we also have to adjust the starting balance of our recurring amount by this amount.
                 // just a little helpful feature.
                 if (!(int) $_REQUEST['finance_id']) {
                     $balance = module_config::c('finance_recurring_start_balance', 0);
                     if ($balance != 0) {
                         if ($data['type'] == 'e') {
                             $balance -= $data['amount'];
                         } else {
                             if ($data['type'] == 'i') {
                                 $balance += $data['amount'];
                             }
                         }
                         module_config::save_config('finance_recurring_start_balance', $balance);
                     }
                 }
                 // redirect back to recurring listing.
                 set_message('Recurring transaction saved successfully');
                 if (isset($_REQUEST['recurring_next']) && $_REQUEST['recurring_next']) {
                     redirect_browser($_REQUEST['recurring_next']);
                 }
                 redirect_browser(self::link_open_recurring(false));
             }
             set_message(_l('Transaction saved successfully: %s', module_finance::link_open($finance_id, true)));
             if (isset($_REQUEST['job_id']) && (int) $_REQUEST['job_id'] > 0) {
                 redirect_browser(module_job::link_open((int) $_REQUEST['job_id']));
             }
             if (isset($_REQUEST['butt_save_return'])) {
                 if (isset($_REQUEST['_redirect']) && strlen($_REQUEST['_redirect'])) {
                     redirect_browser($_REQUEST['_redirect']);
                 }
                 redirect_browser(self::link_open(false, false));
             }
             if ($_REQUEST['_process'] == 'quick_save_finance') {
                 redirect_browser(self::link_open(false, false));
             }
             redirect_browser(self::link_open($finance_id, false));
             break;
         case 'save_recurring':
             if (isset($_REQUEST['butt_del'])) {
                 $this->delete_recurring($_REQUEST['finance_recurring_id']);
                 redirect_browser(self::link_open_recurring(false));
             }
             $data = $_POST;
             // save the finance categories and account.
             $account_id = $_REQUEST['finance_account_id'];
             if ((string) (int) $account_id != (string) $account_id && strlen($account_id) > 2) {
                 // we have a new account to create.
                 $account_id = update_insert('finance_account_id', 'new', 'finance_account', array('name' => $account_id));
             }
             if (isset($_REQUEST['finance_recurring_id']) && (int) $_REQUEST['finance_recurring_id']) {
                 $original_finance_recurring = self::get_recurring($_REQUEST['finance_recurring_id']);
             } else {
                 $original_finance_recurring = array();
             }
             $data['finance_account_id'] = $account_id;
             $finance_recurring_id = update_insert('finance_recurring_id', isset($_REQUEST['finance_recurring_id']) ? $_REQUEST['finance_recurring_id'] : 'new', 'finance_recurring', $data);
             if ((int) $finance_recurring_id > 0) {
                 $category_ids = isset($_REQUEST['finance_category_id']) && is_array($_REQUEST['finance_category_id']) ? $_REQUEST['finance_category_id'] : array();
                 $sql = "DELETE FROM `" . _DB_PREFIX . "finance_recurring_catrel` WHERE finance_recurring_id = {$finance_recurring_id}";
                 query($sql);
                 foreach ($category_ids as $category_id) {
                     $category_id = (int) $category_id;
                     if ($category_id <= 0) {
                         continue;
                     }
                     $sql = "REPLACE INTO `" . _DB_PREFIX . "finance_recurring_catrel` SET finance_recurring_id = {$finance_recurring_id}, finance_category_id = {$category_id}";
                     query($sql);
                 }
                 if (isset($_REQUEST['finance_category_new']) && strlen(trim($_REQUEST['finance_category_new'])) > 0) {
                     $category_name = trim($_REQUEST['finance_category_new']);
                     $category_id = update_insert('finance_category_id', 'new', 'finance_category', array('name' => $category_name));
                     if (isset($_REQUEST['finance_category_new_checked'])) {
                         $sql = "REPLACE INTO `" . _DB_PREFIX . "finance_recurring_catrel` SET finance_recurring_id = {$finance_recurring_id}, finance_category_id = {$category_id}";
                         query($sql);
                     }
                 }
                 $calculated_next_date = self::calculate_recurring_date($finance_recurring_id);
                 if (isset($data['set_next_due_date']) && $data['set_next_due_date']) {
                     $next_date = input_date($data['set_next_due_date']);
                     $next_due_date_real = module_finance::calculate_recurring_date($finance_recurring_id, true, false);
                     if ($next_date != $next_due_date_real) {
                         // we have accustom date.
                         update_insert('finance_recurring_id', $finance_recurring_id, 'finance_recurring', array('next_due_date' => $next_date, 'next_due_date_custom' => 1));
                     } else {
                         // date is the same. not doing a custom date any more
                         update_insert('finance_recurring_id', $finance_recurring_id, 'finance_recurring', array('next_due_date' => $next_due_date_real, 'next_due_date_custom' => 0));
                     }
                 }
                 /*
                                     $finance_recurring = self::get_recurring($finance_recurring_id);
                                     if($finance_recurring['next_due_date_custom']){
                                         $next_due_date_real = module_finance::calculate_recurring_date($finance_recurring_id,true,false);
                                         // unset the "custom" flag if we've picked the same date as what it should be.
                                         if($next_due_date_real == $finance_recurring['next_due_date']){
                                             module_finance::calculate_recurring_date($finance_recurring_id,true,true);
                                         }
                                     }*/
             }
             set_message('Recurring transaction saved successfully');
             //redirect_browser(self::link_open($finance_id,false));
             redirect_browser(self::link_open_recurring(false, false));
             break;
     }
 }
Exemple #2
0
 public function save_report($report_id, $data)
 {
     if ((int) $report_id > 0) {
         $original_report_data = $this->get_report($report_id);
         if (!$original_report_data || $original_report_data['report_id'] != $report_id) {
             $original_report_data = array();
             $report_id = false;
         }
     } else {
         $original_report_data = array();
         $report_id = false;
     }
     // check create permissions.
     if (!$report_id && !self::can_i('create', 'reports')) {
         // user not allowed to create reports.
         set_error('Unable to create new reports');
         redirect_browser(self::link_open(false));
     }
     $report_id = update_insert("report_id", $report_id, "report", $data);
     module_extra::save_extras('report', 'report_id', $report_id);
     return $report_id;
 }
Exemple #3
0
 public static function save_invoice($invoice_id, $data)
 {
     if (!(int) $invoice_id && isset($data['job_id']) && $data['job_id']) {
         $linkedjob = module_job::get_job($data['job_id']);
         $data['currency_id'] = $linkedjob['currency_id'];
         $data['customer_id'] = $linkedjob['customer_id'];
     }
     if ($invoice_id) {
         // used when working out the hourly rate fix below
         $original_invoice_data = self::get_invoice($invoice_id);
     } else {
         $original_invoice_data = 0;
     }
     $invoice_id = update_insert("invoice_id", $invoice_id, "invoice", $data);
     if ($invoice_id) {
         module_cache::clear('invoice');
         // save the invoice tax rates (copied to finance.php)
         if (isset($data['tax_ids']) && isset($data['tax_names']) && $data['tax_percents']) {
             $existing_taxes = get_multiple('invoice_tax', array('invoice_id' => $invoice_id), 'invoice_tax_id', 'exact', 'order');
             $order = 1;
             foreach ($data['tax_ids'] as $key => $val) {
                 if (isset($data['tax_percents'][$key]) && $data['tax_percents'][$key] == 0) {
                     // we are not saving this particular tax item because it has a 0% tax rate
                 } else {
                     if ((int) $val > 0 && isset($existing_taxes[$val])) {
                         // this means we are trying to update an existing record on the invoice_tax table, we confirm this id matches this invoice.
                         $invoice_tax_id = $val;
                         unset($existing_taxes[$invoice_tax_id]);
                         // so we know which ones to remove from the end.
                     } else {
                         $invoice_tax_id = false;
                         // create new record
                     }
                     $invoice_tax_data = array('invoice_id' => $invoice_id, 'percent' => isset($data['tax_percents'][$key]) ? $data['tax_percents'][$key] : 0, 'amount' => 0, 'name' => isset($data['tax_names'][$key]) ? $data['tax_names'][$key] : 'TAX', 'order' => $order++, 'increment' => isset($data['tax_increment_checkbox']) && $data['tax_increment_checkbox'] ? 1 : 0);
                     $invoice_tax_id = update_insert('invoice_tax_id', $invoice_tax_id, 'invoice_tax', $invoice_tax_data);
                 }
             }
             foreach ($existing_taxes as $existing_tax) {
                 delete_from_db('invoice_tax', array('invoice_id', 'invoice_tax_id'), array($invoice_id, $existing_tax['invoice_tax_id']));
             }
         }
         $invoice_data = self::get_invoice($invoice_id);
         if (!$invoice_data) {
             set_error('No permissions to access invoice.');
             return $invoice_id;
         }
         // check for new invoice_items or changed invoice_items.
         $invoice_items = self::get_invoice_items($invoice_id, $invoice_data);
         if (isset($data['invoice_invoice_item']) && is_array($data['invoice_invoice_item'])) {
             foreach ($data['invoice_invoice_item'] as $invoice_item_id => $invoice_item_data) {
                 $invoice_item_id = (int) $invoice_item_id;
                 if (!is_array($invoice_item_data)) {
                     continue;
                 }
                 if ($invoice_item_id > 0 && !isset($invoice_items[$invoice_item_id])) {
                     continue;
                 }
                 // wrong invoice_item save - will never happen.
                 if (!isset($invoice_item_data['description']) || $invoice_item_data['description'] == '') {
                     if ($invoice_item_id > 0) {
                         // remove invoice_item.
                         $sql = "DELETE FROM `" . _DB_PREFIX . "invoice_item` WHERE invoice_item_id = '{$invoice_item_id}' AND invoice_id = {$invoice_id} LIMIT 1";
                         query($sql);
                     }
                     continue;
                 }
                 // add / save this invoice_item.
                 $invoice_item_data['invoice_id'] = $invoice_id;
                 // what type of task is this?
                 $invoice_task_type = isset($invoice_item_data['manual_task_type']) && $invoice_item_data['manual_task_type'] >= 0 ? $invoice_item_data['manual_task_type'] : $invoice_data['default_task_type'];
                 $invoice_item_data['hours_mins'] = 0;
                 if (isset($invoice_item_data['hours']) && $invoice_task_type == _TASK_TYPE_HOURS_AMOUNT) {
                 }
                 if (isset($invoice_item_data['hours']) && $invoice_task_type == _TASK_TYPE_HOURS_AMOUNT && function_exists('decimal_time_in')) {
                     $invoice_item_data['hours'] = decimal_time_in($invoice_item_data['hours']);
                     if (strpos($invoice_item_data['hours'], ':') !== false) {
                         $invoice_item_data['hours_mins'] = str_replace(":", ".", $invoice_item_data['hours']);
                     }
                 } else {
                     if (isset($invoice_item_data['hours']) && strlen($invoice_item_data['hours'])) {
                         $invoice_item_data['hours'] = number_in($invoice_item_data['hours']);
                     } else {
                         $invoice_item_data['hours'] = 0;
                     }
                 }
                 // number formatting
                 //print_r($invoice_item_data);
                 if (isset($invoice_item_data['hourly_rate']) && strlen($invoice_item_data['hourly_rate'])) {
                     $invoice_item_data['hourly_rate'] = number_in($invoice_item_data['hourly_rate'], module_config::c('task_amount_decimal_places', -1));
                 }
                 //print_r($invoice_item_data);exit;
                 // somenew hacks here to support out new method of creating an item.
                 // the 'amount' column is never edited any more
                 // this column is now always automatically calculated based on
                 // 'hours' and 'hourly_rate'
                 if (!isset($invoice_item_data['amount'])) {
                     if ($invoice_task_type == _TASK_TYPE_AMOUNT_ONLY) {
                         // ignore the quantity field all together.
                         $invoice_item_data['amount'] = $invoice_item_data['hourly_rate'];
                         $invoice_item_data['hourly_rate'] = 0;
                     } else {
                         if (isset($invoice_item_data['hourly_rate']) && strlen($invoice_item_data['hourly_rate']) > 0) {
                             // if we have inputted an hourly rate (ie: not left empty)
                             if (isset($invoice_item_data['hours']) && strlen($invoice_item_data['hours']) == 0) {
                                 // no hours entered (eg: empty) so we treat whatever was in 'hourly_rate' as the amount
                                 $invoice_item_data['amount'] = $invoice_item_data['hourly_rate'];
                             } else {
                                 if (isset($invoice_item_data['hours']) && strlen($invoice_item_data['hours']) > 0) {
                                     // hours inputted, along with hourly rate. work out the new amount.
                                     $invoice_item_data['amount'] = round($invoice_item_data['hours'] * $invoice_item_data['hourly_rate'], module_config::c('currency_decimal_places', 2));
                                 }
                             }
                         }
                     }
                 }
                 if ($invoice_task_type == _TASK_TYPE_HOURS_AMOUNT) {
                     if ($invoice_item_data['hourly_rate'] == $invoice_data['hourly_rate'] || isset($original_invoice_data['hourly_rate']) && $invoice_item_data['hourly_rate'] == $original_invoice_data['hourly_rate']) {
                         $invoice_item_data['hourly_rate'] = -1;
                     }
                 }
                 // remove the amount of it equals the hourly rate.
                 /*if(isset($invoice_item_data['amount']) && isset($invoice_item_data['hours']) && $invoice_item_data['amount'] > 0 && $invoice_item_data['hours'] > 0){
                       if($invoice_item_data['amount'] - ($invoice_item_data['hours'] * $data['hourly_rate']) == 0){
                           unset($invoice_item_data['amount']);
                       }
                   }*/
                 // check if we haven't unticked a non-hourly invoice_item
                 /*if(isset($invoice_item_data['completed_t']) && $invoice_item_data['completed_t'] && !isset($invoice_item_data['completed'])){
                       $invoice_item_data['completed'] = 0;
                   }*/
                 if (!isset($invoice_item_data['taxable_t'])) {
                     $invoice_item_data['taxable'] = module_config::c('task_taxable_default', 1);
                 } else {
                     if (isset($invoice_item_data['taxable_t']) && $invoice_item_data['taxable_t'] && !isset($invoice_item_data['taxable'])) {
                         $invoice_item_data['taxable'] = 0;
                     }
                 }
                 if (!strlen($invoice_item_data['hours'])) {
                     $invoice_item_data['hours'] = 0;
                 }
                 $invoice_item_data['hourly_rate'] = number_out($invoice_item_data['hourly_rate'], false, module_config::c('task_amount_decimal_places', -1));
                 $invoice_item_data['hours'] = number_out($invoice_item_data['hours']);
                 $invoice_item_data['amount'] = number_out($invoice_item_data['amount']);
                 update_insert('invoice_item_id', $invoice_item_id, 'invoice_item', $invoice_item_data);
             }
         }
         $last_payment_time = 0;
         if (isset($data['invoice_invoice_payment']) && is_array($data['invoice_invoice_payment'])) {
             foreach ($data['invoice_invoice_payment'] as $invoice_payment_id => $invoice_payment_data) {
                 $invoice_payment_id = (int) $invoice_payment_id;
                 if (!is_array($invoice_payment_data)) {
                     continue;
                 }
                 if (isset($invoice_payment_data['amount'])) {
                     $invoice_payment_data['amount'] = number_in($invoice_payment_data['amount']);
                     // toggle between 'normal' and 'refund' payment types
                     if (isset($invoice_payment_data['payment_type'])) {
                         if ($invoice_payment_data['amount'] < 0 && $invoice_payment_data['payment_type'] == _INVOICE_PAYMENT_TYPE_NORMAL) {
                             // this is a refund.
                             $invoice_payment_data['payment_type'] = _INVOICE_PAYMENT_TYPE_REFUND;
                         } else {
                             if ($invoice_payment_data['payment_type'] == _INVOICE_PAYMENT_TYPE_REFUND) {
                                 $invoice_payment_data['payment_type'] = _INVOICE_PAYMENT_TYPE_NORMAL;
                             }
                         }
                     }
                 }
                 // check this invoice payment actually matches this invoice.
                 $invoice_payment_data_existing = false;
                 if ($invoice_payment_id > 0) {
                     $invoice_payment_data_existing = get_single('invoice_payment', array('invoice_payment_id', 'invoice_id'), array($invoice_payment_id, $invoice_id));
                     if (!$invoice_payment_data_existing || $invoice_payment_data_existing['invoice_payment_id'] != $invoice_payment_id || $invoice_payment_data_existing['invoice_id'] != $invoice_id) {
                         $invoice_payment_id = 0;
                         $invoice_payment_data_existing = false;
                     }
                 }
                 if (!isset($invoice_payment_data['amount']) || $invoice_payment_data['amount'] == '' || $invoice_payment_data['amount'] == 0) {
                     // || $invoice_payment_data['amount'] <= 0
                     if ($invoice_payment_id > 0) {
                         // if this is a customer credit payment, return that back to the customer account.
                         if ($invoice_payment_data_existing && $invoice_data['customer_id']) {
                             switch ($invoice_payment_data_existing['payment_type']) {
                                 case _INVOICE_PAYMENT_TYPE_CREDIT:
                                     module_customer::add_credit($invoice_data['customer_id'], $invoice_payment_data_existing['amount'], 'Refunded credit from invoice payment');
                                     break;
                             }
                         }
                         // remove invoice_payment.
                         $sql = "DELETE FROM `" . _DB_PREFIX . "invoice_payment` WHERE invoice_payment_id = '{$invoice_payment_id}' AND invoice_id = {$invoice_id} LIMIT 1";
                         query($sql);
                         // delete any existing transactions from the system as well.
                         hook_handle_callback('invoice_payment_deleted', $invoice_payment_id, $invoice_id);
                     }
                     continue;
                 }
                 if (!$invoice_payment_id && (!isset($_REQUEST['add_payment']) || $_REQUEST['add_payment'] != 'go')) {
                     continue;
                     // not saving a new one.
                 }
                 // add / save this invoice_payment.
                 $invoice_payment_data['invoice_id'] = $invoice_id;
                 // $invoice_payment_data['currency_id'] = $invoice_data['currency_id'];
                 $last_payment_time = max($last_payment_time, strtotime(input_date($invoice_payment_data['date_paid'])));
                 if (isset($invoice_payment_data['custom_notes'])) {
                     $details = @unserialize($invoice_payment_data['data']);
                     if (!is_array($details)) {
                         $details = array();
                     }
                     $details['custom_notes'] = $invoice_payment_data['custom_notes'];
                     $invoice_payment_data['data'] = serialize($details);
                 }
                 $invoice_payment_data['amount'] = number_out($invoice_payment_data['amount']);
                 update_insert('invoice_payment_id', $invoice_payment_id, 'invoice_payment', $invoice_payment_data);
             }
         }
         if (!$last_payment_time) {
             $last_payment_time = strtotime(date('Y-m-d'));
         }
         // check if the invoice has been paid
         module_cache::clear('invoice');
         //module_cache::clear_cache(); // this helps fix the bug where part payments are not caulcated a correct paid date.
         $invoice_data = self::get_invoice($invoice_id);
         if (!$invoice_data) {
             set_error('No permissions to access invoice.');
             return $invoice_id;
         }
         if ((!$invoice_data['date_paid'] || $invoice_data['date_paid'] == '0000-00-00') && $invoice_data['total_amount_due'] <= 0 && ($invoice_data['total_amount_paid'] > 0 || $invoice_data['discount_amount'] > 0) && (!$invoice_data['date_cancel'] || $invoice_data['date_cancel'] == '0000-00-00')) {
             // find the date of the last payment history.
             // if the sent date is null also update that.
             $date_sent = $invoice_data['date_sent'];
             if (!$date_sent || $date_sent == '0000-00-00') {
                 $date_sent = date('Y-m-d', $last_payment_time);
             }
             update_insert("invoice_id", $invoice_id, "invoice", array('date_paid' => date('Y-m-d', $last_payment_time), 'date_sent' => $date_sent, 'status' => _l('Paid')));
             // hook for our ticketing plugin to mark a priority support ticket as paid.
             // or anything else down the track.
             module_cache::clear('invoice');
             handle_hook('invoice_paid', $invoice_id);
             if (module_config::c('invoice_automatic_receipt', 1)) {
                 // send receipt to customer.
                 self::email_invoice_to_customer($invoice_id);
             }
         }
         if ($invoice_data['total_amount_due'] > 0) {
             // update the status to unpaid.
             update_insert("invoice_id", $invoice_id, "invoice", array('date_paid' => '', 'status' => $invoice_data['status'] == _l('Paid') ? module_config::s('invoice_status_default', 'New') : $invoice_data['status']));
         }
         if (class_exists('module_extra', false) && module_extra::is_plugin_enabled()) {
             module_extra::save_extras('invoice', 'invoice_id', $invoice_id);
         }
         if ($invoice_data['customer_id']) {
             //module_cache::clear_cache();
             module_cache::clear('invoice');
             module_customer::update_customer_status($invoice_data['customer_id']);
         }
         hook_handle_callback('invoice_saved', $invoice_id, $invoice_data);
     }
     module_cache::clear('invoice');
     module_cache::clear('job');
     return $invoice_id;
 }
Exemple #4
0
    function process()
    {
        if ('plupload' == $_REQUEST['_process']) {
            if (!self::can_i('edit', 'Files') && !self::can_i('create', 'Files')) {
                die('{"jsonrpc" : "2.0", "error" : {"code": 102, "message": "Permission error."}, "id" : "id"}');
            }
            @ob_end_clean();
            // HTTP headers for no cache etc
            header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
            header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
            header("Cache-Control: no-store, no-cache, must-revalidate");
            header("Cache-Control: post-check=0, pre-check=0", false);
            header("Pragma: no-cache");
            // Settings
            $targetDir = _FILE_UPLOAD_PATH . "plupload";
            //$targetDir = 'uploads';
            $cleanupTargetDir = true;
            // Remove old files
            $maxFileAge = 5 * 3600;
            // Temp file age in seconds
            // 5 minutes execution time
            @set_time_limit(5 * 60);
            // Uncomment this one to fake upload time
            // usleep(5000);
            // Get parameters
            $chunk = isset($_REQUEST["chunk"]) ? intval($_REQUEST["chunk"]) : 0;
            $chunks = isset($_REQUEST["chunks"]) ? intval($_REQUEST["chunks"]) : 0;
            $fileName = isset($_REQUEST["plupload_key"]) ? $_REQUEST["plupload_key"] : '';
            $fileName .= isset($_REQUEST["fileid"]) ? '-' . $_REQUEST["fileid"] : '';
            $fileName = preg_replace('/[^a-zA-Z0-9-_]+/', '', $fileName);
            if (!$fileName) {
                die('{"jsonrpc" : "2.0", "error" : {"code": 102, "message": "No plupload_key defined."}, "id" : "id"}');
            }
            // Make sure the fileName is unique but only if chunking is disabled
            if ($chunks < 2 && file_exists($targetDir . DIRECTORY_SEPARATOR . $fileName)) {
                $ext = strrpos($fileName, '.');
                $fileName_a = substr($fileName, 0, $ext);
                $fileName_b = substr($fileName, $ext);
                $count = 1;
                while (file_exists($targetDir . DIRECTORY_SEPARATOR . $fileName_a . '_' . $count . $fileName_b)) {
                    $count++;
                }
                $fileName = $fileName_a . '_' . $count . $fileName_b;
            }
            $filePath = $targetDir . DIRECTORY_SEPARATOR . $fileName;
            // Create target dir
            if (!file_exists($targetDir)) {
                @mkdir($targetDir);
            }
            // Remove old temp files
            if ($cleanupTargetDir) {
                if (!is_dir($targetDir) || !($dir = opendir($targetDir))) {
                    die('{"jsonrpc" : "2.0", "error" : {"code": 100, "message": "Failed to open temp directory."}, "id" : "id"}');
                }
                while (($file = readdir($dir)) !== false) {
                    $tmpfilePath = $targetDir . DIRECTORY_SEPARATOR . $file;
                    // If temp file is current file proceed to the next
                    if ($tmpfilePath == "{$filePath}.part") {
                        continue;
                    }
                    // Remove temp file if it is older than the max age and is not the current file
                    if (preg_match('/\\.part$/', $file) && filemtime($tmpfilePath) < time() - $maxFileAge) {
                        @unlink($tmpfilePath);
                    }
                }
                closedir($dir);
            }
            /// Open temp file
            if (!($out = @fopen("{$filePath}.part", $chunks ? "ab" : "wb"))) {
                die('{"jsonrpc" : "2.0", "error" : {"code": 102, "message": "Failed to open output stream."}, "id" : "id"}');
            }
            if (!empty($_FILES)) {
                if ($_FILES["file"]["error"] || !is_uploaded_file($_FILES["file"]["tmp_name"])) {
                    die('{"jsonrpc" : "2.0", "error" : {"code": 103, "message": "Failed to move uploaded file."}, "id" : "id"}');
                }
                // Read binary input stream and append it to temp file
                if (!($in = @fopen($_FILES["file"]["tmp_name"], "rb"))) {
                    die('{"jsonrpc" : "2.0", "error" : {"code": 101, "message": "Failed to open input stream."}, "id" : "id"}');
                }
            } else {
                if (!($in = @fopen("php://input", "rb"))) {
                    die('{"jsonrpc" : "2.0", "error" : {"code": 101, "message": "Failed to open input stream."}, "id" : "id"}');
                }
            }
            while ($buff = fread($in, 4096)) {
                fwrite($out, $buff);
            }
            @fclose($out);
            @fclose($in);
            // Check if file has been uploaded
            if (!$chunks || $chunk == $chunks - 1) {
                // Strip the temp .part suffix off
                rename("{$filePath}.part", $filePath);
            }
            die('{"jsonrpc" : "2.0", "result" : null, "id" : "id"}');
        } else {
            if ('download' == $_REQUEST['_process']) {
                @ob_end_clean();
                $file_id = (int) $_REQUEST['file_id'];
                $file_data = $this->get_file($file_id);
                if (isset($file_data['file_url']) && strlen($file_data['file_url'])) {
                    redirect_browser($file_data['file_url']);
                } else {
                    if (is_file($file_data['file_path'])) {
                        header("Pragma: public");
                        header("Expires: 0");
                        header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
                        header("Cache-Control: private", false);
                        //header("Content-Type: application/pdf");
                        header("Content-type: " . dtbaker_mime_type($file_data['file_name'], $file_data['file_path']));
                        header("Content-Disposition: attachment; filename=\"" . $file_data['file_name'] . "\";");
                        header("Content-Transfer-Encoding: binary");
                        header("Content-Length: " . filesize($file_data['file_path']));
                        //readfile($file_data['file_path']);
                        $size = @readfile($file_data['file_path']);
                        if (!$size) {
                            echo file_get_contents($file_data['file_path']);
                        }
                    } else {
                        echo 'Not found';
                    }
                }
                exit;
            } else {
                if ('save_file_popup' == $_REQUEST['_process']) {
                    $file_id = $_REQUEST['file_id'];
                    $file_path = false;
                    $file_name = false;
                    $options = unserialize(base64_decode($_REQUEST['options']));
                    // have we uploaded anything
                    if (isset($_FILES['file_upload']) && is_uploaded_file($_FILES['file_upload']['tmp_name'])) {
                        // copy to file area.
                        $file_name = basename($_FILES['file_upload']['name']);
                        if ($file_name) {
                            $file_path = _FILE_UPLOAD_PATH . md5(time() . $file_name);
                            if (move_uploaded_file($_FILES['file_upload']['tmp_name'], $file_path)) {
                                // it worked. umm.. do something.
                            } else {
                                ?>

                    <script type="text/javascript">
                        alert('Unable to save file. Please check permissions.');
                    </script>
                    <?php 
                                // it didnt work. todo: display error.
                                $file_path = false;
                                $file_name = false;
                                //set_error('Unable to save file');
                            }
                        }
                    }
                    if (isset($_REQUEST['file_name']) && $_REQUEST['file_name']) {
                        $file_name = $_REQUEST['file_name'];
                    }
                    if (!$file_path && !$file_name) {
                        return false;
                    }
                    if (!$file_id || $file_id == 'new') {
                        $file_data = array('file_id' => $file_id, 'owner_id' => (int) $_REQUEST['owner_id'], 'owner_table' => $_REQUEST['owner_table'], 'file_time' => time(), 'file_name' => $file_name, 'file_path' => $file_path);
                    } else {
                        // some fields we dont want to overwrite on existing files:
                        $file_data = array('file_id' => $file_id, 'file_path' => $file_path, 'file_name' => $file_name);
                    }
                    // make sure we're saving a file we have access too.
                    module_security::sanatise_data('file', $file_data);
                    $file_id = update_insert('file_id', $file_id, 'file', $file_data);
                    $file_data = $this->get_file($file_id);
                    // we've updated from a popup.
                    // this means we have to replace an existing file id with the updated output.
                    // or if none exists on the page, we add a new one to the holder.
                    $layout_type = isset($_REQUEST['layout']) && $_REQUEST['layout'] ? $_REQUEST['layout'] : 'gallery';
                    ?>

			<script type="text/javascript">
				// check if it exists in parent window
				var new_html = '<?php 
                    echo addcslashes(preg_replace('/\\s+/', ' ', $this->print_file($file_id, $layout_type, true, $options)), "'");
                    ?>
';
				parent.new_file_added<?php 
                    echo $file_data['owner_table'];
                    ?>
_<?php 
                    echo $file_data['owner_id'];
                    ?>
(<?php 
                    echo $file_id;
                    ?>
,'<?php 
                    echo $file_data['owner_table'];
                    ?>
',<?php 
                    echo $file_data['owner_id'];
                    ?>
,new_html);
			</script>
			<?php 
                    exit;
                } else {
                    if ('save_file' == $_REQUEST['_process']) {
                        $file_id = (int) $_REQUEST['file_id'];
                        $file_path = false;
                        $file_name = false;
                        $file_url = '';
                        if (isset($_REQUEST['butt_del']) && self::can_i('delete', 'Files')) {
                            if (module_form::confirm_delete('file_id', 'Really delete this file?')) {
                                $ucm_file = new ucm_file($file_id);
                                $ucm_file->delete();
                                set_message('File removed successfully');
                            }
                            redirect_browser(module_file::link_open(false));
                        } else {
                            $files_to_save = array();
                            // pump data in to here for multiple file uploads.
                            // todo: stop people changing the "file_id" to another file they don't own.
                            if (self::can_i('edit', 'Files') || self::can_i('create', 'Files')) {
                                // have we uploaded anything
                                $file_changed = false;
                                if (isset($_REQUEST['plupload_key']) && isset($_REQUEST['plupload_file_name']) && is_array($_REQUEST['plupload_file_name']) && strlen(preg_replace('/[^a-zA-Z0-9-_]+/', '', basename($_REQUEST['plupload_key'])))) {
                                    $plupload_key = preg_replace('/[^a-zA-Z0-9-_]+/', '', basename($_REQUEST['plupload_key']));
                                    foreach ($_REQUEST['plupload_file_name'] as $plupload_file_name_key => $file_name) {
                                        $plupload_file_name_key = preg_replace('/[^a-zA-Z0-9-_]+/', '', basename($plupload_file_name_key));
                                        if ($plupload_key && $plupload_file_name_key && $file_name && is_file(_FILE_UPLOAD_PATH . 'plupload' . DIRECTORY_SEPARATOR . $plupload_key . '-' . $plupload_file_name_key)) {
                                            $file_path = _FILE_UPLOAD_PATH . time() . '-' . md5(time() . $file_name);
                                            if (rename(_FILE_UPLOAD_PATH . 'plupload' . DIRECTORY_SEPARATOR . $plupload_key . '-' . $plupload_file_name_key, $file_path)) {
                                                // it worked. umm.. do something.
                                                $file_changed = true;
                                                $files_to_save[] = array('file_path' => $file_path, 'file_name' => $file_name);
                                            } else {
                                                // it didnt work. todo: display error.
                                                $file_path = false;
                                                $file_name = false;
                                                set_error('Unable to save file via plupload.');
                                            }
                                        }
                                    }
                                }
                                // the old file upload method, no plupload:
                                if (!$file_changed && isset($_FILES['file_upload']) && is_uploaded_file($_FILES['file_upload']['tmp_name'])) {
                                    // copy to file area.
                                    $file_name = basename($_FILES['file_upload']['name']);
                                    if ($file_name) {
                                        $file_path = _FILE_UPLOAD_PATH . time() . '-' . md5(time() . $file_name);
                                        if (move_uploaded_file($_FILES['file_upload']['tmp_name'], $file_path)) {
                                            // it worked. umm.. do something.
                                            $file_changed = true;
                                            $files_to_save[] = array('file_path' => $file_path, 'file_name' => $file_name);
                                        } else {
                                            // it didnt work. todo: display error.
                                            $file_path = false;
                                            $file_name = false;
                                            set_error('Unable to save file');
                                        }
                                    }
                                }
                                if (!$file_path && isset($_REQUEST['file_url']) && isset($_REQUEST['file_name'])) {
                                    $files_to_save[] = array('file_path' => '', 'file_url' => $_REQUEST['file_url'], 'file_name' => $_REQUEST['file_name']);
                                }
                                if (!$file_path && isset($_REQUEST['bucket'])) {
                                    $files_to_save[] = array('file_name' => $_REQUEST['file_name'], 'bucket' => 1);
                                }
                                // make sure we have a valid customer_id and job_id selected.
                                $possible_customers = $possible_jobs = array();
                                if (class_exists('module_customer', false)) {
                                    $possible_customers = module_customer::get_customers();
                                }
                                if (class_exists('module_job', false)) {
                                    $possible_jobs = module_job::get_jobs();
                                }
                                $original_file_data = array();
                                if ($file_id > 0) {
                                    $original_file_data = self::get_file($file_id);
                                    if (!$original_file_data || $original_file_data['file_id'] != $file_id) {
                                        die('No permissions to update this file');
                                    }
                                }
                                $new_file = false;
                                if (!$file_id) {
                                    $file_data = array('file_id' => $file_id, 'bucket_parent_file_id' => isset($_REQUEST['bucket_parent_file_id']) ? (int) $_REQUEST['bucket_parent_file_id'] : false, 'customer_id' => isset($_REQUEST['customer_id']) ? (int) $_REQUEST['customer_id'] : false, 'job_id' => isset($_REQUEST['job_id']) ? (int) $_REQUEST['job_id'] : false, 'quote_id' => isset($_REQUEST['quote_id']) ? (int) $_REQUEST['quote_id'] : false, 'website_id' => isset($_REQUEST['website_id']) ? (int) $_REQUEST['website_id'] : false, 'status' => isset($_REQUEST['status']) ? $_REQUEST['status'] : false, 'pointers' => isset($_REQUEST['pointers']) ? $_REQUEST['pointers'] : false, 'description' => isset($_REQUEST['description']) ? $_REQUEST['description'] : false, 'file_time' => time());
                                    if (!isset($possible_customers[$file_data['customer_id']])) {
                                        $file_data['customer_id'] = 0;
                                    }
                                    if (!isset($possible_jobs[$file_data['job_id']])) {
                                        $file_data['job_id'] = 0;
                                    }
                                    $new_file = true;
                                } else {
                                    // some fields we dont want to overwrite on existing files:
                                    $file_data = array('file_id' => $file_id, 'bucket_parent_file_id' => isset($_REQUEST['bucket_parent_file_id']) ? (int) $_REQUEST['bucket_parent_file_id'] : false, 'pointers' => isset($_REQUEST['pointers']) ? $_REQUEST['pointers'] : false, 'customer_id' => isset($_REQUEST['customer_id']) ? (int) $_REQUEST['customer_id'] : false, 'job_id' => isset($_REQUEST['job_id']) ? (int) $_REQUEST['job_id'] : false, 'quote_id' => isset($_REQUEST['quote_id']) ? (int) $_REQUEST['quote_id'] : false, 'website_id' => isset($_REQUEST['website_id']) ? (int) $_REQUEST['website_id'] : false, 'status' => isset($_REQUEST['status']) ? $_REQUEST['status'] : false, 'description' => isset($_REQUEST['description']) ? $_REQUEST['description'] : false);
                                    if (!isset($possible_customers[$file_data['customer_id']]) && $file_data['customer_id'] != $original_file_data['customer_id']) {
                                        $file_data['customer_id'] = $original_file_data['customer_id'];
                                    }
                                    if ($file_data['job_id'] && !isset($possible_jobs[$file_data['job_id']]) && $file_data['job_id'] != $original_file_data['job_id']) {
                                        $file_data['job_id'] = $original_file_data['job_id'];
                                    }
                                }
                                $sub_bucket_fields = array('customer_id', 'job_id', 'quote_id', 'website_id');
                                if ($file_data['bucket_parent_file_id']) {
                                    // we're saving a sub bucket file, pull in the file data from the parent file.
                                    $parent_file = new ucm_file($file_data['bucket_parent_file_id']);
                                    $parent_file_data = $parent_file->get_data();
                                    foreach ($sub_bucket_fields as $sub_bucket_field) {
                                        $file_data[$sub_bucket_field] = $parent_file_data[$sub_bucket_field];
                                    }
                                }
                                if (!count($files_to_save)) {
                                    $files_to_save[] = array();
                                }
                                foreach ($files_to_save as $id => $file_to_save) {
                                    $file_data_to_save = array_merge($file_data, $file_to_save);
                                    $files_to_save[$id]['file_id'] = update_insert('file_id', $file_data['file_id'], 'file', $file_data_to_save);
                                    $file_data['file_id'] = 0;
                                    // incease we're uploading multiple files
                                    if (isset($_POST['staff_ids_save']) && (int) $files_to_save[$id]['file_id'] > 0) {
                                        delete_from_db('file_user_rel', array('file_id'), array($files_to_save[$id]['file_id']));
                                        if (isset($_POST['staff_ids']) && is_array($_POST['staff_ids'])) {
                                            foreach ($_POST['staff_ids'] as $staff_id) {
                                                $sql = "REPLACE INTO `" . _DB_PREFIX . "file_user_rel` SET ";
                                                $sql .= " `user_id` = " . (int) $staff_id;
                                                $sql .= ", `file_id` = " . (int) $files_to_save[$id]['file_id'];
                                                query($sql);
                                            }
                                        }
                                    }
                                    if ($files_to_save[$id]['file_id'] > 0 && isset($file_data_to_save['bucket']) && $file_data_to_save['bucket']) {
                                        // update certain fields of all the child files to match the parent bucket.
                                        $search = array('bucket_parent_file_id' => $files_to_save[$id]['file_id']);
                                        $sub_files = module_file::get_files($search);
                                        $vals = array();
                                        foreach ($sub_bucket_fields as $field) {
                                            $vals[$field] = isset($file_data_to_save[$field]) ? $file_data_to_save[$field] : false;
                                        }
                                        foreach ($sub_files as $sub_file) {
                                            update_insert('file_id', $sub_file['file_id'], 'file', $vals);
                                            // and save the staff assignment manually too
                                            if (isset($_POST['staff_ids_save']) && (int) $sub_file['file_id'] > 0) {
                                                delete_from_db('file_user_rel', array('file_id'), array($sub_file['file_id']));
                                                if (isset($_POST['staff_ids']) && is_array($_POST['staff_ids'])) {
                                                    foreach ($_POST['staff_ids'] as $staff_id) {
                                                        $sql = "REPLACE INTO `" . _DB_PREFIX . "file_user_rel` SET ";
                                                        $sql .= " `user_id` = " . (int) $staff_id;
                                                        $sql .= ", `file_id` = " . (int) $sub_file['file_id'];
                                                        query($sql);
                                                    }
                                                }
                                            }
                                        }
                                    }
                                    module_extra::save_extras('file', 'file_id', $files_to_save[$id]['file_id']);
                                    if ($file_changed) {
                                        $this->send_file_changed_notice($files_to_save[$id]['file_id'], $new_file);
                                    }
                                    // file changed
                                }
                            }
                            if (module_file::can_i('create', 'File Comments')) {
                                $this->save_file_comments($file_id);
                            }
                            if (isset($_REQUEST['delete_file_comment_id']) && $_REQUEST['delete_file_comment_id']) {
                                $file_comment_id = (int) $_REQUEST['delete_file_comment_id'];
                                $comment = get_single('file_comment', 'file_comment_id', $file_comment_id);
                                if ($comment['create_user_id'] == module_security::get_loggedin_id() || module_file::can_i('delete', 'File Comments')) {
                                    $sql = "DELETE FROM `" . _DB_PREFIX . "file_comment` WHERE file_id = '" . (int) $file_id . "' AND file_comment_id = '{$file_comment_id}' ";
                                    $sql .= " LIMIT 1";
                                    query($sql);
                                }
                            }
                            if (isset($_REQUEST['butt_email']) && $_REQUEST['butt_email'] && module_file::can_i('edit', 'File Approval')) {
                                redirect_browser($this->link_open_email($file_id));
                            }
                            if (count($files_to_save)) {
                                if (count($files_to_save) > 1) {
                                    $file_id = false;
                                    set_message(_l('%s Files saved successfully', count($files_to_save)));
                                } else {
                                    set_message(_l('File saved successfully'));
                                    $file_id = $files_to_save[0]['file_id'];
                                }
                            }
                            redirect_browser($this->link_open($file_id));
                        }
                    } else {
                        if ('delete_file_popup' == $_REQUEST['_process']) {
                            $file_id = (int) $_REQUEST['file_id'];
                            if (!$file_id || $file_id == 'new') {
                                // cant delete a new file.. do nothing.
                            } else {
                                $file_data = $this->get_file($file_id);
                                if (true) {
                                    //module_security::can_access_data('file',$file_data,$file_id)){
                                    // delete the physical file.
                                    if (is_file($file_data['file_path'])) {
                                        unlink($file_data['file_path']);
                                    }
                                    // delete the db entry.
                                    delete_from_db('file', 'file_id', $file_id);
                                    // update ui with changes.
                                    ?>

					<script type="text/javascript">
						var new_html = '';
						parent.new_file_added<?php 
                                    echo $file_data['owner_table'];
                                    ?>
_<?php 
                                    echo $file_data['owner_id'];
                                    ?>
(<?php 
                                    echo $file_id;
                                    ?>
,'<?php 
                                    echo $file_data['owner_table'];
                                    ?>
',<?php 
                                    echo $file_data['owner_id'];
                                    ?>
,new_html);
					</script>
					<?php 
                                }
                            }
                            exit;
                        }
                    }
                }
            }
        }
    }
Exemple #5
0
 public function save_subscription($subscription_id, $data)
 {
     if (isset($data['settings'])) {
         $data['settings'] = json_encode($data['settings']);
     }
     if (isset($data['default_automatic_renew']) && !isset($data['automatic_renew'])) {
         $data['automatic_renew'] = 0;
     }
     if (isset($data['default_automatic_email']) && !isset($data['automatic_email'])) {
         $data['automatic_email'] = 0;
     }
     $subscription_id = update_insert("subscription_id", $subscription_id, "subscription", $data);
     module_extra::save_extras('subscription', 'subscription_id', $subscription_id);
     return $subscription_id;
 }
Exemple #6
0
 public function save_product($product_id, $data)
 {
     if (isset($data['default_billable']) && !isset($data['billable'])) {
         $data['billable'] = 0;
     }
     if (isset($data['default_taxable']) && !isset($data['taxable'])) {
         $data['taxable'] = 0;
     }
     $product_id = update_insert("product_id", $product_id, "product", $data);
     module_extra::save_extras('product', 'product_id', $product_id);
     return $product_id;
 }
Exemple #7
0
 public static function save_quote($quote_id, $data)
 {
     if (isset($data['customer_id']) && $data['customer_id'] > 0) {
         // check we have access to this customer from this quote.
         $customer_check = module_customer::get_customer($data['customer_id']);
         if (!$customer_check || $customer_check['customer_id'] != $data['customer_id']) {
             unset($data['customer_id']);
         }
     }
     if (isset($data['website_id']) && $data['website_id']) {
         $website = module_website::get_website($data['website_id']);
         if ($website && (int) $website['website_id'] > 0 && $website['website_id'] == $data['website_id']) {
             // website exists.
             // make this one match the website customer_id, or set teh website customer_id if it doesn't have any.
             if ((int) $website['customer_id'] > 0) {
                 if ($data['customer_id'] > 0 && $data['customer_id'] != $website['customer_id']) {
                     set_message('Changed this Quote to match the Website customer');
                 }
                 $data['customer_id'] = $website['customer_id'];
             } else {
                 if (isset($data['customer_id']) && $data['customer_id'] > 0) {
                     // set the website customer id to this as well.
                     update_insert('website_id', $website['website_id'], 'website', array('customer_id' => $data['customer_id']));
                 }
             }
         }
     }
     if ((int) $quote_id > 0) {
         $original_quote_data = self::get_quote($quote_id, false);
         if (!$original_quote_data || $original_quote_data['quote_id'] != $quote_id) {
             $original_quote_data = array();
             $quote_id = false;
         }
     } else {
         $original_quote_data = array();
         $quote_id = false;
     }
     // check create permissions.
     if (!$quote_id && !self::can_i('create', 'Quotes')) {
         // user not allowed to create quotes.
         set_error('Unable to create new Quotes');
         redirect_browser(self::link_open(false));
     }
     if (!(int) $quote_id && module_config::c('quote_name_incrementing', 0)) {
         // incrememnt next quote number on save.
         $quote_number = module_config::c('quote_name_incrementing_next', 1);
         module_config::save_config('quote_name_incrementing_next', $quote_number + 1);
     }
     $quote_id = update_insert("quote_id", $quote_id, "quote", $data);
     $return = false;
     if ($quote_id) {
         hook_handle_callback('quote_save', $quote_id);
         // save the quote tax rates (copied from invoice.php)
         if (isset($data['tax_ids']) && isset($data['tax_names']) && $data['tax_percents']) {
             $existing_taxes = get_multiple('quote_tax', array('quote_id' => $quote_id), 'quote_tax_id', 'exact', 'order');
             $order = 1;
             foreach ($data['tax_ids'] as $key => $val) {
                 if (isset($data['tax_percents'][$key]) && $data['tax_percents'][$key] == 0) {
                     // we are not saving this particular tax item because it has a 0% tax rate
                 } else {
                     if ((int) $val > 0 && isset($existing_taxes[$val])) {
                         // this means we are trying to update an existing record on the quote_tax table, we confirm this id matches this quote.
                         $quote_tax_id = $val;
                         unset($existing_taxes[$quote_tax_id]);
                         // so we know which ones to remove from the end.
                     } else {
                         $quote_tax_id = false;
                         // create new record
                     }
                     $quote_tax_data = array('quote_id' => $quote_id, 'percent' => isset($data['tax_percents'][$key]) ? $data['tax_percents'][$key] : 0, 'amount' => 0, 'name' => isset($data['tax_names'][$key]) ? $data['tax_names'][$key] : 'TAX', 'order' => $order++, 'increment' => isset($data['tax_increment_checkbox']) && $data['tax_increment_checkbox'] ? 1 : 0);
                     $quote_tax_id = update_insert('quote_tax_id', $quote_tax_id, 'quote_tax', $quote_tax_data);
                 }
             }
             foreach ($existing_taxes as $existing_tax) {
                 delete_from_db('quote_tax', array('quote_id', 'quote_tax_id'), array($quote_id, $existing_tax['quote_tax_id']));
             }
         }
         module_cache::clear('quote');
         $return = array('quote_id' => $quote_id, 'task_result' => self::save_quote_tasks($quote_id, $data));
         $check_completed = true;
         switch ($return['task_result']['status']) {
             case 'created':
                 // we added a new task.
                 break;
             case 'deleted':
                 // we deleted a task.
                 break;
             case 'edited':
                 // we changed a task (ie: completed?);
                 break;
             default:
                 // nothing changed.
                 // $check_completed = false;
                 break;
         }
         if ($check_completed) {
             self::update_quote_completion_status($quote_id);
         }
         if ($original_quote_data) {
             // we check if the hourly rate has changed
             if (isset($data['hourly_rate']) && $data['hourly_rate'] != $original_quote_data['hourly_rate']) {
                 // update all the task hours, but only for hourly tasks:
                 $sql = "UPDATE `" . _DB_PREFIX . "quote_task` SET `amount` = 0 WHERE `hours` > 0 AND quote_id = " . (int) $quote_id . " AND ( manual_task_type = " . _TASK_TYPE_HOURS_AMOUNT;
                 if ($data['default_task_type'] == _TASK_TYPE_HOURS_AMOUNT) {
                     $sql .= " OR manual_task_type = -1 ";
                 }
                 $sql .= " )";
                 query($sql);
             }
             // check if the quote assigned user id has changed.
             if (module_config::c('quote_allow_staff_assignment', 1)) {
                 if (isset($data['user_id'])) {
                     // && $data['user_id'] != $original_quote_data['user_id']){
                     // user id has changed! update any that were the old user id.
                     $sql = "UPDATE `" . _DB_PREFIX . "quote_task` SET `user_id` = " . (int) $data['user_id'] . " WHERE (`user_id` = " . (int) $original_quote_data['user_id'] . " OR user_id = 0) AND quote_id = " . (int) $quote_id;
                     query($sql);
                 }
             }
             // check if the quote was approved.
             if (!isset($original_quote_data['date_approved']) || !$original_quote_data['date_approved'] || $original_quote_data['date_approved'] == '0000-00-00') {
                 // original quote wasn't approved.
                 if (isset($data['date_approved']) && !empty($data['date_approved']) && $data['date_approved'] != '0000-00-00') {
                     // quote was approved!
                     self::quote_approved($quote_id);
                 }
             }
         }
     }
     if (class_exists('module_extra', false) && module_extra::is_plugin_enabled()) {
         module_extra::save_extras('quote', 'quote_id', $quote_id);
     }
     module_cache::clear('quote');
     return $return;
 }
Exemple #8
0
 public static function save_job($job_id, $data)
 {
     if (isset($data['default_renew_auto']) && !isset($data['renew_auto'])) {
         $data['renew_auto'] = 0;
     }
     if (isset($data['default_renew_invoice']) && !isset($data['renew_invoice'])) {
         $data['renew_invoice'] = 0;
     }
     if (isset($data['total_percent_complete_override']) && $data['total_percent_complete_override'] != '' && $data['total_percent_complete_override'] <= 100) {
         $data['total_percent_complete_manual'] = 1;
         $data['total_percent_complete'] = $data['total_percent_complete_override'] / 100;
     } else {
         $data['total_percent_complete_manual'] = 0;
     }
     if (isset($data['customer_id']) && $data['customer_id'] > 0) {
         // check we have access to this customer from this job.
         $customer_check = module_customer::get_customer($data['customer_id']);
         if (!$customer_check || $customer_check['customer_id'] != $data['customer_id']) {
             unset($data['customer_id']);
         }
     }
     if (isset($data['website_id']) && $data['website_id']) {
         $website = module_website::get_website($data['website_id']);
         if ($website && (int) $website['website_id'] > 0 && $website['website_id'] == $data['website_id']) {
             // website exists.
             // make this one match the website customer_id, or set teh website customer_id if it doesn't have any.
             if ((int) $website['customer_id'] > 0) {
                 if ($data['customer_id'] > 0 && $data['customer_id'] != $website['customer_id']) {
                     set_message('Changed this Job to match the Website customer');
                 }
                 $data['customer_id'] = $website['customer_id'];
             } else {
                 if (isset($data['customer_id']) && $data['customer_id'] > 0) {
                     // set the website customer id to this as well.
                     update_insert('website_id', $website['website_id'], 'website', array('customer_id' => $data['customer_id']));
                 }
             }
         }
     }
     if ((int) $job_id > 0) {
         $original_job_data = self::get_job($job_id, false);
         if (!$original_job_data || $original_job_data['job_id'] != $job_id) {
             $original_job_data = array();
             $job_id = false;
         }
     } else {
         $original_job_data = array();
         $job_id = false;
     }
     if (!(int) $job_id && module_config::c('job_name_incrementing', 0)) {
         // incrememnt next job number on save.
         $job_number = module_config::c('job_name_incrementing_next', 1);
         module_config::save_config('job_name_incrementing_next', $job_number + 1);
     }
     $job_id = update_insert("job_id", $job_id, "job", $data);
     if ($job_id) {
         // save the job tax rates (copied from invoice.php)
         if (isset($data['tax_ids']) && isset($data['tax_names']) && $data['tax_percents']) {
             $existing_taxes = get_multiple('job_tax', array('job_id' => $job_id), 'job_tax_id', 'exact', 'order');
             $order = 1;
             foreach ($data['tax_ids'] as $key => $val) {
                 if (isset($data['tax_percents'][$key]) && $data['tax_percents'][$key] == 0) {
                     // we are not saving this particular tax item because it has a 0% tax rate
                 } else {
                     if ((int) $val > 0 && isset($existing_taxes[$val])) {
                         // this means we are trying to update an existing record on the job_tax table, we confirm this id matches this job.
                         $job_tax_id = $val;
                         unset($existing_taxes[$job_tax_id]);
                         // so we know which ones to remove from the end.
                     } else {
                         $job_tax_id = false;
                         // create new record
                     }
                     $job_tax_data = array('job_id' => $job_id, 'percent' => isset($data['tax_percents'][$key]) ? $data['tax_percents'][$key] : 0, 'amount' => 0, 'name' => isset($data['tax_names'][$key]) ? $data['tax_names'][$key] : 'TAX', 'order' => $order++, 'increment' => isset($data['tax_increment_checkbox']) && $data['tax_increment_checkbox'] ? 1 : 0);
                     $job_tax_id = update_insert('job_tax_id', $job_tax_id, 'job_tax', $job_tax_data);
                 }
             }
             foreach ($existing_taxes as $existing_tax) {
                 delete_from_db('job_tax', array('job_id', 'job_tax_id'), array($job_id, $existing_tax['job_tax_id']));
             }
         }
         module_cache::clear('job');
         $result = self::save_job_tasks($job_id, $data);
         $check_completed = true;
         switch ($result['status']) {
             case 'created':
                 // we added a new task.
                 break;
             case 'deleted':
                 // we deleted a task.
                 break;
             case 'edited':
                 // we changed a task (ie: completed?);
                 break;
             default:
                 // nothing changed.
                 // $check_completed = false;
                 break;
         }
         if ($check_completed) {
             self::update_job_completion_status($job_id);
         }
         if ($original_job_data) {
             // we check if the hourly rate has changed
             if (isset($data['hourly_rate']) && $data['hourly_rate'] != $original_job_data['hourly_rate']) {
                 // update all the task hours, but only for hourly tasks:
                 $sql = "UPDATE `" . _DB_PREFIX . "task` SET `amount` = 0 WHERE `hours` > 0 AND job_id = " . (int) $job_id . " AND ( manual_task_type = " . _TASK_TYPE_HOURS_AMOUNT;
                 if ($data['default_task_type'] == _TASK_TYPE_HOURS_AMOUNT) {
                     $sql .= " OR manual_task_type = -1 ";
                 }
                 $sql .= " )";
                 query($sql);
             }
             // check if the job assigned user id has changed.
             if (module_config::c('job_allow_staff_assignment', 1)) {
                 if (isset($data['user_id'])) {
                     // && $data['user_id'] != $original_job_data['user_id']){
                     // user id has changed! update any that were the old user id.
                     $sql = "UPDATE `" . _DB_PREFIX . "task` SET `user_id` = " . (int) $data['user_id'] . " WHERE (`user_id` = " . (int) $original_job_data['user_id'] . " OR user_id = 0) AND job_id = " . (int) $job_id;
                     query($sql);
                 }
             }
             // check if the due date has changed.
             if (isset($original_job_data['date_due']) && $original_job_data['date_due'] && isset($data['date_due']) && $data['date_due'] && $data['date_due'] != '0000-00-00' && $original_job_data['date_due'] != $data['date_due']) {
                 // the date has changed.
                 // update all the tasks with this new date.
                 $tasks = self::get_tasks($job_id);
                 foreach ($tasks as $task) {
                     if (!$task['date_due'] || $task['date_due'] == '0000-00-00') {
                         // no previously set task date. set it
                         update_insert('task_id', $task['task_id'], 'task', array('date_due' => $data['date_due']));
                     } else {
                         if ($task['date_due'] == $original_job_data['date_due']) {
                             // the date was the old date. do we change it?
                             // only change it on incompleted tasks.
                             $percentage = self::get_percentage($task);
                             if ($percentage < 1 || module_config::c('job_tasks_overwrite_completed_due_dates', 0) && $percentage == 1) {
                                 update_insert('task_id', $task['task_id'], 'task', array('date_due' => $data['date_due']));
                             }
                         } else {
                             // there's a new date
                             if (module_config::c('job_tasks_overwrite_diff_due_date', 0)) {
                                 update_insert('task_id', $task['task_id'], 'task', array('date_due' => $data['date_due']));
                             }
                         }
                     }
                 }
             }
         }
     }
     if (class_exists('module_extra', false) && module_extra::is_plugin_enabled()) {
         module_extra::save_extras('job', 'job_id', $job_id);
     }
     module_cache::clear('job');
     return $job_id;
 }
Exemple #9
0
 public function external_hook($hook)
 {
     switch ($hook) {
         case 'public_signup_form':
             $signup_form = module_template::get_template_by_key('customer_signup_form_wrapper');
             $signup_form->page_title = $signup_form->description;
             $signup_form->assign_values(array('signup_form' => self::get_customer_signup_form_html()));
             echo $signup_form->render('pretty_html');
             exit;
         case 'public_signup':
             // sign out if testing.
             if (module_security::is_logged_in()) {
                 set_message('Logged out due to signup');
                 module_security::logout();
             }
             $result = array('messages' => array());
             function customer_signup_complete($result)
             {
                 if (isset($_REQUEST['via_ajax'])) {
                     echo json_encode($result);
                 } else {
                     echo implode('<br/>', $result['messages']);
                 }
                 exit;
             }
             if (!module_config::c('customer_signup_allowed', 0)) {
                 $result['error'] = 1;
                 $result['messages'][] = 'Customer signup disabled';
                 customer_signup_complete($result);
             }
             //recaptcha on signup form.
             if (module_config::c('captcha_on_signup_form', 0)) {
                 if (!module_captcha::check_captcha_form()) {
                     $result['error'] = 1;
                     $result['messages'][] = 'Captcha fail, please go back and enter correct captcha code.';
                     customer_signup_complete($result);
                 }
             }
             $customer = isset($_POST['customer']) && is_array($_POST['customer']) ? $_POST['customer'] : array();
             $contact = isset($_POST['contact']) && is_array($_POST['contact']) ? $_POST['contact'] : array();
             $contact_extra = isset($contact['extra']) && is_array($contact['extra']) ? $contact['extra'] : array();
             $contact_group = isset($contact['group_ids']) && is_array($contact['group_ids']) ? $contact['group_ids'] : array();
             $customer_extra = isset($customer['extra']) ? $customer['extra'] : array();
             $customer_group = isset($customer['group_ids']) && is_array($customer['group_ids']) ? $customer['group_ids'] : array();
             $address = isset($_POST['address']) ? $_POST['address'] : array();
             $website = isset($_POST['website']) ? $_POST['website'] : array();
             $website_extra = isset($website['extra']) ? $website['extra'] : array();
             $website_group = isset($website['group_ids']) && is_array($website['group_ids']) ? $website['group_ids'] : array();
             $job = isset($_POST['job']) ? $_POST['job'] : array();
             $job_extra = isset($job['extra']) ? $job['extra'] : array();
             $subscription = isset($_POST['subscription']) ? $_POST['subscription'] : array();
             // sanatise possibly problematic fields:
             // customer:
             $allowed = array('name', 'last_name', 'customer_name', 'email', 'phone', 'mobile', 'extra', 'type');
             foreach ($customer as $key => $val) {
                 if (!in_array($key, $allowed)) {
                     unset($customer[$key]);
                 }
             }
             if (isset($customer['type']) && $customer['type'] != _CUSTOMER_TYPE_NORMAL && $customer['type'] != _CUSTOMER_TYPE_LEAD) {
                 unset($customer['type']);
             }
             // added multiple contact support in the form of arrays.
             $contact_fields = array('name', 'last_name', 'email', 'phone');
             if (module_config::c('customer_signup_password', 0)) {
                 $contact_fields[] = 'password';
             }
             foreach ($contact_fields as $multi_value) {
                 if (isset($contact[$multi_value])) {
                     if (!is_array($contact[$multi_value])) {
                         $contact[$multi_value] = array($contact[$multi_value]);
                     }
                 } else {
                     if (isset($customer[$multi_value])) {
                         $contact[$multi_value] = array($customer[$multi_value]);
                     } else {
                         $contact[$multi_value] = array();
                     }
                 }
             }
             $valid_contact_email = false;
             $name_fallback = false;
             $primary_email = false;
             foreach ($contact['email'] as $contact_key => $email) {
                 if (!$name_fallback && isset($contact['name'][$contact_key])) {
                     $name_fallback = $contact['name'][$contact_key];
                 }
                 $contact['email'][$contact_key] = filter_var(strtolower(trim($email)), FILTER_VALIDATE_EMAIL);
                 if ($contact['email'][$contact_key]) {
                     $valid_contact_email = true;
                     if (!$primary_email) {
                         $primary_email = $contact['email'][$contact_key];
                         // set the primary contact details here by adding them to the master customer array
                         foreach ($contact_fields as $primary_contact_field) {
                             $customer[$primary_contact_field] = isset($contact[$primary_contact_field][$contact_key]) ? $contact[$primary_contact_field][$contact_key] : '';
                             unset($contact[$primary_contact_field][$contact_key]);
                         }
                     }
                 }
             }
             // start error checking / required fields
             if (!isset($customer['customer_name']) || !strlen($customer['customer_name'])) {
                 $customer['customer_name'] = $name_fallback;
             }
             if (!strlen($customer['customer_name'])) {
                 $result['error'] = 1;
                 $result['messages'][] = "Failed, please go back and provide a customer name.";
             }
             if (!$valid_contact_email || !$primary_email) {
                 $result['error'] = 1;
                 $result['messages'][] = "Failed, please go back and provide an email address.";
             }
             // check all posted required fields.
             function check_required($postdata, $messages = array())
             {
                 if (is_array($postdata)) {
                     foreach ($postdata as $key => $val) {
                         if (strpos($key, '_required') && strlen($val)) {
                             $required_key = str_replace('_required', '', $key);
                             if (!isset($postdata[$required_key]) || !$postdata[$required_key]) {
                                 $messages[] = 'Required field missing: ' . htmlspecialchars($val);
                             }
                         }
                         if (is_array($val)) {
                             $messages = check_required($val, $messages);
                         }
                     }
                 }
                 return $messages;
             }
             $messages = check_required($_POST);
             if (count($messages)) {
                 $result['error'] = 1;
                 $result['messages'] = array_merge($result['messages'], $messages);
             }
             if (isset($result['error'])) {
                 customer_signup_complete($result);
             }
             // end error checking / required fields.
             // check if this customer already exists in the system, based on email address
             $customer_id = false;
             $creating_new = true;
             $_REQUEST['user_id'] = 0;
             if (isset($customer['email']) && strlen($customer['email']) && !module_config::c('customer_signup_always_new', 0)) {
                 $users = module_user::get_contacts(array('email' => $customer['email']));
                 foreach ($users as $user) {
                     if (isset($user['customer_id']) && (int) $user['customer_id'] > 0) {
                         // this user exists as a customer! yey!
                         // add them to this listing.
                         $customer_id = $user['customer_id'];
                         $creating_new = false;
                         $_REQUEST['user_id'] = $user['user_id'];
                         // dont let signups update existing passwords.
                         if (isset($customer['password'])) {
                             unset($customer['password']);
                         }
                         if (isset($customer['new_password'])) {
                             unset($customer['new_password']);
                         }
                     }
                 }
             }
             $_REQUEST['extra_customer_field'] = array();
             $_REQUEST['extra_user_field'] = array();
             module_extra::$config['allow_new_keys'] = false;
             module_extra::$config['delete_existing_empties'] = false;
             // save customer extra fields.
             if (count($customer_extra)) {
                 // format the address so "save_customer" handles the save for us
                 foreach ($customer_extra as $key => $val) {
                     $_REQUEST['extra_customer_field'][] = array('key' => $key, 'val' => $val);
                 }
             }
             // save customer and customer contact details:
             $customer_id = $this->save_customer($customer_id, $customer);
             if (!$customer_id) {
                 $result['error'] = 1;
                 $result['messages'][] = 'System error: failed to create customer.';
                 customer_signup_complete($result);
             }
             $customer_data = module_customer::get_customer($customer_id);
             // todo - merge primary and secondary contact/extra/group saving into a single loop
             if (!$customer_data['primary_user_id']) {
                 $result['error'] = 1;
                 $result['messages'][] = 'System error: Failed to create customer contact.';
                 customer_signup_complete($result);
             } else {
                 $role_id = module_config::c('customer_signup_role', 0);
                 if ($role_id > 0) {
                     module_user::add_user_to_role($customer_data['primary_user_id'], $role_id);
                 }
                 // save contact extra data (repeated below for additional contacts)
                 if (isset($contact_extra[0]) && count($contact_extra[0])) {
                     $_REQUEST['extra_user_field'] = array();
                     foreach ($contact_extra[0] as $key => $val) {
                         $_REQUEST['extra_user_field'][] = array('key' => $key, 'val' => $val);
                     }
                     module_extra::save_extras('user', 'user_id', $customer_data['primary_user_id']);
                 }
                 // save contact groups
                 if (isset($contact_group[0]) && count($contact_group[0])) {
                     foreach ($contact_group[0] as $group_id => $tf) {
                         if ($tf) {
                             module_group::add_to_group($group_id, $customer_data['primary_user_id'], 'user');
                         }
                     }
                 }
             }
             foreach ($contact['email'] as $contact_key => $email) {
                 // add any additional contacts to the customer.
                 $users = module_user::get_contacts(array('email' => $email, 'customer_id' => $customer_id));
                 if (count($users)) {
                     // this contact already exists for this customer, dont update/change it.
                     continue;
                 }
                 $new_contact = array('customer_id' => $customer_id);
                 foreach ($contact_fields as $primary_contact_field) {
                     $new_contact[$primary_contact_field] = isset($contact[$primary_contact_field][$contact_key]) ? $contact[$primary_contact_field][$contact_key] : '';
                 }
                 // dont let additional contacts have passwords.
                 if (isset($new_contact['password'])) {
                     unset($new_contact['password']);
                 }
                 if (isset($new_contact['new_password'])) {
                     unset($new_contact['new_password']);
                 }
                 global $plugins;
                 $contact_user_id = $plugins['user']->create_user($new_contact, 'signup');
                 if ($contact_user_id) {
                     $role_id = module_config::c('customer_signup_role', 0);
                     if ($role_id > 0) {
                         module_user::add_user_to_role($contact_user_id, $role_id);
                     }
                     // save contact extra data  (repeated below for primary contacts)
                     if (isset($contact_extra[$contact_key]) && count($contact_extra[$contact_key])) {
                         $_REQUEST['extra_user_field'] = array();
                         foreach ($contact_extra[$contact_key] as $key => $val) {
                             $_REQUEST['extra_user_field'][] = array('key' => $key, 'val' => $val);
                         }
                         module_extra::save_extras('user', 'user_id', $contact_user_id);
                     }
                     // save contact groups
                     if (isset($contact_group[$contact_key]) && count($contact_group[$contact_key])) {
                         foreach ($contact_group[$contact_key] as $group_id => $tf) {
                             if ($tf) {
                                 module_group::add_to_group($group_id, $contact_user_id, 'user');
                             }
                         }
                     }
                 }
             }
             if (count($customer_group)) {
                 // format the address so "save_customer" handles the save for us
                 foreach ($customer_group as $group_id => $tf) {
                     if ($tf) {
                         module_group::add_to_group($group_id, $customer_id, 'customer');
                     }
                 }
             }
             $note_keys = array('customer', 'website', 'job', 'address', 'subscription');
             $note_text = _l('Customer signed up from Signup Form:');
             $note_text .= "\n\n";
             foreach ($note_keys as $note_key) {
                 $note_text .= "\n" . ucwords(_l($note_key)) . "\n";
                 if (isset($_POST[$note_key]) && is_array($_POST[$note_key])) {
                     foreach ($_POST[$note_key] as $post_key => $post_val) {
                         $note_text .= "\n - " . _l($post_key) . ": ";
                         if (is_array($post_val)) {
                             foreach ($post_val as $p => $v) {
                                 $note_text .= "\n  - - " . _l($p) . ': ' . $v;
                             }
                         } else {
                             $note_text .= $post_val;
                         }
                     }
                 }
             }
             $note_data = array('note_id' => false, 'owner_id' => $customer_id, 'owner_table' => 'customer', 'note_time' => time(), 'note' => $note_text, 'rel_data' => module_customer::link_open($customer_id), 'reminder' => 0, 'user_id' => 0);
             update_insert('note_id', false, 'note', $note_data);
             // save customer address fields.
             if (count($address)) {
                 $address_db = module_address::get_address($customer_id, 'customer', 'physical');
                 $address_id = $address_db && isset($address_db['address_id']) ? (int) $address_db['address_id'] : false;
                 $address['owner_id'] = $customer_id;
                 $address['owner_table'] = 'customer';
                 $address['address_type'] = 'physical';
                 // we have post data to save, write it to the table!!
                 module_address::save_address($address_id, $address);
             }
             // website:
             $allowed = array('url', 'name', 'extra', 'notes');
             foreach ($website as $key => $val) {
                 if (!in_array($key, $allowed)) {
                     unset($website[$key]);
                 }
             }
             $website['url'] = isset($website['url']) ? strtolower(trim($website['url'])) : '';
             $website_id = 0;
             if (count($website) && class_exists('module_website', false) && module_website::is_plugin_enabled()) {
                 if (strlen($website['url'])) {
                     // see if website already exists, don't create or update existing one for now.
                     $existing_websites = module_website::get_websites(array('customer_id' => $customer_id, 'url' => $website['url']));
                     foreach ($existing_websites as $existing_website) {
                         $website_id = $existing_website['website_id'];
                     }
                 }
                 //   echo $website_id;echo $website['url']; print_r($website_extra);exit;
                 if (!$website_id) {
                     $website_data = module_website::get_website($website_id);
                     $website_data['url'] = isset($website['url']) ? $website['url'] : 'N/A';
                     $website_data['name'] = isset($website['url']) ? $website['url'] : 'N/A';
                     $website_data['customer_id'] = $customer_id;
                     $website_id = update_insert('website_id', false, 'website', $website_data);
                     // save website extra data.
                     if ($website_id && count($website_extra)) {
                         $_REQUEST['extra_website_field'] = array();
                         foreach ($website_extra as $key => $val) {
                             $_REQUEST['extra_website_field'][] = array('key' => $key, 'val' => $val);
                         }
                         module_extra::save_extras('website', 'website_id', $website_id);
                     }
                     if ($website_id && isset($website['notes']) && strlen($website['notes'])) {
                         // add notes to this website.
                         $note_data = array('note_id' => false, 'owner_id' => $website_id, 'owner_table' => 'website', 'note_time' => time(), 'note' => $website['notes'], 'rel_data' => module_website::link_open($website_id), 'reminder' => 0, 'user_id' => $customer_data['primary_user_id']);
                         $note_id = update_insert('note_id', false, 'note', $note_data);
                     }
                 }
                 if ($website_id) {
                     if (count($website_group)) {
                         // format the address so "save_customer" handles the save for us
                         foreach ($website_group as $group_id => $tf) {
                             if ($tf) {
                                 module_group::add_to_group($group_id, $website_id, 'website');
                             }
                         }
                     }
                 }
             }
             // generate jobs for this customer.
             $job_created = array();
             if ($job && isset($job['type']) && is_array($job['type'])) {
                 if (module_config::c('customer_signup_any_job_type', 0)) {
                     foreach ($job['type'] as $type_name) {
                         // we have a match in our system. create the job.
                         $job_data = module_job::get_job(false);
                         $job_data['type'] = $type_name;
                         if (!$job_data['name']) {
                             $job_data['name'] = $type_name;
                         }
                         $job_data['website_id'] = $website_id;
                         $job_data['customer_id'] = $customer_id;
                         $job_id = update_insert('job_id', false, 'job', $job_data);
                         // todo: add default tasks for this job type.
                         $job_created[] = $job_id;
                     }
                 } else {
                     foreach (module_job::get_types() as $type_id => $type) {
                         foreach ($job['type'] as $type_name) {
                             if ($type_name == $type) {
                                 // we have a match in our system. create the job.
                                 $job_data = module_job::get_job(false);
                                 $job_data['type'] = $type;
                                 if (!$job_data['name']) {
                                     $job_data['name'] = $type;
                                 }
                                 $job_data['website_id'] = $website_id;
                                 $job_data['customer_id'] = $customer_id;
                                 $job_id = update_insert('job_id', false, 'job', $job_data);
                                 // todo: add default tasks for this job type.
                                 $job_created[] = $job_id;
                             }
                         }
                     }
                 }
                 if (count($job_created) && count($job_extra)) {
                     // save job extra data.
                     foreach ($job_created as $job_created_id) {
                         if ($job_created_id && count($job_extra)) {
                             $_REQUEST['extra_job_field'] = array();
                             foreach ($job_extra as $key => $val) {
                                 $_REQUEST['extra_job_field'][] = array('key' => $key, 'val' => $val);
                             }
                             module_extra::save_extras('job', 'job_id', $job_created_id);
                         }
                     }
                 }
             }
             // save files against customer
             $uploaded_files = array();
             if (isset($_FILES['customerfiles']) && isset($_FILES['customerfiles']['tmp_name'])) {
                 foreach ($_FILES['customerfiles']['tmp_name'] as $file_id => $tmp_file) {
                     if (is_uploaded_file($tmp_file)) {
                         // save to file module for this customer
                         $file_name = basename($_FILES['customerfiles']['name'][$file_id]);
                         if (strlen($file_name)) {
                             $file_path = 'includes/plugin_file/upload/' . md5(time() . $file_name);
                             if (move_uploaded_file($tmp_file, $file_path)) {
                                 // success! write to db.
                                 $file_data = array('customer_id' => $customer_id, 'job_id' => current($job_created), 'website_id' => $website_id, 'status' => module_config::c('file_default_status', 'Uploaded'), 'pointers' => false, 'description' => "Uploaded from Customer Signup form", 'file_time' => time(), 'file_name' => $file_name, 'file_path' => $file_path, 'file_url' => false);
                                 $file_id = update_insert('file_id', false, 'file', $file_data);
                                 $uploaded_files[] = $file_id;
                             }
                         }
                     }
                 }
             }
             // we create subscriptions for this customer/website (if none already exist)
             $subscription['subscription_name'] = array();
             $subscription['subscription_invoice'] = array();
             if (class_exists('module_subscription', false) && module_subscription::is_plugin_enabled() && isset($subscription['for']) && isset($subscription['subscriptions'])) {
                 if ($subscription['for'] == 'website' && $website_id > 0) {
                     $owner_table = 'website';
                     $owner_id = $website_id;
                 } else {
                     $owner_table = 'customer';
                     $owner_id = $customer_id;
                 }
                 $available_subscriptions = module_subscription::get_subscriptions();
                 $members_subscriptions = module_subscription::get_subscriptions_by($owner_table, $owner_id);
                 foreach ($subscription['subscriptions'] as $subscription_id => $tf) {
                     if (isset($available_subscriptions[$subscription_id])) {
                         if (isset($members_subscriptions[$subscription_id])) {
                             // we don't allow a member to sign up to the same subscription twice (just yet)
                         } else {
                             $subscription['subscription_name'][$subscription_id] = $available_subscriptions[$subscription_id]['name'];
                             $start_date = date('Y-m-d');
                             $start_modifications = module_config::c('customer_signup_subscription_start', '');
                             if ($start_modifications == 'hidden') {
                                 $start_modifications = isset($_REQUEST['customer_signup_subscription_start']) ? $_REQUEST['customer_signup_subscription_start'] : '';
                             }
                             if (!empty($start_modifications)) {
                                 $start_date = date('Y-m-d', strtotime($start_modifications));
                             }
                             $sql = "INSERT INTO `" . _DB_PREFIX . "subscription_owner` SET ";
                             $sql .= " owner_id = '" . (int) $owner_id . "'";
                             $sql .= ", owner_table = '" . mysql_real_escape_string($owner_table) . "'";
                             $sql .= ", subscription_id = '" . (int) $subscription_id . "'";
                             $sql .= ", start_date = '{$start_date}'";
                             query($sql);
                             module_subscription::update_next_due_date($subscription_id, $owner_table, $owner_id, true);
                             // and the same option here to send a subscription straight away upon signup
                             if (module_config::c('subscription_send_invoice_straight_away', 0)) {
                                 global $plugins;
                                 $plugins['subscription']->run_cron();
                                 // check if there are any invoices for this subscription
                                 $history = module_subscription::get_subscription_history($subscription_id, $owner_table, $owner_id);
                                 if (count($history) > 0) {
                                     foreach ($history as $h) {
                                         if ($h['invoice_id']) {
                                             $invoice_data = module_invoice::get_invoice($h['invoice_id']);
                                             if ($invoice_data['date_cancel'] != '0000-00-00') {
                                                 continue;
                                             }
                                             $subscription['subscription_invoice'][] = '<a href="' . module_invoice::link_public($h['invoice_id']) . '">' . _l('Invoice #%s for %s', htmlspecialchars($invoice_data['name']), dollar($invoice_data['total_amount'], true, $invoice_data['currency_id'])) . '</a>';
                                         }
                                     }
                                 }
                             }
                         }
                     }
                 }
             }
             if (!count($subscription['subscription_name'])) {
                 $subscription['subscription_name'][] = _l('N/A');
             }
             if (!count($subscription['subscription_invoice'])) {
                 $subscription['subscription_invoice'][] = _l('N/A');
             }
             $subscription['subscription_name'] = implode(', ', $subscription['subscription_name']);
             $subscription['subscription_invoice'] = implode(', ', $subscription['subscription_invoice']);
             // email the admin when a customer signs up.
             $values = array_merge($customer, $customer_extra, $website, $website_extra, $address, $subscription);
             $values['customer_name'] = $customer['customer_name'];
             $values['CUSTOMER_LINK'] = module_customer::link_open($customer_id);
             $values['CUSTOMER_NAME_LINK'] = module_customer::link_open($customer_id, true);
             if ($website_id) {
                 $values['WEBSITE_LINK'] = module_website::link_open($website_id);
                 $values['WEBSITE_NAME_LINK'] = module_website::link_open($website_id, true);
             } else {
                 $values['WEBSITE_LINK'] = _l('N/A');
                 $values['WEBSITE_NAME_LINK'] = _l('N/A');
             }
             $values['JOB_LINKS'] = '';
             if (count($job_created)) {
                 $values['JOB_LINKS'] .= 'The customer created ' . count($job_created) . ' jobs in the system: <br>';
                 foreach ($job_created as $job_created_id) {
                     $values['JOB_LINKS'] .= module_job::link_open($job_created_id, true) . "<br>\n";
                 }
             } else {
                 $values['JOB_LINKS'] = _l('N/A');
             }
             if (count($uploaded_files)) {
                 $values['uploaded_files'] = 'The customer uploaded ' . count($uploaded_files) . " files:<br>\n";
                 foreach ($uploaded_files as $uploaded_file) {
                     $values['uploaded_files'] .= module_file::link_open($uploaded_file, true) . "<br>\n";
                 }
             } else {
                 $values['uploaded_files'] = 'No files were uploaded';
             }
             $values['WEBSITE_NAME'] = isset($website['url']) ? $website['url'] : 'N/A';
             if (!$creating_new) {
                 $values['system_note'] = "Note: this signup updated the existing customer record in the system.";
             } else {
                 $values['system_note'] = "Note: this signup created a new customer record in the system.";
             }
             $customer_signup_template = module_config::c('customer_signup_email_admin_template', 'customer_signup_email_admin');
             if (isset($_REQUEST['customer_signup_email_admin_template'])) {
                 $customer_signup_template = $_REQUEST['customer_signup_email_admin_template'];
             }
             if ($customer_signup_template) {
                 $template = module_template::get_template_by_key($customer_signup_template);
                 if ($template->template_id) {
                     $template->assign_values($values);
                     $html = $template->render('html');
                     $email = module_email::new_email();
                     $email->replace_values = $values;
                     $email->set_subject($template->description);
                     $email->set_to_manual(module_config::c('customer_signup_admin_email', module_config::c('admin_email_address')));
                     // do we send images inline?
                     $email->set_html($html);
                     if ($email->send()) {
                         // it worked successfully!!
                     } else {
                         /// log err?
                     }
                 }
             }
             $customer_signup_template = module_config::c('customer_signup_email_welcome_template', 'customer_signup_email_welcome');
             if (isset($_REQUEST['customer_signup_email_welcome_template'])) {
                 $customer_signup_template = $_REQUEST['customer_signup_email_welcome_template'];
             }
             if ($customer_signup_template) {
                 $template = module_template::get_template_by_key($customer_signup_template);
                 if ($template->template_id) {
                     $template->assign_values($values);
                     $html = $template->render('html');
                     $email = module_email::new_email();
                     $email->customer_id = $customer_id;
                     $email->replace_values = $values;
                     $email->set_subject($template->description);
                     $email->set_to('user', $customer_data['primary_user_id']);
                     // do we send images inline?
                     $email->set_html($html);
                     if ($email->send()) {
                         // it worked successfully!!
                     } else {
                         /// log err?
                     }
                 }
             }
             //todo: optional redirect to url
             if (isset($_REQUEST['via_ajax'])) {
                 echo json_encode(array('success' => 1, 'customer_id' => $customer_id));
                 exit;
             }
             if (module_config::c('customer_signup_redirect', '')) {
                 redirect_browser(module_config::c('customer_signup_redirect', ''));
             }
             // load up the thank you template.
             $template = module_template::get_template_by_key('customer_signup_thank_you_page');
             $template->page_title = _l("Customer Signup");
             foreach ($values as $key => $val) {
                 if (!is_array($val)) {
                     $values[$key] = htmlspecialchars($val);
                 }
             }
             $template->assign_values($values);
             echo $template->render('pretty_html');
             exit;
             break;
     }
 }
Exemple #10
0
    public function external_hook($hook)
    {
        switch ($hook) {
            case 'subscribe_form':
                // handle subscriptions to the member database and also the newsletter system.
                // todo - tie in with "subscription" module to allow users to select which subscription they want as well.
            // handle subscriptions to the member database and also the newsletter system.
            // todo - tie in with "subscription" module to allow users to select which subscription they want as well.
            case 'subscribe':
                $member = isset($_REQUEST['member']) && is_array($_REQUEST['member']) ? $_REQUEST['member'] : false;
                $provided_member_id = isset($_REQUEST['i']) ? (int) $_REQUEST['i'] : false;
                $hash = isset($_REQUEST['hash']) ? trim($_REQUEST['hash']) : false;
                $member_id = false;
                if ($member) {
                    if (isset($member['email']) && $member['email']) {
                        // proceed with signup
                        $email = filter_var(strtolower(trim($member['email'])), FILTER_VALIDATE_EMAIL);
                        if (strlen($email) > 3) {
                            $adding_new_member = true;
                            // are we adding a new member to the system or updating an old one
                            if ($provided_member_id && $hash) {
                                $real_hash = $this->link_public_details($provided_member_id, true);
                                if ($real_hash == $hash) {
                                    $existing_member = get_single('member', 'email', $email);
                                    if ($existing_member && $existing_member['member_id'] != $provided_member_id) {
                                        // this user is trying to update their email address to a user who exists in the system already
                                        $template = module_template::get_template_by_key('member_subscription_error');
                                        $template->page_title = htmlspecialchars(_l('Subscription'));
                                        $template->assign_values(array('message' => _l('The email address %s is already linked to another member.', htmlspecialchars($email))));
                                        echo $template->render('pretty_html');
                                        exit;
                                    }
                                    $adding_new_member = false;
                                    // updating details in the system.
                                    update_insert("member_id", $provided_member_id, "member", $member);
                                    $member_id = $provided_member_id;
                                    // update extra fields...
                                }
                            }
                            if (!$member_id) {
                                // add member to system.
                                $existing_member = get_single('member', 'email', $email);
                                if ($existing_member && $existing_member['member_id'] > 0) {
                                    // todo: give them link to change details.
                                    $template = module_template::get_template_by_key('member_subscription_error');
                                    $template->page_title = htmlspecialchars(_l('Subscription'));
                                    $template->assign_values(array('message' => _l('The email address %s is already a member. Please click the link in our newsletter to modify your details.', htmlspecialchars($email))));
                                    echo $template->render('pretty_html');
                                    exit;
                                }
                                // todo - sanatise input here, this will allow anyone to insert member details:
                                $member_id = update_insert("member_id", 'new', "member", $member);
                            }
                            if ($member_id) {
                                // save extra fields against member.
                                $extra_fields = module_extra::get_defaults('member');
                                $extra_values = array();
                                foreach ($extra_fields as $extra_field) {
                                    // check if this field was submitted.
                                    if (isset($member[$extra_field['key']])) {
                                        $extra_values[$extra_field['key']] = array('val' => $member[$extra_field['key']], 'key' => $extra_field['key']);
                                    }
                                }
                                if (count($extra_values)) {
                                    $_REQUEST['extra_member_field'] = $extra_values;
                                    module_extra::save_extras('member', 'member_id', $member_id, false);
                                }
                                if (class_exists('module_newsletter', false)) {
                                    $newsletter_member_id = module_newsletter::member_from_email(array('email' => $email, 'member_id' => $member_id, 'data_callback' => 'module_member::get_newsletter_recipient', 'data_args' => $member_id), true, true);
                                    module_newsletter::subscribe_member($email, $newsletter_member_id);
                                    // now add thsi member to the grups they have selected.
                                    if (isset($member['group']) && is_array($member['group'])) {
                                        $group_items = module_group::get_groups('newsletter_subscription');
                                        $public_group_ids = array();
                                        foreach ($group_items as $group_item) {
                                            $public_group_ids[$group_item['group_id']] = true;
                                            // remove user group all these groups.
                                            module_group::delete_member($member_id, 'newsletter_subscription');
                                        }
                                        //print_r($member['group']);print_r($public_group_ids);exit;
                                        foreach ($member['group'] as $group_id => $tf) {
                                            if ($tf && isset($public_group_ids[$group_id])) {
                                                // add member to group - but only public group ids!
                                                module_group::add_to_group($group_id, $member_id);
                                            }
                                        }
                                    }
                                }
                                // is the newsletter module giving us a subscription redirection?
                                if ($adding_new_member) {
                                    if (module_config::c('newsletter_subscribe_redirect', '')) {
                                        redirect_browser(module_config::c('newsletter_subscribe_redirect', ''));
                                    }
                                    $template = module_template::get_template_by_key('member_subscription_success');
                                    $template->page_title = htmlspecialchars(_l('Subscription'));
                                    $template->assign_values(array('email' => $email));
                                    echo $template->render('pretty_html');
                                    exit;
                                } else {
                                    if (module_config::c('newsletter_update_details_redirect', '')) {
                                        redirect_browser(module_config::c('newsletter_update_details_redirect', ''));
                                    }
                                    $template = module_template::get_template_by_key('member_update_details_success');
                                    $template->page_title = htmlspecialchars(_l('Subscription'));
                                    $template->assign_values(array('email' => $email));
                                    echo $template->render('pretty_html');
                                    exit;
                                }
                            } else {
                                echo 'database failure.. please try again.';
                            }
                        } else {
                            $template = module_template::get_template_by_key('member_subscription_error');
                            $template->page_title = htmlspecialchars(_l('Subscription'));
                            $template->assign_values(array('message' => _l('Sorry please go back and complete all required fields (especially email address)')));
                            echo $template->render('pretty_html');
                            exit;
                        }
                    } else {
                        $template = module_template::get_template_by_key('member_subscription_error');
                        $template->page_title = htmlspecialchars(_l('Subscription'));
                        $template->assign_values(array('message' => _l('Sorry please go back and complete all required fields')));
                        echo $template->render('pretty_html');
                        exit;
                    }
                } else {
                    $template = module_template::get_template_by_key('member_subscription_form');
                    $template->page_title = htmlspecialchars(_l('Subscription'));
                    // we also treat this as a subscription modification form.
                    $newsletter_subscriptions = array();
                    $member = array('email' => '', 'first_name' => '', 'last_name' => '', 'business' => '', 'phone' => '', 'mobile' => '');
                    // extra fields:
                    $extra_fields = module_extra::get_defaults('member');
                    foreach ($extra_fields as $extra_field) {
                        $member[$extra_field['key']] = '';
                    }
                    if ($provided_member_id && $hash) {
                        $real_hash = $this->link_public_details($provided_member_id, true);
                        if ($real_hash == $hash) {
                            // we can load these details into the forum successfully.
                            $member = array_merge($member, $this->get_member($provided_member_id));
                            // get their fields:
                            $extra_fields = module_extra::get_extras(array('owner_table' => 'member', 'owner_id' => $provided_member_id));
                            foreach ($extra_fields as $extra_field) {
                                $member[$extra_field['extra_key']] = $extra_field['extra'];
                            }
                            // find out what newsletter subscriptions this member has.
                            if (class_exists('module_newsletter', false)) {
                                $newsletter_member_id = module_newsletter::member_from_email($member, true, true);
                                $newsletter_subscriptions = module_group::get_member_groups('newsletter_subscription', $provided_member_id);
                            }
                        }
                    }
                    $template->assign_values($member);
                    if (class_exists('module_newsletter', false)) {
                        $group_items = module_group::get_groups('newsletter_subscription');
                        ob_start();
                        foreach ($group_items as $group_item) {
                            ?>

                            <div class="group_select">
                                <input type="checkbox" name="member[group][<?php 
                            echo $group_item['group_id'];
                            ?>
]" value="1"<?php 
                            foreach ($newsletter_subscriptions as $newsletter_subscription) {
                                if ($newsletter_subscription['group_id'] == $group_item['group_id']) {
                                    echo ' checked';
                                }
                            }
                            ?>
 > <?php 
                            echo htmlspecialchars($group_item['name']);
                            ?>

                            </div>
                            <?php 
                        }
                        $template->assign_values(array('newsletter_options' => ob_get_clean()));
                    } else {
                        $template->assign_values(array('newsletter_options' => ''));
                    }
                    echo $template->render('pretty_html');
                    exit;
                }
                break;
        }
    }
Exemple #11
0
 public function save_user($user_id, $data, $from_public = false)
 {
     $use_master_key = $this->get_contact_master_key();
     if ($from_public) {
         $user_id = 0;
     } else {
         if ($use_master_key && isset($data[$use_master_key]) && $data[$use_master_key]) {
             if (!module_user::can_i('edit', 'Contacts', 'Customer')) {
                 set_error('Unable to edit contacts.');
                 return false;
             }
         } else {
             if (!self::can_i('edit', 'Users', 'Config')) {
                 set_error('Unable to edit users.');
                 return false;
             }
         }
         $user_id = (int) $user_id;
     }
     $temp_user = array();
     if ($user_id > 0) {
         // check permissions
         $temp_user = $this->get_user($user_id, true, false);
         if (!$temp_user || $temp_user['user_id'] != $user_id || isset($temp_user['_perms'])) {
             $user_id = false;
         }
     }
     if (!$user_id && !$from_public) {
         if ($use_master_key && isset($data[$use_master_key]) && $data[$use_master_key]) {
             if (!module_user::can_i('create', 'Contacts', 'Customer')) {
                 set_error('Unable to create new contacts.');
                 return false;
             }
         } else {
             if (!self::can_i('create', 'Users', 'Config')) {
                 set_error('Unable to create new users.');
                 return false;
             }
         }
     } else {
         if ($user_id == 1 && module_security::get_loggedin_id() != 1) {
             set_error('Sorry only the administrator can modify this account');
         }
     }
     // check the customer id is valid assignment to someone who has these perms.
     if (!$from_public) {
         if (isset($data['customer_id']) && (int) $data['customer_id'] > 0) {
             $temp_customer = module_customer::get_customer($data['customer_id']);
             if (!$temp_customer || $temp_customer['customer_id'] != $data['customer_id']) {
                 unset($data['customer_id']);
             }
         }
         if (isset($data['vendor_id']) && (int) $data['vendor_id'] > 0) {
             $temp_vendor = module_vendor::get_vendor($data['vendor_id']);
             if (!$temp_vendor || $temp_vendor['vendor_id'] != $data['vendor_id']) {
                 unset($data['vendor_id']);
             }
         }
     }
     if (isset($data['password'])) {
         unset($data['password']);
     }
     // we do the password hash thing here.
     if (isset($data['password_new']) && strlen($data['password_new'])) {
         // an admin is trying to set the password for this account.
         // same permissions checks as on the user_admin_edit_login.php page
         if (!$user_id || isset($temp_user['password']) && !$temp_user['password'] || module_user::can_i('create', 'Users Passwords', 'Config') || isset($_REQUEST['reset_password']) && $_REQUEST['reset_password'] == module_security::get_auto_login_string($user_id)) {
             // we allow the admin to set a new password without typing in previous password.
             $data['password'] = $data['password_new'];
         } else {
             set_error('Sorry, no permissions to set a new password.');
         }
     } else {
         if ($user_id && isset($data['password_new1']) && isset($data['password_new2']) && strlen($data['password_new1'])) {
             // the user is trying to change their password.
             // only do this if the user has edit password permissions and their password matches.
             if (module_user::can_i('edit', 'Users Passwords', 'Config') || $user_id == module_security::get_loggedin_id()) {
                 if (isset($data['password_old']) && (md5($data['password_old']) == $temp_user['password'] || $data['password_old'] == $temp_user['password'])) {
                     // correct old password
                     // verify new password.
                     if ($data['password_new1'] == $data['password_new2']) {
                         $data['password'] = $data['password_new1'];
                     } else {
                         set_error('Verified password mismatch. Password unchanged.');
                     }
                 } else {
                     set_error('Old password does not match. Password unchanged.');
                 }
             } else {
                 set_error('No permissions to change passwords');
             }
         }
     }
     // and we finally hash our password
     if (isset($data['password']) && strlen($data['password']) > 0) {
         $data['password'] = md5($data['password']);
         // if you change md5 also change it in customer import.
         // todo - salt? meh.
     }
     $user_id = update_insert("user_id", $user_id, "user", $data);
     $use_master_key = $this->get_contact_master_key();
     // this will be customer_id or supplier_id
     if ($use_master_key && (isset($data[$use_master_key]) && $data[$use_master_key])) {
         if ($user_id) {
             if (isset($data['customer_primary']) && $data['customer_primary']) {
                 // update the customer/supplier to mark them as primary or not..
                 switch ($use_master_key) {
                     case 'customer_id':
                         module_customer::set_primary_user_id($data['customer_id'], $user_id);
                         break;
                     case 'vendor_id':
                         module_vendor::set_primary_user_id($data['vendor_id'], $user_id);
                         break;
                 }
             } else {
                 // check if this contact was the old customer/supplier primary and
                 switch ($use_master_key) {
                     case 'customer_id':
                         $customer_data = module_customer::get_customer($data['customer_id']);
                         if ($customer_data['primary_user_id'] == $user_id) {
                             module_customer::set_primary_user_id($data['customer_id'], 0);
                         }
                         break;
                     case 'vendor_id':
                         $vendor_data = module_vendor::get_vendor($data['vendor_id']);
                         if ($vendor_data['primary_user_id'] == $user_id) {
                             module_vendor::set_primary_user_id($data['vendor_id'], 0);
                         }
                         break;
                 }
             }
         }
     }
     if (!$from_public) {
         // hack for linked user accounts.
         if ($user_id && isset($data['link_customers']) && $data['link_customers'] == 'yes' && isset($data['link_user_ids']) && is_array($data['link_user_ids']) && isset($data['email']) && $data['email']) {
             $others = module_user::get_contacts(array('email' => $data['email']));
             foreach ($data['link_user_ids'] as $link_user_id) {
                 if (!(int) $link_user_id) {
                     continue;
                 }
                 if ($link_user_id == $user_id) {
                     continue;
                 }
                 // shouldnt happen
                 foreach ($others as $other) {
                     if ($other['user_id'] == $link_user_id) {
                         // success! they'renot trying to hack us.
                         $sql = "REPLACE INTO `" . _DB_PREFIX . "user_customer_rel` SET user_id = '" . (int) $link_user_id . "', customer_id = '" . (int) $other['customer_id'] . "', `primary` = " . (int) $user_id;
                         query($sql);
                         update_insert('user_id', $link_user_id, 'user', array('linked_parent_user_id' => $user_id));
                     }
                 }
             }
             update_insert('user_id', $user_id, 'user', array('linked_parent_user_id' => $user_id));
         }
         if ($user_id && isset($data['unlink']) && $data['unlink'] == 'yes') {
             $sql = "DELETE FROM `" . _DB_PREFIX . "user_customer_rel` WHERE user_id = '" . (int) $user_id . "'";
             query($sql);
             update_insert('user_id', $user_id, 'user', array('linked_parent_user_id' => 0));
         }
         handle_hook("address_block_save", $this, "physical", "user", "user_id", $user_id);
         handle_hook("address_block_save", $this, "postal", "user", "user_id", $user_id);
         if (class_exists('module_extra', false) && module_extra::is_plugin_enabled()) {
             module_extra::save_extras('user', 'user_id', $user_id);
         }
         // find current role / permissions
         $user_data = $this->get_user($user_id);
         $previous_user_roles = $user_data['roles'];
         $re_save_role_perms = false;
         // hack to support only 1 role (we may support multi-role in the future)
         // TODO: check we have permissions to set this role id, otherwise anyone can set their own role.
         if (isset($_REQUEST['role_id'])) {
             $sql = "DELETE FROM `" . _DB_PREFIX . "user_role` WHERE user_id = '" . (int) $user_id . "'";
             query($sql);
             if ((int) $_REQUEST['role_id'] > 0) {
                 if (!isset($previous_user_roles[$_REQUEST['role_id']])) {
                     $re_save_role_perms = (int) $_REQUEST['role_id'];
                 }
                 $_REQUEST['role'] = array($_REQUEST['role_id'] => 1);
             }
         }
         // save users roles (support for multi roles in future - but probably will never happen)
         if (isset($_REQUEST['role']) && is_array($_REQUEST['role'])) {
             foreach ($_REQUEST['role'] as $role_id => $tf) {
                 $this->add_user_to_role($user_id, $role_id);
             }
         }
         if ($re_save_role_perms) {
             // copy role permissiosn to user permissions
             $sql = "DELETE FROM `" . _DB_PREFIX . "user_perm` WHERE user_id = " . (int) $user_id;
             query($sql);
             // update - we are not relying on these permissions any more.
             // if the user has a role assigned, we use those permissions period
             // we ignore all permissions in the user_perm table if the user has a role.
             // if the user doesn't have a role, then we use these user_perm permissions.
             /*$security_role = module_security::get_security_role($re_save_role_perms);
             		foreach($security_role['permissions'] as $security_permission_id => $d){
             			$sql = "INSERT INTO `"._DB_PREFIX."user_perm` SET user_id = ".(int)$user_id.", security_permission_id = '".(int)$security_permission_id."'";
             			foreach(module_security::$available_permissions as $perm){
             				$sql .= ", `".$perm."` = ".(int)$d[$perm];
             			}
             			query($sql);
             		}*/
         } else {
             if (isset($_REQUEST['permission']) && is_array($_REQUEST['permission'])) {
                 $sql = "DELETE FROM `" . _DB_PREFIX . "user_perm` WHERE user_id = '" . (int) $user_id . "'";
                 query($sql);
                 // update permissions for this user.
                 foreach ($_REQUEST['permission'] as $security_permission_id => $permissions) {
                     $actions = array();
                     foreach (module_security::$available_permissions as $permission) {
                         if (isset($permissions[$permission]) && $permissions[$permission]) {
                             $actions[$permission] = 1;
                         }
                     }
                     $sql = "REPLACE INTO `" . _DB_PREFIX . "user_perm` SET user_id = '" . (int) $user_id . "', security_permission_id = '" . (int) $security_permission_id . "' ";
                     foreach ($actions as $permission => $tf) {
                         $sql .= ", `" . mysql_real_escape_string($permission) . "` = 1";
                     }
                     query($sql);
                 }
             }
         }
         /*global $plugins;
         		if($user_id && isset($data['user_type_id']) && $data['user_type_id'] == 1 && $data['site_id']){
         			// update the site.
         			$plugins['site']->set_primary_user_id($data['site_id'],$user_id);
         		}else{
         			//this use isn't (or isnt any more) the sites primary user.
         			// unset this if he was the primary user before
         			$site_data = $plugins['site']->get_site($data['site_id']);
         			if(isset($site_data['primary_user_id']) && $site_data['primary_user_id'] == $user_id){
         				$plugins['site']->set_primary_user_id($data['site_id'],0);
         			}
         		}*/
         // save the company information if it's available
         if (class_exists('module_company', false) && module_company::can_i('edit', 'Company') && module_company::is_enabled() && module_user::can_i('edit', 'User')) {
             if (isset($_REQUEST['available_user_company']) && is_array($_REQUEST['available_user_company'])) {
                 $selected_companies = isset($_POST['user_company']) && is_array($_POST['user_company']) ? $_POST['user_company'] : array();
                 foreach ($_REQUEST['available_user_company'] as $company_id => $tf) {
                     if (!isset($selected_companies[$company_id]) || !$selected_companies[$company_id]) {
                         // remove user from this company
                         module_company::delete_user($company_id, $user_id);
                     } else {
                         // add user to this company (if they are not already existing)
                         module_company::add_user_to_company($company_id, $user_id);
                     }
                 }
             }
         }
     }
     module_cache::clear('user');
     return $user_id;
 }
Exemple #12
0
 public function save_vendor($vendor_id, $data)
 {
     $vendor_id = (int) $vendor_id;
     $temp_vendor = false;
     if ($vendor_id > 0) {
         // check permissions
         $temp_vendor = $this->get_vendor($vendor_id);
         if (!$temp_vendor || $temp_vendor['vendor_id'] != $vendor_id) {
             $temp_vendor = false;
             $vendor_id = false;
         }
     }
     if (_DEMO_MODE && $vendor_id == 1) {
         set_error('Sorry this is a Demo Vendor. It cannot be changed.');
         redirect_browser(self::link_open($vendor_id));
     }
     if (isset($data['default_tax_system']) && $data['default_tax_system']) {
         $data['default_tax'] = -1;
         $data['default_tax_name'] = '';
     }
     if (isset($data['primary_user_id'])) {
         unset($data['primary_user_id']);
     }
     // only allow this to be set through the method.
     $vendor_id = update_insert("vendor_id", $vendor_id, "vendor", $data);
     if (isset($_REQUEST['user_id'])) {
         $user_id = (int) $_REQUEST['user_id'];
         if ($user_id > 0) {
             // check permissions
             $temp_user = module_user::get_user($user_id);
             if (!$temp_user || $temp_user['user_id'] != $user_id) {
                 $user_id = false;
             }
         }
         // assign specified user_id to this vendor.
         // could this be a problem?
         // maybe?
         // todo: think about security precautions here, maybe only allow admins to set primary contacts.
         $data['vendor_id'] = $vendor_id;
         if (!$user_id) {
             // hack to set the default role of a contact (if one is set in settings).
             if (!isset($data['last_name']) && isset($data['name']) && strpos($data['name'], ' ') > 0) {
                 // todo - save from vendor import
                 $bits = explode(' ', $data['name']);
                 $data['last_name'] = array_pop($bits);
                 $data['name'] = implode(' ', $bits);
             }
             $user_id = update_insert("user_id", false, "user", $data);
             module_cache::clear('user');
             $role_id = module_config::c('contact_default_role', 0);
             if ($role_id > 0) {
                 module_user::add_user_to_role($user_id, $role_id);
             }
             $this->set_primary_user_id($vendor_id, $user_id);
         } else {
             // make sure this user is part of this vendor.
             // wait! addition, we want to be able to move an existing vendor contact to this new vendor.
             $saved_user_id = false;
             if (isset($_REQUEST['move_user_id']) && (int) $_REQUEST['move_user_id'] && module_vendor::can_i('create', 'Companies')) {
                 $old_user = module_user::get_user((int) $_REQUEST['move_user_id']);
                 if ($old_user && $old_user['user_id'] == (int) $_REQUEST['move_user_id']) {
                     $saved_user_id = $user_id = update_insert("user_id", $user_id, "user", $data);
                     module_cache::clear('user');
                     hook_handle_callback('vendor_contact_moved', $user_id, $old_user['vendor_id'], $vendor_id);
                     $this->set_primary_user_id($vendor_id, $user_id);
                     module_cache::clear('user');
                 }
             } else {
                 // save normally, only those linked to this account:
                 $users = module_user::get_contacts(array('vendor_id' => $vendor_id));
                 foreach ($users as $user) {
                     if ($user['user_id'] == $user_id) {
                         $saved_user_id = $user_id = update_insert("user_id", $user_id, "user", $data);
                         $this->set_primary_user_id($vendor_id, $user_id);
                         module_cache::clear('user');
                         break;
                     }
                 }
             }
             if (!$saved_user_id) {
                 $this->set_primary_user_id($vendor_id, 0);
                 module_cache::clear('user');
             }
         }
         // todo: move this functionality back into the user class.
         // maybe with a static save_user method ?
         if ($user_id > 0 && class_exists('module_extra', false) && module_extra::is_plugin_enabled()) {
             module_extra::save_extras('user', 'user_id', $user_id);
         }
     }
     handle_hook("address_block_save", $this, "physical", "vendor", "vendor_id", $vendor_id);
     //handle_hook("address_block_save",$this,"postal","vendor","vendor_id",$vendor_id);
     if (class_exists('module_extra', false) && module_extra::is_plugin_enabled()) {
         module_extra::save_extras('vendor', 'vendor_id', $vendor_id);
     }
     // save the company information if it's available
     if (class_exists('module_company', false) && module_company::can_i('view', 'Company') && module_company::is_enabled()) {
         if (isset($_REQUEST['available_vendor_company']) && is_array($_REQUEST['available_vendor_company'])) {
             $selected_companies = isset($_POST['vendor_company']) && is_array($_POST['vendor_company']) ? $_POST['vendor_company'] : array();
             $company_access = module_company::get_company_data_access();
             if ($company_access == _COMPANY_ACCESS_ALL && !count($selected_companies)) {
                 // user is unassignging this vendor from all companies we have access to, dont let them do this?
             }
             foreach ($_REQUEST['available_vendor_company'] as $company_id => $tf) {
                 if (!isset($selected_companies[$company_id]) || !$selected_companies[$company_id]) {
                     // remove vendor from this company
                     module_company::delete_vendor($company_id, $vendor_id);
                 } else {
                     // add vendor to this company (if they are not already existing)
                     module_company::add_vendor_to_company($company_id, $vendor_id);
                 }
             }
         }
     }
     self::update_vendor_status($vendor_id);
     module_cache::clear('vendor');
     return $vendor_id;
 }
Exemple #13
0
 public function save_website($website_id, $data)
 {
     if ((int) $website_id > 0) {
         $original_website_data = $this->get_website($website_id);
         if (!$original_website_data || $original_website_data['website_id'] != $website_id) {
             $original_website_data = array();
             $website_id = false;
         }
     } else {
         $original_website_data = array();
         $website_id = false;
     }
     if (_DEMO_MODE && $website_id == 1) {
         set_error('This is a Demo Website. Some things cannot be changed.');
         foreach (array('name', 'url', 'customer_id') as $key) {
             if (isset($data[$key])) {
                 unset($data[$key]);
             }
         }
     }
     // check create permissions.
     if (!$website_id && !self::can_i('create', 'Websites')) {
         // user not allowed to create websites.
         set_error('Unable to create new Websites');
         redirect_browser(self::link_open(false));
     }
     $website_id = update_insert("website_id", $website_id, "website", $data);
     if (isset($original_website_data['customer_id']) && $original_website_data['customer_id'] && isset($data['customer_id']) && $data['customer_id'] && $original_website_data['customer_id'] != $data['customer_id']) {
         //module_cache::clear_cache();
         // the customer id has changed. update jobs and invoices.
         // bad! this will swap all jobs, invoices and files from this customer to another customer.
         //module_job::customer_id_changed($original_website_data['customer_id'],$data['customer_id']);
     }
     module_extra::save_extras('website', 'website_id', $website_id);
     return $website_id;
 }
Exemple #14
0
 public function save_newsletter($newsletter_id, $data)
 {
     $newsletter_id = update_insert("newsletter_id", $newsletter_id, "newsletter", $data);
     module_extra::save_extras('newsletter', 'newsletter_id', $newsletter_id);
     return $newsletter_id;
 }
Exemple #15
0
 public function save_ticket($ticket_id, $data)
 {
     if (isset($data['website_id']) && $data['website_id']) {
         $website = module_website::get_website($data['website_id']);
         $data['customer_id'] = $website['customer_id'];
     }
     if (isset($data['user_id']) && $data['user_id']) {
         $user = module_user::get_user($data['user_id'], false);
         if (!isset($data['customer_id']) || !$data['customer_id']) {
             $data['customer_id'] = $user['customer_id'];
         }
     }
     if ((int) $ticket_id > 0) {
         $existing_ticket_data = $this->get_ticket($ticket_id);
     } else {
         $existing_ticket_data = array();
     }
     if (isset($data['change_assigned_user_id']) && (int) $data['change_assigned_user_id'] > 0) {
         // check if we're realling changing the user.
         if ($ticket_id > 0) {
             if ($existing_ticket_data['assigned_user_id'] != $data['change_assigned_user_id']) {
                 // they are really changing the user
                 $data['assigned_user_id'] = $data['change_assigned_user_id'];
             }
         } else {
             $data['assigned_user_id'] = $data['change_assigned_user_id'];
         }
         module_cache::clear('ticket');
     }
     $ticket_id = update_insert("ticket_id", $ticket_id, "ticket", $data);
     if ($ticket_id) {
         // save any extra data
         if (isset($data['ticket_extra']) && is_array($data['ticket_extra'])) {
             $available_extra_fields = $this->get_ticket_extras_keys();
             foreach ($data['ticket_extra'] as $ticket_data_key_id => $ticket_data_key_value) {
                 if (strlen($ticket_data_key_value) > 0 && isset($available_extra_fields[$ticket_data_key_id])) {
                     // save this one!
                     // hack: addition for encryption module.
                     // bit nasty, but it works.
                     if (class_exists('module_encrypt', false) && isset($available_extra_fields[$ticket_data_key_id]['encrypt_key_id']) && $available_extra_fields[$ticket_data_key_id]['encrypt_key_id'] && strpos($ticket_data_key_value, 'encrypt:') === false && ($available_extra_fields[$ticket_data_key_id]['type'] == 'text' || $available_extra_fields[$ticket_data_key_id]['type'] == 'textarea')) {
                         // encrypt this value using this key.
                         $page_name = 'ticket_extras';
                         // match the page_name we have in ticket_extra_sidebar.php
                         $input_id = 'ticket_extras_' . $ticket_data_key_id;
                         // match the input id we have in ticket_extra_sidebar.php
                         $ticket_data_key_value = module_encrypt::save_encrypt_value($available_extra_fields[$ticket_data_key_id]['encrypt_key_id'], $ticket_data_key_value, $page_name, $input_id);
                     }
                     // check for existing
                     $existing = get_single('ticket_data', array('ticket_id', 'ticket_data_key_id'), array($ticket_id, $ticket_data_key_id));
                     if ($existing) {
                         update_insert('ticket_data_id', $existing['ticket_data_id'], 'ticket_data', array('value' => $ticket_data_key_value));
                     } else {
                         update_insert('ticket_data_id', 'new', 'ticket_data', array('ticket_data_key_id' => $ticket_data_key_id, 'ticket_id' => $ticket_id, 'value' => $ticket_data_key_value));
                     }
                 }
             }
         }
         $ticket_message_id = false;
         if (isset($data['new_ticket_message']) && strlen($data['new_ticket_message']) > 1) {
             // post a new reply to this message.
             // who are we replying to?
             $ticket_data = $this->get_ticket($ticket_id);
             if (isset($data['change_status_id']) && $data['change_status_id']) {
                 update_insert("ticket_id", $ticket_id, "ticket", array('status_id' => $data['change_status_id']));
             } else {
                 if ($ticket_data['status_id'] == _TICKET_STATUS_RESOLVED_ID || $ticket_data['status_id'] == 7) {
                     $data['change_status_id'] = _TICKET_STATUS_IN_PROGRESS_ID;
                     // change to in progress.
                 }
             }
             module_cache::clear('ticket');
             // it's either a reply from the admin, or from the user via the web interface.
             $ticket_data = $this->get_ticket($ticket_id);
             $logged_in_user = isset($data['force_logged_in_user_id']) ? $data['force_logged_in_user_id'] : false;
             if (!$logged_in_user) {
                 $logged_in_user = module_security::get_loggedin_id();
                 if (!$logged_in_user) {
                     $logged_in_user = $ticket_data['user_id'];
                 }
             }
             if (!$ticket_data['user_id'] && module_security::get_loggedin_id()) {
                 update_insert('ticket_id', $ticket_id, 'ticket', array('user_id' => module_security::get_loggedin_id()));
                 $ticket_data['user_id'] = module_security::get_loggedin_id();
             }
             $ticket_creator = $ticket_data['user_id'];
             // echo "creator: $ticket_creator logged in: $logged_in_user"; print_r($ticket_data);exit;
             //echo "Creator: ".$ticket_data['user_id'] . " logged in ".$logged_in_user;exit;
             if ($ticket_creator == $logged_in_user) {
                 // we are sending a reply back to the admin, from the end user.
                 self::mark_as_unread($ticket_id);
                 $ticket_message_id = $this->send_reply($ticket_id, $data['new_ticket_message'], $ticket_creator, $ticket_data['assigned_user_id'] ? $ticket_data['assigned_user_id'] : module_config::c('ticket_default_user_id', 1), 'end_user', '', array('private_message' => isset($data['private_message']) && $data['private_message']));
             } else {
                 // we are sending a reply back to the ticket user.
                 // admin is allowed to change the status of a message.
                 $from_user_id = $ticket_data['assigned_user_id'] ? $ticket_data['assigned_user_id'] : module_security::get_loggedin_id();
                 //echo "From $from_user_id to $ticket_creator ";exit;
                 $ticket_message_id = $this->send_reply($ticket_id, $data['new_ticket_message'], $from_user_id, $ticket_creator, 'admin', '', array('private_message' => isset($data['private_message']) && $data['private_message']));
                 // do we add cc/bcc here?
             }
             if ($ticket_message_id && isset($data['change_status_id']) && $data['change_status_id']) {
                 // store the ticket status change here.
                 update_insert("ticket_message_id", $ticket_message_id, "ticket_message", array('status_id' => $data['change_status_id']));
             }
         }
         if (isset($data['change_status_id']) && $data['change_status_id']) {
             // we only update this status if the sent reply or send reply and next buttons are clicked.
             if (isset($_REQUEST['newmsg']) || isset($_REQUEST['newmsg_next'])) {
                 update_insert("ticket_id", $ticket_id, "ticket", array('status_id' => $data['change_status_id']));
             }
         }
     }
     module_extra::save_extras('ticket', 'ticket_id', $ticket_id);
     // automaticall send notification email to assigned staff membeR?
     if (module_config::c('ticket_auto_notify_staff', 0)) {
         module_cache::clear('ticket');
         $new_ticket_data = self::get_ticket($ticket_id);
         if ($new_ticket_data['assigned_user_id'] && (!$existing_ticket_data || $existing_ticket_data['assigned_user_id'] != $new_ticket_data['assigned_user_id'])) {
             // copied from ticket_admin_notify.php
             // template for sending emails.
             // are we sending the paid one? or the dueone.
             $template = module_template::get_template_by_key('ticket_email_notify');
             $new_ticket_data['from_name'] = module_security::get_loggedin_name();
             $new_ticket_data['ticket_url'] = module_ticket::link_open($ticket_id);
             $new_ticket_data['ticket_subject'] = $new_ticket_data['subject'];
             // sending to the staff member.
             $replace_fields = self::get_replace_fields($new_ticket_data['ticket_id'], $new_ticket_data);
             $template->assign_values($replace_fields);
             $template->assign_values($new_ticket_data);
             $html = $template->render('html');
             $email = module_email::new_email();
             $email->replace_values = $new_ticket_data + $replace_fields;
             $email->set_subject($template->description);
             $email->set_to('user', $new_ticket_data['assigned_user_id']);
             // do we send images inline?
             $email->set_html($html);
             if ($email->send()) {
                 // it worked successfully!!
             } else {
                 /// log err?
             }
         }
     }
     module_cache::clear('ticket');
     return $ticket_id;
 }