DID   F
last analyzed

Complexity

Total Complexity 147

Size/Duplication

Total Lines 826
Duplicated Lines 10.05 %

Coupling/Cohesion

Components 0
Dependencies 2

Importance

Changes 0
Metric Value
dl 83
loc 826
rs 1.0434
c 0
b 0
f 0
wmc 147
lcom 0
cbo 2

23 Methods

Rating   Name   Duplication   Size   Complexity  
A did_add() 0 9 2
B did_edit() 0 32 5
C did_save() 0 47 11
A did_remove() 0 5 1
C did_list_release() 4 50 9
C did_list() 21 50 11
A did_list_json() 13 13 2
A did_list_search() 13 13 3
A did_list_clearsearchfilter() 0 4 1
B reseller_did() 0 31 2
C customer_did() 0 62 9
A did_delete_multiple() 0 12 1
C did_reseller_edit() 4 84 9
B did_reseller_purchase() 0 47 6
A add_invoice_data_user() 0 15 1
A did_download_sample_file() 12 12 1
A did_import() 0 16 3
D did_preview_file() 0 46 10
F did_import_file() 0 153 41
F data_validate() 9 28 13
A did_error_download() 7 7 1
B did_export_data_xls() 0 29 3
A DID() 0 13 2

How to fix   Duplicated Code    Complexity   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

Complex Class

 Tip:   Before tackling complexity, make sure that you eliminate any duplication first. This often can reduce the size of classes significantly.

