Accounts_model   D
last analyzed

Complexity

Total Complexity 137

Size/Duplication

Total Lines 752
Duplicated Lines 20.48 %

Coupling/Cohesion

Components 1
Dependencies 2

Importance

Changes 0
Metric Value
dl 154
loc 752
rs 4.4444
c 0
b 0
f 0
wmc 137
lcom 1
cbo 2

34 Methods

Rating   Name   Duplication   Size   Complexity  
A Accounts_model() 0 3 1
F add_account() 7 90 17
C reseller_rates_batch_update() 37 62 13
C customer_rates_batch_update() 37 58 12
A edit_account() 7 7 1
F bulk_insert_accounts() 6 168 23
A get_max_limit() 0 15 1
C account_process_payment() 0 42 8
C get_admin_Account_list() 0 31 8
C get_customer_Account_list() 0 32 11
A get_reseller_Account_list() 13 13 4
A get_provider_Account_list() 13 13 4
A remove_customer() 0 7 1
A insert_block() 0 13 3
A get_pattern_by_id() 0 5 1
A get_callerid() 0 4 1
A get_account_number() 7 7 2
A add_callerid() 0 6 1
A edit_callerid() 0 8 1
A remove_all_account_tax() 0 5 1
A add_account_tax() 0 3 1
A get_accounttax_by_id() 0 8 2
A check_account_num() 0 10 2
A get_account_by_number() 0 9 2
A get_currency_by_id() 8 8 2
A update_balance() 9 9 3
A account_authentication() 0 9 2
A get_animap() 10 10 2
A add_animap() 0 4 1
A edit_animap() 0 6 1
A remove_ani_map() 0 5 1
A animap_authentication() 0 9 2
A add_invoice_config() 0 4 1
A edit_invoice_config() 0 5 1

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 Accounts_model 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 Accounts_model, 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 Accounts_model extends CI_Model {
26
27
	function Accounts_model() {
28
		parent::__construct();
0 ignored issues
show
Comprehensibility Bug introduced by
It seems like you call parent on a different method (__construct() instead of Accounts_model()). 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
31
	function add_account($accountinfo) {
32
	
33
		$account_data = $this->session->userdata("accountinfo");
34
		$accountinfo['reseller_id'] = ($account_data['type'] == 1 ) ? $account_data['id'] : 0;
35
		$accountinfo['maxchannels'] = ($accountinfo['type'] == 1 || $account_data['type'] == 2 || $account_data['type'] == -1 ) ? "0" : $accountinfo['maxchannels'];
36
		unset($accountinfo['action']);
37
		$sip_flag = isset($accountinfo['sip_device_flag']) ? 1 : 0;
38
		$opensip_flag = isset($accountinfo['opensips_device_flag']) ? 1 : 0;
39
		unset($accountinfo['sip_device_flag'],$accountinfo['opensips_device_flag'],$accountinfo['tax_id']);
40
41
		/*         * ******************************** */
42
		$accountinfo['creation'] = gmdate('Y-m-d H:i:s');
43
		$accountinfo['expiry'] = gmdate('Y-m-d H:i:s', strtotime('+20 years'));
44
		/*if(isset($accountinfo['is_recording'])){
0 ignored issues
show
Unused Code Comprehensibility introduced by
81% 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...
45
	  $accountinfo['is_recording']=0;
46
        }else{
47
	  $accountinfo['is_recording']=1;
48
        }
49
        if(isset($accountinfo['allow_ip_management'])){
50
	  $accountinfo['allow_ip_management']=0;
51
        }else{
52
	  $accountinfo['allow_ip_management']=1;
53
        }*/
54
		if(isset($accountinfo['local_call'])){
55
	  $accountinfo['local_call']=0;
56
		}else{
57
	  $accountinfo['local_call']=1;
58
		}
59
		if ($accountinfo['type'] == 1){
60
		$invoice_config = $accountinfo['invoice_config_flag'];
61
		}else{
62
		$invoice_config = "";		
63
		}
64
		unset($accountinfo['invoice_config_flag']);
65
		$result = $this->db->insert('accounts', $accountinfo);
66
		$last_id = $this->db->insert_id();
67
				/**
68
          ASTPP  3.0 
69
          For Invoice Configuration
70
				 * */ 
71
		 if ($accountinfo['type'] == 1 && isset($invoice_config) && $invoice_config == "0") {
72 View Code Duplication
				if ($accountinfo['country_id'] == NULL) {
73
					$accountinfo['country_id'] = "";
74
				} else {
75
					$data = $this->db_model->getSelect("country", "countrycode", array("id" => $accountinfo['country_id']));
76
					$data = $data->result_array();
77
					$country_name = $data[0];
78
				}
79
				if ($accountinfo['postal_code'] == NULL) {
80
					$accountinfo['postal_code'] = "";
81
				}
82
83
				$invoice_config = array('accountid' => $last_id, 'company_name' => $accountinfo['company_name'], 'address' => $accountinfo['address_1'], 'city' => $accountinfo['city'], 'province' => $accountinfo['province'], 'country' => $country_name['country'], 'zipcode' => $accountinfo['postal_code'], 'telephone' => $accountinfo['telephone_1'], 'emailaddress' => $accountinfo['email']);
0 ignored issues
show
Bug introduced by
The variable $country_name 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...
84
				$this->db->where('account_id', $accountinfo['id']);
85
				$this->db->insert('invoice_conf', $invoice_config);
86
			}
87
		if ($sip_flag == '1') {
88
			$this->db->select('id');
89
			$this->db->where('name','default');
90
			$sipprofile_result=(array)$this->db->get('sip_profiles')->first_row();
91
			$free_switch_array = array('fs_username' => $accountinfo['number'],
92
				'fs_password' => $this->common->decode($accountinfo['password']),
93
				'context' => 'default',
94
				'effective_caller_id_name' => $accountinfo['number'],
95
				'effective_caller_id_number' => $accountinfo['number'],
96
				'sip_profile_id' => $sipprofile_result['id'],
97
				'pricelist_id' => $accountinfo['pricelist_id'],
98
				'accountcode' => $last_id,
99
				'status' => $accountinfo['status']);
100
			$this->load->model('freeswitch/freeswitch_model');
101
			$this->freeswitch_model->add_freeswith($free_switch_array);
102
		}
103
		if ($opensip_flag == 1) {
104
			$opensips_array = array('username' => $accountinfo['number'],
105
				'domain' => common_model::$global_config['system_config']['opensips_domain'],
106
				'password' => $accountinfo['password'],
107
				'accountcode' => $accountinfo['number'],
108
				'pricelist_id' => $accountinfo['pricelist_id']);
109
			$this->load->model('opensips/opensips_model');
110
			$this->opensips_model->add_opensipsdevices($opensips_array);
111
		}
112
		$accountinfo['confirm'] =  base_url();
113
		if($accountinfo['id'] == ""){
114
		$accountinfo['id'] = $last_id;
115
		}
116
		$accountinfo['password'] = $this->common->decode($accountinfo['password']);    
117
118
		$this->common->mail_to_users('email_add_user', $accountinfo);
119
		return $last_id;
120
	}
121
122
	/**
123
      ASTPP  3.0 
124
      Reseller Batch Update
125
	 * */
126
	function reseller_rates_batch_update($update_array) {
127
		unset($update_array['action']);
128
		$update_array['type'] = 1;
129
		$date = gmdate("Y-m-d h:i:s");
130
		$this->db_model->build_search('reseller_list_search');
131
		if ($update_array['type'] == 1) {
132
			$this->db_model->build_batch_update_array($update_array);
133
			$login_type = $this->session->userdata('logintype');
134
			$reseller_info = $this->session->userdata['accountinfo'];
135 View Code Duplication
			if ($reseller_info['type'] == 1) {
136
				$this->db->where('reseller_id', $reseller_info['id']);
137
			} else {
138
				$this->db->where('reseller_id', '0');
139
			}
140
			$this->db->where('type', '1');
141
			$this->db->update("accounts");
142
			$this->db_model->build_search('reseller_list_search');
143
			if (isset($update_array['balance']['balance']) && $update_array['balance']['balance'] != '') {
144
				$search_flag = $this->db_model->build_search('reseller_list_search');
145
				$account_data = $this->session->userdata("accountinfo");
146
				if ($account_data['type'] == 1) {
147
					$where = array('type' => 1, "balance" => $update_array['balance']['balance'], "reseller_id" => $account_data['id'], 'deleted' => '0', 'status' => '0');
148 View Code Duplication
				} else {
149
					$where = array('type' => 1, "balance" => $update_array['balance']['balance'], 'deleted' => '0', 'status' => '0');
150
				}
151
152
				$this->db_model->build_search('reseller_list_search');
153
				$query_pricelist = $this->db_model->getSelect("id,reseller_id,balance", "accounts", $where);
154 View Code Duplication
				if ($query_pricelist->num_rows > 0) {
155
					$description = '';
156
					if ($update_array['balance']['operator'] == '2') {
157
						$description .="Reseller update set balance by admin";
158
					}
159
					if ($update_array['balance']['operator'] == '3') {
160
						$description .="Reseller update increase balance by admin";
161
					}
162
					if ($update_array['balance']['operator'] == '4') {
163
						$description .="Reseller update descrise balance by admin";
164
					}
165
					foreach ($query_pricelist->result_array() as $key => $reseller_payment) {
166
						if (!empty($reseller_payment['reseller_id']) && $reseller_payment['reseller_id'] != '') {
167
							$payment_by = $reseller_payment['reseller_id'];
168
						} else {
169
							$payment_by = '-1';
170
						}
171
						$insert_arr = array("accountid" => $reseller_payment['id'],
172
							"credit" => $update_array['balance']['balance'],
173
							'payment_mode' => 0,
174
							'type' => "SYSTEM",
175
							"notes" => $description,
176
							"payment_date" => $date,
177
							'payment_by' => $payment_by,
178
							'reseller_id' => $reseller_payment['reseller_id'],
179
						);
180
						$this->db->insert("payments", $insert_arr);
181
					}
182
				}
183
			}
184
		}
185
186
		return true;
187
	}
188
	/**
189
      ASTPP  3.0 
190
      Customer Batch Update
191
	 * */
192
	function customer_rates_batch_update($update_array) {
193
194
		unset($update_array['action']);
195
		$date = gmdate("Y-m-d h:i:s");
196
		$this->db_model->build_search('customer_list_search');
197
		$reseller_info = $this->session->userdata['accountinfo'];
198 View Code Duplication
		if ($reseller_info['type'] == 1) {
199
			$this->db->where('reseller_id', $reseller_info['id']);
200
		} else {
201
			$this->db->where('reseller_id', '0');
202
		}
203
		$this->db_model->build_search('customer_list_search');
204
		$this->db->where('type !=', '1');
205
		$this->db_model->build_batch_update_array($update_array);
206
		$this->db->update("accounts");
207
		if (isset($update_array['balance']['balance']) && $update_array['balance']['balance'] != '') {
208
			$account_data = $this->session->userdata("accountinfo");
209
210
			if ($account_data['type'] == 1) {
211
				$where = array('type' => 1, "reseller_id" => $account_data['id'], 'deleted' => '0', 'status' => '0');
212 View Code Duplication
			} else {
213
				$where = array('type !=' => '-1', "balance" => $update_array['balance']['balance'], 'deleted' => '0', 'status' => '0');
214
			}
215
216
			$this->db_model->build_search('customer_list_search');
217
			$query_pricelist = $this->db_model->getSelect("id,reseller_id,balance", "accounts", $where);
218 View Code Duplication
			if ($query_pricelist->num_rows > 0) {
219
				$description = '';
220
				if ($update_array['balance']['operator'] == '2') {
221
					$description .="Customer update set balance by admin";
222
				}
223
				if ($update_array['balance']['operator'] == '3') {
224
					$description .="Customer update increase balance by admin";
225
				}
226
				if ($update_array['balance']['operator'] == '4') {
227
					$description .="Customer update descrise balance by admin";
228
				}
229
				foreach ($query_pricelist->result_array() as $key => $customer_payment) {
230
					if (!empty($customer_payment['reseller_id']) && $customer_payment['reseller_id'] != '0') {
231
						$payment_by = $customer_payment['reseller_id'];
232
					} else {
233
						$payment_by = '-1';
234
					}
235
					$insert_arr = array("accountid" => $customer_payment['id'],
236
						"credit" => $update_array['balance']['balance'],
237
						'payment_mode' => 0,
238
						'type' => "SYSTEM",
239
						"notes" => $description,
240
						"payment_date" => $date,
241
						'payment_by' => $payment_by,
242
						'reseller_id' => $customer_payment['reseller_id'],
243
					);
244
					$this->db->insert("payments", $insert_arr);
245
				}
246
			}
247
		}
248
		return true;
249
	}
250
251
	/*     * ************************************************************************ */
252
253 View Code Duplication
	function edit_account($accountinfo, $edit_id) {
254
		unset($accountinfo['action']);
255
		unset($accountinfo['onoffswitch']);
256
		$this->db->where('id', $edit_id);
257
		$result = $this->db->update('accounts', $accountinfo);
258
		return true;
259
	}
260
261
	function bulk_insert_accounts($add_array) {
262
		$logintype = $this->session->userdata('logintype');
263
		$creation_limit = $this->get_max_limit($add_array);
264
		$count = $add_array['count'];
265
		$pin_flag = $add_array['pin'];
266
        
267
		$balance = $add_array['balance'] != '' ? $add_array['balance'] : 0.0000;
268
		$credit_limit = $add_array['credit_limit'] != '' ? $add_array['credit_limit'] : 0.0000;
269
		$prefix = $add_array['prefix'];
270
		$account_length = $add_array['account_length'];
271
        
272
		$length = strlen($prefix);
273
		if ($length != 0) {
274
			$number_length = $account_length - $length;
275
		} else {
276
			$number_length = $account_length;
277
		}
278
279
		$pricelist_id = $add_array['pricelist_id'] != '' ? $add_array['pricelist_id'] : 0;
280
		$number = $this->common->find_uniq_rendno_accno($number_length, 'number', 'accounts', $prefix, $count);
281
		$password = $this->common->find_uniq_rendno_accno($number_length, 'password', 'accounts', '', $count);
282
		if ($pin_flag) {
283
			$pin = $this->common->find_uniq_rendno_accno($number_length, 'pin', 'accounts', '', $count);
284
		}
285
		$sip_flag = false;
286
		$opensip_flag=false;
287 View Code Duplication
		if (isset($add_array['sip_device_flag']) && common_model::$global_config['system_config']['opensips']== 0) {
288
			$sip_flag = true;
289
		}
290 View Code Duplication
		if (isset($add_array['opensips_device_flag']) && common_model::$global_config['system_config']['opensips']== 1) {
291
			$opensip_flag = true;
292
		}
293
		unset(
294
				$add_array['count'],
295
				$add_array['pin'],
296
				$add_array['account_length'],
297
				$add_array['prefix'],
298
				$add_array['sip_device_flag'],
299
				$add_array['opensips_device_flag']
300
		);
301
		if(isset($add_array['is_recording']) &&  $add_array['is_recording'] != ''){
302
		$is_recording=1;
303
		}else{
304
		$is_recording=0;
305
		}
306
		if(isset($add_array['allow_ip_management']) &&  $add_array['allow_ip_management'] != ''){
307
		$allow_ip_management=1;
308
		}else{
309
		$allow_ip_management=0;
310
		}
311
		if(isset($add_array['local_call']) &&  $add_array['local_call'] != ''){
312
		$local_call=1;
313
		}else{
314
		$local_call=0;
315
		}
316
		if ($sip_flag) {
317
			$query = $this->db_model->select("*", "sip_profiles", array('status' => "0"), "id", "ASC", '1', '0');
318
			$sip_id = $query->result_array();
319
			$sip_profile_id = $sip_id[0]['id'];
320
			for ($i = 0; $i < $count; $i++) {
321
				$acc_num = $number[$i];
322
				$current_password = $password[$i];
323
				$insert_array = array('number' => $acc_num,
324
					'password' => $this->common->encode($current_password),
325
					'pricelist_id' => $pricelist_id,
326
					'reseller_id' => $add_array['reseller_id'],
327
					'status' => 0,
328
					'credit_limit' => $credit_limit,
329
					'posttoexternal' => $add_array['posttoexternal'],
330
					'balance' => $balance,
331
					'currency_id' => $add_array['currency_id'],
332
					'country_id' => $add_array['country_id'],
333
					'timezone_id' => $add_array['timezone_id'],
334
					'company_name' => $add_array['company_name'],
335
					'first_name' => $acc_num,
336
					'type' => 0,
337
					'charge_per_min'=>$add_array['charge_per_min'],
338
					'validfordays' => $add_array['validfordays'],
339
					"creation"=>gmdate("Y-m-d H:i:s"),
340
					"maxchannels"=>0,
341
					"sweep_id"=>$add_array['sweep_id'],
342
					"local_call"=>$local_call,
343
					 "invoice_day"=>$add_array['invoice_day'],
344
					"allow_ip_management"=>$allow_ip_management,
345
					"is_recording"=>$is_recording,
346
					"expiry" => gmdate('Y-m-d H:i:s', strtotime('+10 years'))
347
				);
348
				if ($pin_flag == 1) {
349
					$insert_array['pin'] = $pin[$i];
0 ignored issues
show
Bug introduced by
The variable $pin 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...
350
				}
351
				$this->db->insert('accounts', $insert_array);
352
				$last_id = $this->db->insert_id();
353
				$params_array = array('password' => $password[$i],
354
					"vm-enabled"=>"true",
355
					"vm-password"=>"",
356
					"vm-mailto"=>"",
357
					"vm-attach-file"=>"true",
358
					"vm-keep-local-after-email"=>"true",
359
					"vm-email-all-messages"=>"true"
360
					);
361
				$params_array_vars = array('effective_caller_id_name' => $acc_num,
362
					'effective_caller_id_number' => $acc_num,
363
					'user_context' => 'default');
364
				$sip_device_array[$i] = array('username' => $acc_num,
0 ignored issues
show
Coding Style Comprehensibility introduced by
$sip_device_array was never initialized. Although not strictly required by PHP, it is generally a good practice to add $sip_device_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...
365
					'sip_profile_id' => $sip_profile_id,
366
					'reseller_id' => $add_array['reseller_id'],
367
					'accountid' => $last_id,
368
					'dir_params' => json_encode($params_array),
369
					'dir_vars' => json_encode($params_array_vars),
370
					'status' => 0,
371
					'creation_date' => gmdate("Y-m-d H:i:s")
372
					);
373
			}
374
			$this->db->insert_batch('sip_devices', $sip_device_array);
0 ignored issues
show
Bug introduced by
The variable $sip_device_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...
375
		} else {
376
			for ($i = 0; $i < $count; $i++) {
377
				$acc_num = $number[$i];
378
				$current_password = $password[$i];
379
				$insert_array[$i] = array('number' => $acc_num,
0 ignored issues
show
Coding Style Comprehensibility introduced by
$insert_array was never initialized. Although not strictly required by PHP, it is generally a good practice to add $insert_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...
380
					'password' => $this->common->encode($current_password),
381
					'pricelist_id' => $pricelist_id,
382
					'reseller_id' => $add_array['reseller_id'],
383
					'status' => 0,
384
					'credit_limit' => $credit_limit,
385
					'sweep_id' => 0,
386
					'posttoexternal' => $add_array['posttoexternal'],
387
					'balance' => $balance,
388
					'currency_id' => $add_array['currency_id'],
389
					'country_id' => $add_array['country_id'],
390
					'timezone_id' => $add_array['timezone_id'],
391
					'company_name' => $add_array['company_name'],
392
					'invoice_day' => 0,
393
					'first_name' => $acc_num,
394
					'type' => 0,
395
					'validfordays' => $add_array['validfordays'],
396
					"creation"=>gmdate("Y-m-d H:i:s"),
397
					"is_recording"=>0,
398
					"maxchannels"=>0,
399
					"sweep_id"=>2,
400
					"invoice_day"=>gmdate("d"),
401
					"expiry" => gmdate('Y-m-d H:i:s', strtotime('+10 years'))
402
                    
403
				);
404
				if ($pin_flag == 1) {
405
					$insert_array[$i]['pin'] = $pin[$i];
0 ignored issues
show
Bug introduced by
The variable $insert_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...
406
				}
407
				if ($opensip_flag) {
408
					$opensips_domain = common_model::$global_config['system_config']['opensips_domain'];
409
					$opensips_array[$i] = array('username' => $acc_num,
0 ignored issues
show
Coding Style Comprehensibility introduced by
$opensips_array was never initialized. Although not strictly required by PHP, it is generally a good practice to add $opensips_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...
410
						'domain' => $opensips_domain,
411
						'password' => $current_password,
412
						'accountcode' => $acc_num,
413
						'reseller_id' => $add_array['reseller_id'],
414
						"creation_date" => gmdate("Y-m-d H:i:s"),
415
						"status"=>0
416
						);
417
				}
418
			}
419
			$this->db->insert_batch('accounts', $insert_array);
420
			if ($opensip_flag == 1) {
421
				$db_config = Common_model::$global_config['system_config'];
422
				$opensipdsn = "mysql://" . $db_config['opensips_dbuser'] . ":" . $db_config['opensips_dbpass'] . "@" . $db_config['opensips_dbhost'] . "/" . $db_config['opensips_dbname'] . "?char_set=utf8&dbcollat=utf8_general_ci&cache_on=true&cachedir=";
423
				$this->opensips_db = $this->load->database($opensipdsn, true);
0 ignored issues
show
Bug introduced by
The property opensips_db does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
424
				$this->opensips_db->insert_batch("subscriber", $opensips_array);
0 ignored issues
show
Bug introduced by
The variable $opensips_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...
425
			}
426
		}
427
		return TRUE;
428
	}
429
430
	function get_max_limit($add_array) {
431
		$this->db->where('deleted','0');
432
		$this->db->where("length(number)", $add_array['account_length']);
433
		$this->db->like('number', $add_array['prefix'], 'after');
434
		$this->db->select("count(id) as count");
435
		$this->db->from('accounts');
436
		$result = $this->db->get();
437
		$result = $result->result_array();
438
		$count = $result[0]['count'];
439
		$remaining_length = 0;
440
		$remaining_length = $add_array['account_length'] - strlen($add_array['prefix']);
441
		$currentlength = pow(10, $remaining_length);
442
		$currentlength = $currentlength - $count;
443
		return $currentlength;
444
	}
445
	function account_process_payment($data) {
446
	$data['accountid'] = $data['id'];
447
		$accountdata=(array)$this->db->get_where('accounts',array("id"=>$data['accountid']))->first_row();
448
		$accountinfo =$this->session->userdata('accountinfo');
449
	$data["payment_by"] = $accountdata['reseller_id'] > 0 ? $accountdata['reseller_id'] : '-1';
450
	$data['payment_mode'] = $data['payment_type'];
451
	unset($data['action'],$data['id'],$data['account_currency'],$data['payment_type']);
452
	if (isset($data) && !empty($accountdata)) {
453
		$data['credit']=$data['credit'] =='' ?  0 : $data['credit'];
454
		$date = gmdate('Y-m-d H:i:s');
455
		if($data['payment_mode']== 1){       
456
		  $balance = $this->update_balance($data['credit'], $data['accountid'],$data['payment_mode']);
457
			  $insert_arr = array("accountid" => $data['accountid'],
458
			  "credit" => "-".$data['credit'],
459
			  'payment_mode'=>$data['payment_mode'],
460
			  'type'=>"SYSTEM",
461
			  "notes" => $data['notes'],
462
			  "payment_date" => $date, 
463
			  'payment_by'=>$data['payment_by'],
464
		  );
465
		  $this->db->insert("payments", $insert_arr);
466
		} else { 
467
		  $balance = $this->update_balance($data['credit'], $data['accountid'], $data['payment_mode']);
468
		  $insert_arr = array("accountid" => $data['accountid'],
469
			  "credit" => $data['credit'],
470
			  'payment_mode'=>$data['payment_mode'],
471
			  'type'=>"SYSTEM",
472
			  "notes" => $data['notes'],
473
			  "payment_date" => $date, 
474
			  'payment_by'=>$data['payment_by'],
475
		  );
476
		  $this->db->insert("payments", $insert_arr);
477
		  $accountdata['refill_amount']=$data['credit'];
478
		  $current_id=$accountinfo['type'] ==1 ? $accountinfo['id'] : '0';
479
		  if($accountdata['reseller_id'] == $current_id){
480
			$this->common->mail_to_users('voip_account_refilled', $accountdata);
481
		  }else{
482
			$this->common->mail_to_users('voip_child_account_refilled', $accountdata);
483
		  }
484
		}
485
	}
486
	}
487
/****************Completed******************/
488
489
	function get_admin_Account_list($flag, $start = 0, $limit = 0, $reseller_id = 0) {
490
		$this->db_model->build_search('admin_list_search');
491
		$where = "reseller_id =" . $reseller_id . " AND deleted =0 AND type in (2,4,-1)";
492
		if ($this->session->userdata('advance_search') == 1) {
493
			$search = $this->session->userdata('admin_list_search');
494
			if ($search['type'] == '') {
495
				$this->db->where($where);
496
				$this->db_model->build_search('admin_list_search');
497
			} else {
498
				$this->db->where('type', $search['type']);
499
			}
500
		} else {
501
			$this->db->where($where);
502
			$this->db_model->build_search('admin_list_search');
503
		}
504
		if ($flag) {
505
			$this->db->limit($limit, $start);
506
		}
507
		if (isset($_GET['sortname']) && $_GET['sortname'] != 'undefined'){
508
		  $this->db->order_by($_GET['sortname'], ($_GET['sortorder']=='undefined')?'desc':$_GET['sortorder']);
509
		}else{
510
			$this->db->order_by('number','desc');
511
		}
512
		$result = $this->db->get('accounts');
513
514
		if ($flag) {
515
			return $result;
516
		} else {
517
			return $result->num_rows();
518
		}
519
	}
520
521
	function get_customer_Account_list($flag, $start = 0, $limit = 0, $export = false) {
522
		$this->db_model->build_search('customer_list_search');
523
		$accountinfo = $this->session->userdata("accountinfo");
524
		$reseller_id = $accountinfo['type'] == 1 ? $accountinfo['id'] : 0;
525
		$where = array("deleted" => "0", 'reseller_id' => $reseller_id);
526
		$this->db->select('*');
527
		$type = "type IN (0,3)";
528
		$this->db->where($where);
529
		if ($this->session->userdata('advance_search') == 1) {
530
			$search = $this->session->userdata('customer_list_search');
531
			if ($search['type'] != '0' && $search['type'] != '3') {
532
				$this->db->where($type);
533
			}
534
		} else {
535
			$this->db->where($type);
536
		}
537
		if ($flag) {
538
			if (!$export)
539
				$this->db->limit($limit, $start);
540
		}
541
		if (isset($_GET['sortname']) && $_GET['sortname'] != 'undefined'){
542
		  $this->db->order_by($_GET['sortname'], ($_GET['sortorder']=='undefined')?'desc':$_GET['sortorder']);
543
		}else{
544
			$this->db->order_by('number','desc');
545
		}
546
		$result = $this->db->get('accounts');
547
		if ($flag) {
548
			return $result;
549
		} else {
550
			return $result->num_rows();
551
		}
552
	}
553
554 View Code Duplication
	function get_reseller_Account_list($flag, $start = 0, $limit = 0, $export = false) {
0 ignored issues
show
Unused Code introduced by
The parameter $export is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
555
		$this->db_model->build_search('reseller_list_search');
556
		$where = array('reseller_id' => "0", "deleted" => "0", "type" => "1");
557
		if ($this->session->userdata('logintype') == 1 || $this->session->userdata('logintype') == 5) {
558
			$where['reseller_id'] = $this->session->userdata["accountinfo"]['id'];
559
		}
560
		if ($flag) {
561
			$query = $this->db_model->select("*", "accounts", $where, "number", "desc", $limit, $start);
562
		} else {
563
			$query = $this->db_model->countQuery("*", "accounts", $where);
564
		}
565
		return $query;
566
	}
567
568 View Code Duplication
	function get_provider_Account_list($flag, $start = 0, $limit = 0) {
569
		$this->db_model->build_search('provider_list_search');
570
		$where = array("deleted" => "0", "type" => "3", 'reseller_id' => 0);
571
		if ($this->session->userdata('logintype') == 1 || $this->session->userdata('logintype') == 5) {
572
			$where['reseller_id'] = $this->session->userdata["accountinfo"]['id'];
573
		}
574
		if ($flag) {
575
			$query = $this->db_model->select("*", "accounts", $where, "number", "desc", $limit, $start);
576
		} else {
577
			$query = $this->db_model->countQuery("*", "accounts", $where);
578
		}
579
		return $query;
580
	}
581
582
	function remove_customer($id) {
583
		$this->db->where("id", $id);
584
		$this->db->where("type <>", "-1");
585
		$data = array('deleted' => '1');
586
		$this->db->update("accounts", $data);
587
		return true;
588
	}
589
590
	function insert_block($data, $accountid) {
591
		$data = explode(",", $data);
592
		$tmp = array();
593
		if (!empty($data)) {
594
			foreach ($data as $key => $data_value) {
595
				$tmp[$key]["accountid"] = $accountid;
596
				$result = $this->get_pattern_by_id($data_value);
597
				$tmp[$key]["blocked_patterns"] = $result[0]['pattern'];
598
				$tmp[$key]["destination"] = $result[0]['comment'];
599
			}
600
			return $this->db->insert_batch("block_patterns", $tmp);
601
		}
602
	}
603
604
	function get_pattern_by_id($pattern) {
605
		$patterns = $this->db_model->getSelect("pattern,comment", "routes", array("id" => $pattern));
606
		$patterns_value = $patterns->result_array();
607
		return $patterns_value;
608
	}
609
610
	function get_callerid($account_id) {
611
		$query = $this->db_model->getSelect("*", "accounts_callerid", array("accountid" => $account_id));
612
		return $query;
613
	}
614
615 View Code Duplication
	function get_account_number($accountid) {
616
		$query = $this->db_model->getSelect("number", "accounts", array("id" => $accountid));
617
		if ($query->num_rows() > 0)
618
			return $query->row_array();
619
		else
620
			return false;
621
	}
622
623
	function add_callerid($data) {
624
		unset($data['action'],$data['flag']);
625
		$data['accountid'] = $this->common->get_field_name('id', 'accounts', array('number' => $data['accountid']));
626
		$this->db->insert('accounts_callerid', $data);
627
		return true;
628
	}
629
630
	function edit_callerid($data) {
631
		unset($data['action']);
632
		unset($data['flag']);
633
		$data['accountid'] = $this->common->get_field_name('id', 'accounts', array('number' => $data['accountid']));
634
		$this->db->where('accountid', $data['accountid']);
635
		$this->db->update('accounts_callerid', $data);
636
		return true;
637
	}
638
639
	/**
640
	 * -------Here we write code for model accounting functions remove_all_account_tax------
641
	 * for remove all account's taxes enteries from database.
642
	 */
643
	function remove_all_account_tax($account_tax) {
644
		$this->db->where('accountid', $account_tax);
645
		$this->db->delete('taxes_to_accounts');
646
		return true;
647
	}
648
649
	/**
650
	 * -------Here we write code for model accounting functions add_account_tax------
651
	 * this function use to insert data for add taxes to account.
652
	 */
653
	function add_account_tax($data) {
654
		$this->db->insert('taxes_to_accounts', $data);
655
	}
656
657
	/**
658
	 * -------Here we write code for model accounting functions get_accounttax_by_id------
659
	 * this function use get the account taxes details as per account number
660
	 * @account_id = account id
661
	 */
662
	function get_accounttax_by_id($account_id) {
663
		$this->db->where("accountid", trim($account_id));
664
		$query = $this->db->get("taxes_to_accounts");
665
		if ($query->num_rows() > 0)
666
			return $query->result_array();
667
		else
668
			return false;
669
	}
670
671
	/**
672
	 * -------Here we write code for model accounting functions check_account_num------
673
	 * this function write to verify the account number is valid or not.
674
	 * @acc_num = account number
675
	 */
676
	function check_account_num($acc_num) {
677
		$this->db->select('accountid');
678
		$this->db->where("number", $acc_num);
679
		$query = $this->db->get("accounts");
680
681
		if ($query->num_rows() > 0)
682
			return $query->row_array();
683
		else
684
			return false;
685
	}
686
687
	function get_account_by_number($id) {
688
		$this->db->where("id", $id);
689
		$query = $this->db->get("accounts");
690
691
		if ($query->num_rows() > 0)
692
			return $query->row_array();
693
		else
694
			return false;
695
	}
696
697 View Code Duplication
	function get_currency_by_id($currency_id) {
698
699
		$query = $this->db_model->getSelect("*", 'currency', array('id' => $currency_id));
700
		if ($query->num_rows() > 0)
701
			return $query->row_array();
702
		else
703
			return false;
704
	}
705
706
707 View Code Duplication
	function update_balance($amount, $accountid, $payment_type) {
708
		if ($payment_type == 0) {
709
			$query = 'UPDATE `accounts` SET `balance` = (balance + ' . $amount . ') WHERE `id` = ' . $accountid;
710
			return $this->db->query($query);
711
		}if ($payment_type == 1) {
712
			$query = 'UPDATE `accounts` SET `balance` = (balance - ' . $amount . ') WHERE `id` = ' . $accountid;
713
			return $this->db->query($query);
714
		}
715
	}
716
717
	function account_authentication($where_data, $id) {
718
		if ($id != "") {
719
			$this->db->where("id <>", $id);
720
		}
721
		$this->db->where($where_data);
722
		$this->db->from("accounts");
723
		$query = $this->db->count_all_results();
724
		return $query;
725
	}
726
727 View Code Duplication
	function get_animap($flag, $start, $limit, $id) {
728
		$where = array('accountid' => $id);
729
730
		if ($flag) {
731
			$query = $this->db_model->select("*", "ani_map", $where, "number", "DESC", $limit, $start);
732
		} else {
733
			$query = $this->db_model->countQuery("*", "ani_map", $where);
734
		}
735
		return $query;
736
	}
737
738
	function add_animap($data) {
739
		$this->db->insert('ani_map', $data);
740
		return true;
741
	}
742
743
	function edit_animap($data, $id) {
744
		$new_array = array('number' => $data['number'], 'status' => $data['status']);
745
		$this->db->where('id', $id);
746
		$this->db->update('ani_map', $new_array);
747
		return true;
748
	}
749
750
	function remove_ani_map($id) {
751
		$this->db->where('id', $id);
752
		$this->db->delete('ani_map');
753
		return true;
754
	}
755
756
	function animap_authentication($where_data, $id) {
757
		if ($id != "") {
758
			$this->db->where("id <>", $id);
759
		}
760
		$this->db->where($where_data);
761
		$this->db->from("ani_map");
762
		$query = $this->db->count_all_results();
763
		return $query;
764
	}
765
	function add_invoice_config($add_array) {
766
		$result = $this->db->insert('invoice_conf', $add_array);
767
		return true;
768
	}
769
770
	function edit_invoice_config($add_array, $edit_id) {
771
		$this->db->where('id', $edit_id);
772
		$result = $this->db->update('invoice_conf', $add_array);
773
		return true;
774
	}
775
776
}
777