function execute()
 {
     /*
     	Define form structure
     */
     $this->obj_form = new form_input();
     $this->obj_form->formname = "translation_form";
     $this->obj_form->language = $_SESSION["user"]["lang"];
     $this->obj_form->action = "popup/translation_form-process.php";
     $this->obj_form->method = "post";
     $this->num_trans = 5;
     for ($i = 1; $i <= $this->num_trans; $i++) {
         $structure = NULL;
         $structure["fieldname"] = "untranslated_" . $i;
         $structure["type"] = "input";
         $this->obj_form->add_input($structure);
         $structure = NULL;
         $structure["fieldname"] = "translated_" . $i;
         $structure["type"] = "input";
         $this->obj_form->add_input($structure);
     }
     $structure = NULL;
     $structure["fieldname"] = "submit";
     $structure["type"] = "submit";
     $structure["defaultvalue"] = "Save Translations";
     $this->obj_form->add_input($structure);
     $structure = NULL;
     $structure["fieldname"] = "num_trans";
     $structure["type"] = "hidden";
     $structure["defaultvalue"] = $this->num_trans;
     $this->obj_form->add_input($structure);
     if (error_check()) {
         $this->obj_form->load_data_error();
     }
 }
示例#2
0
 function execute()
 {
     /*
     	Define form structure
     */
     $this->obj_form = new form_input();
     $this->obj_form->formname = "name_server_edit";
     $this->obj_form->language = $_SESSION["user"]["lang"];
     $this->obj_form->action = "servers/group-edit-process.php";
     $this->obj_form->method = "post";
     // general
     $structure = NULL;
     $structure["fieldname"] = "group_name";
     $structure["type"] = "input";
     $structure["options"]["req"] = "yes";
     $this->obj_form->add_input($structure);
     $structure = NULL;
     $structure["fieldname"] = "group_description";
     $structure["type"] = "textarea";
     $this->obj_form->add_input($structure);
     // submit section
     $structure = NULL;
     $structure["fieldname"] = "submit";
     $structure["type"] = "submit";
     $structure["defaultvalue"] = "Save Changes";
     $this->obj_form->add_input($structure);
     // subforms
     $this->obj_form->subforms["group_details"] = array("group_name", "group_description");
     $this->obj_form->subforms["submit"] = array("submit");
     // load data
     if (error_check()) {
         $this->obj_form->load_data_error();
     }
 }
示例#3
0
 function execute()
 {
     /*
     	Define form structure
     */
     $this->obj_form = new form_input();
     $this->obj_form->formname = "name_server_delete";
     $this->obj_form->language = $_SESSION["user"]["lang"];
     $this->obj_form->action = "servers/delete-process.php";
     $this->obj_form->method = "post";
     // general
     $structure = NULL;
     $structure["fieldname"] = "server_name";
     $structure["type"] = "text";
     $this->obj_form->add_input($structure);
     $structure = NULL;
     $structure["fieldname"] = "server_description";
     $structure["type"] = "text";
     $this->obj_form->add_input($structure);
     // hidden section
     $structure = NULL;
     $structure["fieldname"] = "id_name_server";
     $structure["type"] = "hidden";
     $structure["defaultvalue"] = $this->obj_name_server->id;
     $this->obj_form->add_input($structure);
     // confirm delete
     $structure = NULL;
     $structure["fieldname"] = "delete_confirm";
     $structure["type"] = "checkbox";
     $structure["options"]["label"] = "Yes, I wish to delete this server and realise that once deleted the data can not be recovered.";
     $this->obj_form->add_input($structure);
     // submit
     $structure = NULL;
     $structure["fieldname"] = "submit";
     $structure["type"] = "submit";
     $structure["defaultvalue"] = "delete";
     $this->obj_form->add_input($structure);
     // define subforms
     $this->obj_form->subforms["server_delete"] = array("server_name", "server_description");
     $this->obj_form->subforms["hidden"] = array("id_name_server");
     $this->obj_form->subforms["submit"] = array("delete_confirm", "submit");
     // import data
     if (error_check()) {
         $this->obj_form->load_data_error();
     } else {
         if ($this->obj_name_server->load_data()) {
             $this->obj_form->structure["server_name"]["defaultvalue"] = $this->obj_name_server->data["server_name"];
             $this->obj_form->structure["server_description"]["defaultvalue"] = $this->obj_name_server->data["server_description"];
         }
     }
 }
function safe_query($query)
{
    set_error_handler("exception_error_handler");
    try {
        $result = pg_query($query);
    } catch (Exception $e) {
        echo "<pre>Problem with query: " . $query . "\n";
        echo "<pre>Error Message:" . $e->getMessage() . "</pre>\n";
        // This needs to be updated to redirect to a well-formatted error screen
    }
    //This checks for non-fatal errors that return nothing to $result
    error_check($result, $query);
    return $result;
}
 function execute()
 {
     /*
     	Define form structure
     */
     $this->obj_form = new form_input();
     $this->obj_form->formname = "config_integration";
     $this->obj_form->language = $_SESSION["user"]["lang"];
     $this->obj_form->action = "admin/config_integration-process.php";
     $this->obj_form->method = "post";
     // customer portal stuff
     $structure = NULL;
     $structure["fieldname"] = "MODULE_CUSTOMER_PORTAL";
     $structure["type"] = "checkbox";
     $structure["options"]["no_translate_fieldname"] = "yes";
     $structure["options"]["label"] = "Enable/disable the customer portal integration.";
     $this->obj_form->add_input($structure);
     // submit section
     $structure = NULL;
     $structure["fieldname"] = "submit";
     $structure["type"] = "submit";
     $structure["defaultvalue"] = "Save Changes";
     $this->obj_form->add_input($structure);
     // define subforms
     $this->obj_form->subforms["config_integration"] = array("MODULE_CUSTOMER_PORTAL");
     $this->obj_form->subforms["submit"] = array("submit");
     if (error_check()) {
         // load error datas
         $this->obj_form->load_data_error();
     } else {
         // fetch all the values from the database
         $sql_config_obj = new sql_query();
         $sql_config_obj->string = "SELECT name, value FROM config ORDER BY name";
         $sql_config_obj->execute();
         $sql_config_obj->fetch_array();
         foreach ($sql_config_obj->data as $data_config) {
             $this->obj_form->structure[$data_config["name"]]["defaultvalue"] = $data_config["value"];
         }
         unset($sql_config_obj);
     }
 }
 function execute()
 {
     $this->statement_array = $_SESSION["statement_array"];
     $values_array = array("ar", "ap", "transfer", "bank_fee", "interest");
     $this->obj_form = new form_input();
     $this->obj_form->formname = "bankstatement_assign";
     $i = 1;
     foreach ($this->statement_array as $transaction => $data) {
         $name = "transaction" . $i;
         /*
         	1. DETERMINE TRANSACTION TYPE
         
         	Determine what type of row this bank statement line item is. We do this
         	by keyword matching and checking for information such as amount being
         	positive/negative.
         */
         $row_assignment = null;
         if ($data["amount"] > 0) {
             $row_assignment = 'ar';
         }
         $lowercased_strings = strtolower($data['other_party']) . " " . strtolower($data['transaction_type']) . " " . strtolower($data['particulars']) . " " . strtolower($data['code']);
         $search_regex = "/(interest|transfer|fee|tax|account\\smaintenance){1}/";
         preg_match($search_regex, $lowercased_strings, $matches);
         switch ($matches[1]) {
             case 'tax':
             case 'transfer':
                 $row_assignment = 'transfer';
                 break;
             case 'interest':
                 $row_assignment = 'interest';
                 break;
             case 'fee':
             case 'account maintenance':
                 $row_assignment = 'bank_fee';
                 break;
             default:
                 if ($row_assignment == null) {
                     $row_assignment = 'ap';
                 }
                 break;
         }
         // assignment drop down
         $structure = NULL;
         $structure["fieldname"] = $name . "-assign";
         $structure["type"] = "dropdown";
         $structure["values"] = $values_array;
         $structure["defaultvalue"] = $row_assignment;
         $this->obj_form->add_input($structure);
         /*
         	2. HIDDEN ATTRIBUTES NEEDED FOR PROCESSING
         */
         // hidden date field
         $structure = NULL;
         $structure["fieldname"] = $name . "-date";
         $structure["type"] = "hidden";
         $structure["defaultvalue"] = date("Y-m-d", strtotime(str_replace("/", "-", $data["date"])));
         $this->obj_form->add_input($structure);
         // hidden amount field
         $structure = NULL;
         $structure["fieldname"] = $name . "-amount";
         $structure["type"] = "hidden";
         $structure["defaultvalue"] = $data["amount"];
         $this->obj_form->add_input($structure);
         //hidden other_party field
         if (isset($data["other_party"]) && $data["other_party"] != "") {
             $structure = NULL;
             $structure["fieldname"] = $name . "-other_party";
             $structure["type"] = "hidden";
             $structure["defaultvalue"] = $data["other_party"];
             $this->obj_form->add_input($structure);
         }
         //hidden transaction_type field
         if (isset($data["transaction_type"]) && $data["transaction_type"] != "") {
             $structure = NULL;
             $structure["fieldname"] = $name . "-transaction_type";
             $structure["type"] = "hidden";
             $structure["defaultvalue"] = $data["transaction_type"];
             $this->obj_form->add_input($structure);
         }
         //hidden code field
         if (isset($data["code"]) && $data["code"] != "") {
             $structure = NULL;
             $structure["fieldname"] = $name . "-code";
             $structure["type"] = "hidden";
             $structure["defaultvalue"] = $data["code"];
             $this->obj_form->add_input($structure);
         }
         //hidden reference field
         if (isset($data["reference"]) && $data["reference"] != "") {
             $structure = NULL;
             $structure["fieldname"] = $name . "-reference";
             $structure["type"] = "hidden";
             $structure["defaultvalue"] = $data["reference"];
             $this->obj_form->add_input($structure);
         }
         //hidden particulars field
         if (isset($data["particulars"]) && $data["particulars"] != "") {
             $structure = NULL;
             $structure["fieldname"] = $name . "-particulars";
             $structure["type"] = "hidden";
             $structure["defaultvalue"] = $data["particulars"];
             $this->obj_form->add_input($structure);
         }
         /*
         	3. AR TRANSACTION OPTIONS
         
         	We attempt to match the customer and/or the invoice here.
         */
         // customer drop down
         $structure = NULL;
         $structure = form_helper_prepare_dropdownfromdb($name . "-customer", "SELECT id, code_customer AS label, name_customer AS label1 FROM customers ORDER BY code_customer ASC");
         $search_values = array();
         $search_values[] = strtolower(preg_quote($data['other_party'], "/"));
         if ($data["reference"] != null) {
             $search_values[] = strtolower(preg_quote($data['reference'], "/"));
         }
         if ($data["code"] != null) {
             $search_values[] = strtolower(preg_quote($data['code'], "/"));
         }
         if ($data["particulars"] != null) {
             $search_values[] = strtolower(preg_quote($data['particulars'], "/"));
         }
         if (is_array($search_values) && is_array($structure["translations"])) {
             $matching_entries = preg_grep("/" . implode("|", $search_values) . "/i", $structure['translations']);
             $matching_entry_keys = array_keys($matching_entries);
             $structure["defaultvalue"] = $matching_entry_keys[0];
         }
         $this->obj_form->add_input($structure);
         // AR invoice drop down
         $structure = NULL;
         $structure = form_helper_prepare_dropdownfromdb($name . "-arinvoice", "SELECT id, code_invoice AS label, amount_total AS label1 FROM account_ar WHERE amount_paid < amount_total ORDER BY code_invoice ASC");
         $search_values = array();
         $search_values[] = strtolower(preg_quote(str_replace("-", '', " " . $data['amount']), "/"));
         if ($data["reference"] != null) {
             $search_values[] = strtolower(preg_quote($data['reference'], "/"));
         }
         if ($data["code"] != null) {
             $search_values[] = strtolower(preg_quote($data['code'], "/"));
         }
         if ($data["particulars"] != null) {
             $search_values[] = strtolower(preg_quote($data['particulars'], "/"));
         }
         if (is_array($search_values) && is_array($structure["translations"])) {
             $matching_entries = preg_grep("/" . implode("|", $search_values) . "/i", $structure['translations']);
             $matching_entry_keys = array_keys($matching_entries);
             $structure["defaultvalue"] = $matching_entry_keys[0];
         }
         $this->obj_form->add_input($structure);
         /*
         	4. AP TRANSACTION OPTIONS
         
         	We attempt to match the vendor and/or the invoice here.
         */
         // vendors drop down
         $structure = NULL;
         $structure = form_helper_prepare_dropdownfromdb($name . "-vendor", "SELECT id, code_vendor AS label, name_vendor AS label1 FROM vendors ORDER BY code_vendor ASC");
         $search_values = array();
         $search_values[] = strtolower(preg_quote($data['other_party'], "/"));
         if ($data["reference"] != null) {
             $search_values[] = strtolower(preg_quote($data['reference'], "/"));
         }
         if ($data["code"] != null) {
             $search_values[] = strtolower(preg_quote($data['code'], "/"));
         }
         if ($data["particulars"] != null) {
             $search_values[] = strtolower(preg_quote($data['particulars'], "/"));
         }
         if (is_array($search_values) && is_array($structure["translations"])) {
             $matching_entries = preg_grep("/" . implode("|", $search_values) . "/i", $structure['translations']);
             $matching_entry_keys = array_keys($matching_entries);
             $structure["defaultvalue"] = $matching_entry_keys[0];
         }
         $this->obj_form->add_input($structure);
         //AP invoice drop down
         $structure = NULL;
         $structure = form_helper_prepare_dropdownfromdb($name . "-apinvoice", "SELECT id, code_invoice AS label, amount_total AS label1 FROM account_ap WHERE amount_paid < amount_total ORDER BY code_invoice ASC");
         $search_values = array();
         $search_values[] = strtolower(preg_quote(str_replace("-", '', " " . $data['amount']), "/"));
         if ($data["reference"] != null) {
             $search_values[] = strtolower(preg_quote($data['reference'], "/"));
         }
         if ($data["code"] != null) {
             $search_values[] = strtolower(preg_quote($data['code'], "/"));
         }
         if ($data["particulars"] != null) {
             $search_values[] = strtolower(preg_quote($data['particulars'], "/"));
         }
         if (is_array($search_values) && is_array($structure["translations"])) {
             $matching_entries = preg_grep("/" . implode("|", $search_values) . "/i", $structure['translations']);
             $matching_entry_keys = array_keys($matching_entries);
             $structure["defaultvalue"] = $matching_entry_keys[0];
         }
         $this->obj_form->add_input($structure);
         /*
         	5. BANK FEE/CHARGES
         
         	Bank charges are always going to be from the current asset account to an expense account.
         */
         //Bank fees expense account drop down
         $structure = NULL;
         $structure = form_helper_prepare_dropdownfromdb($name . "-bankfeesexpense", "SELECT ac.id, ac.code_chart AS label, ac.description AS label1 FROM account_charts ac JOIN account_chart_type act ON ac.chart_type = act.id WHERE act.value = \"Expense\" ORDER BY ac.code_chart ASC");
         $this->obj_form->add_input($structure);
         //Bank fees asset account drop down
         $structure = NULL;
         $structure = form_helper_prepare_dropdownfromdb($name . "-bankfeesasset", "SELECT ac.id, ac.code_chart AS label, ac.description AS label1 FROM account_charts ac JOIN account_chart_type act ON ac.chart_type = act.id WHERE act.value = \"Asset\" ORDER BY ac.code_chart ASC");
         $structure["defaultvalue"] = $_SESSION["dest_account"];
         $this->obj_form->add_input($structure);
         /*
         	6. INTEREST
         */
         //Interest asset account drop down
         $structure = NULL;
         $structure = form_helper_prepare_dropdownfromdb($name . "-interestasset", "SELECT ac.id, ac.code_chart AS label, ac.description AS label1 FROM account_charts ac JOIN account_chart_type act ON ac.chart_type = act.id WHERE act.value = \"Asset\" ORDER BY ac.code_chart ASC");
         $this->obj_form->add_input($structure);
         //Interest income account drop down
         $structure = NULL;
         $structure = form_helper_prepare_dropdownfromdb($name . "-interestincome", "SELECT ac.id, ac.code_chart AS label, ac.description AS label1 FROM account_charts ac JOIN account_chart_type act ON ac.chart_type = act.id WHERE act.value = \"Income\" ORDER BY ac.code_chart ASC");
         $this->obj_form->add_input($structure);
         /*
         	7. GENERAL ACCOUNT TRANSFER
         
         	Not much to do for account transfers, but we can choose which account is selected for to/from based on
         	the default selected account.
         */
         if ($data["amount"] > 0) {
             // Transfer INTO the selected account
             //
             // Transfer from account drop down
             $structure = NULL;
             $structure = form_helper_prepare_dropdownfromdb($name . "-transferfrom", "SELECT ac.id, ac.code_chart AS label, ac.description AS label1 FROM account_charts ac JOIN account_chart_type act ON ac.chart_type = act.id ORDER BY ac.code_chart ASC");
             $this->obj_form->add_input($structure);
             //Transfer to account drop down
             $structure = NULL;
             $structure = form_helper_prepare_dropdownfromdb($name . "-transferto", "SELECT ac.id, ac.code_chart AS label, ac.description AS label1 FROM account_charts ac JOIN account_chart_type act ON ac.chart_type = act.id ORDER BY ac.code_chart ASC");
             $structure["defaultvalue"] = $_SESSION["dest_account"];
             $this->obj_form->add_input($structure);
         } else {
             // Transfer FROM the selected account
             //
             // Transfer from account drop down
             $structure = NULL;
             $structure = form_helper_prepare_dropdownfromdb($name . "-transferfrom", "SELECT ac.id, ac.code_chart AS label, ac.description AS label1 FROM account_charts ac JOIN account_chart_type act ON ac.chart_type = act.id ORDER BY ac.code_chart ASC");
             $structure["defaultvalue"] = $_SESSION["dest_account"];
             $this->obj_form->add_input($structure);
             //Transfer to account drop down
             $structure = NULL;
             $structure = form_helper_prepare_dropdownfromdb($name . "-transferto", "SELECT ac.id, ac.code_chart AS label, ac.description AS label1 FROM account_charts ac JOIN account_chart_type act ON ac.chart_type = act.id ORDER BY ac.code_chart ASC");
             $this->obj_form->add_input($structure);
         }
         /*
         	8. ENABLE/DISABLE FIELD
         
         	Users have the option of excluding rows that they don't want processed by unchecking them from the import.
         */
         // Hidden enabled field
         $structure = NULL;
         $structure["fieldname"] = $name . "-enabled";
         $structure["type"] = "hidden";
         // if the amount is not a number, disable the row
         if (!is_numeric($data["amount"])) {
             $structure["defaultvalue"] = "false";
         } else {
             $structure["defaultvalue"] = "true";
         }
         $this->obj_form->add_input($structure);
         $i++;
     }
     // hidden field for number of transactions
     $structure = NULL;
     $structure["fieldname"] = "num_trans";
     $structure["type"] = "hidden";
     $structure["defaultvalue"] = count($this->statement_array);
     $this->obj_form->add_input($structure);
     $structure = NULL;
     $structure["fieldname"] = "submit";
     $structure["type"] = "submit";
     $structure["defaultvalue"] = "Apply";
     $this->obj_form->add_input($structure);
     if (error_check()) {
         $this->obj_form->load_data_error();
     }
 }