Complex classes like DID often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use DID, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
###############################################################################
4
# ASTPP - Open Source VoIP Billing Solution
5
#
6
# Copyright (C) 2016 iNextrix Technologies Pvt. Ltd.
7
# Samir Doshi <[email protected]>
8
# ASTPP Version 3.0 and above
9
# License https://www.gnu.org/licenses/agpl-3.0.html
10
#
11
# This program is free software: you can redistribute it and/or modify
12
# it under the terms of the GNU Affero General Public License as
13
# published by the Free Software Foundation, either version 3 of the
14
# License, or (at your option) any later version.
15
# 
16
# This program is distributed in the hope that it will be useful,
17
# but WITHOUT ANY WARRANTY; without even the implied warranty of
18
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19
# GNU Affero General Public License for more details.
20
# 
21
# You should have received a copy of the GNU Affero General Public License
22
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
23
###############################################################################
24
25
class DID extends MX_Controller {
26
27
	function DID() {
28
		parent::__construct();
0 ignored issues
show
Comprehensibility Bug introduced by
It seems like you call parent on a different method (__construct() instead of DID()). Are you sure this is correct? If so, you might want to change this to $this->__construct().

This check looks for a call to a parent method whose name is different than the method from which it is called.

Consider the following code:

class Daddy
{
    protected function getFirstName()
    {
        return "Eidur";
    }

    protected function getSurName()
    {
        return "Gudjohnsen";
    }
}

class Son
{
    public function getFirstName()
    {
        return parent::getSurname();
    }
}

The getFirstName() method in the Son calls the wrong method in the parent class.

Loading history...
29
30
		$this->load->helper('template_inheritance');
31
		$this->load->library('session');
32
		$this->load->library('did_form');
33
		$this->load->library('astpp/form');
34
		$this->load->model('did_model');
35
		$this->load->library('csvreader');
36
37
		if ($this->session->userdata('user_login') == FALSE)
38
			redirect(base_url() . '/astpp/login');
39
	}
40
41
	function did_add() {
42
		$data['page_title'] = 'Create DID';
0 ignored issues
show
Coding Style Comprehensibility introduced by
$data was never initialized. Although not strictly required by PHP, it is generally a good practice to add $data = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
43
		$data['form'] = $this->form->build_form($this->did_form->get_dids_form_fields(), '');
44
		$data['country_id'] = $this->common->get_field_name('id', 'countrycode', array('country' => Common_model::$global_config['system_config']['country']));
45
		if (!$data['country_id']) {
46
			$data['country_id'] = 1;
47
		}
48
		$this->load->view('view_did_add_edit', $data);
49
	}
50
51
	function did_edit($edit_id = '') {
52
		$data['page_title'] = 'Edit DID';
0 ignored issues
show
Coding Style Comprehensibility introduced by
$data was never initialized. Although not strictly required by PHP, it is generally a good practice to add $data = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
53
		$where = array('id' => $edit_id);
54
		$account = $this->db_model->getSelect("*", "dids", $where);
55
		foreach ($account->result_array() as $value) {
56
			$edit_data = $value;
57
		}
58
		/**
59
          ASTPP  3.0 
60
          In DID Edit Country Field not change
61
		 * */
62
		$data['country_id'] = $edit_data['country_id'];
0 ignored issues
show
Bug introduced by
The variable $edit_data does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
63
		if ($edit_data['country_id'] == "") {
64
			$data['country_id'] = Common_model::$global_config['system_config']['country'];
65
		}
66
		/*         * ************************************************* */
67
		if (!$data['country_id']) {
68
			$data['country_id'] = 1;
69
		}
70
		$edit_data['setup'] = $this->common_model->to_calculate_currency($edit_data['setup'], '', '', false, false);
71
		$edit_data['monthlycost'] = $this->common_model->to_calculate_currency($edit_data['monthlycost'], '', '', false, false);
72
		$edit_data['connectcost'] = $this->common_model->to_calculate_currency($edit_data['connectcost'], '', '', false, false);
73
		$edit_data['cost'] = $this->common_model->to_calculate_currency($edit_data['cost'], '', '', false, false);
74
		$parent_id = $edit_data['parent_id'];
75
		$account_id = $edit_data['accountid'];
76
		if ($parent_id > 0) {
77
			$data['form'] = $this->form->build_form($this->did_form->get_dids_form_fields($edit_id, $parent_id, $account_id), $edit_data);
78
		} else {
79
			$data['form'] = $this->form->build_form($this->did_form->get_dids_form_fields($edit_id, '', $account_id), $edit_data);
80
		}
81
		$this->load->view('view_did_add_edit', $data);
82
	}
83
84
	function did_save() {
85
		$add_array = $this->input->post();
86
		$parent_id =isset($add_array['parent_id']) && $add_array['parent_id'] >0 ? $add_array['parent_id'] : '';
87
		$accountid =isset($add_array['accountid']) && $add_array['accountid'] > 0 ? $add_array['accountid'] : '';
88
		$data['form'] = $this->form->build_form($this->did_form->get_dids_form_fields($add_array['id'],$parent_id,$accountid), $add_array);
0 ignored issues
show
Coding Style Comprehensibility introduced by
$data was never initialized. Although not strictly required by PHP, it is generally a good practice to add $data = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
89
		if ($add_array['id'] != '') {
90
			$data['page_title'] = 'Edit DID';
91
			if ($this->form_validation->run() == FALSE) {
92
				$data['validation_errors'] = validation_errors();
93
				echo $data['validation_errors'];
94
				exit;
95
			} else {
96
				$number = $add_array['number'];
97
				unset($add_array['number']);
98
				$add_array['accountid']=isset($add_array['accountid']) ?$add_array['accountid'] : 0;
99
				$add_array['setup'] = $this->common_model->add_calculate_currency($add_array['setup'], '', '', false, false);
100
				$add_array['monthlycost'] = $this->common_model->add_calculate_currency($add_array['monthlycost'], '', '', false, false);
101
				$add_array['connectcost'] = $this->common_model->add_calculate_currency($add_array['connectcost'], '', '', false, false);
102
				$add_array['cost'] = $this->common_model->add_calculate_currency($add_array['cost'], '', '', false, false);
103
				$this->did_model->edit_did($add_array, $add_array['id'], $number);
104
				echo json_encode(array("SUCCESS" => $number . " DID Updated Successfully!"));
105
				exit;
106
			}
107
		} else {
108
			$data['page_title'] = 'Add DID';
109
			if ($this->form_validation->run() == FALSE) {
110
				$data['validation_errors'] = validation_errors();
111
				echo $data['validation_errors'];
112
				exit;
113
			} else {
114
				$check_did_number = $this->did_model->check_unique_did($add_array['number']);
115
				if ($check_did_number > 0) {
116
					echo json_encode(array("number_error" => "Number already exist in system."));
117
					exit;
118
				}
119
				$add_array['setup'] = $this->common_model->add_calculate_currency($add_array['setup'], '', '', false, false);
120
				$add_array['monthlycost'] = $this->common_model->add_calculate_currency($add_array['monthlycost'], '', '', false, false);
121
				$add_array['connectcost'] = $this->common_model->add_calculate_currency($add_array['connectcost'], '', '', false, false);
122
				$add_array['cost'] = $this->common_model->add_calculate_currency($add_array['cost'], '', '', false, false);
123
				$add_array['accountid']=isset($add_array['accountid'])?$add_array['accountid'] : 0;
124
				$this->did_model->add_did($add_array);
125
				echo json_encode(array("SUCCESS" => $add_array["number"] . " DID Added Successfully!"));
126
				exit;
127
				exit;
0 ignored issues
show
Unused Code introduced by
die; does not seem to be reachable.

This check looks for unreachable code. It uses sophisticated control flow analysis techniques to find statements which will never be executed.

Unreachable code is most often the result of return, die or exit statements that have been added for debug purposes.

function fx() {
    try {
        doSomething();
        return true;
    }
    catch (\Exception $e) {
        return false;
    }

    return false;
}

In the above example, the last return false will never be executed, because a return statement has already been met in every possible execution path.

Loading history...
128
			}
129
		}
130
	}
131
132
	function did_remove($id) {
133
		$this->did_model->remove_did($id);
134
		$this->session->set_flashdata('astpp_notification', 'DID Removed Successfully!');
135
		redirect(base_url() . 'did/did_list/');
136
	}
137
138
	/*
139
      ASTPP  3.0
140
      function Spelling change.
141
     */
142
143
	function did_list_release($id) {
144
	 $accountinfo=$this->session->userdata('accountinfo'); 
145
	 $this->db->where('id',$id);
146
	 $this->db->select('parent_id,accountid,number');
147
	 $did_info=(array)$this->db->get('dids')->first_row();
148
	 if($did_info['parent_id'] > 0){
149
	$str=$this->common->get_parent_info($did_info['parent_id'],$accountinfo['id']);
150
	$str=rtrim($str,",");
151
	$account_result=(array)$this->db->get_where('accounts',"id IN (".$str.")")->result_array();
152 View Code Duplication
	foreach($account_result as $key=>$acc_row){
153
	   $acc_row['did_number']=$did_info['number'];
154
	   $this->common->mail_to_users('email_remove_did', $acc_row);
155
	}
156
	 }
157
	 if($accountinfo['type'] == -1){
158
	  $update_array = array('parent_id' => 0, 'accountid' => 0, 'assign_date' => '0000-00-00 00:00:00', "charge_upto" => "0000-00-00 00:00:00","last_modified_date"=>gmdate("Y-m-d H:i:s"),'call_type'=>'-1','extensions'=>'');
159
	  $where = array('id' => $id);
160
	  $this->db->where($where);
161
	  $this->db->update('dids', $update_array);
162
	  if($did_info['parent_id'] > 0){
163
		$this->db->where('note',$did_info['number']);
164
		$this->db->delete("reseller_pricing");
165
	  }
166
	  }else{
167
	  $reseller_ids=$this->common->get_subreseller_info($accountinfo['id']);
168
	  $reseller_ids=rtrim($reseller_ids,",");
169
	  $where="parent_id IN ($reseller_ids)";
170
	  $this->db->where('note',$did_info['number']);
171
	  $this->db->delete('reseller_pricing',$where);  
172
	  }
173
	  if($accountinfo['type']==1){
174
		  $update_array = array('parent_id' => $accountinfo['id'], 'accountid' => 0, 'assign_date' => '0000-00-00 00:00:00', "charge_upto" => "0000-00-00 00:00:00","last_modified_date"=>gmdate("Y-m-d H:i:s"),'call_type'=>'-1','extensions'=>'');
175
	  }else{
176
    	  $update_array = array('parent_id' => 0, 'accountid' => 0, 'assign_date' => '0000-00-00 00:00:00', "charge_upto" => "0000-00-00 00:00:00","last_modified_date"=>gmdate("Y-m-d H:i:s"),'call_type'=>'-1','extensions'=>'');
177
	  }
178
	  $where = array('id' => $id);
179
	  $this->db->where($where);
180
	  $this->db->update('dids', $update_array);
181
	  $accountid=$did_info['accountid'] > 0 ? $did_info['accountid']:0;
182
	  if($did_info['accountid'] > 0 ){
183
	   $email_user_id=$did_info['accountid'];
184
	  }elseif($did_info['parent_id'] > 0){
185
	$email_user_id=$did_info['parent_id'];
186
	  }
187
	  $accountinfo=(array)$this->db->get_where('accounts',array("id"=>$email_user_id))->first_row();
0 ignored issues
show
Bug introduced by
The variable $email_user_id does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
188
	  $accountinfo['did_number'] = $did_info['number'];
189
	  $this->common->mail_to_users('email_remove_did', $accountinfo);
190
	  $this->session->set_flashdata('astpp_errormsg', 'DID Released Successfully!');
191
	  redirect(base_url() . 'did/did_list/');
192
	}
193
194
	function did_list() {
195
		$data['app_name'] = 'ASTPP - Open Source Billing Solution | Manage DIDs | DIDS';
0 ignored issues
show
Coding Style Comprehensibility introduced by
$data was never initialized. Although not strictly required by PHP, it is generally a good practice to add $data = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
196
		$data['username'] = $this->session->userdata('user_name');
197
		$data['page_title'] = gettext('DIDs');
198
		$data['search_flag'] = true;
199
		$this->session->set_userdata('did_search', 0);
200 View Code Duplication
		if ($this->session->userdata('logintype') == 2) {
201
			$data["grid_buttons"] = $this->did_form->build_grid_buttons();
202
		} else {
203
			$data["grid_buttons"] = json_encode(array());
204
		}
205
         
206
		if ($this->session->userdata['userlevel_logintype'] == '1') {
207
		$drp_list=array();
208
		$accountinfo = $this->session->userdata('accountinfo');
209
		if($accountinfo['reseller_id'] > 0){
210
		  $dids_array=$this->db->query("SELECT a.id AS id,a.number as number, b.monthlycost, b.setup FROM dids AS a, reseller_pricing AS b WHERE a.number = b.note AND b.reseller_id = ".$accountinfo['reseller_id']." AND a.parent_id =".$accountinfo['reseller_id'])->result_array();
211
			}else{
212
			  $this->db->select('id,monthlycost,setup,number');
213
			  $this->db->where('accountid',0);
214
			  $this->db->where('parent_id',0);
215
			  $dids_array=$this->db->get('dids')->result_array();
216
			}
217 View Code Duplication
			if(!empty($dids_array)){
218
		foreach ($dids_array as $drp_value) {
219
			if (!empty($drp_value['monthlycost']) && $drp_value['monthlycost'] != 0) {
220
			$did_cost = $this->common_model->to_calculate_currency($drp_value['monthlycost'], '', '', true, false);
221
			} else {
222
			$did_cost = 0;
223
			}
224
			if (!empty($drp_value['setup']) && $drp_value['setup'] != 0) {
225
			$did_setup = $this->common_model->to_calculate_currency($drp_value['setup'], '', '', true, false);
226
			} else {
227
			$did_setup = 0;
228
			}
229
			$drp_list[$drp_value['id']] = $drp_value['number'] . ' ( Setup : ' . $did_setup . ')' . '( Monthly : ' . $did_cost . ' )';
230
			/*                 * ********************************************************************************************* */
231
		}
232
		}
233
	  $data['didlist'] = form_dropdown_all(array("name"=>"free_did_list","id"=>"free_did_list","class"=>"did_dropdown"), $drp_list, '');
0 ignored issues
show
Documentation introduced by
array('name' => 'free_di...ass' => 'did_dropdown') is of type array<string,string,{"na...ing","class":"string"}>, but the function expects a string.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
Documentation introduced by
'' is of type string, but the function expects a array.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
234
		}
235
		if ($this->session->userdata['userlevel_logintype'] == '1') {
236
			$data['grid_fields'] = $this->did_form->build_did_list_for_reseller_login();
237
			$data['form_search'] = $this->form->build_serach_form($this->did_form->get_search_did_form_for_reseller());
238
		} else {
239
			$data['grid_fields'] = $this->did_form->build_did_list_for_admin();
240
			$data['form_search'] = $this->form->build_serach_form($this->did_form->get_search_did_form());
241
		}
242
		$this->load->view('view_did_list', $data);
243
	}
244
245
	/**
246
	 * -------Here we write code for controller accounts functions account_list------
247
	 * Listing of Accounts table data through php function json_encode
248
	 */
249 View Code Duplication
	function did_list_json() {
250
		$json_data = array();
251
252
		$count_all = $this->did_model->getdid_list(false);
253
		$paging_data = $this->form->load_grid_config($count_all, $_GET['rp'], $_GET['page']);
254
		$json_data = $paging_data["json_paging"];
255
		$list = $this->session->userdata['userlevel_logintype'] == 1 ? $this->did_form->build_did_list_for_reseller_login() : $this->did_form->build_did_list_for_admin();
256
		$query = $this->did_model->getdid_list(true, $paging_data["paging"]["start"], $paging_data["paging"]["page_no"]);
257
		$grid_fields = json_decode($list);
258
		$json_data['rows'] = $this->form->build_grid($query, $grid_fields);
259
260
		echo json_encode($json_data);
261
	}
262
263 View Code Duplication
	function did_list_search() {
264
		$ajax_search = $this->input->post('ajax_search', 0);
265
		if ($this->input->post('advance_search', TRUE) == 1) {
266
			$this->session->set_userdata('advance_search', $this->input->post('advance_search'));
267
			$action = $this->input->post();
268
			unset($action['action']);
269
			unset($action['advance_search']);
270
			$this->session->set_userdata('did_list_search', $action);
271
		}
272
		if (@$ajax_search != 1) {
273
			redirect(base_url() . 'did/did_list/');
274
		}
275
	}
276
277
	function did_list_clearsearchfilter() {
278
		$this->session->set_userdata('advance_search', 0);
279
		$this->session->set_userdata('did_search', "");
280
	}
281
282
283
284
	function reseller_did($accountid, $accounttype) {
285
		$json_data = array();
286
		$account_query = $this->db_model->getSelect("*", "accounts", array("id" => $accountid));
287
		$account_arr = $account_query->result_array();
288
289
		$this->db->where("reseller_id", $accountid);
290
		$this->db->select('id');
291
		$query = $this->db->get('accounts');
292
		$data = $query->result_array();
293
294
		$count_all = $this->db_model->countQuery("*", "reseller_pricing", array("reseller_id" => $accountid));
295
		$paging_data = $this->form->load_grid_config($count_all, $_GET['rp'], $_GET['page']);
296
		$json_data = $paging_data["json_paging"];
297
		$this->db->select('*,note as number', false);
298
299
		$this->db->where("reseller_id", $accountid);
300
301
		if (@$flag) {
0 ignored issues
show
Bug introduced by
The variable $flag does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
302
			$this->db->order_by('id', 'ASC');
303
			$this->db->limit($limit, $start);
0 ignored issues
show
Bug introduced by
The variable $limit does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
Bug introduced by
The variable $start does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
304
		}
305
306
		$query = $this->db->get('reseller_pricing');
307
		//echo $this->db->last_query();exit;
0 ignored issues
show
Unused Code Comprehensibility introduced by
75% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
308
		$did_grid_fields = json_decode($this->did_form->build_did_list_for_reseller($accountid, $accounttype));
309
		$json_data['rows'] = $this->form->build_grid($query, $did_grid_fields);
310
311
312
313
		echo json_encode($json_data);
314
	}
315
/*  ASTPP  3.0 
316
 *  Left panel DID Quick search added
317
 * 
318
 */
319
	function customer_did($accountid, $accounttype) {
320
		$json_data = array();
321
		$instant_search=$this->session->userdata('left_panel_search_'.$accounttype.'_did'); 
322
		$account_arr=(array)$this->db->get_where('accounts',array("id"=>$accountid))->first_row();
323
		$field_name = $accounttype == "reseller" ? "parent_id" : 'accountid';
324
	$like_str=!empty($instant_search) ? 
325
					"(a.note like '%$instant_search%'
326
					OR  a.init_inc like '%$instant_search%'
327
					OR  a.inc like '%$instant_search%'
328
					OR  a.cost like '%$instant_search%'
329
					OR  a.includedseconds like '%$instant_search%'
330
					OR  a.setup like '%$instant_search%'
331
					OR  a.monthlycost like '%$instant_search%'
332
					OR  a.connectcost like '%$instant_search%'
333
					    )" :null;
334
		if ($account_arr['reseller_id'] != 0) {
335
		if(!empty($like_str))
336
			$this->db->where($like_str);
337
			if($accounttype=='reseller'){
338
		  $this->db->where('a.note','b.number',false);
339
		  $this->db->where('a.reseller_id',$account_arr['id']);
340
		  $this->db->where('a.parent_id',$account_arr['reseller_id']);
341
		  $this->db->select('count(a.id) as count');
342
		  $count_result=(array)$this->db->get('reseller_pricing as a,dids as b')->first_row();
343
		  $paging_data = $this->form->load_grid_config($count_result['count'], $_GET['rp'], $_GET['page']);
344
		  $json_data = $paging_data["json_paging"];
345
		  $this->db->where('a.note','b.number',false);
346
		  $this->db->where('a.reseller_id',$account_arr['id']);
347
		  $this->db->where('a.parent_id',$account_arr['reseller_id']);
348
		  $this->db->select('a . * , b.id, a.reseller_id AS accountid,a.note as number,b.country_id as country_id');
349
		  $this->db->limit($paging_data["paging"]["page_no"],$paging_data["paging"]["start"]);
350
		  $query=$this->db->get('reseller_pricing as a,dids as b');
351
		  }else{
352
		  $count_result=(array)$this->db->query('select count(id) as count from dids where accountid='.$accountid." AND parent_id =".$account_arr['reseller_id'])->first_row();
353
			  $paging_data = $this->form->load_grid_config($count_result['count'], $_GET['rp'], $_GET['page']);
354
		  $json_data = $paging_data["json_paging"];
355
			  $query=$this->db->query("SELECT a . * ,a.note as number,b.country_id as country_id,b.id FROM reseller_pricing AS a, dids AS b WHERE b.accountid =".$account_arr['id']." AND a.note = b.number AND a.reseller_id =".$account_arr['reseller_id']);
356
		  }
357
		}else{
358
						$like_str=!empty($instant_search) ? 
359
												"(dids.number like '%$instant_search%'
360
                                                    OR dids.inc like '%$instant_search%'
361
                                                    OR dids.cost like '%$instant_search%'
362
                                                    OR dids.includedseconds like '%$instant_search%'
363
                                                    OR dids.setup like '%$instant_search%'
364
                                                    OR dids.monthlycost like '%$instant_search%'
365
                                                    OR dids.connectcost like '%$instant_search%'
366
                                                        )" :null;
367
			if(!empty($like_str))
368
			$this->db->where($like_str);
369
			$where = array($field_name => $accountid);
370
			$count_all = $this->db_model->countQuery("*", "dids", $where);
371
			$paging_data = $this->form->load_grid_config($count_all, $_GET['rp'], $_GET['page']);
372
			$json_data = $paging_data["json_paging"];
373
			if(!empty($like_str))
374
			$this->db->where($like_str);
375
			$query = $this->db_model->select("*", "dids", $where, "id", "ASC", $paging_data["paging"]["page_no"], $paging_data["paging"]["start"]);
376
		}
