NewsletterSubscriber::subscribe()   F
last analyzed

Complexity

Conditions 19
Paths 2324

Size

Total Lines 122
Code Lines 73

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 42
CRAP Score 60.9017

Importance

Changes 0
Metric Value
cc 19
eloc 73
nc 2324
nop 1
dl 0
loc 122
rs 2
c 0
b 0
f 0
ccs 42
cts 82
cp 0.5122
crap 60.9017

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
 * NewsletterSubscriber
4
 *
5
 * This class handles the subscribers to the the different lists.
6
 *
7
 * @category  Intraface
8
 * @package   Intraface_Newsletter
9
 * @author    Lars Olesen <[email protected]>
10
 * @version   @package-version@
11
 */
12
require_once 'Intraface/functions.php';
13
require_once 'Intraface/modules/contact/Contact.php';
14
require_once 'Intraface/shared/email/Email.php';
15
16
class NewsletterSubscriber extends Intraface_Standard
17
{
18
    public $list; //object
19
    public $value;
20
    public $error;
21
    public $contact;
22
    public $id;
23
    private $dbquery;
24
    private $observers = array();
25
26
    /**
27
     * Constructor
28
     *
29
     * @param object  $list List object
30
     * @param integer $id   Subscriber id
31
     *
32
     * @return void
0 ignored issues
show
Comprehensibility Best Practice introduced by
Adding a @return annotation to constructors is generally not recommended as a constructor does not have a meaningful return value.

Adding a @return annotation to a constructor is not recommended, since a constructor does not have a meaningful return value.

Please refer to the PHP core documentation on constructors.

Loading history...
33
     */
34 10 View Code Duplication
    public function __construct($list, $id = 0)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
35
    {
36 10
        $this->error = new Intraface_Error;
37 10
        $this->list = $list;
38
39 10
        $this->id = (int)$id;
40
41 10
        if ($this->id > 0) {
42
            $this->load();
43
        }
44 10
    }
45
46
    /**
47
     * @return DBQuery object
48
     */
49 2
    public function getDBQuery()
50
    {
51 2
        if ($this->dbquery) {
52 2
            return $this->dbquery;
53
        }
54
        // optin = 1 should not be set here
55 2
        $this->dbquery = new Intraface_DBQuery($this->list->kernel, "newsletter_subscriber", "newsletter_subscriber.list_id=". $this->list->get("id") . " AND newsletter_subscriber.intranet_id = " . $this->list->kernel->intranet->get('id'));
56 2
        $this->dbquery->setJoin("LEFT", "contact", "newsletter_subscriber.contact_id = contact.id AND contact.intranet_id = ".$this->list->kernel->intranet->get("id"), '');
57 2
        $this->dbquery->setJoin("LEFT", "address", "address.belong_to_id = contact.id AND address.active = 1 AND address.type = 3", '');
58 2
        $this->dbquery->useErrorObject($this->error);
59 2
        $this->dbquery->setFilter('optin', 1);
60 2
        $this->dbquery->setFilter('active', 1);
61 2
        $this->dbquery->setSorting('date_submitted DESC');
62 2
        return $this->dbquery;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $this->dbquery; (Intraface_DBQuery) is incompatible with the return type documented by NewsletterSubscriber::getDBQuery of type DBQuery.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
63
    }
64
65
    /**
66
     * Starter NewsletterSubscriber ud fra alt andet end list
67
     *
68
     * @todo Skal laves til at have f�lgende parameter: $kernel, $from_what (code, email, id), $id
69
     *
70
     * @param object $object Different objects
71
     * @param string $type   What type to create the object from
72
     * @param string $value  Which value should be connected to the type
73
     *
74
     * @return object
75
     */
76 4
    public function factory($object, $type, $value)
77
    {
78
        switch ($type) {
79 4
            case 'code':
80
                $gateway = new Intraface_modules_newsletter_SubscribersGateway($object);
81
                return $gateway->findByCode($value);
82
                /*
0 ignored issues
show
Unused Code Comprehensibility introduced by
55% 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...
83
                // kernel og kode
84
                $code = trim($value);
85
                $code = mysql_escape_string($code);
86
                $code = strip_tags($code);
87
88
                $db = new DB_Sql;
89
                $db->query("SELECT id, list_id FROM newsletter_subscriber WHERE code = '".$code."' AND intranet_id = " . $object->intranet->get('id')." and active = 1");
90
                if (!$db->nextRecord()) {
91
                    return false;
92
                }
93
94
                return new NewsletterSubscriber(new NewsletterList($object, $db->f('list_id')), $db->f('id'));
95
				*/
96
            break;
0 ignored issues
show
Unused Code introduced by
break is not strictly necessary here and could be removed.

The break statement is not necessary if it is preceded for example by a return statement:

switch ($x) {
    case 1:
        return 'foo';
        break; // This break is not necessary and can be left off.
}

If you would like to keep this construct to be consistent with other case statements, you can safely mark this issue as a false-positive.

Loading history...
97
98 4
            case 'email':
99 4
                $gateway = new Intraface_modules_newsletter_SubscribersGateway($object->kernel);
100 4
                return $gateway->findByListAndEmail($object, $value);
101
                /*
0 ignored issues
show
Unused Code Comprehensibility introduced by
57% 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...
102
                // email og list
103
                $email = safeToDb($value);
104
                $db = new DB_Sql;
105
                $db->query("SELECT newsletter_subscriber.id
106
                    FROM newsletter_subscriber
107
                    LEFT JOIN contact
108
                        ON newsletter_subscriber.contact_id = contact.id
109
                    LEFT JOIN address
110
                        ON address.belong_to_id = contact.id
111
                    WHERE address.email = '".$email."'
112
                        AND newsletter_subscriber.list_id = " . $object->get('id') . "
113
                        AND newsletter_subscriber.intranet_id = " . $object->kernel->intranet->get('id') . "
114
                        AND newsletter_subscriber.active = 1
115
                        AND contact.active = 1");
116
                if (!$db->nextRecord()) {
117
                    return 0;
118
                }
119
120
                return new NewsletterSubscriber($object, $db->f('id'));
121
				*/
122
            break;
0 ignored issues
show
Unused Code introduced by
break is not strictly necessary here and could be removed.

The break statement is not necessary if it is preceded for example by a return statement:

switch ($x) {
    case 1:
        return 'foo';
        break; // This break is not necessary and can be left off.
}

If you would like to keep this construct to be consistent with other case statements, you can safely mark this issue as a false-positive.

Loading history...
123
124
            default:
125
                throw new Exception('NewsletterSubscriber::factory: Ulovlig Type');
126
            break;
0 ignored issues
show
Unused Code introduced by
break; 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...
127
        }
128
    }
129
130
    /**
131
     * Loads the subscriber
132
     *
133
     * @return boolean
134
     */
135 4
    private function load()
136
    {
137 4
        $db = new DB_Sql;
138 4
        $db->query("SELECT * FROM newsletter_subscriber WHERE id = " . $this->id." and active = 1");
139 4 View Code Duplication
        if (!$db->nextRecord()) {
140 1
            $this->id = 0;
141 1
            $this->value['id'] = 0;
142 1
            return false;
143
        }
144
145 3
        $this->value['id'] = $db->f('id');
146 3
        $this->value['contact_id'] = $db->f('contact_id');
147 3
        $this->value['code'] = $db->f('code');
148 3
        $this->contact = new Contact($this->list->kernel, $db->f('contact_id'));
149 3
        $this->value['email'] = $this->contact->get('email');
150 3
        $this->value['resend_optin_email_count'] = $db->f('resend_optin_email_count');
151
152 3
        return true;
153
    }
154
155
    /**
156
     * @return boolean
157
     */
158 2
    public function delete()
159
    {
160 2
        $db = new DB_Sql;
161 2
        $db->query('UPDATE newsletter_subscriber SET active = 0 WHERE id = ' . $this->id);
162 2
        return true;
163
    }
164
165
    /**
166
     * @param integer $contact_id Contact id
167
     *
168
     * @return Contact object
169
     */
170 2
    public function getContact($contact_id)
171
    {
172 2
        require_once 'Intraface/modules/contact/Contact.php';
173 2
        return new Contact($this->list->kernel, $contact_id);
174
    }
175
176
    /**
177
     * Adds an existing contact
178
     *
179
     * @param integer $contact_id Contact id
0 ignored issues
show
Documentation introduced by
There is no parameter named $contact_id. Did you maybe mean $contact?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function. It has, however, found a similar but not annotated parameter which might be a good fit.

Consider the following example. The parameter $ireland is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $ireland
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was changed, but the annotation was not.

Loading history...
180
     *
181
     * @return integer of the id of the subscriber
182
     */
183 2
    public function addContact($contact)
184
    {
185 2
        $db = new DB_sql;
186
187 2
        $db->query("SELECT id FROM newsletter_subscriber WHERE contact_id = '".$contact->getId()."' AND list_id = " . $this->list->get("id") . " AND intranet_id = ".$this->list->kernel->intranet->get('id')." AND active = 1");
188 2
        if ($db->nextRecord()) {
189
            return $db->f('id');
190
        }
191
192
        // Spørgsmålet er om vedkommende bør få en e-mail, hvor man kan acceptere?
193 2
        $db->query("INSERT INTO newsletter_subscriber SET
194 2
                    contact_id = '".$contact->getId()."',
195 2
                    list_id = " . $this->list->get("id") . ",
196
                    date_submitted=NOW(),
197
                    optin = 1,
198 2
                    code = '".md5($this->list->get("id") . $this->list->kernel->intranet->get('id') . date('Y-m-d H:i:s') . $contact->getId())."',
199 2
                    intranet_id = ".$this->list->kernel->intranet->get('id'));
200
201 2
        return $db->insertedId();
202
    }
203
204
    /**
205
     * IMPORTANT: To comply with spam legislation we must save which date it is submitted and the ip.
206
     *
207
     * @param struct $input With all values
208
     *
209
     * @return boolean
210
     */
211 3
    public function subscribe($input)
212
    {
213 3
        $input = safeToDb($input);
214 3
        $input = array_map('strip_tags', $input);
215
216 3
        $validator = new Intraface_Validator($this->error);
217 3
        $validator->isEmail($input['email'], $input['email'] . ' er ikke en gyldig e-mail');
218
219 3
        if (empty($input['name'])) {
220 2
            $input['name'] = $input['email'];
221 2
        }
222
223 3
        if (!empty($input['name'])) {
224 3
            $validator->isString($input['name'], 'Der er brugt ulovlige tegn i navnet', '', 'allow_empty');
225 3
        }
226
227 3
        if ($this->error->isError()) {
228
            return false;
229
        }
230
231
        // Det er smartere hvis vi bare loader fra e-mail
232 3
        $db = new DB_Sql;
233
234
        // jeg kan dog ikke få lov at reassigne i php5 - så hvad skal jeg gøre i stedet?
235 3
        $which_subscriber_has_email = NewsletterSubscriber::factory($this->list, 'email', $input['email']);
236 3
        if (is_object($which_subscriber_has_email)) {
237
            $this->id = $which_subscriber_has_email->get('id');
238
            $this->load();
239
        }
240
241 3
        if (is_object($this->contact) && $this->contact->get('id') != 0) {
242
            $contact = $this->contact;
243
        } else {
244 3
            $gateway = new Intraface_modules_contact_ContactGateway($this->list->kernel, new DB_Sql);
245 3
            $contacts = $gateway->findByEmail($input['email']);
246 3
            if (count($contacts) > 0) {
247
                $contact = $contacts[0];
248
            } else {
249 3
                require_once 'Intraface/modules/contact/Contact.php';
250 3
                $contact = new Contact($this->list->kernel);
251 3
                if (empty($input['name'])) {
252
                    $input['name'] = $input['email'];
253
                }
254
255 3
                if (!$contact->save($input)) {
256
                    $this->error->set('Kunne ikke gemme kontaktpersonen');
257
                    $this->error->merge($contact->error->getMessage());
258
                    return false;
259
                }
260
            }
261
        }
262
263
264 3
        if (!empty($input['name']) && $input['name'] != $contact->get('name')) {
265
            $save = $contact->address->get();
266
            $save['name'] = $input['name'];
267
            unset($save['id']);
268
            unset($save['type']);
269
            unset($save['address_id']);
270
            unset($save['belong_to_id']);
271
            $contact->save($save);
272
        }
273
274 3
        if ($this->id > 0) {
275
            // name og e-mail bør vel ikke nødv. gemmes?
276
277
            $db->query("UPDATE newsletter_subscriber
278
                SET
279
                    contact_id = '".$contact->get('id')."',
280
                    name='".$input['name']."',
281
                    email = '".$input['email']."',
282
                    date_submitted = NOW(),
283
                    ip_submitted = '".$input['ip']."'
284
                WHERE id = ".$this->id."
285
                    AND list_id = " . $this->list->get("id") . "
286
                    AND intranet_id = " . $this->list->kernel->intranet->get('id'));
287
            //code =  '" . md5($input['email'] . date('Y-m-d H:i:s') . $input['ip'])."'
288
        } else {
289 3
            $contact = Contact::factory($this->list->kernel, 'email', $input['email']);
290
291 3
            if ($contact->get('id') == 0) {
292
                if (empty($input['name'])) {
293
                    $name = $input['email'];
294
                } else {
295
                    $name = $input['name'];
296
                }
297
                if (!$contact_id = $contact->save(array('name' => $name, 'email' => $input['email']))) {
298
                    //$contact->error->view();
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...
299
                    $this->error->set('Kunne ikke gemme kontaktpersonen');
300
                }
301
            }
302
303 3
            $db->query("INSERT INTO newsletter_subscriber
304
                SET
305 3
                    contact_id = '".$contact->get('id')."',
306 3
                    email = '".$input['email']."',
307 3
                    name='".$input['name']."',
308 3
                    list_id = " . $this->list->get("id") . ",
309 3
                    ip_submitted='".$input['ip']."',
310
                    date_submitted=NOW(),
311 3
                    code= '" . md5($input['email'] . date('Y-m-d H:i:s') . $input['ip'])."',
312 3
                    intranet_id = ".$this->list->kernel->intranet->get('id'));
313
        }
314
315 3
        if ($this->id == 0) {
316 3
            $this->id = $db->insertedId();
317 3
        }
318
319
        // sender kun optinbrev, hvis man ikke er opted in
320 3
        if (!$this->optedIn()) {
321
            // TODO replace by observer
322 3
            if (!$this->sendOptInEmail()) {
323
                $this->error->set('could not send optin email');
324
                return false;
325
            }
326
327
            // $this->notifyObservers('new subscriber');
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...
328 3
        }
329
330
331 3
        return true;
332
    }
333
334
    /**
335
     * Checks whether subscriber has opted in yet
336
     *
337
     * @return boolean
338
     */
339 3
    public function optedIn()
340
    {
341 3
        if ($this->id == 0) {
342
            return false;
343
        }
344 3
        $db = new DB_Sql;
345 3
        $db->query("SELECT * FROM newsletter_subscriber WHERE id = " . $this->id." and active = 1");
346 3
        if (!$db->nextRecord()) {
347
            return false;
348
        }
349
350 3
        if ($db->f('optin') == 0) {
351 3
            return false;
352
        }
353 1
        return true;
354
    }
355
356
    /**
357
     * Deletes the user from a newsletter list
358
     *
359
     * IMPORTANT: The user must be deleted, not just deactivated.
360
     *
361
     * @param string $email Email
362
     *
363
     * @return boolean
364
     */
365 1
    public function unsubscribe($email)
366
    {
367 1
        $email = strip_tags($email);
368
369 1
        $validator = new Intraface_Validator($this->error);
370 1
        $validator->isEmail($email, 'E-mailen er ikke gyldig');
371
372 1
        if ($this->error->isError()) {
373
            return false;
374
        }
375
376 1
        $which_subscriber_has_email = NewsletterSubscriber::factory($this->list, 'email', $email);
377 1
        if (is_object($which_subscriber_has_email)) {
378
            $this->id = $which_subscriber_has_email->get('id');
379
        }
380 1
        $this->load();
381
382 1
        $db = new DB_Sql;
383 1
        $db->query("UPDATE newsletter_subscriber SET active = 0, date_unsubscribe = '".date('Y-m-d H:i:s')."' WHERE id=".$this->id." AND list_id = " . $this->list->get("id") . " AND intranet_id = " . $this->list->kernel->intranet->get('id'));
384 1
        return true;
385
    }
386
387
    /**
388
     * IMPORTANT: To comply with spam legislation we must save date_optin and ip_optin.
389
     *
390
     * @param string $code Optin code
391
     * @param string $ip   IP
392
     *
393
     * @return boolean
394
     */
395 2
    public function optIn($code, $ip)
396
    {
397
        // lets assume that a newsletter which has been set to active = 0 which wants to
398
        // optin really wants to optin, so we will not make that a part of the select query
399
        // and we will set it in the update query
400 2
        $db = new DB_Sql;
401 2
        $db->query("SELECT id, ip_submitted FROM newsletter_subscriber WHERE code = '".$code."' AND list_id = " . $this->list->get('id'));
402 2
        if (!$db->nextRecord()) {
403 1
            return false;
404
        }
405
406 2
        $db->query("UPDATE newsletter_subscriber SET optin = 1, ip_optin = '".$ip."', date_optin = NOW(), active = 1 WHERE code = '" . $code . "' AND list_id = " . $this->list->get('id'));
407
408
        // makes sure that the submitted ip is also set - not really a part of this method.
409 2
        if ($db->f('ip_submitted')) {
410 2
            $db->query("UPDATE newsletter_subscriber SET ip_submitted = '".$ip."' WHERE id = " . $db->f("id"));
411 2
        }
412 2
        return true;
413
    }
414
415
    /**
416
     * The subscriber must receive an e-mail so the subscribtion can be confirmed
417
     * The e-mail should say that the subscription should be confirmed within a week.
418
     *
419
     * E-mailen skal indeholde følgende:
420
     * - url til privacy policy på sitet
421
     * - en kort beskrivelse af mailinglisten
422
     * - url som brugeren følger for at bekræfte tilmeldingen
423
     *
424
     * - I virkeligheden skal den nok nøjes med lige at logge ind i ens personlige webinterface
425
     *   hvor man så kan lave bekræftelsen fra. Det skal altså bare være loginkoden fra
426
     *   den personlige konto, der står der, og så skal nyhedsbreve på forsiden (hvis dette sted
427
     *   har nogle nyhedsbreve).
428
     *
429
     * @see tilføj cleanUp();
430
     *
431
     * @return boolean
432
     */
433 3
    public function sendOptInEmail()
434
    {
435 3
        if ($this->id == 0) {
436
            $this->error->set('no id');
437
            return false;
438
        }
439
440
        // @todo hack for legacy purposes, could also just update the db
441 3
        $subscribe_subject = $this->list->get('subscribe_subject');
442 3
        if (empty($subscribe_subject)) {
443
            $subscribe_subject = 'Bekræft tilmelding';
444
        }
445
446 3
        $this->load();
447
448 3
        $contact = new Contact($this->list->kernel, $this->get('contact_id'));
449
450
        // @todo should probably also introduce some kind of greeting setting in list
451 3
        $email = new Email($this->list->kernel);
452
        $data = array(
453 3
                'subject' => $subscribe_subject,
454
                'body' =>
455 3
                    $this->list->get('subscribe_message') . "\n\n" .
456 3
                    $this->getLoginUrl($contact) .
457 3
                    "\n\n".$this->list->get('sender_name'),
458 3
                'contact_id' => $this->get('contact_id'),
459 3
                'from_email' => $this->list->get('reply_email'),
460 3
                'from_name' => $this->list->get('sender_name'),
461 3
                'type_id' => 7, // nyhedsbreve
462 3
                'belong_to' => $this->list->get('id')
463 3
            );
464
465 3
        if (!$email->save($data)) {
0 ignored issues
show
Documentation introduced by
$data is of type array<string,?,{"subject...eger","belong_to":"?"}>, but the function expects a object<Struct>.

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...
466
            $this->error->set('could not send the e-mail' . implode(',', $email->error->messages));
0 ignored issues
show
Bug introduced by
The property messages does not seem to exist. Did you mean message?

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
467
            return false;
468
        }
469
470 3 View Code Duplication
        if ($email->queue()) {
471 3
            $db = new DB_Sql;
472 3
            $db->query("UPDATE newsletter_subscriber SET date_optin_email_sent = NOW() WHERE id = " . $this->id);
473 3
            return true;
474
        }
475
        $this->error->set('could not send the e-mail' . implode(',', $email->error->message));
0 ignored issues
show
Bug introduced by
The property message cannot be accessed from this context as it is declared private in class Ilib_Error.

This check looks for access to properties that are not accessible from the current context.

If you need to make a property accessible to another context you can either raise its visibility level or provide an accessible getter in the defining class.

Loading history...
476
        return false;
477
    }
478
479
    /**
480
     * Resends the optin e-mail to the user again, and adds one to count of resend times.
481
     *
482
     */
483 View Code Duplication
    function resendOptInEmail()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
484
    {
485
        if ($this->sendOptInEmail()) {
486
            $db = new DB_Sql;
487
            $db->query("UPDATE newsletter_subscriber SET resend_optin_email_count = resend_optin_email_count + 1 WHERE id = " . $this->id);
488
            return true;
489
        }
490
    }
491
492 3
    private function getLoginUrl($contact)
493
    {
494 3
        if (!$link = $this->list->get('optin_link')) {
495
            return $contact->getLoginUrl() . '&optin=' . $this->get('code');
496
        }
497 3
        return $link . '?optin=' . $this->get('code');
498
    }
499
500
    /**
501
     * gets a list
502
     *
503
     * @return boolean
504
     */
505 2
    public function getList()
506
    {
507 2
        $subscribers = array();
508
509
        //$db = new DB_Sql;
0 ignored issues
show
Unused Code Comprehensibility introduced by
38% 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...
510
        //$db->query("SELECT id, contact_id, date_submitted, DATE_FORMAT(date_submitted, '%d-%m-%Y') AS dk_date_submitted FROM newsletter_subscriber WHERE list_id=". $this->list->get("id") . " AND intranet_id = " . $this->list->kernel->intranet->get('id') . " AND optin = 1 AND active = 1");
0 ignored issues
show
Unused Code Comprehensibility introduced by
56% 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...
511 2
        $i = 0;
512 2
        $this->getDBQuery()->setCondition('newsletter_subscriber.optin = '.$this->getDBQuery()->getFilter('optin'));
513 2
        $this->getDBQuery()->setCondition('newsletter_subscriber.active = '.$this->getDBQuery()->getFilter('active'));
514 2 View Code Duplication
        if ($this->getDBQuery()->checkFilter("q")) {
515
            $this->getDBQuery()->setCondition("(address.name LIKE \"%".$this->getDBQuery()->getFilter("q")."%\" OR address.email LIKE \"%".$this->getDBQuery()->getFilter("q")."%\")");
516
        }
517
518 2
        $db = $this->getDBQuery()->getRecordset("newsletter_subscriber.id, date_optin_email_sent, contact_id, resend_optin_email_count, date_submitted, DATE_FORMAT(date_submitted, '%d-%m-%Y') AS dk_date_submitted, optin", "", false);
519
520 2
        while ($db->nextRecord()) {
521 1
            $contact_id = $db->f('contact_id');
0 ignored issues
show
Unused Code introduced by
$contact_id is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
522 1
            $subscribers[$i]['id'] = $db->f('id');
523 1
            $subscribers[$i]['contact_id'] = $db->f('contact_id');
524 1
            $subscribers[$i]['dk_date_submitted'] = $db->f('dk_date_submitted');
525 1
            $subscribers[$i]['date_submitted'] = $db->f('date_submitted');
526 1
            $subscribers[$i]['date_optin_email_sent'] = $db->f('date_optin_email_sent');
527 1
            $subscribers[$i]['optin'] = $db->f('optin');
528 1
            $subscribers[$i]['resend_optin_email_count'] = $db->f('resend_optin_email_count');
529
530 1
            if (isset($this->list->kernel->user)) { // only if we are logged in.
531 1
                $contact = $this->getContact($db->f('contact_id'));
532 1
                $subscribers[$i]['contact_number'] = $contact->get('number');
533 1
                $subscribers[$i]['contact_name'] = $contact->address->get('name');
534 1
                $subscribers[$i]['contact_address'] = $contact->address->get('address');
535 1
                $subscribers[$i]['contact_postcode'] = $contact->address->get('postcode');
536 1
                $subscribers[$i]['contact_city'] = $contact->address->get('city');
537 1
                $subscribers[$i]['contact_email'] = $contact->address->get('email');
538 1
                $subscribers[$i]['contact_country'] = $contact->address->get('country');
539 1
                $subscribers[$i]['contact_login_url'] = $contact->getLoginUrl();
540 1
            }
541 1
            $i++;
542 1
        }
543
544 2
        $db->free();
545
546
        // vi skal have result free
547 2
        return $subscribers;
548
    }
549
550
    /**
551
     * @param object $observer Must implement an update() method
552
     */
553 1
    public function addObserver($observer)
554
    {
555 1
        $this->observers[] = $observer;
556 1
    }
557
558
    /**
559
     * @return array with observers
560
     */
561 1
    public function getObservers()
562
    {
563 1
        return $this->observers;
564
    }
565
566
    /**
567
     * @param string $state Of this object
568
     */
569
    public function notifyObservers($state)
570
    {
571
        foreach ($this->getObservers() as $observer) {
572
            $observer->update($this, $state);
573
        }
574
    }
575
}
576