function graph_cumulative_bydate2($p_metrics, $p_graph_width = 300, $p_graph_height = 380)
{
    $t_graph_font = 'c:\\windows\\fonts\\arial.ttf';
    //graph_get_font();
    error_check(is_array($p_metrics) ? count($p_metrics) : 0, plugin_lang_get('cumulative') . ' ' . lang_get('by_date'));
    $graph = new ezcGraphLineChart();
    $graph->xAxis = new ezcGraphChartElementNumericAxis();
    $graph->data[0] = new ezcGraphArrayDataSet($p_metrics[0]);
    $graph->data[0]->label = plugin_lang_get('legend_reported');
    $graph->data[0]->color = '#FF0000';
    $graph->data[1] = new ezcGraphArrayDataSet($p_metrics[1]);
    $graph->data[1]->label = plugin_lang_get('legend_resolved');
    $graph->data[1]->color = '#0000FF';
    $graph->data[2] = new ezcGraphArrayDataSet($p_metrics[2]);
    $graph->data[2]->label = plugin_lang_get('legend_still_open');
    $graph->data[2]->color = '#000000';
    $graph->additionalAxis[2] = $nAxis = new ezcGraphChartElementNumericAxis();
    $nAxis->chartPosition = 1;
    $nAxis->background = '#005500';
    $nAxis->border = '#005500';
    $nAxis->position = ezcGraph::BOTTOM;
    $graph->data[2]->yAxis = $nAxis;
    $graph->xAxis->labelCallback = 'graph_date_format';
    $graph->xAxis->axisLabelRenderer = new ezcGraphAxisRotatedLabelRenderer();
    $graph->xAxis->axisLabelRenderer->angle = -45;
    //$graph->xAxis->axisSpace = .8;
    $graph->legend->position = ezcGraph::BOTTOM;
    $graph->legend->background = '#FFFFFF80';
    $graph->driver = new ezcGraphGdDriver();
    //$graph->driver->options->supersampling = 1;
    $graph->driver->options->jpegQuality = 100;
    $graph->driver->options->imageFormat = IMG_JPEG;
    //	$graph->img->SetMargin( 40, 40, 40, 170 );
    //	if( ON == config_get_global( 'jpgraph_antialias' ) ) {
    //		$graph->img->SetAntiAliasing();
    //	}
    //	$graph->SetScale( 'linlin');
    //	$graph->yaxis->SetColor("red");
    //	$graph->SetY2Scale("lin");
    //	$graph->SetMarginColor( 'white' );
    //	$graph->SetFrame( false );
    $graph->title = plugin_lang_get('cumulative') . ' ' . lang_get('by_date');
    $graph->options->font = $t_graph_font;
    //	$graph->title->SetFont( $t_graph_font, FS_BOLD );
    /*	$graph->legend->Pos( 0.05, 0.9, 'right', 'bottom' );
    	$graph->legend->SetShadow( false );
    	$graph->legend->SetFillColor( 'white' );
    	$graph->legend->SetLayout( LEGEND_HOR );
    	$graph->legend->SetFont( $t_graph_font );
    
    	$graph->yaxis->scale->ticks->SetDirection( -1 );
    	$graph->yaxis->SetFont( $t_graph_font );
    	$graph->y2axis->SetFont( $t_graph_font );
    
    	if( FF_FONT2 <= $t_graph_font ) {
    		$graph->xaxis->SetLabelAngle( 60 );
    	} else {
    		$graph->xaxis->SetLabelAngle( 90 );
    
    		# can't rotate non truetype fonts
    	}
    	$graph->xaxis->SetLabelFormatCallback( 'graph_date_format' );
    	$graph->xaxis->SetFont( $t_graph_font );
    
    	$p1 = new LinePlot( $reported_plot, $plot_date );
    	$p1->SetColor( 'blue' );
    	$p1->SetCenter();
    	$graph->AddY2( $p1 );
    
    	$p3 = new LinePlot( $still_open_plot, $plot_date );
    	$p3->SetColor( 'red' );
    	$p3->SetCenter();
    	$p3->SetLegend(  );
    	$graph->Add( $p3 );
    
    	$p2 = new LinePlot( $resolved_plot, $plot_date );
    	$p2->SetColor( 'black' );
    	$p2->SetCenter();
    	$p2->SetLegend(  );
    	$graph->AddY2( $p2 );
    */
    /*	if( helper_show_queries() ) {
    		$graph->subtitle->Set( db_count_queries() . ' queries (' . db_time_queries() . 'sec)' );
    		$graph->subtitle->SetFont( $t_graph_font, FS_NORMAL, 8 );
    	}*/
    $graph->renderToOutput($p_graph_width, $p_graph_height);
}
function service_form_delete_process()
{
    log_debug("inc_services_process", "Executing service_form_delete_process()");
    /*
    	Fetch all form data
    */
    // get form data
    $id = @security_form_input_predefined("int", "id_service", 1, "");
    $data["delete_confirm"] = @security_form_input_predefined("any", "delete_confirm", 1, "You must confirm the deletion");
    //// ERROR CHECKING ///////////////////////
    // make sure the service actually exists
    $sql_obj = new sql_query();
    $sql_obj->string = "SELECT id FROM services WHERE id='{$id}' LIMIT 1";
    $sql_obj->execute();
    if (!$sql_obj->num_rows()) {
        log_write("error", "process", "The service you have attempted to edit - {$id} - does not exist in this system.");
    }
    // make sure the service is not active for any customers
    $sql_obj = new sql_query();
    $sql_obj->string = "SELECT id FROM services_customers WHERE serviceid='{$id}' LIMIT 1";
    $sql_obj->execute();
    if ($sql_obj->num_rows()) {
        log_write("error", "process", "Service is active for customers and can therefore not be deleted.");
    }
    /// if there was an error, go back to the entry page
    if ($_SESSION["error"]["message"]) {
        $_SESSION["error"]["form"]["service_delete"] = "failed";
        header("Location: ../index.php?page=services/delete.php&id={$id}");
        exit(0);
    } else {
        /*
        	Begin Transaction
        */
        $sql_obj = new sql_query();
        $sql_obj->trans_begin();
        /*
        	Delete the service data
        */
        $sql_obj->string = "DELETE FROM services WHERE id='{$id}' LIMIT 1";
        $sql_obj->execute();
        /*
        	Delete the service taxes
        */
        $sql_obj->string = "DELETE FROM services_taxes WHERE serviceid='{$id}'";
        $sql_obj->execute();
        /*
        	Delete the service bundle components (if any)
        */
        $sql_bundle_obj = new sql_query();
        $sql_bundle_obj->string = "SELECT id FROM services_bundles WHERE id_service='{$id}'";
        $sql_bundle_obj->execute();
        if ($sql_bundle_obj->num_rows()) {
            $sql_bundle_obj->fetch_array();
            foreach ($sql_bundle_obj->data as $data_bundle) {
                // delete any options for each bundle item
                $sql_obj->string = "DELETE FROM services_options WHERE option_type='service' AND option_type_id='" . $data_bundle["id"] . "'";
                $sql_obj->execute();
            }
        }
        $sql_obj->string = "DELETE FROM services_bundles WHERE id_service='{$id}'";
        $sql_obj->execute();
        /*
        	Delete the service cdr rate overrides (if any)
        */
        $sql_obj->string = "DELETE FROM cdr_rate_tables_overrides WHERE option_type='service' AND option_type_id='{$id}'";
        $sql_obj->execute();
        /*
        	Delete service journal data
        */
        journal_delete_entire("services", $id);
        /*
        	Commit
        */
        if (error_check()) {
            $sql_obj->trans_rollback();
            log_write("error", "process", "An error occured whilst attempting to delete the transaction. No changes have been made.");
            header("Location: ../index.php?page=services/view.php&id={$id}");
            exit(0);
        } else {
            $sql_obj->trans_commit();
            log_write("notification", "process", "Service successfully deleted");
            header("Location: ../index.php?page=services/services.php");
            exit(0);
        }
    }
    // end if passed tests
}
示例#9
0
function graph_bydate($p_metrics, $p_labels, $p_title, $p_graph_width = 300, $p_graph_height = 380)
{
    $t_graph_font = graph_get_font();
    error_check(is_array($p_metrics) ? count($p_metrics) : 0, lang_get('by_date'));
    $graph = new Graph($p_graph_width, $p_graph_height);
    $graph->img->SetMargin(40, 140, 40, 100);
    if (ON == config_get_global('jpgraph_antialias')) {
        $graph->img->SetAntiAliasing();
    }
    $graph->SetScale('linlin');
    $graph->SetMarginColor('white');
    $graph->SetFrame(false);
    $graph->title->Set($p_title . ' ' . lang_get('by_date'));
    $graph->title->SetFont($t_graph_font, FS_BOLD);
    $graph->legend->Pos(0.01, 0.05, 'right', 'top');
    $graph->legend->SetShadow(false);
    $graph->legend->SetFillColor('white');
    $graph->legend->SetLayout(LEGEND_VERT);
    $graph->legend->SetFont($t_graph_font);
    $graph->yaxis->scale->ticks->SetDirection(-1);
    $graph->yaxis->SetFont($t_graph_font);
    $graph->yaxis->scale->SetAutoMin(0);
    if (FF_FONT2 <= $t_graph_font) {
        $graph->xaxis->SetLabelAngle(60);
    } else {
        $graph->xaxis->SetLabelAngle(90);
        # can't rotate non truetype fonts
    }
    $graph->xaxis->SetLabelFormatCallback('graph_date_format');
    $graph->xaxis->SetFont($t_graph_font);
    $t_line_colours = config_get('graph_colors');
    $t_count_colours = count($t_line_colours);
    $t_lines = count($p_metrics) - 1;
    $t_line = array();
    for ($i = 1; $i <= $t_lines; $i++) {
        $t_line[$i] = new LinePlot($p_metrics[$i], $p_metrics[0]);
        $t_line[$i]->SetColor($t_line_colours[$i % $t_count_colours]);
        $t_line[$i]->SetCenter();
        $t_line[$i]->SetLegend(lang_get_defaulted($p_labels[$i]));
        $graph->Add($t_line[$i]);
    }
    if (helper_show_queries()) {
        $graph->subtitle->Set(db_count_queries() . ' queries (' . db_count_unique_queries() . ' unique) (' . db_time_queries() . 'sec)');
        $graph->subtitle->SetFont($t_graph_font, FS_NORMAL, 8);
    }
    $graph->Stroke();
}
示例#10
0
function graph_cumulative_bydate($p_metrics, $p_graph_width = 300, $p_graph_height = 380)
{
    $t_graph_font = graph_get_font();
    error_check(is_array($p_metrics) ? count($p_metrics) : 0, lang_get('cumulative') . ' ' . lang_get('by_date'));
    foreach ($p_metrics as $i => $vals) {
        if ($i > 0) {
            $plot_date[] = $i;
            $reported_plot[] = $p_metrics[$i][0];
            $resolved_plot[] = $p_metrics[$i][1];
            $still_open_plot[] = $p_metrics[$i][2];
        }
    }
    $graph = new Graph($p_graph_width, $p_graph_height);
    $graph->img->SetMargin(40, 40, 40, 170);
    $graph->img->SetAntiAliasing();
    $graph->SetScale('linlin');
    $graph->SetMarginColor('white');
    $graph->SetFrame(false);
    $graph->title->Set(lang_get('cumulative') . ' ' . lang_get('by_date'));
    $graph->title->SetFont($t_graph_font, FS_BOLD);
    $graph->legend->Pos(0.05, 0.9, 'right', 'bottom');
    $graph->legend->SetShadow(false);
    $graph->legend->SetFillColor('white');
    $graph->legend->SetLayout(LEGEND_HOR);
    $graph->legend->SetFont($t_graph_font);
    $graph->yaxis->scale->ticks->SetDirection(-1);
    $graph->yaxis->SetFont($t_graph_font);
    if (FF_FONT2 <= $t_graph_font) {
        $graph->xaxis->SetLabelAngle(60);
    } else {
        $graph->xaxis->SetLabelAngle(90);
        # can't rotate non truetype fonts
    }
    $graph->xaxis->SetLabelFormatCallback('graph_date_format');
    $graph->xaxis->SetFont($t_graph_font);
    $p1 = new LinePlot($reported_plot, $plot_date);
    $p1->SetColor('blue');
    $p1->SetCenter();
    $p1->SetLegend(lang_get('legend_reported'));
    $graph->Add($p1);
    $p3 = new LinePlot($still_open_plot, $plot_date);
    $p3->SetColor('red');
    $p3->SetCenter();
    $p3->SetLegend(lang_get('legend_still_open'));
    $graph->Add($p3);
    $p2 = new LinePlot($resolved_plot, $plot_date);
    $p2->SetColor('black');
    $p2->SetCenter();
    $p2->SetLegend(lang_get('legend_resolved'));
    $graph->Add($p2);
    if (ON == config_get('show_queries_count')) {
        $graph->subtitle->Set(db_count_queries() . ' queries (' . db_count_unique_queries() . ' unique) (' . db_time_queries() . 'sec)');
        $graph->subtitle->SetFont($t_graph_font, FS_NORMAL, 8);
    }
    $graph->Stroke();
}
示例#11
0
 function action_delete()
 {
     log_debug("inc_taxes", "Executing action_delete()");
     /*
     	Start SQL Transaction
     */
     $sql_obj = new sql_query();
     $sql_obj->trans_begin();
     /*
     	Delete Tax
     */
     $sql_obj->string = "DELETE FROM account_taxes WHERE id='" . $this->id . "' LIMIT 1";
     $sql_obj->execute();
     /*
     	Delete tax from any services it is assigned to
     */
     $sql_obj->string = "DELETE FROM products_taxes WHERE taxid='" . $this->id . "'";
     $sql_obj->execute();
     /*
     	Delete tax from any services it is assigned to
     */
     $sql_obj->string = "DELETE FROM services_taxes WHERE taxid='" . $this->id . "'";
     $sql_obj->execute();
     /*
     	Delete tax from any vendors it is assigned to
     */
     // delete mapping from table
     $sql_obj->string = "DELETE FROM vendors_taxes WHERE taxid='" . $this->id . "'";
     $sql_obj->execute();
     // unset any defaulttax usage
     $sql_obj->string = "UPDATE vendors SET tax_default='0' WHERE tax_default='" . $this->id . "'";
     $sql_obj->execute();
     /*
     	Delete tax from any customers it is assigned to
     */
     // delete mapping from table
     $sql_obj->string = "DELETE FROM customers_taxes WHERE taxid='" . $this->id . "'";
     $sql_obj->execute();
     // unset any defaulttax usage
     $sql_obj->string = "UPDATE customers SET tax_default='0' WHERE tax_default='" . $this->id . "'";
     $sql_obj->execute();
     /*
     	Commit
     */
     if (error_check()) {
         $sql_obj->trans_rollback();
         log_write("error", "inc_taxes", "An error occured whilst attempting to delete the tax. No change has been made.");
         return 0;
     } else {
         $sql_obj->trans_commit();
         log_write("notification", "inc_taxes", "Tax has been successfully deleted.");
         return 1;
     }
 }
 function execute()
 {
     /*
     	Define form structure
     */
     $this->obj_form = new form_input();
     $this->obj_form->formname = "services_bundles_service";
     $this->obj_form->language = $_SESSION["user"]["lang"];
     $this->obj_form->action = "services/bundles-service-edit-process.php";
     $this->obj_form->method = "post";
     // bundle details
     $structure = NULL;
     $structure["fieldname"] = "name_bundle";
     $structure["type"] = "text";
     $this->obj_form->add_input($structure);
     $structure = NULL;
     $structure["fieldname"] = "description_bundle";
     $structure["type"] = "text";
     // service details
     $structure = NULL;
     $structure["fieldname"] = "name_service";
     $structure["type"] = "input";
     $structure["defaultvalue"] = $this->obj_component->data["name_service"];
     $this->obj_form->add_input($structure);
     $structure = NULL;
     $structure["fieldname"] = "service_type";
     $structure["type"] = "text";
     $structure["defaultvalue"] = $this->obj_component->data["typeid_string"];
     $this->obj_form->add_input($structure);
     $structure = NULL;
     $structure["fieldname"] = "description_service";
     $structure["type"] = "input";
     $structure["defaultvalue"] = $this->obj_component->data["description"];
     $this->obj_form->add_input($structure);
     // hidden fields
     $structure = NULL;
     $structure["fieldname"] = "id_bundle";
     $structure["type"] = "hidden";
     $structure["defaultvalue"] = $this->id;
     $this->obj_form->add_input($structure);
     $structure = NULL;
     $structure["fieldname"] = "id_component";
     $structure["type"] = "hidden";
     $structure["defaultvalue"] = $this->id_component;
     $this->obj_form->add_input($structure);
     // submit section
     $structure = NULL;
     $structure["fieldname"] = "submit";
     $structure["type"] = "submit";
     $structure["defaultvalue"] = "Save Changes";
     $this->obj_form->add_input($structure);
     // define subforms
     $this->obj_form->subforms["bundle_details"] = array("name_bundle", "description_bundle");
     $this->obj_form->subforms["service_details"] = array("service_type", "name_service", "description_service");
     $this->obj_form->subforms["hidden"] = array("id_bundle", "id_component");
     $this->obj_form->subforms["submit"] = array("submit");
     /*
     	Load Data
     */
     if (error_check()) {
         // fetch error data
         $this->obj_form->load_data_error();
     }
     // fetch service bundle data
     $this->obj_form->sql_query = "SELECT\n\t\t\t\t\t\tservices.name_service as name_bundle,\n\t\t\t\t\t\tservices.description as description_bundle\n\t\t\t\t\t\tFROM services\n\t\t\t\t\t\tWHERE id = '" . $this->id . "'";
     $this->obj_form->load_data_sql();
 }