377
		$did_grid_fields = json_decode($this->did_form->build_did_list_for_customer($accountid, $accounttype));
378
		$json_data['rows'] = $this->form->build_grid($query, $did_grid_fields);
379
		echo json_encode($json_data);
380
	}
381
	function did_delete_multiple() {
382
		$ids = $this->input->post("selected_ids", true);
383
		$where = "id IN ($ids)";
384
		$this->db->where($where);
385
		$this->db->select("group_concat(concat('''',number,'''')) as number",false);
386
		$dids_result=(array)$this->db->get('dids')->first_row();
387
		$notes_where="note IN (".$dids_result['number'].")";
388
		$this->db->where($notes_where);
389
		$this->db->delete('reseller_pricing');
390
		$this->db->where($where);
391
		echo $this->db->delete("dids");
392
	}
393
394
	/**
395
	 * -------Here we write code for controller did functions manage------
396
	 * @action: Add, Edit, Delete, List DID
397
	 * @id: DID number
398
	 */
399
	function did_reseller_edit($action = false, $id = false) {
400
		$data['page_title'] = 'Edit DID ';
0 ignored issues
show
Coding Style Comprehensibility introduced by
$data was never initialized. Although not strictly required by PHP, it is generally a good practice to add $data = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
401
		$accountinfo=$this->session->userdata('accountinfo');
402
		if ($action == 'edit') {
403
			if (($this->input->post())) {
404
				$post = $this->input->post();
405
				/*
406
                  ASTPP  3.0 last modified date update
407
                 */
408
				$post['last_modified_date'] = gmdate('Y-m-d H:i:s');
409
				/*                 * ***************************************************** */
410
				unset($post['action']);
411
				$post['setup'] = $this->common_model->add_calculate_currency($post['setup'], '', '', false, false);
412
				$post['monthlycost'] = $this->common_model->add_calculate_currency($post['monthlycost'], '', '', false, false);
413
				$post['connectcost'] = $this->common_model->add_calculate_currency($post['connectcost'], '', '', false, false);
414
				$post['cost'] = $this->common_model->add_calculate_currency($post['cost'], '', '', false, false);
415
				$this->db->where(array('note' => $post['note'], "reseller_id" => $accountinfo['id']));
416
				$this->db->update("reseller_pricing", $post);
417
				$where_update_did = array('extensions' => $post['extensions'], 'call_type' => $post['call_type']);
418
				$this->db->where(array('note' => $post['note']));
419
				$this->db->update("reseller_pricing", $where_update_did);
420
				$where = array('number' => $post['note']);
421
				$this->db->where($where);
422
				$this->db->update("dids", $where_update_did);
423
				echo json_encode(array("SUCCESS" => " DID Updated Successfully!!"));
424
				exit;
425
			} else {
426
				if ($this->session->userdata('logintype') == 1) {
427
					$accountinfo = $this->did_model->get_account($accountinfo['number']);
428
					$reseller_did = $this->db_model->getSelect("*", "reseller_pricing", array('id' => $id));
429
					$reseller_didinfo = (array)$reseller_did->first_row();
430
					if (!empty($reseller_didinfo)) {
431
						$reseller_didinfo['setup'] = $this->common_model->to_calculate_currency($reseller_didinfo['setup'], '', '', true, false);
432
						$reseller_didinfo['monthlycost'] = $this->common_model->to_calculate_currency($reseller_didinfo['monthlycost'], '', '', true, false);
433
						$reseller_didinfo['connectcost'] = $this->common_model->to_calculate_currency($reseller_didinfo['connectcost'], '', '', true, false);
434
						$reseller_didinfo['cost'] = $this->common_model->to_calculate_currency($reseller_didinfo['cost'], '', '', true, false);
435
						$data['did'] = $reseller_didinfo['note'];
436
					}
437
					$data['reseller_didinfo'] = $reseller_didinfo;
438
					$data['accountinfo'] = $accountinfo;
439
					$this->load->view('view_did_manage_reseller_add', $data);
440
				}
441
			}
442
		}
443
		if ($action == 'delete') {
444
				$this->db->where('id',$id);
445
		$this->db->select('note');
446
			$reseller_pricing=(array)$this->db->get('reseller_pricing')->first_row();
447
			$did_number=$reseller_pricing['note'];
448
			$did_info=(array)$this->db->get_where('dids',array('number'=>$did_number))->first_row();
449
			$query="select count(id) as count from reseller_pricing where id >= (select id from reseller_pricing where note =$did_number AND parent_id =".$accountinfo['reseller_id']." AND reseller_id =".$accountinfo['id'].") AND note= $did_number order by id desc";
450
		$result=(array)$this->db->query($query)->first_row();
451
		if($result['count'] > 0){
452
		$str=$this->common->get_parent_info($did_info['parent_id'],$accountinfo['id']);
453
		$str=rtrim($str,",");
454
		$account_result=(array)$this->db->get_where('accounts',"id IN (".$str.")")->result_array();
455 View Code Duplication
		foreach($account_result as $key=>$acc_row){
456
		  $acc_row['did_number']=$did_info['number'];
457
		  $this->common->mail_to_users('email_remove_did', $acc_row);
458
		}
459
			$reseller_ids=$this->common->get_subreseller_info($accountinfo['id']);
460
		$reseller_ids=rtrim($reseller_ids,",");
461
		$where="parent_id IN ($reseller_ids)";
462
		$this->db->where('note',$did_info['number']);
463
		$this->db->delete('reseller_pricing',$where);  
464
		$this->db->where('reseller_id',$accountinfo['id']);
465
		$this->db->where('note',$did_info['number']);
466
		$this->db->delete('reseller_pricing');  
467
		}
468
		$this->db->where('number',$did_number);
469
		$this->db->select('accountid');
470
		$did_array=(array)$this->db->get('dids')->first_row();
471
		if($did_array['accountid'] > 0){
472
		 $customer_info=(array)$this->db->get_where('accounts',array('id'=>$did_array['accountid']))->first_row();
473
		 $customer_info['did_number']=$did_number;
474
		 $this->common->mail_to_users('email_remove_did', $customer_info);
475
		}
476
		$did_array=array("accountid"=>0,"parent_id"=>$accountinfo['reseller_id'], "assign_date" => "0000-00-00 00:00:00", "charge_upto" => "0000-00-00 00:00:00");
477
		$this->db->where('number',$did_number);
478
		$this->db->update('dids',$did_array);
479
			$this->session->set_flashdata('astpp_notification', 'DID Removed Successfully!');
480
			redirect(base_url() . 'did/did_list/');
481
		}
482
	}
