Service::getSearchQuery()   F
last analyzed

Complexity

Conditions 35
Paths > 20000

Size

Total Lines 91

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 74
CRAP Score 35

Importance

Changes 0
Metric Value
cc 35
nc 4294967295
nop 2
dl 0
loc 91
ccs 74
cts 74
cp 1
crap 35
rs 0
c 0
b 0
f 0

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
/**
3
 * BoxBilling
4
 *
5
 * @copyright BoxBilling, Inc (http://www.boxbilling.com)
6
 * @license   Apache-2.0
7
 *
8
 * Copyright BoxBilling, Inc
9
 * This source file is subject to the Apache-2.0 License that is bundled
10
 * with this source code in the file LICENSE
11
 */
12
13
14
namespace Box\Mod\Client;
15
16
use Box\InjectionAwareInterface;
17
18
class Service implements InjectionAwareInterface
19
{
20
    protected $di = null;
21
22
    /**
23
     * @param Box_Di|null $di
24
     */
25 43
    public function setDi($di)
26
    {
27 43
        $this->di = $di;
28 43
    }
29
30
    /**
31
     * @return Box_Di|null
32
     */
33 1
    public function getDi()
34
    {
35 1
        return $this->di;
36
    }
37
38 2
    public function approveClientEmailByHash($hash)
39
    {
40 2
        $db = $this->di['db'];
41 2
        $result = $db->getRow('SELECT id, client_id FROM extension_meta WHERE extension = "mod_client" AND meta_key = "confirm_email" AND meta_value = :hash', array(':hash'=>$hash));
42 2
        if(!$result) {
43 1
            throw new \Box_Exception('Invalid email confirmation link');
44
        }
45 1
        $db->exec('UPDATE client SET email_approved = 1 WHERE id = :id', array('id'=>$result['client_id']));
46 1
        $db->exec('DELETE FROM extension_meta WHERE id = :id', array('id'=>$result['id']));
47 1
        return true;
48
    }
49
    
50 1
    public function generateEmailConfirmationLink($client_id)
51
    {
52 1
        $hash = strtolower($this->di['tools']->generatePassword(50));
53 1
        $db = $this->di['db'];
54
55 1
        $meta = $db->dispense('ExtensionMeta');
56 1
        $meta->extension    = 'mod_client';
57 1
        $meta->client_id    = $client_id;
58 1
        $meta->meta_key     = 'confirm_email';
59 1
        $meta->meta_value   = $hash;
60 1
        $meta->created_at   = date('Y-m-d H:i:s');
61 1
        $meta->updated_at   = date('Y-m-d H:i:s');
62 1
        $db->store($meta);
63
64 1
        return $this->di['tools']->url('/client/confirm-email/'.$hash);
65
    }
66
    
67 3
    public static function onAfterClientSignUp(\Box_Event $event)
68
    {
69 3
        $di = $event->getDi();
70 3
        $params = $event->getParameters();
71 3
        $config = $di['mod_config']('client');
72 3
        $emailService = $di['mod_service']('email');
73
        try {
74 3
            $email = array();
75 3
            $email['to_client'] = $params['id'];
76 3
            $email['code']      = 'mod_client_signup';
77 3
            $email['password']  = $params['password'];
78 3
            $email['require_email_confirmation']  = false;
79 3
            if(isset($config['require_email_confirmation']) && $config['require_email_confirmation']) {
80 1
                $clientService = $di['mod_service']('client');
81 1
                $email['require_email_confirmation']  = true;
82 1
                $email['email_confirmation_link'] = $clientService->generateEmailConfirmationLink($params['id']);
83 1
            }
84
85 3
            $emailService->sendTemplate($email);
86 3
        } catch(\Exception $exc) {
87 1
            error_log($exc->getMessage());
88
        }
89
        
90 3
        return true;
91
    }
92
93 16
    public function getSearchQuery($data, $selectStmt = 'SELECT c.*')
94
    {
95 14
        $sql = $selectStmt;
96 14
        $sql .= ' FROM client as c left join client_group as cg on c.client_group_id = cg.id';
97
98 14
        $search     = (isset($data['search']) && !empty($data['search'])) ? $data['search'] : NULL;
99 14
        $client_id  = (isset($data['client_id']) && !empty($data['client_id'])) ? $data['client_id'] : NULL;
100 16
        $group_id   = (isset($data['group_id']) && !empty($data['group_id'])) ? $data['group_id'] : NULL;
101 14
        $id         = (isset($data['id']) && !empty($data['id'])) ? $data['id'] : NULL;
102 14
        $status     = (isset($data['status']) && !empty($data['status'])) ? $data['status'] : NULL;
103 14
        $name       = (isset($data['name']) && !empty($data['name'])) ? $data['name'] : NULL;
104 14
        $company    = (isset($data['company']) && !empty($data['company'])) ? $data['company'] : NULL;
105 14
        $email      = (isset($data['email']) && !empty($data['email'])) ? $data['email'] : NULL;
106 14
        $created_at = (isset($data['created_at']) && !empty($data['created_at'])) ? $data['created_at'] : NULL;
107 14
        $date_from  = (isset($data['date_from']) && !empty($data['date_from'])) ? $data['date_from'] : NULL;
108 14
        $date_to    = (isset($data['date_to']) && !empty($data['date_to'])) ? $data['date_to'] : NULL;
109
110 14
        $where = array();
111 14
        $params = array();
112 14
        if($id) {
113 1
            $where[] = 'c.id = :client_id or c.aid = :alt_client_id';
114 1
            $params[':client_id'] = $id;
115 1
            $params[':alt_client_id'] = $id;
116 1
        }
117
118 14
        if($name) {
119 1
            $where[] = '(c.first_name LIKE :first_name or c.last_name LIKE :last_name )';
120 1
            $name = "%" . $name . "%";
121 1
            $params[':first_name'] = $name;
122 1
            $params[':last_name'] = $name;
123 1
        }
124
125 14
        if($email) {
126 1
            $where[] = 'c.email LIKE :email';
127 1
            $params[':email'] = "%" . $email . "%";
128 1
        }
129
130 14
        if($company) {
131 1
            $where[] = 'c.company LIKE :company';
132 1
            $params[':company'] = "%" . $company . "%";
133 1
        }
134
135 14
        if($status) {
136 1
            $where[] = 'c.status = :status';
137 1
            $params[':status'] = $status;
138 1
        }
139
140 14
        if($group_id) {
141 1
            $where[] = 'c.client_group_id = :group_id';
142 1
            $params[':group_id'] = $group_id;
143 1
        }
144
145 14
        if($created_at) {
146 1
            $where[] = "DATE_FORMAT(c.created_at, '%Y-%m-%d') = :created_at";
147 1
            $params[':created_at'] = date('Y-m-d', strtotime($created_at)) ;
148 1
        }
149
150 14
        if($date_from) {
151 1
            $where[] = 'UNIX_TIMESTAMP(c.created_at) >= :date_from';
152 1
            $params[':date_from'] = strtotime($date_from);
153 1
        }
154
155 14
        if($date_to) {
156 1
            $where[] = 'UNIX_TIMESTAMP(c.created_at) <= :date_from';
157 1
            $params[':date_to'] = strtotime($date_to);
158 1
        }
159
160
        //smartSearch
161 14
        if($search) {
162 2
            if(is_numeric($search)) {
163 1
                $where[] = 'c.id = :cid or c.aid = :caid';
164 1
                $params[':cid'] = $search;
165 1
                $params[':caid'] = $search;
166 1
            } else {
167 1
                $where[] = "c.company LIKE :s_company OR c.first_name LIKE :s_first_time OR c.last_name LIKE :s_last_name OR c.email LIKE :s_email OR CONCAT(c.first_name,  ' ', c.last_name ) LIKE  :full_name";
168 1
                $search = "%" . $search . "%";
169 1
                $params[':s_company'] = $search;
170 1
                $params[':s_first_time'] = $search;
171 1
                $params[':s_last_name'] = $search;
172 1
                $params[':s_email'] = $search;
173 1
                $params[':full_name'] = $search;
174
            }
175 2
        }
176
177 14
        if (!empty($where)){
178 11
            $sql .= ' WHERE '.implode(' AND ', $where);
179 11
        }
180 14
        $sql = $sql.' ORDER BY c.created_at desc';
181
182 14
        return array($sql, $params);
183
    }
184
185 1
    public function getPairs($data)
186
    {
187 1
        $limit =  $this->di['array_get']($data, 'per_page', 30);
188 1
        list($sql, $params) = $this->getSearchQuery($data, "SELECT c.id, CONCAT(c.first_name,  ' ', c.last_name) as full_name");
189 1
        $sql = $sql.' LIMIT '.$limit;
190 1
        return $this->di['db']->getAssoc($sql, $params);
191
    }
192
193 1
    public function toSessionArray(\Model_Client $model)
194
    {
195
        return array(
196 1
            'id'        =>  $model->id,
197 1
            'email'     =>  $model->email,
198 1
            'name'      =>  $model->getFullName(),
199 1
            'role'      =>  $model->role,
200 1
        );
201
    }
202
203 2
    public function emailAreadyRegistered($new_email, \Model_Client $model = null)
204
    {
205 2
        if($model && $model->email == $new_email) {
206 1
            return false;
207
        }
208
209 1
        $result = $this->di['db']->findOne('Client', 'email = ?', array($new_email));
210
211 1
        return ($result) ? true : false;
212
    }
213
214 5
    public function canChangeCurrency(\Model_Client $model, $currency = null)
215
    {
216 5
        if (!$model->currency) {
217 1
            return true;
218
        }
219
220 4
        if ($model->currency == $currency) {
221 1
            return false;
222
        }
223
224 3
        $invoice = $this->di['db']->findOne('Invoice', 'client_id = :client_id', array(':client_id' => $model->id));
225 3
        if ($invoice instanceof \Model_Invoice) {
226 1
            throw new \Box_Exception('Currency can not be changed. Client already have invoices issued.');
227
        }
228
229 2
        $order = $this->di['db']->findOne('ClientOrder', 'client_id = :client_id', array(':client_id' => $model->id));
230 2
        if ($order instanceof \Model_ClientOrder) {
231 1
            throw new \Box_Exception('Currency can not be changed. Client already have orders.');
232
        }
233
234 1
        return true;
235
    }
236
237 4
    public function addFunds(\Model_Client $client, $amount, $description, array $data = array())
238
    {
239 4
        if(!$client->currency) {
240 1
            throw new \Box_Exception('Define clients currency before adding funds.');
241
        }
242
243 3
        if(!is_numeric($amount)) {
244 1
            throw new \Box_Exception('Funds amount is not valid');
245
        }
246
247 2
        if(empty($description)) {
248 1
            throw new \Box_Exception('Funds description is not valid');
249
        }
250
251 1
        $credit = $this->di['db']->dispense('ClientBalance');
252
253 1
        $credit->client_id = $client->id;
254 1
        $credit->type =  $this->di['array_get']($data, 'type', 'gift');
255 1
        $credit->rel_id =  $this->di['array_get']($data, 'rel_id');
256 1
        $credit->description = $description;
257 1
        $credit->amount = $amount;
258 1
        $credit->created_at = date('Y-m-d H:i:s');
259 1
        $credit->updated_at = date('Y-m-d H:i:s');
260
261 1
        $this->di['db']->store($credit);
262 1
        return true;
263
    }
264
265 1
    public function getExpiredPasswordReminders()
266
    {
267 1
        $expire_after_hours = 2;
268 1
        $expired = $this->di['db']->find('ClientPasswordReset', 'UNIX_TIMESTAMP() - ? > UNIX_TIMESTAMP(created_at)', array($expire_after_hours * 60 * 60));
269 1
        return $expired;
270
    }
271
272 3
    public function getHistorySearchQuery($data)
273
    {
274
        $q = 'SELECT ach.*, c.first_name, c.last_name, c.email
275
              FROM activity_client_history as ach
276 3
                LEFT JOIN client as c on ach.client_id = c.id ';
277
278 3
        $search =  $this->di['array_get']($data, 'search');
279 3
        $client_id =  $this->di['array_get']($data, 'client_id');
280
281 3
        $where = array();
282 3
        $params = array();
283 3
        if($search) {
284 1
            $where[] = 'c.first_name LIKE :first_name OR c.last_name LIKE :last_name OR c.id LIKE :id';
285 1
            $params[':first_name'] = "%".$search."%";
286 1
            $params[':last_name'] = "%".$search."%";
287 1
            $params[':id'] = $search;
288 1
        }
289
290 3
        if($client_id) {
291 1
            $where[] = 'ach.client_id = :client_id';
292 1
            $params[':client_id'] = $client_id;
293 1
        }
294
295 3
        if (!empty($where)){
296 2
            $q .= ' WHERE '.implode(' AND ', $where);
297 2
        }
298
299 3
        $q .= ' ORDER BY ach.id desc';
300
301 3
        return array($q, $params);
302
    }
303
304 1
    public function counter()
305
    {
306
        $sql = 'SELECT status, COUNT(id) as counter
307
                FROM client
308 1
                group by status';
309 1
        $data = $this->di['db']->getAssoc($sql);
310
        return array(
311 1
            'total' =>  array_sum($data),
312 1
            \Model_Client::ACTIVE =>  isset($data[\Model_Client::ACTIVE]) ? $data[\Model_Client::ACTIVE] : 0,
313 1
            \Model_Client::SUSPENDED =>  isset($data[\Model_Client::SUSPENDED]) ? $data[\Model_Client::SUSPENDED] : 0,
314 1
            \Model_Client::CANCELED =>  isset($data[\Model_Client::CANCELED]) ? $data[\Model_Client::CANCELED] : 0,
315 1
        );
316
    }
317
318 1
    public function getGroupPairs()
319
    {
320
        $sql = 'SELECT id, title
321 1
                FROM client_group';
322 1
        return $this->di['db']->getAssoc($sql);
323
    }
324
325 1
    public function clientAlreadyExists($email)
326
    {
327 1
        $client = $this->di['db']->findOne('Client', 'email = :email ', array(':email' => $email));
328
329 1
        return ($client instanceof \Model_Client);
330
    }
331
332 1
    public function getByLoginDetails($email, $password)
333
    {
334 1
        $client = $this->di['db']->findOne('Client', 'email = ? and pass = ? and status = ?', array($email, $password, \Model_Client::ACTIVE));
335 1
        return $client;
336
    }
337
338 1
    public function toApiArray(\Model_Client $model, $deep = false, $identity = null)
339
    {
340
        $details = array(
341 1
            'id'    =>  $model->id,
342 1
            'aid'    =>  $model->aid,
343 1
            'email'    =>  $model->email,
344 1
            'type'    =>  $model->type,
345 1
            'group_id' => $model->client_group_id,
346 1
            'company'    =>  $model->company,
347 1
            'company_vat'  =>  $model->company_vat,
348 1
            'company_number'  =>  $model->company_number,
349 1
            'first_name'    =>  $model->first_name,
350 1
            'last_name'    =>  $model->last_name,
351 1
            'gender'    =>  $model->gender,
352 1
            'birthday'    =>  $model->birthday,
353 1
            'phone_cc'    =>  $model->phone_cc,
354 1
            'phone'    =>  $model->phone,
355 1
            'address_1'    =>  $model->address_1,
356 1
            'address_2'    =>  $model->address_2,
357 1
            'city'    =>  $model->city,
358 1
            'state'    =>  $model->state,
359 1
            'postcode'    =>  $model->postcode,
360 1
            'country'    =>  $model->country,
361 1
            'currency'    =>  $model->currency,
362 1
            'notes'    =>  $model->notes,
363 1
            'created_at'    =>  $model->created_at,
364 1
            'document_nr' => $model->document_nr,
365 1
        );
366
367 1
        if($deep) {
368 1
            $details['balance'] = $this->getClientBalance($model);
369 1
        }
370
371 1
        $m = $this->di['db']->toArray($model);
372 1
        for ($i = 1; $i < 11; $i++) {
373 1
            $k = 'custom_'.$i;
374 1
            if(isset($m[$k]) && !empty($m[$k])) {
375
                $details[$k] = $m[$k];
376
            }
377 1
        }
378
379 1
        $clientGroup = $this->di['db']->load('ClientGroup', $model->client_group_id);
380
381 1
        if($identity instanceof \Model_Admin) {
382 1
            $details['auth_type'] = $model->auth_type;
383 1
            $details['api_token'] = $model->api_token;
384 1
            $details['ip'] = $model->ip;
385 1
            $details['status'] = $model->status;
386 1
            $details['tax_exempt'] = $model->tax_exempt;
387 1
            $details['group'] = ($clientGroup) ? $clientGroup->title : NULL;
388 1
            $details['updated_at'] = $model->updated_at;
389 1
            $details['email_approved'] = $model->email_approved;
390 1
        }
391
392 1
        return $details;
393
    }
394
395 1
    public function getClientBalance(\Model_Client $c)
396
    {
397
        $sql = 'SELECT SUM(amount) as client_total
398
                FROM client_balance
399
                WHERE client_id = ?
400 1
                GROUP BY client_id';
401
402 1
        $balance = $this->di['db']->getCell($sql, array($c->id));
403
404 1
        return $balance;
405
    }
406
407 3
    public function get($data)
408
    {
409 3
        if(!isset($data['id']) && !isset($data['email'])) {
410
            throw new \Box_Exception('Client ID or email is required');
411
        }
412
413 3
        $db = $this->di['db'];
414 3
        $client = null;
415 3
        if(isset($data['id'])) {
416 2
            $client = $db->findOne('Client', 'id = ?', array($data['id']));
417 2
        }
418
419 3
        if(!$client && isset($data['email'])) {
420 1
            $client = $db->findOne('Client', 'email = ?', array($data['email']));
421 1
        }
422
423 3
        if(!$client instanceof \Model_Client ) {
424 1
            throw new \Box_Exception('Client not found');
425
        }
426 2
        return $client;
427
    }
428
429 3
    public function isClientTaxable(\Model_Client $model)
430
    {
431 3
        $systemService = $this->di['mod_service']('system');
432
433 3
        if (!$systemService->getParamValue('tax_enabled', false)) {
434 1
            return false;
435
        }
436
437 2
        if ($model->tax_exempt) {
438 1
            return false;
439
        }
440
441 1
        return true;
442
    }
443
444
    public function createGroup(array $data)
445
    {
446
        $systemService = $this->di['mod_service']('system');
447
        $systemService->checkLimits('Model_ClientGroup', 2);
448
449
        $model = $this->di['db']->dispense('ClientGroup');
450
451
        $model->title = $data['title'];
452
        $model->updated_at = date('Y-m-d H:i:s');
453
        $model->created_at = date('Y-m-d H:i:s');
454
455
        $group_id = $this->di['db']->store($model);
456
457
        $this->di['logger']->info('Created new client group #%s', $model->id);
458
        return $group_id;
459
    }
460
461 2
    public function deleteGroup(\Model_ClientGroup $model)
462
    {
463 2
        $client = $this->di['db']->findOne('Client', 'client_group_id = ?', array($model->id));
464 2
        if($client) {
465 1
            throw new \Box_Exception('Can not remove group with clients');
466
        }
467
468 1
        $this->di['db']->trash($model);
469 1
        $this->di['logger']->info('Removed client group #%s', $model->id);
470 1
        return true;
471
    }
472
473 2
    private function createClient(array $data)
474
    {
475 2
        $password = $this->di['array_get']($data, 'password', uniqid());
476
477 2
        $client = $this->di['db']->dispense('Client');
478
479 2
        $client->auth_type  = $this->di['array_get']($data, 'auth_type');
480 2
        $client->email      = strtolower(trim($this->di['array_get']($data, 'email')));
481 2
        $client->first_name = ucwords($this->di['array_get']($data, 'first_name'));
482 2
        $client->pass       = $this->di['password']->hashIt($password);
483
484 2
        $phoneCC = $this->di['array_get']($data, 'phone_cc', $client->phone_cc);
485 2
        if(!empty($phoneCC)){
486
            $client->phone_cc = intval($phoneCC);
487
        }
488
489 2
        $client->aid             = $this->di['array_get']($data, 'aid');
490 2
        $client->last_name       = $this->di['array_get']($data, 'last_name');
491 2
        $client->client_group_id = $this->di['array_get']($data, 'group_id');
492 2
        $client->status          = $this->di['array_get']($data, 'status');
493 2
        $client->gender          = $this->di['array_get']($data, 'gender');
494 2
        $client->birthday        = $this->di['array_get']($data, 'birthday');
495 2
        $client->phone           = $this->di['array_get']($data, 'phone');
496 2
        $client->company         = $this->di['array_get']($data, 'company');
497 2
        $client->company_vat     = $this->di['array_get']($data, 'company_vat');
498 2
        $client->company_number  = $this->di['array_get']($data, 'company_number');
499 2
        $client->type            = $this->di['array_get']($data, 'type');
500 2
        $client->address_1       = $this->di['array_get']($data, 'address_1');
501 2
        $client->address_2       = $this->di['array_get']($data, 'address_2');
502 2
        $client->city            = $this->di['array_get']($data, 'city');
503 2
        $client->state           = $this->di['array_get']($data, 'state');
504 2
        $client->postcode        = $this->di['array_get']($data, 'postcode');
505 2
        $client->country         = $this->di['array_get']($data, 'country');
506 2
        $client->document_type   = $this->di['array_get']($data, 'document_type');
507 2
        $client->document_nr     = $this->di['array_get']($data, 'document_nr');
508 2
        $client->notes           = $this->di['array_get']($data, 'notes');
509 2
        $client->lang            = $this->di['array_get']($data, 'lang');
510 2
        $client->currency        = $this->di['array_get']($data, 'currency');
511
512 2
        $client->custom_1  = $this->di['array_get']($data, 'custom_1');
513 2
        $client->custom_2  = $this->di['array_get']($data, 'custom_2');
514 2
        $client->custom_3  = $this->di['array_get']($data, 'custom_3');
515 2
        $client->custom_4  = $this->di['array_get']($data, 'custom_4');
516 2
        $client->custom_5  = $this->di['array_get']($data, 'custom_5');
517 2
        $client->custom_6  = $this->di['array_get']($data, 'custom_6');
518 2
        $client->custom_7  = $this->di['array_get']($data, 'custom_7');
519 2
        $client->custom_8  = $this->di['array_get']($data, 'custom_8');
520 2
        $client->custom_9  = $this->di['array_get']($data, 'custom_9');
521 2
        $client->custom_10 = $this->di['array_get']($data, 'custom_10');
522
523 2
        $client->ip = $this->di['array_get']($data, 'ip');
524
525 2
        $created_at = $this->di['array_get']($data, 'created_at');
526 2
        $client->created_at = !empty($created_at) ? date('Y-m-d H:i:s', strtotime($created_at)) : date('Y-m-d H:i:s');
527 2
        $client->updated_at = date('Y-m-d H:i:s');
528 2
        $this->di['db']->store($client);
529 2
        return $client;
530
    }
531
532 1
    public function adminCreateClient(array $data)
533
    {
534 1
        $this->di['events_manager']->fire(array('event'=>'onBeforeAdminCreateClient', 'params'=>$data));
535 1
        $client = $this->createClient($data);
536 1
        $this->di['events_manager']->fire(array('event'=>'onAfterAdminCreateClient', 'params'=>array('id'=>$client->id, 'password'=>$data['password'])));
537 1
        $this->di['logger']->info('Created new client #%s', $client->id);
538
539 1
        return $client->id;
540
    }
541
542 1
    public function guestCreateClient(array $data)
543
    {
544 1
        $event_params = $data;
545 1
        $event_params['ip'] = $this->di['request']->getClientAddress();
546 1
        $this->di['events_manager']->fire(array('event'=>'onBeforeClientSignUp', 'params'=>$event_params));
547
548 1
        $data['ip'] = $this->di['request']->getClientAddress();
549 1
        $data['status'] = \Model_Client::ACTIVE;
550 1
        $client = $this->createClient($data);
551
552 1
        $this->di['events_manager']->fire(array('event'=>'onAfterClientSignUp', 'params'=>array('id'=>$client->id, 'password'=>$data['password'])));
553 1
        $this->di['logger']->info('Client #%s signed up', $client->id);
554
555 1
        return $client;
556
    }
557
558
    public function remove(\Model_Client $model)
559
    {
560
        $service = $this->di['mod_service']('Order');
561
        $service->rmByClient($model);
562
        $service = $this->di['mod_service']('Invoice');
563
        $service->rmByClient($model);
564
        $service = $this->di['mod_service']('Support');
565
        $service->rmByClient($model);
566
        $service = $this->di['mod_service']('Client', 'Balance');
567
        $service->rmByClient($model);
568
569
        $table = $this->di['table']('ActivityClientHistory');
570
        $table->rmByClient($model);
571
572
        $service->rmByClient($model);
573
        $service = $this->di['mod_service']('Email');
574
        $service->rmByClient($model);
575
        $service = $this->di['mod_service']('Activity');
576
        $service->rmByClient($model);
577
578
        $table = $this->di['table']('ForumTopicMessage');
579
        $table->rmByClient($model);
580
581
        $table = $this->di['table']('ClientPasswordReset');
582
        $table->rmByClient($model);
583
584
585
        $pdo = $this->di['pdo'];
586
        $stmt = $pdo->prepare('DELETE FROM extension_meta WHERE client_id = :id');
587
        $stmt->execute(array('id'=>$model->id));
588
589
        $this->di['db']->trash($model);
590
    }
591
592 4
    public function authorizeClient($email, $plainTextPassword)
593
    {
594 4
        $model = $this->di['db']->findOne('Client', 'email = ? AND status = ?', array($email, \Model_Client::ACTIVE));
595 4
        if ($model == null) {
596 1
            return null;
597
        }
598
599 3
        $config = $this->di['mod_config']('client');
600 3
        if (isset($config['require_email_confirmation']) && (int)$config['require_email_confirmation']) {
601 2
            if (!$model->email_approved) {
602 1
                $meta = $this->di['db']->findOne('ExtensionMeta', ' extension = "mod_client" AND meta_key = "confirm_email" AND client_id = :client_id', array(':client_id' => $model->id));
603 1
                if (!is_null($meta)) {
604 1
                    throw new \Box_Exception('Please check your mailbox and confirm email address.');
605
                } else {
606
                    $this->sendEmailConfirmationForClient($model);
607
                    throw new \Box_Exception('Confirmation email was sent to your email address. Please click on link in it in order to verify your email.');
608
                }
609
            }
610 1
        }
611
612 2
        return $this->di['auth']->authorizeUser($model, $plainTextPassword);
613
    }
614
615
    private function sendEmailConfirmationForClient(\Model_Client $client)
616
    {
617
        try {
618
            $email                               = array();
619
            $email['to_client']                  = $client->id;
620
            $email['code']                       = 'mod_client_confirm';
621
            $email['require_email_confirmation'] = true;
622
            $email['email_confirmation_link']    = $this->generateEmailConfirmationLink($client->id);
623
624
            $emailService = $this->di['mod_service']('email');
625
            $emailService->sendTemplate($email);
626
        } catch (\Exception $exc) {
627
            error_log($exc->getMessage());
628
        }
629
    }
630
631 4
    public function canChangeEmail(\Model_Client $client, $email)
632
    {
633 4
        $config  = $this->di['mod_config']('client');
634
635 4
        if ($client->email != $email
636 4
            && isset($config['allow_change_email'])
637 4
            && !$config['allow_change_email']) {
638 1
            throw new \Box_Exception('Email can not be changed');
639
        }
640 3
        return true;
641
642
    }
643
644 1
    public function checkExtraRequiredFields(array $checkArr)
645
    {
646 1
        $config = $this->di['mod_config']('client');
647 1
        $required =  $this->di['array_get']($config, 'required', array());
648 1
        foreach($required as $field) {
649 1
            if(!isset($checkArr[$field]) || empty($checkArr[$field])) {
650 1
                $name = ucwords(str_replace('_', ' ', $field));
651 1
                throw new \Box_Exception('It is required that you provide details for field ":field"', array(':field'=>$name));
652
            }
653
        }
654
    }
655
656 2
    public function checkCustomFields(array $checkArr)
657
    {
658 2
        $config = $this->di['mod_config']('client');
659 2
        $customFields =  $this->di['array_get']($config, 'custom_fields', array());
660 2
        foreach ($customFields as $cFieldName => $cField) {
661 2
            $active   = isset($cField['active']) && $cField['active'] ? true : false;
662 2
            $required = isset($cField['required']) && $cField['required'] ? true : false;
663 2
            if ($active && $required) {
664 1
                if (!isset($checkArr[$cFieldName]) || empty($checkArr[$cFieldName])) {
665 1
                    $name = isset($cField['title']) && !empty($cField['title']) ? $cField['title'] : ucwords(str_replace('_', ' ', $cFieldName));;
666 1
                    throw new \Box_Exception('It is required that you provide details for field ":field"', array(':field' => $name));
667
                }
668
            }
669 1
        }
670
    }
671
}