示例#13
0
function graph_bydate($p_metrics, $p_labels, $p_title, $p_graph_width = 300, $p_graph_height = 380)
{
    $t_graph_font = graph_get_font();
    error_check(is_array($p_metrics) ? count($p_metrics) : 0, lang_get('by_date'));
    if (plugin_config_get('eczlibrary') == ON) {
        $t_metrics = array();
        $t_dates = array_shift($p_metrics);
        //[0];
        $t_cnt = count($p_metrics);
        foreach ($t_dates as $i => $val) {
            //$t_metrics[$val]
            for ($j = 0; $j < $t_cnt; $j++) {
                $t_metrics[$j][$val] = $p_metrics[$j][$i];
            }
        }
        $graph = new ezcGraphLineChart();
        $graph->background->color = '#FFFFFF';
        $graph->xAxis = new ezcGraphChartElementNumericAxis();
        for ($k = 0; $k < $t_cnt; $k++) {
            $graph->data[$k] = new ezcGraphArrayDataSet($t_metrics[$k]);
            $graph->data[$k]->label = $p_labels[$k + 1];
        }
        $graph->xAxis->labelCallback = 'graph_date_format';
        $graph->xAxis->axisLabelRenderer = new ezcGraphAxisRotatedLabelRenderer();
        $graph->xAxis->axisLabelRenderer->angle = -45;
        $graph->legend->position = ezcGraph::BOTTOM;
        $graph->legend->background = '#FFFFFF80';
        $graph->driver = new ezcGraphGdDriver();
        //$graph->driver->options->supersampling = 1;
        $graph->driver->options->jpegQuality = 100;
        $graph->driver->options->imageFormat = IMG_JPEG;
        $graph->title = $p_title . ' ' . lang_get('by_date');
        $graph->options->font = $t_graph_font;
        $graph->renderToOutput($p_graph_width, $p_graph_height);
    } else {
        $graph = new Graph($p_graph_width, $p_graph_height);
        $graph->img->SetMargin(40, 140, 40, 100);
        if (ON == plugin_config_get('jpgraph_antialias')) {
            $graph->img->SetAntiAliasing();
        }
        $graph->SetScale('linlin');
        $graph->SetMarginColor('white');
        $graph->SetFrame(false);
        $graph->title->Set($p_title . ' ' . lang_get('by_date'));
        $graph->title->SetFont($t_graph_font, FS_BOLD);
        $graph->legend->Pos(0.01, 0.05, 'right', 'top');
        $graph->legend->SetShadow(false);
        $graph->legend->SetFillColor('white');
        $graph->legend->SetLayout(LEGEND_VERT);
        $graph->legend->SetFont($t_graph_font);
        $graph->yaxis->scale->ticks->SetDirection(-1);
        $graph->yaxis->SetFont($t_graph_font);
        $graph->yaxis->scale->SetAutoMin(0);
        if (FF_FONT2 <= $t_graph_font) {
            $graph->xaxis->SetLabelAngle(60);
        } else {
            $graph->xaxis->SetLabelAngle(90);
            # can't rotate non truetype fonts
        }
        $graph->xaxis->SetLabelFormatCallback('graph_date_format');
        $graph->xaxis->SetFont($t_graph_font);
        /*		$t_line_colours = plugin_config_get( 'jpgraph_colors' );
        		$t_count_colours = count( $t_line_colours );*/
        $t_lines = count($p_metrics) - 1;
        $t_line = array();
        for ($i = 1; $i <= $t_lines; $i++) {
            $t_line[$i] = new LinePlot($p_metrics[$i], $p_metrics[0]);
            //$t_line[$i]->SetColor( $t_line_colours[$i % $t_count_colours] );
            $t_line[$i]->SetCenter();
            $t_line[$i]->SetLegend($p_labels[$i]);
            $graph->Add($t_line[$i]);
        }
        if (helper_show_query_count()) {
            $graph->subtitle->Set(db_count_queries() . ' queries (' . db_time_queries() . 'sec)');
            $graph->subtitle->SetFont($t_graph_font, FS_NORMAL, 8);
        }
        $graph->Stroke();
    }
}
 function execute()
 {
     log_debug("invoice_form_details", "Executing execute()");
     if ($this->invoiceid) {
         $this->mode = "edit";
     } else {
         $this->mode = "add";
     }
     /*
     	Make sure invoice does exist and fetch locked status
     */
     if ($this->mode == "edit") {
         $sql_invoice_obj = new sql_query();
         $sql_invoice_obj->string = "SELECT id, locked FROM account_" . $this->type . " WHERE id='" . $this->invoiceid . "' LIMIT 1";
         $sql_invoice_obj->execute();
         if (!$sql_invoice_obj->num_rows()) {
             print "<p><b>Error: The requested invoice does not exist. <a href=\"index.php?page=accounts/" . $this->type . "/" . $this->type . ".php\">Try looking on the invoice/invoice list page.</a></b></p>";
             return 0;
         } else {
             $sql_invoice_obj->fetch_array();
             $this->locked = $sql_invoice_obj->data[0]["locked"];
         }
     }
     /*
     	Start Form
     */
     $this->obj_form = new form_input();
     $this->obj_form->formname = $this->type . "_invoice_" . $this->mode;
     $this->obj_form->language = $_SESSION["user"]["lang"];
     $this->obj_form->action = $this->processpage;
     $this->obj_form->method = "POST";
     /*
     	Define form structure
     */
     // basic details
     if ($this->type == "ap") {
         $sql_struct_obj = new sql_query();
         $sql_struct_obj->prepare_sql_settable("vendors");
         $sql_struct_obj->prepare_sql_addfield("id", "vendors.id");
         $sql_struct_obj->prepare_sql_addfield("label", "vendors.code_vendor");
         $sql_struct_obj->prepare_sql_addfield("label1", "vendors.name_vendor");
         $sql_struct_obj->prepare_sql_addorderby("code_vendor");
         $sql_struct_obj->prepare_sql_addwhere("id = 'CURRENTID' OR date_end = '0000-00-00'");
         $structure = form_helper_prepare_dropdownfromobj("vendorid", $sql_struct_obj);
         $structure["options"]["req"] = "yes";
         $structure["options"]["width"] = "600";
         $structure["options"]["search_filter"] = "enabled";
         $structure["defaultvalue"] = $this->vendor_id;
         $this->obj_form->add_input($structure);
     } else {
         // load customer dropdown
         $sql_struct_obj = new sql_query();
         $sql_struct_obj->prepare_sql_settable("customers");
         $sql_struct_obj->prepare_sql_addfield("id", "customers.id");
         $sql_struct_obj->prepare_sql_addfield("label", "customers.code_customer");
         $sql_struct_obj->prepare_sql_addfield("label1", "customers.name_customer");
         $sql_struct_obj->prepare_sql_addorderby("code_customer");
         $sql_struct_obj->prepare_sql_addwhere("id = 'CURRENTID' OR date_end = '0000-00-00'");
         $structure = form_helper_prepare_dropdownfromobj("customerid", $sql_struct_obj);
         $structure["options"]["req"] = "yes";
         $structure["options"]["width"] = "600";
         $structure["options"]["search_filter"] = "enabled";
         $structure["defaultvalue"] = $this->customer_id;
         $this->obj_form->add_input($structure);
     }
     $sql_struct_obj = new sql_query();
     $sql_struct_obj->prepare_sql_settable("staff");
     $sql_struct_obj->prepare_sql_addfield("id", "staff.id");
     $sql_struct_obj->prepare_sql_addfield("label", "staff.staff_code");
     $sql_struct_obj->prepare_sql_addfield("label1", "staff.name_staff");
     $sql_struct_obj->prepare_sql_addorderby("staff_code");
     $sql_struct_obj->prepare_sql_addwhere("id = 'CURRENTID' OR date_end = '0000-00-00'");
     $structure = form_helper_prepare_dropdownfromobj("employeeid", $sql_struct_obj);
     $structure["options"]["req"] = "yes";
     $structure["options"]["autoselect"] = "yes";
     $structure["options"]["width"] = "600";
     $structure["options"]["search_filter"] = "enabled";
     $structure["defaultvalue"] = @$_SESSION["user"]["default_employeeid"];
     $this->obj_form->add_input($structure);
     $structure = NULL;
     $structure["fieldname"] = "code_invoice";
     $structure["type"] = "input";
     if ($this->mode == "edit") {
         $structure["options"]["req"] = "yes";
     }
     $this->obj_form->add_input($structure);
     $structure = NULL;
     $structure["fieldname"] = "code_ordernumber";
     $structure["type"] = "input";
     $this->obj_form->add_input($structure);
     $structure = NULL;
     $structure["fieldname"] = "code_ponumber";
     $structure["type"] = "input";
     $this->obj_form->add_input($structure);
     $structure = NULL;
     $structure["fieldname"] = "notes";
     $structure["type"] = "textarea";
     $structure["options"]["height"] = "100";
     $structure["options"]["width"] = 500;
     $this->obj_form->add_input($structure);
     // dates
     $structure = NULL;
     $structure["fieldname"] = "date_trans";
     $structure["type"] = "date";
     $structure["defaultvalue"] = date("Y-m-d");
     $this->obj_form->add_input($structure);
     $structure = NULL;
     $structure["fieldname"] = "date_due";
     $structure["type"] = "date";
     $structure["defaultvalue"] = invoice_calc_duedate(date("Y-m-d"));
     $this->obj_form->add_input($structure);
     // destination account
     if ($this->type == "ap") {
         $structure = charts_form_prepare_acccountdropdown("dest_account", "ap_summary_account");
     } else {
         $structure = charts_form_prepare_acccountdropdown("dest_account", "ar_summary_account");
     }
     $structure["options"]["req"] = "yes";
     $structure["options"]["autoselect"] = "yes";
     $structure["options"]["search_filter"] = "enabled";
     $structure["options"]["width"] = "600";
     $this->obj_form->add_input($structure);
     // ID
     $structure = NULL;
     $structure["fieldname"] = "id_invoice";
     $structure["type"] = "hidden";
     $structure["defaultvalue"] = $this->invoiceid;
     $this->obj_form->add_input($structure);
     // submit
     $structure = NULL;
     $structure["fieldname"] = "submit";
     $structure["type"] = "submit";
     $structure["defaultvalue"] = "Save Changes";
     $this->obj_form->add_input($structure);
     // load data
     if ($this->type == "ap") {
         $this->obj_form->sql_query = "SELECT vendorid, employeeid, code_invoice, code_ordernumber, code_ponumber, notes, date_trans, date_due, dest_account FROM account_" . $this->type . " WHERE id='" . $this->invoiceid . "'";
     } else {
         $this->obj_form->sql_query = "SELECT customerid, employeeid, code_invoice, code_ordernumber, code_ponumber, notes, date_trans, date_due, dest_account FROM account_" . $this->type . " WHERE id='" . $this->invoiceid . "'";
     }
     $this->obj_form->load_data();
     /*
     	Fetch any provided values from $_GET if adding a new invoice and no error data provided
     */
     if ($this->mode == "add" && error_check()) {
         $this->obj_form->structure["customerid"]["defaultvalue"] = @security_script_input('/^[0-9]*$/', $_GET["customerid"]);
         $this->obj_form->structure["vendorid"]["defaultvalue"] = @security_script_input('/^[0-9]*$/', $_GET["vendorid"]);
     }
     // define subforms
     if ($this->type == "ap") {
         $this->obj_form->subforms[$this->type . "_invoice_details"] = array("vendorid", "employeeid", "code_invoice", "code_ordernumber", "code_ponumber", "date_trans", "date_due");
     } else {
         $this->obj_form->subforms[$this->type . "_invoice_details"] = array("customerid", "employeeid", "code_invoice", "code_ordernumber", "code_ponumber", "date_trans", "date_due");
     }
     $this->obj_form->subforms[$this->type . "_invoice_financials"] = array("dest_account");
     $this->obj_form->subforms[$this->type . "_invoice_other"] = array("notes");
     $this->obj_form->subforms["hidden"] = array("id_invoice");
     if ($this->locked) {
         $this->obj_form->subforms["submit"] = array();
     } else {
         $this->obj_form->subforms["submit"] = array("submit");
     }
     return 1;
 }
示例#15
0
            ?>
 
		<?php 
        } else {
            ?>
			<?php 
            echo __('common.found_some_problems', 'Oh no, we found some problems');
            ?>
		<?php 
        }
        ?>
		</p>
		
		<ul>
			<?php 
        foreach (error_check() as $error) {
            ?>
			<li><?php 
            echo $error;
            ?>
</li>
			<?php 
        }
        ?>
		</ul>
		<?php 
    } else {
        ?>
			<p><?php 
        echo __('common.nice_job', 'Nice job, keep on going!');
        ?>
示例#16
0
 function execute()
 {
     /*
     	Define form structure
     */
     $this->obj_form = new form_input();
     $this->obj_form->formname = "name_server_group_edit";
     $this->obj_form->language = $_SESSION["user"]["lang"];
     $this->obj_form->action = "servers/group-edit-process.php";
     $this->obj_form->method = "post";
     // general
     $structure = NULL;
     $structure["fieldname"] = "group_name";
     $structure["type"] = "input";
     $structure["options"]["req"] = "yes";
     $this->obj_form->add_input($structure);
     $structure = NULL;
     $structure["fieldname"] = "group_description";
     $structure["type"] = "textarea";
     $this->obj_form->add_input($structure);
     // group members
     $member_servers = "";
     $obj_sql = new sql_query();
     $obj_sql->string = "SELECT id, server_name FROM name_servers WHERE id_group='" . $this->obj_name_server_group->id . "' ORDER BY server_name";
     $obj_sql->execute();
     if ($obj_sql->num_rows()) {
         $obj_sql->fetch_array();
         $count = 0;
         foreach ($obj_sql->data as $data) {
             $count++;
             $member_servers .= "<a href=\"index.php?page=servers/view.php&id=" . $data["id"] . "\">" . $data["server_name"] . "</a>";
             if ($count != $obj_sql->data_num_rows) {
                 $member_servers .= "<br> ";
             }
         }
     }
     $structure = NULL;
     $structure["fieldname"] = "group_member_servers";
     $structure["type"] = "text";
     $structure["options"]["nohidden"] = 1;
     $structure["defaultvalue"] = $member_servers;
     $this->obj_form->add_input($structure);
     $member_domains = "";
     $obj_sql = new sql_query();
     $obj_sql->string = "SELECT id, domain_name FROM dns_domains WHERE id IN (SELECT id_domain FROM dns_domains_groups WHERE id_group='" . $this->obj_name_server_group->id . "') ORDER BY domain_name";
     $obj_sql->execute();
     if ($obj_sql->num_rows()) {
         $obj_sql->fetch_array();
         $count = 0;
         foreach ($obj_sql->data as $data) {
             $count++;
             $member_domains .= "<a href=\"index.php?page=domains/view.php&id=" . $data["id"] . "\">" . $data["domain_name"] . "</a>";
             if ($count != $obj_sql->data_num_rows) {
                 $member_domains .= "<br> ";
             }
         }
     }
     $structure = NULL;
     $structure["fieldname"] = "group_member_domains";
     $structure["type"] = "text";
     $structure["options"]["nohidden"] = 1;
     $structure["defaultvalue"] = $member_domains;
     $this->obj_form->add_input($structure);
     // hidden section
     $structure = NULL;
     $structure["fieldname"] = "id_name_server_group";
     $structure["type"] = "hidden";
     $structure["defaultvalue"] = $this->obj_name_server_group->id;
     $this->obj_form->add_input($structure);
     // submit section
     $structure = NULL;
     $structure["fieldname"] = "submit";
     $structure["type"] = "submit";
     $structure["defaultvalue"] = "Save Changes";
     $this->obj_form->add_input($structure);
     // define subforms
     $this->obj_form->subforms["group_details"] = array("group_name", "group_description");
     $this->obj_form->subforms["group_members"] = array("group_member_servers", "group_member_domains");
     $this->obj_form->subforms["hidden"] = array("id_name_server_group");
     $this->obj_form->subforms["submit"] = array("submit");
     // import data
     if (error_check()) {
         $this->obj_form->load_data_error();
     } else {
         if ($this->obj_name_server_group->load_data()) {
             $this->obj_form->structure["group_name"]["defaultvalue"] = $this->obj_name_server_group->data["group_name"];
             $this->obj_form->structure["group_description"]["defaultvalue"] = $this->obj_name_server_group->data["group_description"];
         }
     }
 }
示例#17
0
function validate($data)
{
    //print_r($data);
    /* check for Null all values are required */
    foreach ($data as $key => $val) {
        if ($val == "") {
            error_check("Missing field {$key}.<br>");
        }
    }
}
示例#18
0
 function action_delete()
 {
     log_debug("journal_process", "Executing action_delete()");
     /*
     	Start Transaction
     */
     $sql_obj = new sql_query();
     $sql_obj->trans_begin();
     /*
     	Delete files (if applicable)
     */
     if ($this->structure["type"] == "file") {
         $file_obj = new file_storage();
         $file_obj->data["type"] = "journal";
         $file_obj->data["customid"] = $this->structure["id"];
         $file_obj->load_data_bytype();
         $file_obj->action_delete();
     }
     /*
     	Delete journal record
     */
     $sql_obj->string = "DELETE FROM `journal` WHERE id='" . $this->structure["id"] . "' LIMIT 1";
     $sql_obj->execute();
     /*
     	Commit
     */
     if (error_check()) {
         log_write("error", "journal_process", "An error occured preventing the journal record from being deleted");
         $sql_obj->trans_rollback();
         return 0;
     } else {
         log_write("notification", "journal_process", "Journal record cleanly removed.");
         $sql_obj->trans_commit();
         return 1;
     }
     return 0;
 }
示例#19
0
 function bundle_service_delete($id_service)
 {
     log_write("debug", "inc_services", "Executing bundle_service_delete({$id_service}))");
     /*
     	Begin Transaction
     */
     $sql_obj = new sql_query();
     $sql_obj->trans_begin();
     /*
     	Apply Changes
     */
     $sql_obj->string = "SELECT id FROM `services_bundles` WHERE id_bundle='" . $this->id . "' AND id_service='{$id_service}' LIMIT 1";
     $sql_obj->execute();
     $sql_obj->fetch_array();
     $option_id = $sql_obj->data[0]["id"];
     $sql_obj->string = "DELETE FROM `services_bundles` WHERE id='{$option_id}' LIMIT 1";
     $sql_obj->execute();
     $sql_obj->string = "DELETE FROM `services_options` WHERE option_type='bundle' AND option_type_id='{$option_id}'";
     $sql_obj->execute();
     /*
     	Update the Journal
     */
     journal_quickadd_event("services", $this->id, "Service component removed from bundle.");
     /*
     	Commit
     */
     if (error_check()) {
         $sql_obj->trans_rollback();
         log_write("error", "process", "An error occured whilst attempting to remove a service from the bundle. No changes have been made.");
     } else {
         $sql_obj->trans_commit();
         log_write("notification", "process", "Service successfully removed from bundle.");
     }
     return 0;
 }
示例#20
0
				});

		});
	});
</script>
<!---Sends the form results to page "Results1.php" ---> 
<form action="Results1.php" method="post" id = "movie" class="pick">
	<h4>I want to watch a... <h4>
	<!---results stored in variable called genre ---> 
		<select name ="genre" form="movie" class="genre">
			<option value = ""> Select your genre </option> 
				<?php 
// queries the genres from the database
$query = "SELECT name FROM tagtest WHERE type = 'genre'";
$result = mysql_query($query);
error_check($result);
runQueryForm($result);
?>
		</select> 
		<br/><br/>
		<!--The following is the subgenre question-->
	<h4>With a some bit of... <h4>
		<!---results stored in variable called subgenre ---> 
		<select name="subgenre" form="movie" class="subgenre">
			<option selected=""> Select your subgenre </option>
		</select>
	<br/>
	<br/>
	<input type="submit"/>
	<!---submits form ---> 
</form>
示例#21
0
 function action_delete()
 {
     log_debug("inc_credits_refund", "Executing action_delete()");
     // we must have an ID provided
     if (!$this->id) {
         log_debug("inc_credits_refund", "No credit refund ID to action_delete function");
         return 0;
     }
     /*
     	Start SQL Transaction
     */
     $sql_obj = new sql_query();
     $sql_obj->trans_begin();
     /*
     	Delete Credit Refund
     */
     $sql_obj->string = "DELETE FROM " . $this->type . "s_credits WHERE id='" . $this->id . "' LIMIT 1";
     $sql_obj->execute();
     /*
     	Delete Ledger Items
     */
     if ($this->type == "customer") {
         $sql_obj->string = "DELETE FROM account_trans WHERE (type='ar_refund') AND customid='" . $this->id . "'";
         $sql_obj->execute();
     } else {
         $sql_obj->string = "DELETE FROM account_trans WHERE (type='ap_refund') AND customid='" . $this->id . "'";
         $sql_obj->execute();
     }
     /*
     	Commit
     */
     if (error_check()) {
         $sql_obj->trans_rollback();
         log_write("error", "invoice", "An error occured whilst deleting the credit refund. No changes have been made.");
         return 0;
     } else {
         $sql_obj->trans_commit();
         return 1;
     }
 }
示例#22
0
 function autopay()
 {
     log_write("debug", "invoice_autopay", "Executing autopay()");
     // check capabilities
     if (!$this->capable) {
         if (!$this->check_autopay_capable()) {
             return 0;
         }
     }
     /*
     	Start SQL Transaction
     */
     $sql_obj = new sql_query();
     $sql_obj->trans_begin();
     /*
     	Load Invoice Data
     */
     $this->obj_invoice = new invoice();
     $this->obj_invoice->id = $this->id_invoice;
     $this->obj_invoice->type = $this->type_invoice;
     if (!$this->obj_invoice->load_data()) {
         log_write("error", "invoice_autopay", "Unable to load invoice data for checking for autopayments");
         return -1;
     }
     /*
     	Make AutoPayments
     */
     // handle credit payments
     $this->autopay_credit();
     // future: credit card, direct debit?
     /*
     	Commit
     */
     if (error_check()) {
         $sql_obj->trans_rollback();
         log_write("error", "invoice_autopay", "An error occured whilst making an invoice autopayment");
         return 0;
     } else {
         $sql_obj->trans_commit();
         return 1;
     }
 }