483
484
	function did_reseller_purchase() {
485
		//Get account information from session.
486
		$accountinfo = $this->session->userdata('accountinfo');
487
		$where = array('id' => $accountinfo['id']);
488
		$account = $this->db_model->getSelect("*", "accounts", $where);
489
		$currency_name=$this->common->get_field_name('currency',"currency",array('id'=>$accountinfo['currency_id']));
490
		$accountinfo= (array)$account->first_row();
491
		if (($this->input->post())) {
492
			$post = $this->input->post();
493
			if (isset($post['free_did_list']) && $post['free_did_list'] != '') {
494
				// For deduction of admin price to reseller
495
				$didinfo = $this->did_model->get_did_by_number($post['free_did_list']);
496
				if($accountinfo['reseller_id'] > 0 ){
497
				$reseller_pricing_query = $this->db_model->getSelect("call_type,setup,extensions,monthlycost,connectcost,includedseconds,cost,inc", "reseller_pricing", array("note" => $didinfo['number'],'reseller_id'=>$accountinfo['reseller_id']));
498
				   $reseller_pricing_result = (array)$reseller_pricing_query->first_row();
499
				   $didinfo['call_type']=$reseller_pricing_result['call_type'];
500
				   $didinfo['extensions']=$reseller_pricing_result['extensions'];
501
				   $didinfo['setup']=$reseller_pricing_result['setup'];
502
				   $didinfo['monthlycost']=$reseller_pricing_result['monthlycost'];
503
				   $didinfo['connectcost']=$reseller_pricing_result['connectcost'];
504
				   $didinfo['includedseconds']=$reseller_pricing_result['includedseconds'];
505
				   $didinfo['cost']=$reseller_pricing_result['cost'];
506
				   $didinfo['inc']=$reseller_pricing_result['inc'];
507
				}
508
				$available_bal = $this->db_model->get_available_bal($accountinfo);
509
				 $accountinfo['did_number'] = $didinfo['number'];
510
		 $accountinfo['did_country_id'] = $didinfo['country_id'];
511
		 $accountinfo['did_setup'] = $this->common_model->calculate_currency($didinfo['setup'],'',$currency_name,true,true);
512
		 $accountinfo['did_monthlycost'] = $this->common_model->calculate_currency($didinfo['monthlycost'],'',$currency_name,true,true);
513
		 $accountinfo['did_maxchannels'] = $didinfo['maxchannels'];
514
				if ($available_bal >= $didinfo["setup"]) {
515
					$available_bal = $this->db_model->update_balance($didinfo['setup'], $accountinfo['id'], "debit");
516
					$this->db_model->update("dids", array('parent_id' => $accountinfo['id'],"assign_date"=>gmdate("Y-m-d H:i:s")), array("id" => $didinfo['id']));
517
					$this->did_model->insert_reseller_pricing($accountinfo, $didinfo);
518
					$this->common->add_invoice_details($accountinfo,"DIDCHRG",$didinfo['setup'],$didinfo['number']);
519
					$this->common->mail_to_users('email_add_did', $accountinfo,"",$didinfo['number']);
520
					$this->session->set_flashdata('astpp_errormsg', 'DID Purchased Successfully.');
521
				} else {
522
					$this->session->set_flashdata('astpp_notification', 'Insuffiecient fund to purchase this did');
523
				}
524
			} else {
525
				$this->session->set_flashdata('astpp_notification', 'Please Select DID.');
526
			}
527
		}
528
		redirect(base_url() . 'did/did_list/');
529
		exit;
530
	}