示例#23
0
 function execute()
 {
     /*
      * Validate a POST (page navigation move will prompt this)
      */
     if (isset($_POST['record_custom_page'])) {
         // fetch data from POST and validate - we then return values
         $data = stripslashes_deep($this->obj_domain->validate_custom_records());
         // validate the record_custom_page for returning the user to their page, default to page 1 if any errors in validating...
         $data['record_custom_page'] = @security_form_input_predefined("int", "record_custom_page", 1, "");
         /*
         			echo '<tr><td colspan="100%">post-validation POST data<pre>'; 
         			echo '<pre>';
         			print_R($data);
         			echo '</pre>';
         			echo '</td></tr>';
         			die("debug");
         */
         if (error_check()) {
             log_write("debug", "records-ajax", "POST records provided but error encountered, failing");
             $_SESSION["error"]["form"]["domain_records"] = "failed";
             $this->page = $data['record_custom_page'];
         } else {
             // no errors... set the records to the session
             $_SESSION['form']['domain_records'][$this->obj_domain->id][$data['record_custom_page']] = $data['records'];
         }
     }
     /*
     	Load domain data & records
     */
     $this->num_records_custom_total = $this->obj_domain->data_record_custom_count();
     $this->obj_domain->load_data();
     // if the data is present in the session then it has either changed and is awaiting submission
     // or the user has visited that page before during this edit session
     if (isset($_SESSION['form']['domain_records'][$this->obj_domain->id][$this->page]) && count($_SESSION['form']['domain_records'][$this->obj_domain->id][$this->page])) {
         log_debug("execute", 'Loading records from session as previous load or edit detected');
         $this->obj_domain->data['records'] = $_SESSION['form']['domain_records'][$this->obj_domain->id][$this->page];
         /*
         echo '<tr><td colspan="100%">from sesssion<pre>';
         print_R($this->obj_domain->data['records']);
         echo '</td></tr>';
         */
     } else {
         log_debug("execute", 'Loading records from db for page: ' . $this->page);
         $this->obj_domain->load_data_record_custom($this->offset, $GLOBALS["config"]['PAGINATION_DOMAIN_RECORDS']);
         /*
         echo '<tr><td colspan="100%">from db<pre>';
         print_R($this->obj_domain->data['records']);
         echo '</td></tr>';
         */
     }
     // work out the IP for reverse domains
     if (strpos($this->obj_domain->data["domain_name"], "in-addr.arpa")) {
         // IPv4
         $ip = explode(".", $this->obj_domain->data["domain_name"]);
         $this->obj_domain->data["domain_ip_prefix"] = $ip[2] . "." . $ip[1] . "." . $ip[0];
     } elseif (strpos($this->obj_domain->data["domain_name"], "ip6.arpa")) {
         // IPv6
         $ip_reverse = substr($this->obj_domain->data["domain_name"], 0, strlen($this->obj_domain->data["domain_name"]) - 9);
         $ip_array = array();
         $i = 0;
         foreach (array_reverse(explode(".", $ip_reverse)) as $ip) {
             $i++;
             $ip_array[] = $ip;
             if ($i == 4) {
                 $i = 0;
                 $ip_array[] = ":";
             }
         }
         $this->obj_domain->data["domain_ip_prefix"] = implode("", $ip_array);
     }
     /*
     	Define form structure
     */
     $this->obj_form = new form_input();
     $this->obj_form->formname = "domain_records";
     $this->obj_form->language = $_SESSION["user"]["lang"];
     $this->obj_form->action = "domains/records-process.php";
     $this->obj_form->method = "post";
     /*
     	General Domain Info
     */
     $structure = NULL;
     $structure["fieldname"] = "domain_name";
     $structure["type"] = "message";
     $structure["options"]["css_row_class"] = "table_highlight";
     $structure["defaultvalue"] = "<p><b>Domain " . $this->obj_domain->data["domain_name"] . " selected for adjustment</b></p>";
     $this->obj_form->add_input($structure);
     /*
     	Define stucture for all other record types
     
     	This includes A, AAAA, PTR and other record types.
     */
     // fetch all the known record types from the database
     $dns_record_types = sql_get_singlecol("SELECT type as value FROM `dns_record_types` WHERE user_selectable='1'");
     // unless there has been error data returned, fetch all the records
     // and work out the number of rows
     if (!isset($_SESSION["error"]["form"][$this->obj_form->formname])) {
         $this->num_records_custom = 1;
         foreach ($this->obj_domain->data["records"] as $record) {
             if (in_array($record["type"], $dns_record_types)) {
                 $this->num_records_custom++;
             }
         }
     } else {
         $this->num_records_custom = @security_script_input('/^[0-9]*$/', $_SESSION["error"]["num_records_custom"]);
     }
     // ensure there are at least two rows, if more are needed when entering information,
     // then the javascript functions will provide.
     if ($this->num_records_custom < 2) {
         $this->num_records_custom = 2;
     }
     // custom domain records
     for ($i = 0; $i < $this->num_records_custom; $i++) {
         // values
         $structure = NULL;
         $structure["fieldname"] = "record_custom_" . $i . "_id";
         $structure["type"] = "hidden";
         $this->obj_form->add_input($structure);
         if (strpos($this->obj_domain->data["domain_name"], "arpa")) {
             $structure = NULL;
             $structure["fieldname"] = "record_custom_" . $i . "_type";
             $structure["type"] = "text";
             $structure["defaultvalue"] = "PTR";
             $this->obj_form->add_input($structure);
         } else {
             $structure = form_helper_prepare_dropdownfromdb("record_custom_" . $i . "_type", "SELECT type as label, type as id FROM `dns_record_types` WHERE user_selectable='1' AND is_standard='1'");
             $structure["defaultvalue"] = "A";
             $structure["options"]["width"] = "100";
             $this->obj_form->add_input($structure);
         }
         $structure = NULL;
         $structure["fieldname"] = "record_custom_" . $i . "_name";
         $structure["type"] = "input";
         if (strpos($this->obj_domain->data["domain_name"], "in-addr.arpa")) {
             $structure["options"]["width"] = "50";
             $structure["options"]["max_length"] = "3";
             $structure["options"]["prelabel"] = $this->obj_domain->data["domain_ip_prefix"] . ". ";
             $structure["options"]["help"] = "?";
         } elseif (strpos($this->obj_domain->data["domain_name"], "ip6.arpa")) {
             $structure["options"]["width"] = "300";
             $structure["options"]["prelabel"] = " ";
             $structure["options"]["help"] = $this->obj_domain->data["domain_ip_prefix"] . "....";
             $structure["options"]["autofill"] = $this->obj_domain->data["domain_ip_prefix"];
         } else {
             $structure["options"]["width"] = "300";
             $structure["options"]["help"] = "Record name, eg www";
         }
         $this->obj_form->add_input($structure);
         $structure = NULL;
         $structure["fieldname"] = "record_custom_" . $i . "_content";
         $structure["type"] = "input";
         $structure["options"]["width"] = "300";
         if (strpos($this->obj_domain->data["domain_name"], "arpa")) {
             // both IPv4 and IPv6
             $structure["options"]["help"] = "Reverse record name, eg www.example.com";
         } else {
             $structure["options"]["help"] = "Target IP, eg 192.168.0.1";
         }
         $this->obj_form->add_input($structure);
         $structure = NULL;
         $structure["fieldname"] = "record_custom_" . $i . "_ttl";
         $structure["type"] = "input";
         $structure["options"]["width"] = "80";
         $structure["defaultvalue"] = $this->obj_domain->data["soa_default_ttl"];
         $this->obj_form->add_input($structure);
         $structure = NULL;
         $structure["fieldname"] = "record_custom_" . $i . "_delete_undo";
         $structure["type"] = "hidden";
         $structure["defaultvalue"] = "false";
         $this->obj_form->add_input($structure);
         if (!strpos($this->obj_domain->data["domain_name"], "arpa")) {
             $structure = NULL;
             $structure["fieldname"] = "record_custom_" . $i . "_reverse_ptr";
             $structure["type"] = "checkbox";
             $structure["options"]["label"] = "";
             $this->obj_form->add_input($structure);
             $structure = NULL;
             $structure["fieldname"] = "record_custom_" . $i . "_reverse_ptr_orig";
             $structure["type"] = "hidden";
             $this->obj_form->add_input($structure);
         }
     }
     // load in what data we have
     //disable invalid fields
     $i = 0;
     foreach ($this->obj_domain->data["records"] as $record) {
         if (in_array($record["type"], $dns_record_types)) {
             // special ID rules
             if ($record["id"]) {
                 $this->obj_form->structure["record_custom_" . $i . "_id"]["defaultvalue"] = $record["id"];
             } else {
                 $this->obj_form->structure["record_custom_" . $i . "_id"]["defaultvalue"] = $record["id_record"];
             }
             // fetch data
             $this->obj_form->structure["record_custom_" . $i . "_type"]["defaultvalue"] = $record["type"];
             $this->obj_form->structure["record_custom_" . $i . "_prio"]["defaultvalue"] = $record["prio"];
             $this->obj_form->structure["record_custom_" . $i . "_name"]["defaultvalue"] = $record["name"];
             $this->obj_form->structure["record_custom_" . $i . "_content"]["defaultvalue"] = $record["content"];
             $this->obj_form->structure["record_custom_" . $i . "_ttl"]["defaultvalue"] = $record["ttl"];
             if ($record["type"] == "CNAME") {
                 // disable inappropate values for CNAME fields
                 $this->obj_form->structure["record_custom_" . $i . "_reverse_ptr"]["options"]["disabled"] = "yes";
                 $this->obj_form->structure["record_custom_" . $i . "_reverse_ptr_orig"]["options"]["disabled"] = "yes";
             } elseif ($record["type"] == "PTR") {
                 if (strpos($this->obj_domain->data["domain_name"], "ip6.arpa")) {
                     // IPv6 PTR records are in ARPA format, we should convert it to something human readable
                     $this->obj_form->structure["record_custom_" . $i . "_name"]["defaultvalue"] = ipv6_convert_fromarpa($record["name"]);
                 }
             } elseif ($record["type"] != "PTR") {
                 if ($record["type"] == "A" || $record["type"] == "AAAA") {
                     // check if this record has a reverse PTR value
                     $obj_ptr = new domain_records();
                     $obj_ptr->find_reverse_domain($record["content"]);
                     if ($obj_ptr->id_record) {
                         $obj_ptr->load_data_record();
                         if ($record["name"] == "@" || $record["name"] == "*" || preg_match("/^\\*\\.[A-Za-z0-9:._-]+\$/", $record["name"])) {
                             $record["name"] = $this->obj_domain->data["domain_name"];
                         }
                         if ($obj_ptr->data_record["content"] == $record["name"] || $obj_ptr->data_record["content"] == $record["name"] . "." . $this->obj_domain->data["domain_name"]) {
                             $this->obj_form->structure["record_custom_" . $i . "_reverse_ptr"]["defaultvalue"] = "on";
                             $this->obj_form->structure["record_custom_" . $i . "_reverse_ptr_orig"]["defaultvalue"] = "on";
                         }
                     }
                     unset($obj_ptr);
                 } else {
                     // reverse PTR not valid for this record type
                     $this->obj_form->structure["record_custom_" . $i . "_reverse_ptr"]["options"]["disabled"] = "yes";
                 }
             }
             $i++;
         }
     }
     // hidden
     $structure = NULL;
     $structure["fieldname"] = "id_domain";
     $structure["type"] = "hidden";
     $structure["defaultvalue"] = $this->obj_domain->id;
     $this->obj_form->add_input($structure);
     $structure = NULL;
     $structure["fieldname"] = "record_custom_page";
     $structure["type"] = "hidden";
     $structure["defaultvalue"] = "{$this->page}";
     $this->obj_form->add_input($structure);
     $structure = NULL;
     $structure["fieldname"] = "num_records_custom";
     $structure["type"] = "hidden";
     $structure["defaultvalue"] = "{$this->num_records_custom}";
     $this->obj_form->add_input($structure);
     // a record that can be set to determine the form status for final submit
     $structure = NULL;
     $structure["fieldname"] = "record_custom_status";
     $structure["type"] = "hidden";
     // fetch data in event of an error
     if (error_check()) {
         $this->obj_form->load_data_error();
         $structure["defaultvalue"] = "0";
     } else {
         $structure["defaultvalue"] = "1";
     }
     $this->obj_form->add_input($structure);
 }
         // create a new entry in the DB
         $sql_obj->string = "INSERT INTO `project_phases` (projectid) VALUES ('{$projectid}')";
         $sql_obj->execute();
         $phaseid = $sql_obj->fetch_insert_id();
     }
     /*
     	Update Phase Details
     */
     if ($phaseid) {
         $sql_obj->string = "UPDATE `project_phases` SET " . "name_phase='" . $data["name_phase"] . "', " . "description='" . $data["description"] . "' " . "WHERE id='{$phaseid}' LIMIT 1";
         $sql_obj->execute();
     }
     /*
     	Commit
     */
     if (error_check()) {
         $sql_obj->trans_rollback();
         log_write("error", "process", "A fatal error occuring whilst attempting to update the phase. No changes were made.");
     } else {
         $sql_obj->trans_commit();
         if ($mode == "add") {
             log_write("notification", "project", "Phase successfully created.");
         } else {
             log_write("notification", "project", "Phase successfully updated.");
         }
     }
     // display updated details
     header("Location: ../index.php?page=projects/phases.php&id={$projectid}");
     exit(0);
 }
 /////////////////////////
 function execute()
 {
     // define basic form details
     $this->obj_form = new form_input();
     $this->obj_form->formname = "cdr_rate_table_delete";
     $this->obj_form->language = $_SESSION["user"]["lang"];
     $this->obj_form->action = "services/cdr-rates-delete-process.php";
     $this->obj_form->method = "post";
     // general
     $structure = NULL;
     $structure["fieldname"] = "rate_table_name";
     $structure["type"] = "text";
     $this->obj_form->add_input($structure);
     $structure = NULL;
     $structure["fieldname"] = "rate_table_description";
     $structure["type"] = "text";
     $this->obj_form->add_input($structure);
     // hidden fields
     $structure = NULL;
     $structure["fieldname"] = "id";
     $structure["type"] = "hidden";
     $structure["defaultvalue"] = $this->obj_rate_table->id;
     $this->obj_form->add_input($structure);
     // confirm delete
     $structure = NULL;
     $structure["fieldname"] = "delete_confirm";
     $structure["type"] = "checkbox";
     $structure["options"]["label"] = "Yes, I wish to delete this rate table and realise that once deleted the data can not be recovered.";
     $this->obj_form->add_input($structure);
     // submit button
     $structure = NULL;
     $structure["fieldname"] = "submit";
     $structure["type"] = "submit";
     $structure["defaultvalue"] = "delete";
     $this->obj_form->add_input($structure);
     // define subforms
     $this->obj_form->subforms["rate_table_delete"] = array("rate_table_name", "rate_table_description");
     $this->obj_form->subforms["hidden"] = array("id");
     if ($this->locked) {
         $this->obj_form->subforms["submit"] = array();
     } else {
         $this->obj_form->subforms["submit"] = array("delete_confirm", "submit");
     }
     // load any data
     $this->obj_rate_table->load_data();
     $this->obj_form->structure["rate_table_name"]["defaultvalue"] = $this->obj_rate_table->data["rate_table_name"];
     $this->obj_form->structure["rate_table_description"]["defaultvalue"] = $this->obj_rate_table->data["rate_table_description"];
     if (error_check()) {
         $this->obj_form->load_data_error();
     }
 }
 function execute()
 {
     // load data
     $this->obj_customer->load_data();
     // define basic form details
     $this->obj_form = new form_input();
     $this->obj_form->formname = "cdr_override_edit";
     $this->obj_form->language = $_SESSION["user"]["lang"];
     $this->obj_form->action = "customers/service-cdr-override-edit-process.php";
     $this->obj_form->method = "post";
     // service details
     $structure = NULL;
     $structure["fieldname"] = "name_customer";
     $structure["type"] = "text";
     $this->obj_form->add_input($structure);
     $structure = NULL;
     $structure["fieldname"] = "service_name";
     $structure["type"] = "text";
     $this->obj_form->add_input($structure);
     $structure = NULL;
     $structure["fieldname"] = "service_description";
     $structure["type"] = "text";
     $this->obj_form->add_input($structure);
     // rate table details
     $structure = NULL;
     $structure["fieldname"] = "rate_table_name";
     $structure["type"] = "text";
     $this->obj_form->add_input($structure);
     $structure = NULL;
     $structure["fieldname"] = "rate_table_description";
     $structure["type"] = "text";
     $this->obj_form->add_input($structure);
     // item options
     $structure = NULL;
     $structure["fieldname"] = "rate_prefix";
     $structure["type"] = "input";
     $structure["options"]["req"] = "yes";
     $this->obj_form->add_input($structure);
     $structure = NULL;
     $structure["fieldname"] = "rate_description";
     $structure["type"] = "input";
     $structure["options"]["req"] = "yes";
     $this->obj_form->add_input($structure);
     $structure = form_helper_prepare_dropdownfromdb("rate_billgroup", "SELECT id, billgroup_name as label FROM cdr_rate_billgroups");
     $structure["options"]["req"] = "yes";
     $structure["options"]["width"] = "100";
     $this->obj_form->add_input($structure);
     $structure = NULL;
     $structure["fieldname"] = "rate_price_sale";
     $structure["type"] = "money";
     $structure["options"]["req"] = "yes";
     $this->obj_form->add_input($structure);
     $structure = NULL;
     $structure["fieldname"] = "rate_price_cost";
     $structure["type"] = "money";
     $this->obj_form->add_input($structure);
     // hidden
     $structure = NULL;
     $structure["fieldname"] = "id_customer";
     $structure["type"] = "hidden";
     $structure["defaultvalue"] = $this->obj_customer->id;
     $this->obj_form->add_input($structure);
     $structure = NULL;
     $structure["fieldname"] = "id_service_customer";
     $structure["type"] = "hidden";
     $structure["defaultvalue"] = $this->obj_customer->id_service_customer;
     $this->obj_form->add_input($structure);
     $structure = NULL;
     $structure["fieldname"] = "id_rate_override";
     $structure["type"] = "hidden";
     $structure["defaultvalue"] = $this->obj_cdr_rate_table->id_rate_override;
     $this->obj_form->add_input($structure);
     // submit button
     $structure = NULL;
     $structure["fieldname"] = "submit";
     $structure["type"] = "submit";
     $structure["defaultvalue"] = "submit";
     $this->obj_form->add_input($structure);
     // define subforms
     $this->obj_form->subforms["service_details"] = array("name_customer", "service_name", "service_description");
     $this->obj_form->subforms["rate_table_details"] = array("rate_table_name", "rate_table_description");
     $this->obj_form->subforms["rate_table_items"] = array("rate_prefix", "rate_description", "rate_billgroup", "rate_price_sale", "rate_price_cost");
     $this->obj_form->subforms["hidden"] = array("id_customer", "id_service_customer", "id_rate_override");
     $this->obj_form->subforms["submit"] = array("submit");
     // load any data returned due to errors
     if (error_check()) {
         $this->obj_form->load_data_error();
     } else {
         $this->obj_cdr_rate_table->load_data();
         // load rate values from standard item
         if ($this->obj_cdr_rate_table->id_rate) {
             $this->obj_cdr_rate_table->load_data_rate();
         }
         // load override values
         if ($this->obj_cdr_rate_table->id_rate_override) {
             $this->obj_cdr_rate_table->load_data_rate_override();
         }
         $this->obj_form->structure["name_customer"]["defaultvalue"] = $this->obj_customer->data["name_customer"];
         $this->obj_form->structure["service_name"]["defaultvalue"] = $this->obj_customer->obj_service->data["name_service"];
         $this->obj_form->structure["service_description"]["defaultvalue"] = $this->obj_customer->obj_service->data["description"];
         $this->obj_form->structure["rate_table_name"]["defaultvalue"] = $this->obj_cdr_rate_table->data["rate_table_name"];
         $this->obj_form->structure["rate_table_description"]["defaultvalue"] = $this->obj_cdr_rate_table->data["rate_table_description"];
         $this->obj_form->structure["rate_prefix"]["defaultvalue"] = $this->obj_cdr_rate_table->data_rate["rate_prefix"];
         $this->obj_form->structure["rate_description"]["defaultvalue"] = $this->obj_cdr_rate_table->data_rate["rate_description"];
         $this->obj_form->structure["rate_billgroup"]["defaultvalue"] = $this->obj_cdr_rate_table->data_rate["rate_billgroup"];
         $this->obj_form->structure["rate_price_sale"]["defaultvalue"] = $this->obj_cdr_rate_table->data_rate["rate_price_sale"];
         $this->obj_form->structure["rate_price_cost"]["defaultvalue"] = $this->obj_cdr_rate_table->data_rate["rate_price_cost"];
     }
 }
示例#27
0
 function execute()
 {
     /*
     	Define form structure
     */
     $this->obj_form = new form_input();
     $this->obj_form->formname = "customer_portal";
     $this->obj_form->language = $_SESSION["user"]["lang"];
     $this->obj_form->action = "customers/portal-process.php";
     $this->obj_form->method = "post";
     // general customer details
     $structure = NULL;
     $structure["fieldname"] = "code_customer";
     $structure["type"] = "text";
     $this->obj_form->add_input($structure);
     $structure = NULL;
     $structure["fieldname"] = "name_customer";
     $structure["type"] = "text";
     $this->obj_form->add_input($structure);
     // passwords
     $structure = NULL;
     $structure["fieldname"] = "password_message";
     $structure["type"] = "message";
     $structure["defaultvalue"] = "<i>Only input a password if you wish to change the existing one.</i>";
     $this->obj_form->add_input($structure);
     $structure = NULL;
     $structure["fieldname"] = "password";
     $structure["type"] = "password";
     $this->obj_form->add_input($structure);
     $structure = NULL;
     $structure["fieldname"] = "password_confirm";
     $structure["type"] = "password";
     $this->obj_form->add_input($structure);
     // last login information
     $structure = NULL;
     $structure["fieldname"] = "login_time";
     $structure["type"] = "text";
     $this->obj_form->add_input($structure);
     $structure = NULL;
     $structure["fieldname"] = "login_ipaddress";
     $structure["type"] = "text";
     $this->obj_form->add_input($structure);
     // submit section
     if (user_permissions_get("customers_write")) {
         $structure = NULL;
         $structure["fieldname"] = "submit";
         $structure["type"] = "submit";
         $structure["defaultvalue"] = "Save Changes";
         $this->obj_form->add_input($structure);
     } else {
         $structure = NULL;
         $structure["fieldname"] = "submit";
         $structure["type"] = "message";
         $structure["defaultvalue"] = "<p><i>Sorry, you don't have permissions to make changes to customer records.</i></p>";
         $this->obj_form->add_input($structure);
     }
     // hidden
     $structure = NULL;
     $structure["fieldname"] = "id_customer";
     $structure["type"] = "hidden";
     $structure["defaultvalue"] = $this->obj_customer->id;
     $this->obj_form->add_input($structure);
     // define subforms
     $this->obj_form->subforms["customer_view"] = array("code_customer", "name_customer");
     $this->obj_form->subforms["customer_portal_history"] = array("login_time", "login_ipaddress");
     $this->obj_form->subforms["customer_portal_password"] = array("password_message", "password", "password_confirm");
     $this->obj_form->subforms["hidden"] = array("id_customer");
     if (user_permissions_get("customers_write")) {
         $this->obj_form->subforms["submit"] = array("submit");
     } else {
         $this->obj_form->subforms["submit"] = array();
     }
     // fetch the form data
     $this->obj_customer->load_data();
     $this->obj_form->structure["code_customer"]["defaultvalue"] = $this->obj_customer->data["code_customer"];
     $this->obj_form->structure["name_customer"]["defaultvalue"] = $this->obj_customer->data["name_customer"];
     $this->obj_form->structure["login_time"]["defaultvalue"] = $this->obj_customer->data["portal_login_time"];
     $this->obj_form->structure["login_ipaddress"]["defaultvalue"] = $this->obj_customer->data["portal_login_ipaddress"];
     if (error_check()) {
         $this->obj_form->load_data_error();
     }
 }
示例#28
0
                        // so no need to translate this. This is just in case. :-)
                        $error = 'Invalid characters in login.';
                    } else {
                        if (empty($user)) {
                            // Username cannot be blank. This is currently the only place
                            // that calls addUser that is located in $user_inc.
                            $error = $blankUserStr;
                        } else {
                            user_add_user($user, $upassword1, $ufirstname, $ulastname, $uemail, $uis_admin, $u_enabled);
                            activity_log(0, $login, $user, LOG_USER_ADD, "{$ufirstname} {$ulastname}" . (empty($uemail) ? '' : " <{$uemail}>"));
                        }
                    }
                }
            } else {
                if (!empty($add) && !access_can_access_function(ACCESS_USER_MANAGEMENT)) {
                    $error = print_not_auth(15);
                } else {
                    // Don't allow a user to change themself to an admin by setting
                    // uis_admin in the URL by hand. They must be admin beforehand.
                    if (!$is_admin) {
                        $uis_admin = 'N';
                    }
                    user_update_user($user, $ufirstname, $ulastname, $uemail, $uis_admin, $uenabled);
                    activity_log(0, $login, $user, LOG_USER_UPDATE, "{$ufirstname} {$ulastname}" . (empty($uemail) ? '' : " <{$uemail}>"));
                }
            }
        }
    }
}
echo error_check('users.php', false);
示例#29
0
 function execute()
 {
     if ($this->mode == 1) {
         /*
         	MODE 1: INITAL FILE UPLOAD
         */
         $this->obj_form = new form_input();
         $this->obj_form->formname = "domain_import";
         $this->obj_form->language = $_SESSION["user"]["lang"];
         $this->obj_form->action = "domains/import-process.php";
         $this->obj_form->method = "post";
         // import type
         $structure = NULL;
         $structure["fieldname"] = "import_upload_type";
         $structure["type"] = "radio";
         $structure["values"] = array("file_bind_8");
         $structure["defaultvalue"] = "file_bind_8";
         $this->obj_form->add_input($structure);
         // file upload
         $structure = NULL;
         $structure["fieldname"] = "import_upload_file";
         $structure["type"] = "file";
         $this->obj_form->add_input($structure);
         // submit section
         $structure = NULL;
         $structure["fieldname"] = "submit";
         $structure["type"] = "submit";
         $structure["defaultvalue"] = "Save Changes";
         $this->obj_form->add_input($structure);
         $structure = NULL;
         $structure["fieldname"] = "mode";
         $structure["type"] = "hidden";
         $structure["defaultvalue"] = $this->mode;
         $this->obj_form->add_input($structure);
         // define subforms
         $this->obj_form->subforms["upload"] = array("import_upload_type", "import_upload_file");
         $this->obj_form->subforms["hidden"] = array("mode");
         $this->obj_form->subforms["submit"] = array("submit");
         // import data
         if (error_check()) {
             $this->obj_form->load_data_error();
         }
     } elseif ($this->mode == 2) {
         /*
         	MODE 2: DOMAIN RECORD ASSIGNMENT
         
         	Information from the imported zone file under mode 1 has been converted and loaded into
         	the session variables, from here we can now enter all that information into a form and
         	the user can correct/complete before we push through to the database.
         
         	We also need to address issues like over-writing of existing domains here.
         */
         /*
         	Define form structure
         */
         $this->obj_form = new form_input();
         $this->obj_form->formname = "domain_import";
         $this->obj_form->language = $_SESSION["user"]["lang"];
         $this->obj_form->action = "domains/import-process.php";
         $this->obj_form->method = "post";
         /*
         	General domain & SOA information
         */
         $structure = NULL;
         $structure["fieldname"] = "domain_type";
         $structure["type"] = "radio";
         $structure["values"] = array("domain_standard", "domain_reverse_ipv4", "domain_reverse_ipv6");
         $structure["options"]["req"] = "yes";
         $structure["defaultvalue"] = "domain_standard";
         $this->obj_form->add_input($structure);
         $structure = NULL;
         $structure["fieldname"] = "domain_name";
         $structure["type"] = "input";
         $structure["options"]["req"] = "yes";
         $this->obj_form->add_input($structure);
         $structure = NULL;
         $structure["fieldname"] = "ipv4_help";
         $structure["type"] = "text";
         $structure["options"]["req"] = "yes";
         $structure["defaultvalue"] = "help_ipv4_help";
         $this->obj_form->add_input($structure);
         $structure = NULL;
         $structure["fieldname"] = "ipv6_help";
         $structure["type"] = "text";
         $structure["options"]["req"] = "yes";
         $structure["defaultvalue"] = "help_ipv6_help";
         $this->obj_form->add_input($structure);
         $structure = NULL;
         $structure["fieldname"] = "ipv4_network";
         $structure["type"] = "input";
         $structure["options"]["help"] = "eg: 192.168.0.0";
         $structure["options"]["label"] = " /24";
         $structure["options"]["req"] = "yes";
         $this->obj_form->add_input($structure);
         /*
         		$structure = NULL;
         		$structure["fieldname"] 	= "ipv4_subnet";
         		$structure["type"]		= "radio";
         		$structure["values"]		= array("24", "16", "8");
         		$structure["options"]["req"]	= "yes";
         		$this->obj_form->add_input($structure);
         
         		$structure = NULL;
         		$structure["fieldname"] 	= "ipv4_autofill";
         		$structure["type"]		= "checkbox";
         		$structure["options"]["label"]	= lang_trans("help_ipv4_autofill");
         		$structure["options"]["req"]	= "yes";
         		$this->obj_form->add_input($structure);
         
         		$structure = NULL;
         		$structure["fieldname"] 	= "ipv4_autofill_domain";
         		$structure["type"]		= "input";
         		$structure["options"]["help"]	= "eg: static.example.com";
         		$structure["options"]["req"]	= "yes";
         		$this->obj_form->add_input($structure);
         */
         $structure = NULL;
         $structure["fieldname"] = "ipv6_network";
         $structure["type"] = "input";
         $structure["options"]["help"] = "eg: 2001:db8::/48";
         $structure["options"]["label"] = " always include a /cidr value (/1 though to /64)";
         $structure["options"]["req"] = "yes";
         $this->obj_form->add_input($structure);
         /*
         			$structure = NULL;
         			$structure["fieldname"] 	= "ipv6_autofill";
         			$structure["type"]		= "checkbox";
         			$structure["options"]["label"]	= lang_trans("help_ipv6_autofill");
         			$structure["options"]["req"]	= "yes";
         			$this->obj_form->add_input($structure);
         
         			$structure = NULL;
         			$structure["fieldname"] 	= "ipv6_autofill_forward";
         			$structure["type"]		= "checkbox";
         			$structure["options"]["label"]	= lang_trans("help_ipv6_autofill_forward");
         			$structure["options"]["req"]	= "yes";
         			$this->obj_form->add_input($structure);
         
         			$structure = NULL;
         			$structure["fieldname"] 	= "ipv6_autofill_reverse_from_forward";
         			$structure["type"]		= "checkbox";
         			$structure["options"]["label"]	= lang_trans("help_ipv6_autofill_reverse_from_forward");
         			$structure["options"]["req"]	= "yes";
         			$this->obj_form->add_input($structure);
         
         			$structure = NULL;
         			$structure["fieldname"] 	= "ipv6_autofill_domain";
         			$structure["type"]		= "input";
         			$structure["options"]["help"]	= "eg: static.example.com";
         			$structure["options"]["req"]	= "yes";
         			$this->obj_form->add_input($structure);
         */
         $this->obj_form->add_action("domain_type", "default", "domain_name", "show");
         $this->obj_form->add_action("domain_type", "default", "ipv4_help", "hide");
         $this->obj_form->add_action("domain_type", "default", "ipv4_network", "hide");
         //		$this->obj_form->add_action("domain_type", "default", "ipv4_subnet", "hide");
         //		$this->obj_form->add_action("domain_type", "default", "ipv4_autofill", "hide");
         $this->obj_form->add_action("domain_type", "default", "ipv6_help", "hide");
         $this->obj_form->add_action("domain_type", "default", "ipv6_network", "hide");
         //		$this->obj_form->add_action("domain_type", "default", "ipv4_subnet", "hide");
         //		$this->obj_form->add_action("domain_type", "default", "ipv4_autofill", "hide");
         $this->obj_form->add_action("domain_type", "domain_standard", "domain_name", "show");
         $this->obj_form->add_action("domain_type", "domain_reverse_ipv4", "domain_name", "hide");
         $this->obj_form->add_action("domain_type", "domain_reverse_ipv4", "ipv4_help", "show");
         $this->obj_form->add_action("domain_type", "domain_reverse_ipv4", "ipv4_network", "show");
         //		$this->obj_form->add_action("domain_type", "domain_reverse_ipv4", "ipv4_subnet", "show");
         //		$this->obj_form->add_action("domain_type", "domain_reverse_ipv4", "ipv4_autofill", "show");
         $this->obj_form->add_action("domain_type", "domain_reverse_ipv4", "ipv6_help", "hide");
         $this->obj_form->add_action("domain_type", "domain_reverse_ipv4", "ipv6_network", "hide");
         //		$this->obj_form->add_action("domain_type", "domain_reverse_ipv4", "ipv6_subnet", "hide");
         //		$this->obj_form->add_action("domain_type", "domain_reverse_ipv4", "ipv6_autofill", "hide");
         $this->obj_form->add_action("domain_type", "domain_reverse_ipv6", "domain_name", "hide");
         $this->obj_form->add_action("domain_type", "domain_reverse_ipv6", "ipv4_help", "hide");
         $this->obj_form->add_action("domain_type", "domain_reverse_ipv6", "ipv4_network", "hide");
         //		$this->obj_form->add_action("domain_type", "domain_reverse_ipv6", "ipv4_subnet", "hide");
         //		$this->obj_form->add_action("domain_type", "domain_reverse_ipv6", "ipv4_autofill", "hide");
         $this->obj_form->add_action("domain_type", "domain_reverse_ipv6", "ipv6_help", "show");
         $this->obj_form->add_action("domain_type", "domain_reverse_ipv6", "ipv6_network", "show");
         //		$this->obj_form->add_action("domain_type", "domain_reverse_ipv6", "ipv6_subnet", "hide");
         //		$this->obj_form->add_action("domain_type", "domain_reverse_ipv6", "ipv6_autofill", "hide");
         //		$this->obj_form->add_action("ipv4_autofill", "default", "ipv4_autofill_domain", "hide");
         //		$this->obj_form->add_action("ipv4_autofill", "1", "ipv4_autofill_domain", "show");
         $structure = NULL;
         $structure["fieldname"] = "domain_description";
         $structure["type"] = "textarea";
         $this->obj_form->add_input($structure);
         // SOA configuration
         $structure = NULL;
         $structure["fieldname"] = "soa_hostmaster";
         $structure["type"] = "input";
         $structure["options"]["req"] = "yes";
         $structure["defaultvalue"] = $GLOBALS["config"]["DEFAULT_HOSTMASTER"];
         $this->obj_form->add_input($structure);
         $structure = NULL;
         $structure["fieldname"] = "soa_serial";
         $structure["type"] = "input";
         $structure["options"]["req"] = "yes";
         $structure["defaultvalue"] = date("Ymd") . "01";
         $this->obj_form->add_input($structure);
         $structure = NULL;
         $structure["fieldname"] = "soa_refresh";
         $structure["type"] = "input";
         $structure["options"]["req"] = "yes";
         $structure["defaultvalue"] = "21600";
         $this->obj_form->add_input($structure);
         $structure = NULL;
         $structure["fieldname"] = "soa_retry";
         $structure["type"] = "input";
         $structure["options"]["req"] = "yes";
         $structure["defaultvalue"] = "3600";
         $this->obj_form->add_input($structure);
         $structure["fieldname"] = "soa_expire";
         $structure["type"] = "input";
         $structure["options"]["req"] = "yes";
         $structure["defaultvalue"] = "604800";
         $this->obj_form->add_input($structure);
         $structure["fieldname"] = "soa_default_ttl";
         $structure["type"] = "input";
         $structure["options"]["req"] = "yes";
         $structure["defaultvalue"] = $GLOBALS["config"]["DEFAULT_TTL_SOA"];
         $this->obj_form->add_input($structure);
         // define main domain subforms
         $this->obj_form->subforms["domain_details"] = array("domain_type", "domain_name", "ipv4_help", "ipv4_network", "ipv6_help", "ipv6_network", "domain_description");
         $this->obj_form->subforms["domain_soa"] = array("soa_hostmaster", "soa_serial", "soa_refresh", "soa_retry", "soa_expire", "soa_default_ttl");
         /*
         	Imported Records
         
         	The record import logic is not as advanced as the regular record handling
         	page, it's primarily intended to display the import and allow correction
         	before submission.
         
         	For more advanced configuration and addition of rows, the user should
         	import the domain and then adjust like normal.
         */
         // subform header
         $this->obj_form->subforms["domain_records"] = array("record_import_guide");
         $structure = NULL;
         $structure["fieldname"] = "record_import_guide";
         $structure["type"] = "message";
         $structure["defaultvalue"] = "<p>" . lang_trans("record_import_guide") . "</p>";
         $this->obj_form->add_input($structure);
         if (empty($_SESSION["error"]["num_records"])) {
             // no records returned
             $structure = NULL;
             $structure["fieldname"] = "record_import_notice";
             $structure["type"] = "message";
             $structure["defaultvalue"] = "<p>" . lang_trans("records_not_imported") . "</p>";
             $structure["options"]["css_row_class"] = "table_highlight_important";
             $this->obj_form->add_input($structure);
             $this->obj_form->subforms["domain_records"][] = "record_import_notice";
         } else {
             // headers
             $this->obj_form->subforms["domain_records"][] = "record_header";
             $this->obj_form->subforms_grouped["domain_records"]["record_header"][] = "record_header_type";
             $this->obj_form->subforms_grouped["domain_records"]["record_header"][] = "record_header_ttl";
             $this->obj_form->subforms_grouped["domain_records"]["record_header"][] = "record_header_prio";
             $this->obj_form->subforms_grouped["domain_records"]["record_header"][] = "record_header_name";
             $this->obj_form->subforms_grouped["domain_records"]["record_header"][] = "record_header_content";
             $this->obj_form->subforms_grouped["domain_records"]["record_header"][] = "record_header_import";
             $structure = NULL;
             $structure["fieldname"] = "record_header_type";
             $structure["type"] = "text";
             $structure["defaultvalue"] = lang_trans("record_header_type");
             $this->obj_form->add_input($structure);
             $structure = NULL;
             $structure["fieldname"] = "record_header_ttl";
             $structure["type"] = "text";
             $structure["defaultvalue"] = lang_trans("record_header_ttl");
             $this->obj_form->add_input($structure);
             $structure = NULL;
             $structure["fieldname"] = "record_header_prio";
             $structure["type"] = "text";
             $structure["defaultvalue"] = lang_trans("record_header_prio");
             $this->obj_form->add_input($structure);
             $structure = NULL;
             $structure["fieldname"] = "record_header_name";
             $structure["type"] = "text";
             $structure["defaultvalue"] = lang_trans("record_header_name");
             $this->obj_form->add_input($structure);
             $structure = NULL;
             $structure["fieldname"] = "record_header_content";
             $structure["type"] = "text";
             $structure["defaultvalue"] = lang_trans("record_header_content");
             $this->obj_form->add_input($structure);
             $structure = NULL;
             $structure["fieldname"] = "record_header_import";
             $structure["type"] = "text";
             $structure["defaultvalue"] = lang_trans("record_header_import");
             $this->obj_form->add_input($structure);
             // draw pre-defined nameserver records
             $obj_sql = new sql_query();
             $obj_sql->string = "SELECT server_name FROM name_servers";
             $obj_sql->execute();
             if ($obj_sql->num_rows()) {
                 $obj_sql->fetch_array();
                 $i = 0;
                 foreach ($obj_sql->data as $data_ns) {
                     $i++;
                     // record form items
                     $structure = NULL;
                     $structure["fieldname"] = "ns_" . $i . "_type";
                     $structure["type"] = "text";
                     $structure["defaultvalue"] = "NS";
                     $this->obj_form->add_input($structure);
                     $structure = NULL;
                     $structure["fieldname"] = "ns_" . $i . "_ttl";
                     $structure["type"] = "text";
                     $structure["defaultvalue"] = $GLOBALS["config"]["DEFAULT_TTL_NS"];
                     $this->obj_form->add_input($structure);
                     $structure = NULL;
                     $structure["fieldname"] = "ns_" . $i . "_prio";
                     $structure["type"] = "text";
                     $structure["defaultvalue"] = "";
                     $this->obj_form->add_input($structure);
                     $structure = NULL;
                     $structure["fieldname"] = "ns_" . $i . "_name";
                     $structure["type"] = "text";
                     $structure["defaultvalue"] = "@";
                     $this->obj_form->add_input($structure);
                     $structure = NULL;
                     $structure["fieldname"] = "ns_" . $i . "_content";
                     $structure["type"] = "text";
                     $structure["defaultvalue"] = $data_ns["server_name"];
                     $this->obj_form->add_input($structure);
                     $structure = NULL;
                     $structure["fieldname"] = "ns_" . $i . "_import";
                     $structure["type"] = "checkbox";
                     $structure["defaultvalue"] = "on";
                     $structure["options"]["disabled"] = "yes";
                     $structure["options"]["label"] = "Import";
                     $this->obj_form->add_input($structure);
                     // domain records
                     $this->obj_form->subforms["domain_records"][] = "ns_" . $i;
                     $this->obj_form->subforms_grouped["domain_records"]["ns_" . $i][] = "ns_" . $i . "_type";
                     $this->obj_form->subforms_grouped["domain_records"]["ns_" . $i][] = "ns_" . $i . "_ttl";
                     $this->obj_form->subforms_grouped["domain_records"]["ns_" . $i][] = "ns_" . $i . "_prio";
                     $this->obj_form->subforms_grouped["domain_records"]["ns_" . $i][] = "ns_" . $i . "_name";
                     $this->obj_form->subforms_grouped["domain_records"]["ns_" . $i][] = "ns_" . $i . "_content";
                     $this->obj_form->subforms_grouped["domain_records"]["ns_" . $i][] = "ns_" . $i . "_import";
                 }
             }
             // end of pre-defined nameserver loop
             // loop through imported records and create form structure
             for ($i = 0; $i < $_SESSION["error"]["num_records"]; $i++) {
                 $record = $_SESSION["error"]["records"][$i];
                 // record form items
                 $structure = form_helper_prepare_dropdownfromdb("record_" . $i . "_type", "SELECT type as label, type as id FROM `dns_record_types` WHERE type!='SOA'");
                 $structure["options"]["width"] = "100";
                 $structure["defaultvalue"] = $record["type"];
                 $this->obj_form->add_input($structure);
                 if (!$record["ttl"]) {
                     $record["ttl"] = $GLOBALS["config"]["DEFAULT_TTL_OTHER"];
                 }
                 $structure = NULL;
                 $structure["fieldname"] = "record_" . $i . "_ttl";
                 $structure["type"] = "input";
                 $structure["options"]["width"] = "100";
                 $structure["defaultvalue"] = $record["ttl"];
                 $this->obj_form->add_input($structure);
                 $structure = NULL;
                 $structure["fieldname"] = "record_" . $i . "_prio";
                 $structure["type"] = "input";
                 $structure["options"]["width"] = "100";
                 $structure["defaultvalue"] = $record["prio"];
                 $this->obj_form->add_input($structure);
                 $structure = NULL;
                 $structure["fieldname"] = "record_" . $i . "_name";
                 $structure["type"] = "input";
                 $structure["defaultvalue"] = $record["name"];
                 $this->obj_form->add_input($structure);
                 $structure = NULL;
                 $structure["fieldname"] = "record_" . $i . "_content";
                 $structure["type"] = "input";
                 $structure["defaultvalue"] = $record["content"];
                 $this->obj_form->add_input($structure);
                 $structure = NULL;
                 $structure["fieldname"] = "record_" . $i . "_import";
                 $structure["type"] = "checkbox";
                 $structure["defaultvalue"] = "on";
                 $structure["options"]["label"] = "Import";
                 $this->obj_form->add_input($structure);
                 // domain records
                 $this->obj_form->subforms["domain_records"][] = "record_" . $i;
                 $this->obj_form->subforms_grouped["domain_records"]["record_" . $i][] = "record_" . $i . "_type";
                 $this->obj_form->subforms_grouped["domain_records"]["record_" . $i][] = "record_" . $i . "_ttl";
                 $this->obj_form->subforms_grouped["domain_records"]["record_" . $i][] = "record_" . $i . "_prio";
                 $this->obj_form->subforms_grouped["domain_records"]["record_" . $i][] = "record_" . $i . "_name";
                 $this->obj_form->subforms_grouped["domain_records"]["record_" . $i][] = "record_" . $i . "_content";
                 $this->obj_form->subforms_grouped["domain_records"]["record_" . $i][] = "record_" . $i . "_import";
             }
         }
         /*
         	Unmatched Lines Report
         
         	Sadly it's not always possible to import *every* line of ever zone file out there - the styles can vary
         	by far too much to match at times.
         
         	We have a section of the form to display the records which do not match so that users are notified and thus
         	able to make corrections if needed.
         */
         // subform header
         $this->obj_form->subforms["unmatched_import"] = array("unmatched_import_help", "unmatched_import_notice");
         $structure = NULL;
         $structure["fieldname"] = "unmatched_import_help";
         $structure["type"] = "message";
         $structure["defaultvalue"] = "<p>" . lang_trans("unmatched_import_help") . "</p>";
         $this->obj_form->add_input($structure);
         if (empty($_SESSION["error"]["unmatched"])) {
             // no unmatched rows
             $structure = NULL;
             $structure["fieldname"] = "unmatched_import_notice";
             $structure["type"] = "message";
             $structure["defaultvalue"] = "<p>" . lang_trans("import_notice_no_unmatched_rows") . "</p>";
             $structure["options"]["css_row_class"] = "table_highlight_open";
             $this->obj_form->add_input($structure);
         } else {
             // import notice
             $structure = NULL;
             $structure["fieldname"] = "unmatched_import_notice";
             $structure["type"] = "message";
             $structure["defaultvalue"] = "<p>" . lang_trans("import_notice_unmatched_rows") . "</p>";
             $structure["options"]["css_row_class"] = "table_highlight_important";
             $this->obj_form->add_input($structure);
             // add all the unmatched rows
             for ($i = 0; $i < count($_SESSION["error"]["unmatched"]); $i++) {
                 $this->obj_form->subforms["unmatched_import"][] = "unmatched_row_{$i}";
                 $structure = NULL;
                 $structure["fieldname"] = "unmatched_row_{$i}";
                 $structure["type"] = "message";
                 $structure["defaultvalue"] = "\"" . $_SESSION["error"]["unmatched"][$i] . "\"";
                 $this->obj_form->add_input($structure);
             }
         }
         // end of unmatched lines loop
         /*
         	Submission
         */
         // submit section
         $structure = NULL;
         $structure["fieldname"] = "submit";
         $structure["type"] = "submit";
         $structure["defaultvalue"] = "Save Changes";
         $this->obj_form->add_input($structure);
         $structure = NULL;
         $structure["fieldname"] = "mode";
         $structure["type"] = "hidden";
         $structure["defaultvalue"] = $this->mode;
         $this->obj_form->add_input($structure);
         $structure = NULL;
         $structure["fieldname"] = "num_records";
         $structure["type"] = "hidden";
         $structure["defaultvalue"] = $_SESSION["error"]["num_records"];
         $this->obj_form->add_input($structure);
         // define submit subforms
         $this->obj_form->subforms["hidden"] = array("mode", "num_records");
         $this->obj_form->subforms["submit"] = array("submit");
         // import data
         //			if (error_check())
         //			{
         //				$_SESSION["error"]["form"]["domain_import"] = "error";
         //				$this->obj_form->load_data_error();
         //			}
         foreach (array_keys($this->obj_form->structure) as $fieldname) {
             if (isset($_SESSION["error"][$fieldname])) {
                 $this->obj_form->structure[$fieldname]["defaultvalue"] = stripslashes($_SESSION["error"][$fieldname]);
             }
         }
     }
     // end of mode
 }