531
532
	function add_invoice_data_user($accountid, $charge_type, $description, $credit) {
533
		$insert_array = array('accountid' => $accountid,
534
			'charge_type' => $charge_type,
535
			'description' => $description,
536
			'credit' => $credit,
537
			'charge_id' => '0',
538
			'package_id' => '0'
539
		);
540
541
		$this->db->insert('invoice_item', $insert_array);
542
		$this->load->module('invoices/invoices');
543
		$this->invoices->invoices->generate_receipt($accountid, $credit);
544
545
		return true;
546
	}
547
548 View Code Duplication
	function did_download_sample_file($file_name) {
549
		$this->load->helper('download');
550
		$full_path = base_url() . "assets/Rates_File/" . $file_name . ".csv";
551
		$arrContextOptions=array(
552
			"ssl"=>array(
553
			"verify_peer"=>false,
554
			"verify_peer_name"=>false,
555
			),
556
		);  
557
		$file = file_get_contents($full_path, false, stream_context_create($arrContextOptions));
558
		force_download("samplefile.csv", $file);
559
	}
560
	/* -------Here we write code for controller did functions did_import------
561
     * @Purpose this function check if account number exist or not then remove from database.
562
     * @params $account_number: Account Number
563
     * @return Return Appropreate message If Account Delete or not.
564
     */