function service_invoices_generate($customerid = NULL)
{
    log_debug("inc_services_invoicegen", "Executing service_invoices_generate({$customerid})");
    /*
    	Invoice Report Statistics
    */
    $invoice_stats = array();
    $invoice_stats["time_start"] = time();
    $invoice_stats["total"] = 0;
    $invoice_stats["total_failed"] = 0;
    /*
    	Run through all the customers
    */
    $sql_customers_obj = new sql_query();
    $sql_customers_obj->string = "SELECT id, code_customer, name_customer FROM customers";
    if ($customerid) {
        $sql_customers_obj->string .= " WHERE id='{$customerid}' LIMIT 1";
    }
    $sql_customers_obj->execute();
    if ($sql_customers_obj->num_rows()) {
        $sql_customers_obj->fetch_array();
        foreach ($sql_customers_obj->data as $customer_data) {
            /*
            	Fetch all periods belonging to this customer which need to be billed.
            */
            $sql_periods_obj = new sql_query();
            $sql_periods_obj->string = "SELECT " . "services_customers_periods.id, " . "services_customers_periods.rebill, " . "services_customers_periods.invoiceid, " . "services_customers_periods.invoiceid_usage, " . "services_customers_periods.date_start, " . "services_customers_periods.date_end, " . "services_customers.date_period_first, " . "services_customers.date_period_next, " . "services_customers.date_period_last, " . "services_customers.id as id_service_customer, " . "services_customers.serviceid " . "FROM services_customers_periods " . "LEFT JOIN services_customers ON services_customers.id = services_customers_periods.id_service_customer " . "WHERE " . "services_customers.customerid='" . $customer_data["id"] . "' " . "AND (invoiceid = '0' OR rebill = '1')" . "AND date_billed <= '" . date("Y-m-d") . "'";
            $sql_periods_obj->execute();
            if ($sql_periods_obj->num_rows()) {
                $sql_periods_obj->fetch_array();
                /*
                	BILL CUSTOMER
                
                	This customer has at least one service that needs to be billed. We need to create
                	a new invoice, and then process each service, adding the services to the invoice as 
                	items.
                */
                /*
                	Start Transaction
                
                	(one transaction per invoice)
                */
                $sql_obj = new sql_query();
                $sql_obj->trans_begin();
                /*
                	Create new invoice
                */
                $invoice = new invoice();
                $invoice->type = "ar";
                $invoice->prepare_code_invoice();
                $invoice->data["customerid"] = $customer_data["id"];
                $invoice->data["employeeid"] = 1;
                // set employee to the default internal user
                $invoice->prepare_date_shift();
                if (!$invoice->action_create()) {
                    log_write("error", "services_invoicegen", "Unexpected problem occured whilst attempting to create invoice.");
                    $sql_obj->trans_rollback();
                    return 0;
                }
                $invoiceid = $invoice->id;
                $invoicecode = $invoice->data["code_invoice"];
                unset($invoice);
                /*
                	Create Service Items
                						
                	We need to create an item for basic service plan - IE: the regular fixed fee, and another item for any
                	excess usage.
                */
                foreach ($sql_periods_obj->data as $period_data) {
                    /*
                    	TODO:
                    
                    	We should be able to re-bill usage here when needed with a clever cheat - if we load the periods to be billed,
                    	we can then ignore the plan item, and rebill the usage item.
                    */
                    $period_data["mode"] = "standard";
                    if ($period_data["rebill"]) {
                        if (!$period_data["invoiceid_usage"] && $period_data["invoiceid"]) {
                            // the selected period has been billed, but the usage has been flagged for rebilling - we need to *ignore* the base plan
                            // item and only bill for the usage range.
                            $period_data["mode"] = "rebill_usage";
                        }
                    }
                    // fetch service details
                    $obj_service = new service_bundle();
                    $obj_service->option_type = "customer";
                    $obj_service->option_type_id = $period_data["id_service_customer"];
                    if (!$obj_service->verify_id_options()) {
                        log_write("error", "customers_services", "Unable to verify service ID of " . $period_data["id_service_customer"] . " as being valid.");
                        return 0;
                    }
                    $obj_service->load_data();
                    $obj_service->load_data_options();
                    // ratio is used to adjust prices for partial periods
                    $ratio = 1;
                    if ($obj_service->data["billing_mode_string"] == "monthend" || $obj_service->data["billing_mode_string"] == "monthadvance" || $obj_service->data["billing_mode_string"] == "monthtelco") {
                        log_debug("services_invoicegen", "Invoice bills by month date");
                        /*
                        	Handle monthly billing
                        
                        	Normally, monthly billing is easy, however the very first billing period is special, as it may span a more than 1 month, or
                        	consist of less than the full month, depending on the operational mode.
                        
                        	SERVICE_PARTPERIOD_MODE == seporate
                        
                        		If a service is started on 2008-01-09, the end date of the billing period will be 2008-01-31, which is less
                        		than one month - 22 days.
                        
                        		We can calculate with:
                        
                        		( standard_cost / normal_month_num_days ) * num_days_in_partial_month == total_amount
                        
                        
                        	SERVICE_PARTPERIOD_MODE == merge
                        
                        		If a service is started on 2008-01-09, the end of the billing period will be 2008-02-29, which is 1 month + 21 day.
                        
                        		We can calculate with:
                        
                        		( standard_cost / normal_month_num_days ) * num_days_in_partial_month == extra_amount
                        		total_amount = (extra_amount + normal_amount)
                        
                        	Note: we do not increase included units for licenses service types, since these need to remain fixed and do not
                        	scale with the month.
                        */
                        // check if the period start date is not the first of the month - this means that the period
                        // is an inital partial period.
                        if (time_calculate_daynum($period_data["date_start"]) != "01") {
                            // very first billing month
                            log_write("debug", "services_invoicegen", "First billing month for this service, adjusting pricing to suit days.");
                            // figure out normal period length - rememeber, whilst service may be configured to align monthly, it needs to
                            // handle pricing calculations for variations such as month, year, etc.
                            // get the number of days of a regular period - this correctly handles, month, year, etc
                            // 1. generate the next period dates, this will be of regular length
                            // 2. calculate number of days
                            $tmp_dates = service_period_dates_generate($period_data["date_period_next"], $obj_service->data["billing_cycle_string"], $obj_service->data["billing_mode_string"]);
                            $regular_period_num_days = sql_get_singlevalue("SELECT DATEDIFF('" . $tmp_dates["end"] . "', '" . $tmp_dates["start"] . "') as value");
                            // process for short/long periods
                            //
                            if ($GLOBALS["config"]["SERVICE_PARTPERIOD_MODE"] == "seporate") {
                                log_write("debug", "services_invoicegen", "Adjusting for partial month period (SERVICE_PARTPERIOD_MODE == seporate)");
                                // work out the total number of days in partial month
                                $short_month_days_total = time_calculate_daynum(time_calculate_monthdate_last($period_data["date_start"]));
                                $short_month_days_short = $short_month_days_total - time_calculate_daynum($period_data["date_start"]);
                                log_write("debug", "services_invoicegen", "Short initial billing period of {$short_month_days_short} days");
                                // calculate correct base fee
                                $obj_service->data["price"] = $obj_service->data["price"] / $regular_period_num_days * $short_month_days_short;
                                // calculate ratio
                                $ratio = $short_month_days_short / $regular_period_num_days;
                                log_write("debug", "services_invoicegen", "Calculated service bill ratio of {$ratio} to handle short period.");
                            } else {
                                log_write("debug", "services_invoicegen", "Adjusting for extended month period (SERVICE_PARTPERIOD_MODE == merge");
                                // work out the number of days extra
                                $extra_month_days_total = time_calculate_daynum(time_calculate_monthdate_last($period_data["date_start"]));
                                $extra_month_days_extra = $extra_month_days_total - time_calculate_daynum($period_data["date_start"]);
                                log_debug("services_invoicegen", "{$extra_month_days_extra} additional days ontop of started billing period");
                                // calculate correct base fee
                                $obj_service->data["price"] = $obj_service->data["price"] / $regular_period_num_days * $extra_month_days_extra + $obj_service->data["price"];
                                // calculate ratio
                                $ratio = ($extra_month_days_extra + $extra_month_days_total) / $regular_period_num_days;
                                log_write("debug", "services_invoicegen", "Calculated service bill ratio of {$ratio} to handle extended period.");
                            }
                        }
                    }
                    /*
                    	Service Last Period Handling
                    
                    	If this is the last period for a service, it may be of a different link to the regular full period term
                    	- this effects both month and period based services.
                    */
                    if ($period_data["date_period_last"] != "0000-00-00") {
                        log_write("debug", "services_invoicegen", "Service has a final period date set (" . $period_data["date_period_last"] . ")");
                        if ($period_data["date_period_last"] == $period_data["date_end"] || time_date_to_timestamp($period_data["date_period_last"]) < time_date_to_timestamp($period_data["date_end"])) {
                            log_write("debug", "services_invoicegen", "Service is a final period, checking for time adjustment (if any)");
                            // fetch the regular end date
                            $orig_dates = service_period_dates_generate($period_data["date_start"], $obj_service->data["billing_cycle_string"], $obj_service->data["billing_mode_string"]);
                            if ($orig_dates["end"] != $period_data["date_end"]) {
                                // work out the total number of days
                                $time = NULL;
                                $time["start"] = time_date_to_timestamp($period_data["date_start"]);
                                $time["end_orig"] = time_date_to_timestamp($orig_dates["end"]);
                                $time["end_new"] = time_date_to_timestamp($period_data["date_end"]);
                                $time["orig_days"] = sprintf("%d", ($time["end_orig"] - $time["start"]) / 86400);
                                $time["new_days"] = sprintf("%d", ($time["end_new"] - $time["start"]) / 86400);
                                log_write("debug", "services_invoicegen", "Short initial billing period of " . $time["new_days"] . " days rather than expected " . $time["orig_days"] . "");
                                // calculate correct base fee
                                $obj_service->data["price"] = $obj_service->data["price"] / $time["orig_days"] * $time["new_days"];
                                // calculate ratio
                                $ratio = $time["new_days"] / $time["orig_days"];
                                log_write("debug", "services_invoicegen", "Calculated service bill ratio of {$ratio} to handle short period.");
                                unset($time);
                            } else {
                                log_write("debug", "services_invoicegen", "Final service period is regular size, no adjustment required.");
                            }
                        }
                    }
                    /*
                    	Service Base Plan Item
                    
                    	Note: There can be a suitation where we shouldn't charge for the base plan
                    	fee, when the period end date is older than the service first start date.
                    
                    	This can happen due to the migration mode, which creates a usage-only period
                    	before the actual plan starts properly.
                    */
                    if (time_date_to_timestamp($period_data["date_period_first"]) < time_date_to_timestamp($period_data["date_end"]) && $period_data["mode"] == "standard") {
                        // date of the period is newer than the start date
                        log_write("debug", "inc_service_invoicegen", "Generating base plan item for period " . $period_data["date_start"] . " to " . $period_data["date_end"] . "");
                        // start the item
                        $invoice_item = new invoice_items();
                        $invoice_item->id_invoice = $invoiceid;
                        $invoice_item->type_invoice = "ar";
                        $invoice_item->type_item = "service";
                        $itemdata = array();
                        // chart ID
                        $itemdata["chartid"] = $obj_service->data["chartid"];
                        // service ID
                        $itemdata["customid"] = $obj_service->id;
                        // no units apply
                        $itemdata["units"] = "";
                        // description
                        switch ($obj_service->data["typeid_string"]) {
                            case "phone_single":
                                $itemdata["description"] = addslashes($obj_service->data["name_service"]) . " from " . $period_data["date_start"] . " to " . $period_data["date_end"] . " (" . $obj_service->data["phone_ddi_single"] . ")";
                                if ($obj_service->data["description"]) {
                                    $itemdata["description"] .= "\n\n";
                                    $itemdata["description"] .= addslashes($obj_service->data["description"]);
                                }
                                break;
                            default:
                                $itemdata["description"] = addslashes($obj_service->data["name_service"]) . " from " . $period_data["date_start"] . " to " . $period_data["date_end"];
                                if ($obj_service->data["description"]) {
                                    $itemdata["description"] .= "\n\n";
                                    $itemdata["description"] .= addslashes($obj_service->data["description"]);
                                }
                                break;
                        }
                        // handle final periods
                        if ($period_data["date_period_last"] != "0000-00-00" && $period_data["date_start"] == $period_data["date_end"]) {
                            $itemdata["description"] = addslashes($obj_service->data["name_service"]) . " service terminated as of " . $period_data["date_end"] . "";
                        }
                        // is this service item part of a bundle? if it is, we shouldn't charge for the plan
                        if (!empty($obj_service->data["id_bundle_component"])) {
                            // no charge for the base plan, since this is handled by
                            // the bundle item itself
                            $itemdata["price"] = "0.00";
                            $itemdata["quantity"] = 1;
                            $itemdata["discount"] = "0";
                            // append description
                            $itemdata["description"] .= " (part of bundle)";
                        } else {
                            // amount
                            $itemdata["price"] = $obj_service->data["price"];
                            $itemdata["quantity"] = 1;
                            $itemdata["discount"] = $obj_service->data["discount"];
                        }
                        // create item
                        $invoice_item->prepare_data($itemdata);
                        $invoice_item->action_update();
                        unset($invoice_item);
                    } else {
                        log_write("debug", "inc_service_invoicegen", "Skipping base plan item generation, due to migration or rebill mode operation");
                    }
                    /*
                    	Service Usage Items
                    
                    	Create another item on the invoice for any usage, provided that the service type is a usage service
                    */
                    $period_usage_data = array();
                    /*
                    	Depending on the service type, we need to handle the usage period in one of two ways:
                    	1. Invoice usage for the current period that has just ended (periodend/monthend)
                    	2. Invoice usage for the period BEFORE the current period. (periodtelco/monthtelco)
                    */
                    if ($obj_service->data["billing_mode_string"] == "periodtelco" || $obj_service->data["billing_mode_string"] == "monthtelco") {
                        log_write("debug", "service_invoicegen", "Determining previous period for telco-style usage billing (if any)");
                        if ($period_data["mode"] == "standard") {
                            // fetch previous period (if any) - we can determine the previous by subtracting one day from the current period start date.
                            $tmp_date = explode("-", $period_data["date_start"]);
                            $period_usage_data["date_end"] = date("Y-m-d", mktime(0, 0, 0, $tmp_date[1], $tmp_date[2] - 1, $tmp_date[0]));
                        } elseif ($period_data["mode"] == "rebill_usage") {
                            // use the period as the usage period
                            log_write("debug", "service_invoicegen", "Using the selected period " . $period_usage_data["date_end"] . " for rebill_usage mode");
                            $period_usage_data["date_end"] = $period_data["date_end"];
                        }
                        // fetch period data to confirm previous period
                        $sql_obj = new sql_query();
                        $sql_obj->string = "SELECT id, date_start, date_end FROM services_customers_periods WHERE id_service_customer='" . $period_data["id_service_customer"] . "' AND date_end='" . $period_usage_data["date_end"] . "' LIMIT 1";
                        $sql_obj->execute();
                        if ($sql_obj->num_rows()) {
                            log_write("debug", "service_invoicegen", "Billing for seporate past usage period");
                            // there is a valid usage period
                            $period_usage_data["active"] = "yes";
                            // fetch dates
                            $sql_obj->fetch_array();
                            $period_usage_data["id_service_customer"] = $period_data["id_service_customer"];
                            $period_usage_data["id"] = $sql_obj->data[0]["id"];
                            $period_usage_data["date_start"] = $sql_obj->data[0]["date_start"];
                            $period_usage_data["date_end"] = $sql_obj->data[0]["date_end"];
                            // tracing
                            log_write("debug", "service_invoicegen", "Current period is (" . $period_data["date_start"] . " to " . $period_data["date_end"] . "), usage period is (" . $period_usage_data["date_start"] . " to " . $period_usage_data["date_end"] . ")");
                            // reset ratio
                            $ratio = 1;
                            /*
                            	TODO: This code is a replicant of the section further above for calculating partial
                            	periods and should really be functionalised as part of service usage continual improvements
                            */
                            // calculate usage abnormal period
                            if ($obj_service->data["billing_mode_string"] == "monthend" || $obj_service->data["billing_mode_string"] == "monthadvance" || $obj_service->data["billing_mode_string"] == "monthtelco") {
                                log_debug("services_invoicegen", "Usage period service bills by month date");
                                if (time_calculate_daynum($period_usage_data["date_start"]) != "01") {
                                    // very first billing month
                                    log_write("debug", "services_invoicegen", "First billing month for this usage period, adjusting pricing to suit days.");
                                    if ($GLOBALS["config"]["SERVICE_PARTPERIOD_MODE"] == "seporate") {
                                        log_write("debug", "services_invoicegen", "Adjusting for partial month period (SERVICE_PARTPERIOD_MODE == seporate)");
                                        // work out the total number of days
                                        $short_month_days_total = time_calculate_daynum(time_calculate_monthdate_last($period_usage_data["date_start"]));
                                        $short_month_days_short = $short_month_days_total - time_calculate_daynum($period_usage_data["date_start"]);
                                        log_write("debug", "services_invoicegen", "Short initial billing period of {$short_month_days_short} days");
                                        // calculate ratio
                                        $ratio = $short_month_days_short / $short_month_days_total;
                                        log_write("debug", "services_invoicegen", "Calculated service bill ratio of {$ratio} to handle short period.");
                                    } else {
                                        log_write("debug", "services_invoicegen", "Adjusting for extended month period (SERVICE_PARTPERIOD_MODE == merge");
                                        // work out the number of days extra
                                        $extra_month_days_total = time_calculate_daynum(time_calculate_monthdate_last($period_usage_data["date_start"]));
                                        $extra_month_days_extra = $extra_month_days_total - time_calculate_daynum($period_usage_data["date_start"]);
                                        log_debug("services_invoicegen", "{$extra_month_days_extra} additional days ontop of started billing period");
                                        // calculate ratio
                                        $ratio = ($extra_month_days_extra + $extra_month_days_total) / $extra_month_days_total;
                                        log_write("debug", "services_invoicegen", "Calculated service bill ratio of {$ratio} to handle extended period.");
                                    }
                                }
                            }
                            // end of calculate usage abnormal period
                            if ($period_data["date_period_last"] != "0000-00-00") {
                                log_write("debug", "services_invoicegen", "Service has a final period date set (" . $period_data["date_period_last"] . ")");
                                if ($period_data["date_period_last"] == $period_usage_data["date_end"] || time_date_to_timestamp($period_data["date_period_last"]) < time_date_to_timestamp($period_usage_data["date_end"])) {
                                    log_write("debug", "services_invoicegen", "Service is a final period, checking for time adjustment (if any)");
                                    // fetch the regular end date
                                    $orig_dates = service_period_dates_generate($period_usage_data["date_start"], $obj_service->data["billing_cycle_string"], $obj_service->data["billing_mode_string"]);
                                    if ($orig_dates["end"] != $period_usage_data["date_end"]) {
                                        // work out the total number of days
                                        $time = NULL;
                                        $time["start"] = time_date_to_timestamp($period_usage_data["date_start"]);
                                        $time["end_orig"] = time_date_to_timestamp($orig_dates["end"]);
                                        $time["end_new"] = time_date_to_timestamp($period_usage_data["date_end"]);
                                        $time["orig_days"] = sprintf("%d", ($time["end_orig"] - $time["start"]) / 86400);
                                        $time["new_days"] = sprintf("%d", ($time["end_new"] - $time["start"]) / 86400);
                                        log_write("debug", "services_invoicegen", "Short initial billing period of " . $time["new_days"] . " days rather than expected " . $time["orig_days"] . "");
                                        // calculate correct base fee
                                        $obj_service->data["price"] = $obj_service->data["price"] / $time["orig_days"] * $time["new_days"];
                                        // calculate ratio
                                        $ratio = $time["new_days"] / $time["orig_days"];
                                        log_write("debug", "services_invoicegen", "Calculated service bill ratio of {$ratio} to handle short period.");
                                        unset($time);
                                    } else {
                                        log_write("debug", "services_invoicegen", "Final service period is regular size, no adjustment required.");
                                    }
                                }
                            }
                        } else {
                            log_write("debug", "service_invoicegen", "Not billing for past usage, as this appears to be the first plan period so no usage can exist yet");
                        }
                    } else {
                        log_write("debug", "service_invoicegen", "Using plan period as data usage period (" . $period_data["date_start"] . " to " . $period_data["date_end"] . "");
                        // use current period
                        $period_usage_data["active"] = "yes";
                        $period_usage_data["id_service_customer"] = $period_data["id_service_customer"];
                        $period_usage_data["id"] = $period_data["id"];
                        $period_usage_data["date_start"] = $period_data["date_start"];
                        $period_usage_data["date_end"] = $period_data["date_end"];
                    }
                    /*
                    	Create usage items if there is a valid usage period
                    */
                    if (!empty($period_usage_data["active"])) {
                        log_write("debug", "service_invoicegen", "Creating usage items due to active usage period");
                        switch ($obj_service->data["typeid_string"]) {
                            case "generic_with_usage":
                                /*
                                	GENERIC_WITH_USAGE
                                
                                	This service is to be used for any non-traffic, non-time accounting service that needs to track usage. Examples of this
                                	could be counting the number of API requests, size of disk usage on a vhost, etc.
                                */
                                log_write("debug", "service_invoicegen", "Processing usage items for generic_with_usage");
                                /*
                                	Usage Item Basics
                                */
                                // start the item
                                $invoice_item = new invoice_items();
                                $invoice_item->id_invoice = $invoiceid;
                                $invoice_item->type_invoice = "ar";
                                $invoice_item->type_item = "service_usage";
                                $itemdata = array();
                                $itemdata["chartid"] = $obj_service->data["chartid"];
                                $itemdata["description"] = addslashes($obj_service->data["name_service"]) . " usage from " . $period_usage_data["date_start"] . " to " . $period_usage_data["date_end"];
                                $itemdata["customid"] = $obj_service->id;
                                $itemdata["discount"] = 0;
                                /*
                                	Adjust Included Units to handle partial or extended periods
                                */
                                if ($ratio != "1") {
                                    $obj_service->data["included_units"] = sprintf("%d", $obj_service->data["included_units"] * $ratio);
                                }
                                /*
                                	Fetch usage amount
                                */
                                $usage_obj = new service_usage_generic();
                                $usage_obj->id_service_customer = $period_usage_data["id_service_customer"];
                                $usage_obj->date_start = $period_usage_data["date_start"];
                                $usage_obj->date_end = $period_usage_data["date_end"];
                                if ($usage_obj->load_data_service()) {
                                    $usage_obj->fetch_usagedata();
                                    if ($usage_obj->data["total_byunits"]) {
                                        $usage = $usage_obj->data["total_byunits"];
                                    } else {
                                        $usage = $usage_obj->data["total"];
                                    }
                                }
                                unset($usage_obj);
                                /*
                                	Charge for the usage in units
                                */
                                $unitname = addslashes($obj_service->data["units"]);
                                if ($usage > $obj_service->data["included_units"]) {
                                    // there is excess usage that we can bill for.
                                    $usage_excess = $usage - $obj_service->data["included_units"];
                                    // set item attributes
                                    $itemdata["price"] = $obj_service->data["price_extraunits"];
                                    $itemdata["quantity"] = $usage_excess;
                                    $itemdata["units"] = $unitname;
                                    // description example:		Used 120 ZZ out of 50 ZZ included in plan
                                    //				Excess usage of 70 ZZ charged at $5.00 per ZZ
                                    $itemdata["description"] .= "\nUsed {$usage} {$unitname} out of " . $obj_service->data["included_units"] . " {$unitname} included in plan.";
                                    $itemdata["description"] .= "\nExcess usage of {$usage_excess} {$unitname} charged at " . $obj_service->data["price_extraunits"] . " per {$unitname}.";
                                } else {
                                    // description example:		Used 120 ZZ out of 50 ZZ included in plan
                                    $itemdata["description"] .= "\nUsed {$usage} {$unitname} out of " . $obj_service->data["included_units"] . " {$unitname} included in plan.";
                                }
                                /*
                                	Add the item to the invoice
                                */
                                $invoice_item->prepare_data($itemdata);
                                $invoice_item->action_update();
                                unset($invoice_item);
                                /*
                                	Update usage value for period - this summary value is visable on the service
                                	history page and saves having to query lots of records to generate period totals.
                                */
                                $sql_obj = new sql_query();
                                $sql_obj->string = "UPDATE services_customers_periods SET usage_summary='{$usage}' WHERE id='" . $period_usage_data["id"] . "' LIMIT 1";
                                $sql_obj->execute();
                                break;
                            case "licenses":
                                /*
                                	LICENSES
                                
                                	No data usage, but there is a quantity field for the customer's account to specify the
                                	quantity of licenses that they have.
                                */
                                log_write("debug", "service_invoicegen", "Processing usage items for licenses");
                                /*
                                	Usage Item Basics
                                */
                                // start the item
                                $invoice_item = new invoice_items();
                                $invoice_item->id_invoice = $invoiceid;
                                $invoice_item->type_invoice = "ar";
                                $invoice_item->type_item = "service_usage";
                                $itemdata = array();
                                $itemdata["chartid"] = $obj_service->data["chartid"];
                                $itemdata["description"] = addslashes($obj_service->data["name_service"]) . " usage from " . $period_usage_data["date_start"] . " to " . $period_usage_data["date_end"];
                                $itemdata["customid"] = $obj_service->id;
                                $itemdata["discount"] = 0;
                                /*
                                	Determine Additional Charges
                                */
                                // charge for any extra licenses
                                if ($obj_service->data["quantity"] > $obj_service->data["included_units"]) {
                                    // there is excess usage that we can bill for.
                                    $licenses_excess = $obj_service->data["quantity"] - $obj_service->data["included_units"];
                                    // set item attributes
                                    $itemdata["price"] = $obj_service->data["price_extraunits"] * $ratio;
                                    $itemdata["quantity"] = $licenses_excess;
                                    $itemdata["units"] = addslashes($obj_service->data["units"]);
                                    // description example:		10 licences included
                                    //				2 additional licenses charged at $24.00 each
                                    $itemdata["description"] .= "\n" . $obj_service->data["included_units"] . " " . $obj_service->data["units"] . " included";
                                    $itemdata["description"] .= "\n{$licenses_excess} additional " . $obj_service->data["units"] . " charged at " . $obj_service->data["price_extraunits"] . " each.";
                                } else {
                                    // description example:		10 licenses
                                    $itemdata["description"] .= "\n" . $period_data["quantity"] . " " . $period_data["units"] . ".";
                                }
                                /*
                                	Add the item to the invoice
                                */
                                $invoice_item->prepare_data($itemdata);
                                $invoice_item->action_update();
                                unset($invoice_item);
                                break;
                            case "time":
                                /*
                                	TIME
                                
                                	Simular to the generic usage type, but instead of units being a text field, units
                                	is an ID to the service_units table.
                                */
                                log_write("debug", "service_invoicegen", "Processing usage items for time traffic");
                                /*
                                	Usage Item Basics
                                */
                                // start the item
                                $invoice_item = new invoice_items();
                                $invoice_item->id_invoice = $invoiceid;
                                $invoice_item->type_invoice = "ar";
                                $invoice_item->type_item = "service_usage";
                                $itemdata = array();
                                $itemdata["chartid"] = $obj_service->data["chartid"];
                                $itemdata["description"] = addslashes($obj_service->data["name_service"]) . " usage from " . $period_usage_data["date_start"] . " to " . $period_usage_data["date_end"];
                                $itemdata["customid"] = $obj_service->id;
                                $itemdata["discount"] = 0;
                                /*
                                	Adjust Included Units to handle partial or extended periods
                                */
                                if ($ratio != "1") {
                                    $obj_service->data["included_units"] = sprintf("%d", $obj_service->data["included_units"] * $ratio);
                                }
                                /*
                                	Fetch usage amount
                                */
                                $usage_obj = new service_usage_generic();
                                $usage_obj->id_service_customer = $period_usage_data["id_service_customer"];
                                $usage_obj->date_start = $period_usage_data["date_start"];
                                $usage_obj->date_end = $period_usage_data["date_end"];
                                if ($usage_obj->load_data_service()) {
                                    $usage_obj->fetch_usagedata();
                                    if ($usage_obj->data["total_byunits"]) {
                                        $usage = $usage_obj->data["total_byunits"];
                                    } else {
                                        $usage = $usage_obj->data["total"];
                                    }
                                }
                                unset($usage_obj);
                                /*
                                	Charge for the usage in units
                                */
                                $unitname = sql_get_singlevalue("SELECT name as value FROM service_units WHERE id='" . $obj_service->data["units"] . "'");
                                if ($usage > $obj_service->data["included_units"]) {
                                    // there is excess usage that we can bill for.
                                    $usage_excess = $usage - $obj_service->data["included_units"];
                                    // set item attributes
                                    $itemdata["price"] = $obj_service->data["price_extraunits"];
                                    $itemdata["quantity"] = $usage_excess;
                                    $itemdata["units"] = $unitname;
                                    // description example:		Used 120 GB out of 50 GB included in plan
                                    //				Excess usage of 70 GB charged at $5.00 per GB
                                    $itemdata["description"] .= "\nUsed {$usage} {$unitname} out of " . $obj_service->data["included_units"] . " {$unitname} included in plan.";
                                    $itemdata["description"] .= "\nExcess usage of {$usage_excess} {$unitname} charged at " . $obj_service->data["price_extraunits"] . " per {$unitname}.";
                                } else {
                                    // description example:		Used 10 out of 50 included units
                                    $itemdata["description"] .= "\nUsed {$usage} {$unitname} out of " . $obj_service->data["included_units"] . " {$unitname} included in plan.";
                                }
                                /*
                                	Add the item to the invoice
                                */
                                $invoice_item->prepare_data($itemdata);
                                $invoice_item->action_update();
                                unset($invoice_item);
                                /*
                                	Update usage value for period - this summary value is visable on the service
                                	history page and saves having to query lots of records to generate period totals.
                                */
                                $sql_obj = new sql_query();
                                $sql_obj->string = "UPDATE services_customers_periods SET usage_summary='{$usage}' WHERE id='" . $period_usage_data["id"] . "' LIMIT 1";
                                $sql_obj->execute();
                                break;
                            case "data_traffic":
                                /*
                                	DATA_TRAFFIC
                                
                                	We make use of the service_usage_traffic logic to determine the usage across all IP
                                	addressess assigned to this customer and then bill accordingly.
                                */
                                log_write("debug", "service_invoicegen", "Processing usage items for time/data_traffic");
                                /*
                                	Fetch data traffic plan usage type
                                */
                                $unitname = sql_get_singlevalue("SELECT name as value FROM service_units WHERE id='" . $obj_service->data["units"] . "'");
                                /*
                                	Fetch usage amount - the returned usage structure will include breakdown of traffic
                                	by configured types.
                                */
                                $usage_obj = new service_usage_traffic();
                                $usage_obj->id_service_customer = $period_usage_data["id_service_customer"];
                                $usage_obj->date_start = $period_usage_data["date_start"];
                                $usage_obj->date_end = $period_usage_data["date_end"];
                                /*
                                	Fetch Traffic Caps & Details
                                
                                	Returns all the traffic cap types including overrides.
                                
                                	id_type,
                                	id_cap,
                                	type_name,
                                	type_label,
                                	cap_mode,
                                	cap_units_included,
                                	cap_units_price
                                */
                                $traffic_types_obj = new traffic_caps();
                                $traffic_types_obj->id_service = $obj_service->id;
                                $traffic_types_obj->id_service_customer = $period_usage_data["id_service_customer"];
                                $traffic_types_obj->load_data_traffic_caps();
                                $traffic_types_obj->load_data_override_caps();
                                /*
                                	Generate Traffic Bills
                                */
                                if ($usage_obj->load_data_service()) {
                                    $usage_obj->fetch_usage_traffic();
                                    foreach ($traffic_types_obj->data as $data_traffic_cap) {
                                        // Adjust Included Units to handle partial or extended periods
                                        if ($ratio != "1") {
                                            $data_traffic_cap["cap_units_included"] = sprintf("%d", $data_traffic_cap["cap_units_included"] * $ratio);
                                        }
                                        // if there is only a single traffic cap, we should make the traffic type name blank, since there's only going to be
                                        // one line item anyway.
                                        if ($traffic_types_obj->data_num_rows == 1) {
                                            $data_traffic_cap["type_name"] = "";
                                        }
                                        // if the any traffic type is zero and there are other traffic types, we should skip it, since most likely
                                        // the other traffic types provide everything expected.
                                        //
                                        if ($traffic_types_obj->data_num_rows > 1 && $data_traffic_cap["type_label"] == "*" && $usage_obj->data["total_byunits"]["*"] == 0) {
                                            continue;
                                        }
                                        // start service item
                                        $invoice_item = new invoice_items();
                                        $invoice_item->id_invoice = $invoiceid;
                                        $invoice_item->type_invoice = "ar";
                                        $invoice_item->type_item = "service_usage";
                                        $itemdata = array();
                                        $itemdata["chartid"] = $obj_service->data["chartid"];
                                        $itemdata["customid"] = $obj_service->id;
                                        // base details
                                        $itemdata["price"] = 0;
                                        $itemdata["quantity"] = 0;
                                        $itemdata["discount"] = 0;
                                        $itemdata["units"] = "";
                                        $itemdata["description"] = addslashes($obj_service->data["name_service"]) . " usage from " . $period_usage_data["date_start"] . " to " . $period_usage_data["date_end"];
                                        if ($data_traffic_cap["cap_mode"] == "unlimited") {
                                            // unlimited data cap, there will never be any excess traffic charges, so the line item
                                            // description should be purely for informative purposes.
                                            $itemdata["description"] .= "\nUnlimited " . addslashes($data_traffic_cap["type_name"]) . " traffic, total of " . $usage_obj->data["total_byunits"][$data_traffic_cap["type_label"]] . " {$unitname} used\n";
                                        } else {
                                            // capped traffic - check for excess changes, otherwise just report on how much traffic
                                            // that the customer used.
                                            // description example:		Used 10 GB out of 50 GB included in plan
                                            $itemdata["description"] .= "\nCapped " . addslashes($data_traffic_cap["type_name"]) . " traffic, used " . $usage_obj->data["total_byunits"][$data_traffic_cap["type_label"]] . " {$unitname} out of " . $data_traffic_cap["cap_units_included"] . " {$unitname} in plan.";
                                            // handle excess charges
                                            //
                                            if ($usage_obj->data["total_byunits"][$data_traffic_cap["type_label"]] > $data_traffic_cap["cap_units_included"]) {
                                                // there is excess usage that we can bill for.
                                                $usage_excess = $usage_obj->data["total_byunits"][$data_traffic_cap["type_label"]] - $data_traffic_cap["cap_units_included"];
                                                // set item attributes
                                                $itemdata["price"] = $data_traffic_cap["cap_units_price"];
                                                $itemdata["quantity"] = $usage_excess;
                                                $itemdata["units"] = $unitname;
                                                // description example:		Excess usage of 70 GB charged at $5.00 per GB
                                                $itemdata["description"] .= "\nExcess usage of {$usage_excess} {$unitname} charged at " . format_money($data_traffic_cap["cap_units_price"]) . " per {$unitname}.";
                                            }
                                        }
                                        // end of traffic cap mode
                                        // add trunk usage item
                                        //
                                        $invoice_item->prepare_data($itemdata);
                                        $invoice_item->action_update();
                                        unset($invoice_item);
                                    }
                                }
                                /*
                                	Update usage value for period - this summary value is visable on the service
                                	history page and saves having to query lots of records to generate period totals.
                                */
                                $sql_obj = new sql_query();
                                $sql_obj->string = "UPDATE services_customers_periods SET usage_summary='" . $usage_obj->data["total_byunits"]["total"] . "' WHERE id='" . $period_usage_data["id"] . "' LIMIT 1";
                                $sql_obj->execute();
                                unset($usage_obj);
                                unset($traffic_types_obj);
                                break;
                            case "phone_single":
                            case "phone_tollfree":
                            case "phone_trunk":
                                /*
                                	PHONE_* SERVICES
                                
                                	The phone services are special and contain multiple usage items, for:
                                	* Additional DDI numbers
                                	* Additional Trunks
                                
                                	There are also multiple items for the call charges, grouped into one
                                	item for each DDI.
                                */
                                log_write("debug", "service_invoicegen", "Processing usage items for phone_single/phone_tollfree/phone_trunk");
                                // setup usage object
                                $usage_obj = new service_usage_cdr();
                                $usage_obj->id_service_customer = $period_usage_data["id_service_customer"];
                                $usage_obj->date_start = $period_usage_data["date_start"];
                                $usage_obj->date_end = $period_usage_data["date_end"];
                                $usage_obj->load_data_service();
                                /*
                                	1. DDI CHARGES
                                
                                	We need to fetch the total number of DDIs and see if there are any excess
                                	charges due to overage of the allocated amount in the plan.
                                */
                                if ($obj_service->data["typeid_string"] == "phone_trunk" && $period_data["mode"] == "standard") {
                                    // start service item
                                    $invoice_item = new invoice_items();
                                    $invoice_item->id_invoice = $invoiceid;
                                    $invoice_item->type_invoice = "ar";
                                    $invoice_item->type_item = "service_usage";
                                    $itemdata = array();
                                    $itemdata["chartid"] = $obj_service->data["chartid"];
                                    $itemdata["customid"] = $obj_service->id;
                                    $itemdata["discount"] = 0;
                                    // fetch DDI usage
                                    $usage = $usage_obj->load_data_ddi();
                                    // determine excess usage charges
                                    if ($usage > $obj_service->data["phone_ddi_included_units"]) {
                                        // there is excess usage that we can bill for.
                                        $usage_excess = $usage - $obj_service->data["phone_ddi_included_units"];
                                        // set item attributes
                                        $itemdata["price"] = $obj_service->data["phone_ddi_price_extra_units"] * $ratio;
                                        log_write("debug", "DEBUG", "Ratio is {$ratio}, price is " . $itemdata["price"] . "");
                                        $itemdata["quantity"] = $usage_excess;
                                        $itemdata["units"] = "DDIs";
                                        if ($obj_service->data["phone_ddi_included_units"]) {
                                            $itemdata["description"] = $obj_service->data["phone_ddi_included_units"] . "x DDI numbers included in service plan plus additional " . $usage_excess . "x numbers from " . $period_usage_data["date_start"] . " to " . $period_usage_data["date_end"] . "";
                                        } else {
                                            // no included units, we use an alternative string format
                                            $itemdata["description"] = $usage_excess . "x DDI numbers from " . $period_usage_data["date_start"] . " to " . $period_usage_data["date_end"] . "";
                                        }
                                    } else {
                                        // no charge for this item
                                        $itemdata["description"] = $obj_service->data["phone_ddi_included_units"] . "x DDI numbers included in service plan from " . $period_usage_data["date_start"] . " to " . $period_usage_data["date_end"] . "";
                                    }
                                    // add trunk usage item
                                    $invoice_item->prepare_data($itemdata);
                                    $invoice_item->action_update();
                                    unset($invoice_item);
                                }
                                /*
                                	2. Trunk Charges
                                */
                                if (($obj_service->data["typeid_string"] == "phone_trunk" || $obj_service->data["typeid_string"] == "phone_tollfree") && $period_data["mode"] == "standard") {
                                    // fetch the number of trunks included in the plan, along with the number provided
                                    // we can then see if there are any excess charges for these
                                    // start service item
                                    $invoice_item = new invoice_items();
                                    $invoice_item->id_invoice = $invoiceid;
                                    $invoice_item->type_invoice = "ar";
                                    $invoice_item->type_item = "service_usage";
                                    $itemdata = array();
                                    $itemdata["chartid"] = $obj_service->data["chartid"];
                                    $itemdata["customid"] = $obj_service->id;
                                    $itemdata["discount"] = 0;
                                    // determine excess usage charges
                                    if ($obj_service->data["phone_trunk_quantity"] > $obj_service->data["phone_trunk_included_units"]) {
                                        // there is excess usage that we can bill for.
                                        $usage_excess = $obj_service->data["phone_trunk_quantity"] - $obj_service->data["phone_trunk_included_units"];
                                        // set item attributes
                                        $itemdata["price"] = $obj_service->data["phone_trunk_price_extra_units"] * $ratio;
                                        $itemdata["quantity"] = $usage_excess;
                                        $itemdata["units"] = "trunks";
                                        if ($obj_service->data["phone_trunk_included_units"]) {
                                            $itemdata["description"] = $obj_service->data["phone_trunk_included_units"] . "x trunks included in service plan plus additional " . $usage_excess . "x trunks from " . $period_usage_data["date_start"] . " to " . $period_usage_data["date_end"] . "";
                                        } else {
                                            // no included trunks, adjust string to suit.
                                            $itemdata["description"] = $usage_excess . "x trunks from " . $period_usage_data["date_start"] . " to " . $period_usage_data["date_end"] . "";
                                        }
                                    } else {
                                        // no charge for this item
                                        $itemdata["description"] = $obj_service->data["phone_trunk_included_units"] . "x trunks included in service plan from " . $period_usage_data["date_start"] . " to " . $period_usage_data["date_end"] . "";
                                    }
                                    // add trunk usage item
                                    $invoice_item->prepare_data($itemdata);
                                    $invoice_item->action_update();
                                    unset($invoice_item);
                                }
                                /*
                                									Call Charges
                                	Use CDR usage billing module to handle call charges.
                                */
                                $usage_obj = new service_usage_cdr();
                                $usage_obj->id_service_customer = $period_usage_data["id_service_customer"];
                                $usage_obj->date_start = $period_usage_data["date_start"];
                                $usage_obj->date_end = $period_usage_data["date_end"];
                                $billgroup_obj = new sql_query();
                                $billgroup_obj->string = "SELECT id, billgroup_name FROM cdr_rate_billgroups";
                                $billgroup_obj->execute();
                                $billgroup_obj->fetch_array();
                                if ($usage_obj->load_data_service()) {
                                    $usage_obj->fetch_usage_calls();
                                    foreach ($billgroup_obj->data as $data_billgroup) {
                                        foreach ($usage_obj->data_ddi as $ddi) {
                                            if ($usage_obj->data[$ddi][$data_billgroup["id"]]["charges"] > 0) {
                                                // start service item
                                                $invoice_item = new invoice_items();
                                                $invoice_item->id_invoice = $invoiceid;
                                                $invoice_item->type_invoice = "ar";
                                                $invoice_item->type_item = "service_usage";
                                                $itemdata = array();
                                                $itemdata["chartid"] = $obj_service->data["chartid"];
                                                $itemdata["customid"] = $obj_service->id;
                                                // extra service details
                                                $itemdata["id_service_customer"] = $period_usage_data["id_service_customer"];
                                                $itemdata["id_period"] = $period_usage_data["id"];
                                                // determine excess usage charges
                                                $itemdata["discount"] = 0;
                                                $itemdata["price"] = $usage_obj->data[$ddi][$data_billgroup["id"]]["charges"];
                                                $itemdata["quantity"] = "1";
                                                $itemdata["units"] = "";
                                                $itemdata["description"] = $data_billgroup["billgroup_name"] . " call charges for {$ddi} from " . $period_usage_data["date_start"] . " to " . $period_usage_data["date_end"] . "";
                                                $itemdata["cdr_billgroup"] = $data_billgroup["id"];
                                                // add trunk usage item
                                                $invoice_item->prepare_data($itemdata);
                                                $invoice_item->action_update();
                                                unset($invoice_item);
                                            } else {
                                                log_write("debug", "inc_service_invoicegen", "Excluding DDI {$ddi} from " . $data_billgroup["billgroup_name"] . " due to no charges for the current period");
                                            }
                                        }
                                    }
                                }
                                unset($usage_obj);
                                /*
                                	If enabled, generate the CDR output format for the current service usage and attach
                                	it to the invoice via the invoice journal.
                                
                                	This feature can be enabled/disabled on a per-customer per-service basis.
                                */
                                if ($obj_service->data["billing_cdr_csv_output"]) {
                                    log_write("debug", "inc_service_invoicegen", "Generating CDR export file and attaching to invoice journal");
                                    // generate the CSV formatted export.
                                    $cdr_options = array('id_customer' => $customer_data["id"], 'id_service_customer' => $period_usage_data["id_service_customer"], 'period_start' => $period_usage_data["date_start"], 'period_end' => $period_usage_data["date_end"]);
                                    $csv = new cdr_csv($cdr_options);
                                    if (!($cdr_output = $csv->getCSV())) {
                                        log_write("error", "inc_service_invoicegen", "Unable to generate CSV ouput for the configured range");
                                        return 0;
                                    }
                                    // create journal entry
                                    $journal = new journal_process();
                                    $journal->prepare_set_journalname("account_ar");
                                    $journal->prepare_set_customid($invoiceid);
                                    $journal->prepare_set_type("file");
                                    // we use the prefix "SERVICE:" to find the journal at invoice time
                                    $journal->prepare_set_title("SERVICE: Service CDR Export Attachment");
                                    // details can be anything (just a text block)
                                    $data["content"] = NULL;
                                    $data["content"] .= "Automatically exported CDR for service " . addslashes($obj_service->data["name_service"]) . "\n";
                                    $data["content"] .= "\n";
                                    $journal->prepare_set_content($data["content"]);
                                    $journal->action_update();
                                    // create journal entry
                                    $journal->action_lock();
                                    // lock entry to avoid users deleting it or breaking it
                                    // upload file as an attachment for the journal
                                    $file_obj = new file_storage();
                                    $file_obj->data["type"] = "journal";
                                    $file_obj->data["customid"] = $journal->structure["id"];
                                    $file_obj->data["file_name"] = "invoice_" . $invoicecode . "_service_CDR_export.csv";
                                    if (!$file_obj->action_update_var($cdr_output)) {
                                        log_write("error", "inc_service_invoicegen", "Unable to upload export CDR invoice to journal.");
                                    }
                                    unset($csv);
                                    unset($journal);
                                    unset($file_obj);
                                    unset($cdr_output);
                                }
                                break;
                            case "generic_no_usage":
                            case "bundle":
                                // nothing todo for these service types
                                log_write("debug", "service_invoicegen", "Not processing usage, this is a non-usage service type");
                                break;
                            default:
                                // we should always match all service types, even if we don't need to do anything
                                // in particular for that type.
                                die("Unable to process unknown service type: " . $obj_service->data["typeid_string"] . "");
                                break;
                        }
                        // end of processing usage
                    } else {
                        log_write("debug", "service_invoicegen", "Not billing for current usage, as this appears to be the first plan period so no usage can exist yet");
                    }
                    /*
                    	Set invoice ID for period - this prevents the period from being added to
                    	any other invoices and allows users to see which invoice it was billed under
                    */
                    // set for plan period
                    $sql_obj = new sql_query();
                    $sql_obj->string = "UPDATE services_customers_periods SET invoiceid='{$invoiceid}', rebill='0' WHERE id='" . $period_data["id"] . "' LIMIT 1";
                    $sql_obj->execute();
                    // set for usage period
                    if (!empty($period_usage_data["active"])) {
                        $sql_obj = new sql_query();
                        $sql_obj->string = "UPDATE services_customers_periods SET invoiceid_usage='{$invoiceid}' WHERE id='" . $period_usage_data["id"] . "' LIMIT 1";
                        $sql_obj->execute();
                    }
                }
                // end of processing periods
                /*
                	Only process orders and invoice
                	summary details if we had no errors above.
                */
                if (!error_check()) {
                    /*
                    	Process any customer orders
                    */
                    if ($GLOBALS["config"]["ORDERS_BILL_ONSERVICE"]) {
                        log_write("debug", "inc_service_invoicegen", "Checking for customer orders to add to service invoice");
                        $obj_customer_orders = new customer_orders();
                        $obj_customer_orders->id = $customer_data["id"];
                        if ($obj_customer_orders->check_orders_num()) {
                            log_write("debug", "inc_service_invoicegen", "Order items exist, adding them to service invoice");
                            $obj_customer_orders->invoice_generate($invoiceid);
                        }
                    } else {
                        log_write("debug", "inc_service_invoicegen", "Not checking for customer orders, ORDERS_BILL_ONSERVICE is disabled currently");
                    }
                    /*
                    	Update the invoice details + Ledger
                    
                    	Processes:
                    	- taxes
                    	- ledger
                    	- invoice summary
                    
                    	We use the invoice_items class to perform these tasks, but we don't need
                    	to define an item ID for the functions being used to work.
                    */
                    $invoice = new invoice_items();
                    $invoice->id_invoice = $invoiceid;
                    $invoice->type_invoice = "ar";
                    $invoice->action_update_tax();
                    $invoice->action_update_ledger();
                    $invoice->action_update_total();
                    unset($invoice);
                    /*
                    	Update period information with invoiceid
                    */
                    $sql_obj = new sql_query();
                    $sql_obj->string = "UPDATE services_customers_periods SET invoiceid='{$invoiceid}' WHERE id='" . $period_data["id"] . "'";
                    $sql_obj->execute();
                }
                // end if error check
                /*
                	Automatic Payments
                
                	Makes automatic invoice payments using sources such as customer credit pools, reoccuring credit card transactions
                	and other sources.
                */
                if ($GLOBALS["config"]["ACCOUNTS_AUTOPAY"]) {
                    log_write("debug", "inc_services_invoicegen", "Autopay Functionality Enabled, running appropiate functions for invoice ID {$invoiceid}");
                    $obj_autopay = new invoice_autopay();
                    $obj_autopay->id_invoice = $invoiceid;
                    $obj_autopay->type_invoice = "ar";
                    $obj_autopay->autopay();
                    unset($obj_autopay);
                }
                /*
                	Commit
                
                	Conduct final error check, before commiting the new invoice and sending the customer an email
                	if appropiate.
                
                	(we obviously don't want to email them if the invoice is getting rolled back!)
                */
                $sql_obj = new sql_query();
                if (error_check()) {
                    $sql_obj->trans_rollback();
                    log_write("error", "inc_services_invoicegen", "An error occured whilst creating service invoice. No changes have been made.");
                } else {
                    $sql_obj->trans_commit();
                    // invoice creation complete - remove any notifications made by the invoice functions and return
                    // our own notification
                    $_SESSION["notification"]["message"] = array();
                    log_write("notification", "inc_services_invoicegen", "New invoice {$invoicecode} for customer " . $customer_data["code_customer"] . " created");
                    /*
                    		Send the invoice to the customer as a PDF via email
                    */
                    $emailed = "unsent";
                    if (sql_get_singlevalue("SELECT value FROM config WHERE name='EMAIL_ENABLE'") == "enabled") {
                        if (sql_get_singlevalue("SELECT value FROM config WHERE name='ACCOUNTS_INVOICE_AUTOEMAIL'") == "enabled") {
                            // load completed invoice data
                            $invoice = new invoice();
                            $invoice->id = $invoiceid;
                            $invoice->type = "ar";
                            $invoice->load_data();
                            $invoice->load_data_export();
                            if ($invoice->data["amount_total"] > 0) {
                                // generate an email
                                $email = $invoice->generate_email();
                                // send email
                                $invoice->email_invoice("system", $email["to"], $email["cc"], $email["bcc"], $email["subject"], $email["message"]);
                                // complete
                                log_write("notification", "inc_services_invoicegen", "Invoice {$invoicecode} has been emailed to customer (" . $email["to"] . ")");
                            } else {
                                // complete - invoice is for $0, so don't want to email out
                                log_write("notification", "inc_services_invoicegen", "Invoice {$invoicecode} has not been emailed to the customer due to invoice being for \$0.");
                            }
                            $emailed = "emailed - " . $email["to"];
                            unset($invoice);
                        }
                    }
                    // end if email enabled
                }
                // end if commit successful
                /*
                	Review Status
                
                	Here we need to check whether invoicing succeded/failed for the selected customer and process accordingly - we
                	also want to re-set the error flag if running a batch mode, to enable other customers to still be invoiced.
                */
                if (error_check()) {
                    // an error occured
                    $invoice_stats["total_failed"]++;
                    $invoice_stats["failed"][] = array("code_customer" => $customer_data["code_customer"], "name_customer" => $customer_data["name_customer"], "code_invoice" => $invoicecode);
                    // clear the error strings if we are processing from CLI this will allow us to continue on
                    // with additional invoices.
                    if (!empty($_SESSION["mode"])) {
                        if ($_SESSION["mode"] == "cli") {
                            log_write("debug", "inc_services_invoicegen", "Processing from CLI, clearing error flag and continuing with additional invoices");
                            error_clear();
                        }
                    }
                } else {
                    // successful
                    $invoice_stats["total"]++;
                    $invoice_stats["generated"][] = array("code_customer" => $customer_data["code_customer"], "name_customer" => $customer_data["name_customer"], "code_invoice" => $invoicecode, "sent" => $emailed);
                }
                // end of success/stats review
            }
            // end of processing customers
        }
        // end of if customers exist
    } else {
        log_debug("inc_services_invoicegen", "No services assigned to customer {$customerid}");
    }
    /*
    	Write Invoicing Report
    	
    	This only takes place if no customer ID is provided, eg we have run a full automatic invoice generation report.
    */
    if ($customerid == NULL) {
        log_write("debug", "inc_service_invoicegen", "Generating invoice report for invoice generation process");
        /*
        	Invoice Stats Calculations
        */
        $invoice_stats["time"] = time() - $invoice_stats["time_start"];
        if ($invoice_stats["time"] == 0) {
            $invoice_stats["time"] = 1;
        }
        /*
        	Write Invoice Report
        */
        $invoice_report = array();
        $invoice_report[] = "Complete Invoicing Run Time:\t" . $invoice_stats["time"] . " seconds";
        $invoice_report[] = "Total Invoices Generated:\t" . $invoice_stats["total"];
        $invoice_report[] = "Failed Invoices/Customers:\t" . $invoice_stats["total_failed"];
        if (isset($invoice_stats["generated"])) {
            $invoice_report[] = "";
            $invoice_report[] = "Customers / Invoices Generated";
            foreach (array_keys($invoice_stats["generated"]) as $id) {
                $invoice_report[] = " * " . $invoice_stats["generated"][$id]["code_invoice"] . ": " . $invoice_stats["generated"][$id]["code_customer"] . " -- " . $invoice_stats["generated"][$id]["name_customer"];
                $invoice_report[] = "   [" . $invoice_stats["generated"][$id]["sent"] . "]";
            }
            $invoice_report[] = "";
        }
        if (isset($invoice_stats["failed"])) {
            $invoice_report[] = "";
            $invoice_report[] = "Failed Customers / Invoices";
            foreach (array_keys($invoice_stats["failed"]) as $id) {
                $invoice_report[] = " * " . $invoice_stats["failed"][$id]["code_customer"] . " -- " . $invoice_stats["failed"][$id]["name_customer"];
            }
            $invoice_report[] = "";
            $invoice_report[] = "Failed invoices will be attempted again on the following billing run.";
            $invoice_report[] = "";
        }
        $invoice_report[] = "Invoicing Run Complete";
        // display to debug log
        log_write("debug", "inc_service_invoicegen", "----");
        foreach ($invoice_report as $line) {
            // loop through invoice report lines
            log_write("debug", "inc_service_invoicegen", $line);
        }
        log_write("debug", "inc_service_invoicegen", "----");
        // email if appropiate
        if ($GLOBALS["config"]["ACCOUNTS_INVOICE_BATCHREPORT"] && ($invoice_stats["total"] > 0 || $invoice_stats["total_failed"] > 0)) {
            log_write("debug", "inc_service_invoicegen", "Emailing invoice generation report to " . $GLOBALS["config"]["ACCOUNTS_EMAIL_ADDRESS"] . "");
            /*
            	External dependency of Mail_Mime
            */
            if (!@(include_once 'Mail.php')) {
                log_write("error", "invoice", "Unable to find Mail module required for sending email");
                break;
            }
            if (!@(include_once 'Mail/mime.php')) {
                log_write("error", "invoice", "Unable to find Mail::Mime module required for sending email");
                break;
            }
            /*
            	Email the Report
            */
            $email_sender = $GLOBALS["config"]["ACCOUNTS_EMAIL_ADDRESS"];
            $email_to = $GLOBALS["config"]["ACCOUNTS_EMAIL_ADDRESS"];
            $email_subject = "Invoice Batch Process Report";
            $email_message = $GLOBALS["config"]["COMPANY_NAME"] . "\n\nInvoice Batch Process Report for " . time_format_humandate() . "\n\n";
            foreach ($invoice_report as $line) {
                $email_message .= $line . "\n";
            }
            // prepare headers
            $mail_headers = array('From' => $email_sender, 'Subject' => $email_subject);
            $mail_mime = new Mail_mime("\n");
            $mail_mime->setTXTBody($email_message);
            $mail_body = $mail_mime->get();
            $mail_headers = $mail_mime->headers($mail_headers);
            $mail =& Mail::factory('mail');
            $status = $mail->send($email_to, $mail_headers, $mail_body);
            if (PEAR::isError($status)) {
                log_write("error", "inc_service_invoicegen", "An error occured whilst attempting to send the batch report email: " . $status->getMessage() . "");
            } else {
                log_write("debug", "inc_service_invoicegen", "Successfully sent batch report email.");
            }
        }
        // end if email
    }
    // end if report
    return 1;
}