565
	function did_import() {
566
		$data['page_title'] = 'Import DIDs';
0 ignored issues
show
Coding Style Comprehensibility introduced by
$data was never initialized. Although not strictly required by PHP, it is generally a good practice to add $data = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
567
		$this->session->set_userdata('import_did_rate_csv', "");
568
		$error_data = $this->session->userdata('import_did_csv_error');
569
		$full_path = $this->config->item('rates-file-path');
570
		if (file_exists($full_path . $error_data) && $error_data != "") {
571
			unlink($full_path . $error_data);
572
			$this->session->set_userdata('import_did_csv_error', "");
573
		}
574
		$accountinfo=$this->session->userdata('accountinfo');
575
		$this->db->where('id',$accountinfo['currency_id']);
576
		$this->db->select('currency');
577
		$currency_info=(array)$this->db->get('currency')->first_row();
578
		$data['fields']="DID,Country,Account,Per Minute Cost(".$currency_info['currency']."),Initial Increment,Increment,Setup Fee(".$currency_info['currency']."),Monthly Fee(".$currency_info['currency']."),Call Type,Destination,Status";
579
		$this->load->view('view_import_did', $data);
580
	}
581
582
	function did_preview_file() {
583
		$data['page_title'] = 'Import DIDs';
0 ignored issues
show
Coding Style Comprehensibility introduced by
$data was never initialized. Although not strictly required by PHP, it is generally a good practice to add $data = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
584
		$config_did_array = $this->config->item('DID-rates-field');
585
		$accountinfo=$this->session->userdata('accountinfo');
586
		$this->db->where('id',$accountinfo['currency_id']);
587
		$this->db->select('currency');
588
		$currency_info=(array)$this->db->get('currency')->first_row();
589
		foreach($config_did_array as $key=>$value){
590
		 $key = str_replace('CURRENCY', $currency_info['currency'], $key);
591
		 $did_fields_array[$key]=$value;
0 ignored issues
show
Coding Style Comprehensibility introduced by
$did_fields_array was never initialized. Although not strictly required by PHP, it is generally a good practice to add $did_fields_array = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
592
		}
593
		$check_header = $this->input->post('check_header', true);
594
		$invalid_flag = false;
595
		if (isset($_FILES['didimport']['name']) && $_FILES['didimport']['name'] != "") {
596
			list($txt, $ext) = explode(".", $_FILES['didimport']['name']);
0 ignored issues
show
Unused Code introduced by
The assignment to $txt is unused. Consider omitting it like so list($first,,$third).

This checks looks for assignemnts to variables using the list(...) function, where not all assigned variables are subsequently used.

Consider the following code example.

<?php

function returnThreeValues() {
    return array('a', 'b', 'c');
}

list($a, $b, $c) = returnThreeValues();

print $a . " - " . $c;

Only the variables $a and $c are used. There was no need to assign $b.

Instead, the list call could have been.

list($a,, $c) = returnThreeValues();
Loading history...
597
			if ($ext == "csv" && $_FILES["didimport"]['size'] > 0) {
598
				$error = $_FILES['didimport']['error'];
599
				if ($error == 0) {
600
					$uploadedFile = $_FILES["didimport"]["tmp_name"];
601
					$full_path = $this->config->item('rates-file-path');
602
					$actual_file_name = "ASTPP-DIDs-" . date("Y-m-d H:i:s") . "." . $ext;
603
					if (move_uploaded_file($uploadedFile, $full_path . $actual_file_name)) {
604
						$data['page_title'] = 'Import DIDs Preview';
605
						$data['csv_tmp_data'] = $this->csvreader->parse_file($full_path . $actual_file_name, $did_fields_array, $check_header);
0 ignored issues
show
Bug introduced by
The variable $did_fields_array does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
606
						$data['provider_id'] = $_POST['provider_id'];
607
						$data['check_header'] = $check_header;
608
						$this->session->set_userdata('import_did_rate_csv', $actual_file_name);
609
					} else {
610
						$data['error'] = "File Uploading Fail Please Try Again";
611
					}
612
				}
613
			} else {
614
				$data['error'] = "Invalid file format : Only CSV file allows to import records(Can't import empty file)";
615
			}
616
		} else {
617
			$invalid_flag = true;
618
		}
619
		if ($invalid_flag) {
620
			$str = '';
621
			if (empty($_FILES['didimport']['name'])) {
622
				$str.= '<br/>Please Select  File.';
623
			}
624
			$data['error'] = $str;
625
		}
626
		$this->load->view('view_import_did', $data);
627
	}
628
629
	function did_import_file($provider_id, $check_header = false) {
630
		$new_final_arr = array();
631
		$invalid_array = array();
632
		$new_final_arr_key = $this->config->item('DID-rates-field');
633
		$accountinfo=$this->session->userdata('accountinfo');
634
		$reseller_id = $accountinfo['type']==1 ? $accountinfo['id']: 0;
635
	
636
		$full_path = $this->config->item('rates-file-path');
637
		$did_file_name = $this->session->userdata('import_did_rate_csv');
638
		$csv_tmp_data = $this->csvreader->parse_file($full_path . $did_file_name, $new_final_arr_key, $check_header);
639
		$flag = false;
640
		$i = 0;
641
		$number_arr = array();
642
		$reseller_array=array();
643
		$final_reseller_array=array();
644
		foreach ($csv_tmp_data as $key => $csv_data) {
645
        
646
			if (isset($csv_data['number']) && $csv_data['number'] != '' && $i != 0) {
647
				$str = null;
648
				if(isset($csv_data['call_type'])){
649
					if(strtolower($csv_data['call_type']) == 'sip-did'){
650
						$call_type = '3';
651
					} else if(strtolower($csv_data['call_type']) == 'did-local'){
652
						$call_type = '1';
653
					} else if(strtolower($csv_data['call_type']) == 'other'){
654
						$call_type = '2';
655
					} else {
656
						$call_type = '0';
657
					}
658
				} else{
659
					$call_type = '0';
660
				}
661
				$csv_data['accountid'] = isset($csv_data['accountid']) ? $csv_data['accountid'] : 0;
662
				$csv_data['country_id'] = isset($csv_data['country_id']) ? $csv_data['country_id'] : 0;
663
				//$csv_data['call_type'] = isset($csv_data['call_type']) && (strtolower($csv_data['call_type']) == 'local' || strtolower($csv_data['call_type']) == 'pstn' || strtolower($csv_data['call_type']) == 'other' ) ? $this->common->get_custom_call_type(strtoupper($csv_data['call_type'])) : 0;
0 ignored issues
show
Unused Code Comprehensibility introduced by
65% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
664
				$csv_data['call_type'] = $call_type;
665
				$csv_data['extensions'] = isset($csv_data['extensions']) ? $csv_data['extensions'] : '';
666
				$csv_data['includedseconds'] = isset($csv_data['includedseconds']) ? $csv_data['includedseconds'] : 0;
667
				$csv_data['cost'] = !empty($csv_data['cost']) && is_numeric($csv_data['cost']) && $csv_data['cost'] ? $csv_data['cost'] : 0;
668
				$csv_data['setup'] = !empty($csv_data['setup']) && is_numeric($csv_data['setup']) && $csv_data['setup'] > 0 ? $csv_data['setup'] : 0;
669
				$csv_data['monthlycost'] = !empty($csv_data['monthlycost']) && is_numeric($csv_data['monthlycost']) && $csv_data['monthlycost'] > 0 ? $csv_data['monthlycost'] : 0;
670
				$csv_data['connectcost'] = !empty($csv_data['connectcost']) && is_numeric($csv_data['connectcost']) && $csv_data['connectcost'] > 0 ? $csv_data['connectcost'] : 0;
671
				$csv_data['inc'] = isset($csv_data['inc']) ? $csv_data['inc'] : 0;
672
				$str = $this->data_validate($csv_data);
673
				if ($str != "") {
674
					$invalid_array[$i] = $csv_data;
675
					$invalid_array[$i]['error'] = $str;
676
				} else {
677
					if (!in_array($csv_data['number'], $number_arr)) {
678
						$number_count = $this->db_model->countQuery('id', 'dids', array('number' => $csv_data['number']));
679
						if ($number_count > 0) {
680
							$invalid_array[$i] = $csv_data;
681
							$invalid_array[$i]['error'] = 'Duplicate DID found from database';
682
						} else {
683
							if($csv_data['accountid'] > 0 && $csv_data['setup'] > 0){
684
						  $this->db->where('type IN(0,1,3)');
685
						  $this->db->where('reseller_id',0);
686
						  $this->db->where('deleted',0);
687
						  $this->db->where('status',0);
688
				  $account_info=(array)$this->db->get_where('accounts',array("number"=>$csv_data['accountid']))->first_row();
689
				  if($account_info){
0 ignored issues
show
Bug Best Practice introduced by
The expression $account_info of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
690
					  $account_balance=$this->db_model->get_available_bal($account_info);
691
					  $setup = $this->common_model->add_calculate_currency($csv_data['setup'], '', '', false, false);
692
					  if($account_balance >= $setup){
693
						$field_name=$account_info['type']==1 ? 'parent_id':'accountid';
694
						$currency_name=$this->common->get_field_name('currency',"currency",array('id'=>$account_info['currency_id']));
695
					$csv_data['monthlycost'] = $this->common_model->add_calculate_currency($csv_data['monthlycost'], '', '', false, false);
696
					$csv_data['cost'] = $this->common_model->add_calculate_currency($csv_data['cost'], '', '', false, false);
697
					$csv_data['connectcost'] = $this->common_model->add_calculate_currency($csv_data['connectcost'], '', '', false, false);
698
					$csv_data['setup']=$setup;
699
					$csv_data[$field_name]=$account_info['id'];
700
					$csv_data['status']=$this->common->get_import_status($csv_data['status']);
701
					$available_bal = $this->db_model->update_balance($csv_data["setup"],$account_info['id'], "debit");
702
					$account_info['did_number'] = $csv_data['number'];
703
					$account_info['did_country_id'] = $csv_data['country_id'];
704
					$account_info['did_setup'] = $this->common_model->calculate_currency($csv_data['setup'],'',$currency_name,true,true);
705
					$account_info['did_monthlycost'] = $this->common_model->calculate_currency($csv_data['monthlycost'],'',$currency_name,true,true);
706
					$account_info['did_maxchannels'] = "0";
707
					$csv_data['country_id']=$this->common->get_field_name('id','countrycode',array("country"=>$csv_data['country_id']));
708
					if($account_info['type']==1){
709
					 $reseller_array=$csv_data;
710
					 $reseller_array['note']=$csv_data['number'];
711
					 $reseller_array['reseller_id']=$account_info['id'];
712
					 $reseller_array['parent_id']=$account_info['reseller_id'];
713
					 $reseller_array['assign_date']=gmdate("Y-m-d H:i:s");
714
					 unset($reseller_array['number'],$csv_data['accountid'],$reseller_array['accountid'],$reseller_array['country_id'],$reseller_array['init_inc']);
715
					 $csv_data['accountid']=0;
716
					 $final_reseller_array[$i]=$reseller_array;
717
					}else{
718
					  $csv_data['parent_id']=0;
719
					}
720
					$csv_data['assign_date']=gmdate("Y-m-d H:i:s");
721
					$new_final_arr[$i] = $csv_data;
722
					$this->common->mail_to_users('email_add_did', $account_info);
723
					  }else{
724
					$invalid_array[$i] = $csv_data;
725
					$invalid_array[$i]['error'] = 'Account have not sufficient amount to purchase this DID.';
726
					  }
727
				  }else{
728
				$invalid_array[$i] = $csv_data;
729
				$invalid_array[$i]['error'] = 'Account not found or assign to invalid account';
730
				  }
731
							}else{
732
				  $csv_data['setup'] = $this->common_model->add_calculate_currency($csv_data['setup'], '', '', false, false);
733
				  $csv_data['monthlycost'] = $this->common_model->add_calculate_currency($csv_data['monthlycost'], '', '', false, false);
734
				  $csv_data['cost'] = $this->common_model->add_calculate_currency($csv_data['cost'], '', '', false, false);
735
				  $csv_data['connectcost'] = $this->common_model->add_calculate_currency($csv_data['connectcost'], '', '', false, false);
736
				  $csv_data['accountid']=0;
737
				  $csv_data['country_id']=$this->common->get_field_name('id','countrycode',array("country"=>$csv_data['country_id']));
738
				  $new_final_arr[$i] = $csv_data;
739
							}
740
						}
741
					} else {
742
						$invalid_array[$i] = $csv_data;
743
						$invalid_array[$i]['error'] = 'Duplicate DID found from import file.';
744
					}
745
				}
746
				$number_arr[] = $csv_data['number'];
747
			}
748
			$i++;
749
		}
750
		if (!empty($new_final_arr)) {
751
		   $result = $this->did_model->bulk_insert_dids($new_final_arr);
752
		}
753
		if(!empty($final_reseller_array)){
754
			$this->db->insert_batch('reseller_pricing', $final_reseller_array);
755
		}
756
	unlink($full_path.$did_file_name);
757
		$count = count($invalid_array);
758
		if ($count > 0) {
759
			$session_id = "-1";
760
			$fp = fopen($full_path . $session_id . '.csv', 'w');
761
			foreach ($new_final_arr_key as $key => $value) {
762
				$custom_array[0][$key] = ucfirst($key);
0 ignored issues
show
Coding Style Comprehensibility introduced by
$custom_array was never initialized. Although not strictly required by PHP, it is generally a good practice to add $custom_array = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
763
			}
764
			$custom_array[0]['error'] = "Error";
0 ignored issues
show
Bug introduced by
The variable $custom_array does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
765
			$invalid_array = array_merge($custom_array, $invalid_array);
766
			foreach ($invalid_array as $err_data) {
767
				fputcsv($fp, $err_data);
768
			}
769
			fclose($fp);
770
			$this->session->set_userdata('import_did_csv_error', $session_id . ".csv");
771
			$data["error"] = $invalid_array;
0 ignored issues
show
Coding Style Comprehensibility introduced by
$data was never initialized. Although not strictly required by PHP, it is generally a good practice to add $data = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
772
			$data['provider_id'] = $provider_id;
773
			$data['import_record_count'] = count($new_final_arr)+count($reseller_array);
774
			$data['failure_count'] = count($invalid_array) - 1;
775
			$data['page_title'] = 'DID Import Error';
776
			$this->load->view('view_import_error', $data);
777
		} else {
778
			$this->session->set_flashdata('astpp_errormsg', 'Total ' . count($new_final_arr) . ' DIDs Imported Successfully!');
779
			redirect(base_url() . "did/did_list/");
780
		}
781
	}
782
783
	function data_validate($csvdata) {
784
		$str = null;
785
		$alpha_regex = "/^[a-z ,.'-]+$/i";
786
		$alpha_numeric_regex = "/^[a-z0-9 ,.'-]+$/i";
787
		$email_regex = "/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/";
788
		$str.= $csvdata['number'] != '' ? null : 'Number,';
789
		$str = rtrim($str, ',');
790
		if (!$str) {
791
			$str.= is_numeric($csvdata['number']) ? null : 'Number,';
792
			$str.=!empty($csvdata['connectcost']) && is_numeric($csvdata['connectcost']) ? null : ( empty($csvdata['connectcost']) ? null : 'Connect Cost,');
793
			$str.=!empty($csvdata['includedseconds']) && is_numeric($csvdata['includedseconds']) ? null : ( empty($csvdata['includedseconds']) ? null : 'Included Seconds,');
794 View Code Duplication
			if ($str) {
795
				$str = rtrim($str, ',');
796
				$error_field = explode(',', $str);
797
				$count = count($error_field);
798
				$str.= $count > 1 ? ' are not valid' : ' is not Valid';
799
				return $str;
800
			} else {
801
				return false;
802
			}
803
		} else {
804
			$str = rtrim($str, ',');
805
			$error_field = explode(',', $str);
806
			$count = count($error_field);
807
			$str.= $count > 1 ? ' are required' : ' is Required';
808
			return $str;
809
		}
810
	}
811
812 View Code Duplication
	function did_error_download() {
813
		$this->load->helper('download');
814
		$error_data = $this->session->userdata('import_did_csv_error');
815
		$full_path = $this->config->item('rates-file-path');
816
		$data = file_get_contents($full_path . $error_data);
817
		force_download("error_did_rates.csv", $data);
818
	}
819
820
	function did_export_data_xls() {
821
	$account_info = $accountinfo = $this->session->userdata('accountinfo');
822
	$currency_id=$account_info['currency_id'];
823
	$currency=$this->common->get_field_name('currency', 'currency', $currency_id);
824
	$query = $this->did_model->getdid_list(true, '0', '10000000');
825
	ob_clean();
826
	$outbound_array[] = array("DID", "Country", "Account","Per Minute Cost($currency)","Initial Increment","Increment","Setup Fee($currency)","Monthly Fee($currency)","Call Type","Destination","Status","Modified Date","Is Purchased");
0 ignored issues
show
Coding Style Comprehensibility introduced by
$outbound_array was never initialized. Although not strictly required by PHP, it is generally a good practice to add $outbound_array = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
827
	if ($query->num_rows() > 0) {
828
	  foreach ($query->result_array() as $row) {
829
		$outbound_array[] = array(
830
		$row['number'],
831
		$this->common->get_field_name("country", "countrycode", $row['country_id']),
832
		$this->common->get_field_name("number", "accounts", $row['accountid']),
833
		$this->common_model->calculate_currency($row['cost'], '', '',true, false),
834
		$row['init_inc'],
835
		$row['inc'],
836
		$this->common_model->calculate_currency($row['setup'], '', '',true, false),
837
		$this->common_model->calculate_currency($row['monthlycost'], '', '',true, false),
838
		$this->common->get_call_type("","",$row['call_type']),
839
		$row['extensions'],
840
		$this->common->get_status('export','',$row['status']),
841
		$row['last_modified_date'],
842
		$this->common->check_did_avl_export($row['number'])
843
		);
844
	  }
845
	}
846
		$this->load->helper('csv');
847
		array_to_csv($outbound_array, 'DIDs_' . date("Y-m-d") . '.csv');
848
	}
849
850
}
851
?>
0 ignored issues
show
Best Practice introduced by
It is not recommended to use PHP's closing tag ?> in files other than templates.

Using a closing tag in PHP files that only contain PHP code is not recommended as you might accidentally add whitespace after the closing tag which would then be output by PHP. This can cause severe problems, for example headers cannot be sent anymore.

A simple precaution is to leave off the closing tag as it is not required, and it also has no negative effects whatsoever.

Loading history...
852
 
853