Passed
Pull Request — dev (#6)
by Rafael
79:24 queued 24:08
created

PartnershipUtils   F

Complexity

Total Complexity 86

Size/Duplication

Total Lines 514
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 303
dl 0
loc 514
rs 2
c 0
b 0
f 0
wmc 86

4 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 3 1
F doCancelStatusOfMemberPartnership() 0 200 35
F doWarningOfPartnershipIfDolibarrBacklinkNotfound() 0 230 42
B checkDolibarrBacklink() 0 39 8

How to fix   Complexity   

Complex Class

Complex classes like PartnershipUtils 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.

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 PartnershipUtils, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
/* Copyright (C) 2021       NextGestion                 <[email protected]>
4
 * Copyright (C) 2024		MDW							<[email protected]>
5
 * Copyright (C) 2024       Rafael San José             <[email protected]>
6
 *
7
 * This program is free software; you can redistribute it and/or modify
8
 * it under the terms of the GNU General Public License as published by
9
 * the Free Software Foundation; either version 3 of the License, or
10
 * (at your option) any later version.
11
 *
12
 * This program is distributed in the hope that it will be useful,
13
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15
 * GNU General Public License for more details.
16
 *
17
 * You should have received a copy of the GNU General Public License
18
 * along with this program. If not, see <https://www.gnu.org/licenses/>.
19
 */
20
21
namespace Dolibarr\Code\Partnerships\Classes;
22
23
use DoliDB;
24
25
/**
26
 *  \file       partnership/class/partnershiputils.class.php
27
 *  \ingroup    partnership
28
 *  \brief      Class with utilities
29
 */
30
31
//require_once(DOL_DOCUMENT_ROOT."/core/class/commonobject.class.php");
32
//require_once(DOL_DOCUMENT_ROOT."/societe/class/societe.class.php");
33
require_once constant('DOL_DOCUMENT_ROOT') . '/core/lib/date.lib.php';
34
require_once constant('DOL_DOCUMENT_ROOT') . '/core/lib/files.lib.php';
35
require_once constant('DOL_DOCUMENT_ROOT') . '/core/lib/geturl.lib.php';
36
require_once constant('DOL_DOCUMENT_ROOT') . '/partnership/lib/partnership.lib.php';
37
use Dolibarr\Code\Partnerships\Classes\Partnership;
38
use Dolibarr\Code\Societe\Classes\Societe;
39
use Dolibarr\Code\Adherents\Classes\Adherent;
40
41
/**
42
 *  Class with cron tasks of Partnership module
43
 */
44
class PartnershipUtils
45
{
46
    public $db; //!< To store db handler
47
    public $error; //!< To return error code (or message)
48
    public $errors = array(); //!< To return several error codes (or messages)
49
50
    public $output; // To store output of some cron methods
51
52
53
    /**
54
     *  Constructor
55
     *
56
     *  @param  DoliDB      $db      Database handler
57
     */
58
    public function __construct($db)
59
    {
60
        $this->db = $db;
61
    }
62
63
    /**
64
     * Action executed by scheduler to cancel status of partnership when subscription is expired + x days. (Max number of action batch per call = $conf->global->PARTNERSHIP_MAX_EXPIRATION_CANCEL_PER_CALL)
65
     *
66
     * CAN BE A CRON TASK
67
     *
68
     * @return  int                 0 if OK, <>0 if KO (this function is used also by cron so only 0 is OK)
69
     */
70
    public function doCancelStatusOfMemberPartnership()
71
    {
72
        global $conf, $langs, $user;
73
74
        $managedfor = getDolGlobalString('PARTNERSHIP_IS_MANAGED_FOR', 'thirdparty');
75
76
        if ($managedfor != 'member') {
77
            return 0; // If option 'PARTNERSHIP_IS_MANAGED_FOR' = 'thirdparty', this cron job does nothing.
78
        }
79
80
        $partnership = new Partnership($this->db);
81
        $MAXPERCALL = (!getDolGlobalString('PARTNERSHIP_MAX_EXPIRATION_CANCEL_PER_CALL') ? 25 : $conf->global->PARTNERSHIP_MAX_EXPIRATION_CANCEL_PER_CALL); // Limit to 25 per call
82
83
        $langs->loadLangs(array("partnership", "member"));
84
85
        $error = 0;
86
        $erroremail = '';
87
        $this->output = '';
88
        $this->error = '';
89
        $partnershipsprocessed = array();
90
91
        $gracedelay = getDolGlobalString('PARTNERSHIP_NBDAYS_AFTER_MEMBER_EXPIRATION_BEFORE_CANCEL');
92
        if ($gracedelay < 1) {
93
            $this->error = 'BadValueForDelayBeforeCancelCheckSetup';
94
            return -1;
95
        }
96
97
        dol_syslog(get_class($this) . "::doCancelStatusOfMemberPartnership cancel expired partnerships with grace delay of " . $gracedelay);
98
99
        $now = dol_now();
100
        $datetotest = dol_time_plus_duree($now, -1 * abs((float) $gracedelay), 'd');
101
102
        $this->db->begin();
103
104
        $sql = "SELECT p.rowid, p.fk_member, p.status";
105
        $sql .= ", d.datefin, d.fk_adherent_type, dty.subscription";
106
        $sql .= " FROM " . MAIN_DB_PREFIX . "partnership as p";
107
        $sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "adherent as d on (d.rowid = p.fk_member)";
108
        $sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "adherent_type as dty on (dty.rowid = d.fk_adherent_type)";
109
        $sql .= " WHERE fk_member > 0";
110
        $sql .= " AND (d.datefin < '" . $this->db->idate($datetotest) . "' AND dty.subscription = 1)";
111
        $sql .= " AND p.status = " . ((int) $partnership::STATUS_APPROVED); // Only accepted not yet canceled
112
        $sql .= $this->db->order('d.rowid', 'ASC');
113
        // Limit is managed into loop later
114
115
        $resql = $this->db->query($sql);
116
        if ($resql) {
117
            $numofexpiredmembers = $this->db->num_rows($resql);
118
119
            $somethingdoneonpartnership = 0;
120
            $ifetchpartner = 0;
121
            while ($ifetchpartner < $numofexpiredmembers) {
122
                $ifetchpartner++;
123
124
                $obj = $this->db->fetch_object($resql);
125
                if ($obj) {
126
                    if (!empty($partnershipsprocessed[$obj->rowid])) {
127
                        continue;
128
                    }
129
130
                    if ($somethingdoneonpartnership >= $MAXPERCALL) {
131
                        dol_syslog("We reach the limit of " . $MAXPERCALL . " partnership processed, so we quit loop for this batch doCancelStatusOfMemberPartnership to avoid to reach email quota.", LOG_WARNING);
132
                        break;
133
                    }
134
135
                    $object = new Partnership($this->db);
136
                    $object->fetch($obj->rowid);
137
138
                    // Get expiration date
139
                    $expirationdate = $obj->datefin;
140
141
                    if ($expirationdate && $expirationdate < $now) {  // If contract expired (we already had a test into main select, this is a security)
142
                        $somethingdoneonpartnership++;
143
144
                        $result = $object->cancel($user, 0);
145
                        // $conf->global->noapachereload = null;
146
                        if ($result < 0) {
147
                            $error++;
148
                            $this->error = $object->error;
149
                            if (is_array($object->errors) && count($object->errors)) {
150
                                if (is_array($this->errors)) {
151
                                    $this->errors = array_merge($this->errors, $object->errors);
152
                                } else {
153
                                    $this->errors = $object->errors;
154
                                }
155
                            }
156
                        } else {
157
                            $partnershipsprocessed[$object->id] = $object->ref;
158
159
                            // Send an email to inform member
160
                            $labeltemplate = '(' . getDolGlobalString('PARTNERSHIP_SENDMAIL_IF_AUTO_CANCEL', 'SendingEmailOnPartnershipCanceled') . ')';
161
162
                            dol_syslog("Now we will send an email to member id=" . $object->fk_member . " with label " . $labeltemplate);
163
164
                            // Send deployment email
165
                            $formmail = new FormMail($this->db);
166
167
                            // Define output language
168
                            $outputlangs = $langs;
169
                            $newlang = '';
170
                            if (getDolGlobalInt('MAIN_MULTILANGS') && empty($newlang) && GETPOST('lang_id', 'aZ09')) {
171
                                $newlang = GETPOST('lang_id', 'aZ09');
172
                            }
173
                            if (!empty($newlang)) {
174
                                $outputlangs = new Translate("", $conf);
175
                                $outputlangs->setDefaultLang($newlang);
176
                                $outputlangs->loadLangs(array('main', 'member', 'partnership'));
177
                            }
178
179
                            $arraydefaultmessage = $formmail->getEMailTemplate($this->db, 'partnership_send', $user, $outputlangs, 0, 1, $labeltemplate);
180
181
                            $substitutionarray = getCommonSubstitutionArray($outputlangs, 0, null, $object);
182
                            complete_substitutions_array($substitutionarray, $outputlangs, $object);
183
184
                            $subject = make_substitutions($arraydefaultmessage->topic, $substitutionarray, $outputlangs);
185
                            $msg     = make_substitutions($arraydefaultmessage->content, $substitutionarray, $outputlangs);
186
                            $from = dol_string_nospecial($conf->global->MAIN_INFO_SOCIETE_NOM, ' ', array(",")) . ' <' . getDolGlobalString('MAIN_INFO_SOCIETE_MAIL') . '>';
187
188
                            // We are in the case of autocancellation subscription because of missing backlink
189
                            $fk_partner = $object->fk_member;
190
191
                            $adherent = new Adherent($this->db);
192
                            $adherent->fetch($object->fk_member);
193
                            $sendto = $adherent->email;
194
195
                            $trackid = 'par' . $object->id;
196
                            $sendcontext = 'standard';
197
198
                            $cmail = new CMailFile($subject, $sendto, $from, $msg, array(), array(), array(), '', '', 0, 1, '', '', $trackid, '', $sendcontext);
199
200
                            $result = $cmail->sendfile();
201
202
                            if (!$result || !empty($cmail->error) || !empty($cmail->errors)) {
203
                                $erroremail .= ($erroremail ? ', ' : '') . $cmail->error;
204
                                $this->errors[] = $cmail->error;
205
                                if (is_array($cmail->errors) && count($cmail->errors) > 0) {
206
                                    $this->errors += $cmail->errors;
207
                                }
208
                            } else {
209
                                // Initialisation of datas of object to call trigger
210
                                if (is_object($object)) {
211
                                    $actiontypecode = 'AC_OTH_AUTO'; // Event insert into agenda automatically
212
                                    $attachedfiles = array();
213
214
                                    $object->actiontypecode = $actiontypecode; // Type of event ('AC_OTH', 'AC_OTH_AUTO', 'AC_XXX'...)
215
                                    $object->actionmsg = $arraydefaultmessage->topic . "\n" . $arraydefaultmessage->content; // Long text
216
                                    $object->actionmsg2 = $langs->transnoentities("PartnershipSentByEMail", $object->ref);
217
                                    ; // Short text ($langs->transnoentities('MailSentByTo')...);
218
                                    if (getDolGlobalString('MAIN_MAIL_REPLACE_EVENT_TITLE_BY_EMAIL_SUBJECT')) {
219
                                        $object->actionmsg2     = $subject; // Short text
220
                                    }
221
222
                                    $object->trackid = $trackid;
0 ignored issues
show
Bug Best Practice introduced by
The property trackid does not exist on Dolibarr\Code\Partnerships\Classes\Partnership. Since you implemented __set, consider adding a @property annotation.
Loading history...
223
                                    $object->fk_element = $object->id;
224
                                    $object->elementtype = $object->element;
0 ignored issues
show
Bug Best Practice introduced by
The property elementtype does not exist on Dolibarr\Code\Partnerships\Classes\Partnership. Since you implemented __set, consider adding a @property annotation.
Loading history...
225
                                    if (is_array($attachedfiles) && count($attachedfiles) > 0) {
226
                                        $object->attachedfiles = $attachedfiles;
0 ignored issues
show
Bug Best Practice introduced by
The property attachedfiles does not exist on Dolibarr\Code\Partnerships\Classes\Partnership. Since you implemented __set, consider adding a @property annotation.
Loading history...
227
                                    }
228
229
                                    $object->email_from = $from;
0 ignored issues
show
Bug Best Practice introduced by
The property email_from does not exist on Dolibarr\Code\Partnerships\Classes\Partnership. Since you implemented __set, consider adding a @property annotation.
Loading history...
230
                                    $object->email_subject = $subject;
0 ignored issues
show
Bug Best Practice introduced by
The property email_subject does not exist on Dolibarr\Code\Partnerships\Classes\Partnership. Since you implemented __set, consider adding a @property annotation.
Loading history...
231
                                    $object->email_to = $sendto;
0 ignored issues
show
Bug Best Practice introduced by
The property email_to does not exist on Dolibarr\Code\Partnerships\Classes\Partnership. Since you implemented __set, consider adding a @property annotation.
Loading history...
232
                                    $object->email_subject = $subject;
233
234
                                    $triggersendname = 'PARTNERSHIP_SENTBYMAIL';
235
                                    // Call of triggers (you should have set $triggersendname to execute trigger)
236
                                    if (!empty($triggersendname)) {
237
                                        $result = $object->call_trigger($triggersendname, $user);
238
                                        if ($result < 0) {
239
                                            $error++;
240
                                        }
241
                                    }
242
                                    // End call of triggers
243
                                }
244
                            }
245
                        }
246
                    }
247
                }
248
            }
249
        } else {
250
            $error++;
251
            $this->error = $this->db->lasterror();
252
        }
253
254
        if (!$error) {
255
            $this->db->commit();
256
            $this->output = $numofexpiredmembers . ' expired partnership members found' . "\n";
257
            if ($erroremail) {
258
                $this->output .= '. Got errors when sending some email : ' . $erroremail;
259
            }
260
        } else {
261
            $this->db->rollback();
262
            $this->output = "Rollback after error\n";
263
            $this->output .= $numofexpiredmembers . ' expired partnership members found' . "\n";
264
            if ($erroremail) {
265
                $this->output .= '. Got errors when sending some email : ' . $erroremail;
266
            }
267
        }
268
269
        return ($error ? 1 : 0);
270
    }
271
272
273
    /**
274
     * Action executed by scheduler to check if Dolibarr backlink not found on partner website. (Max number of action batch per call = $conf->global->PARTNERSHIP_MAX_WARNING_BACKLINK_PER_CALL)
275
     *
276
     * CAN BE A CRON TASK
277
     *
278
     * @param   int     $maxpercall     Max per call
279
     * @return  int                     0 if OK, <>0 if KO (this function is used also by cron so only 0 is OK)
280
     */
281
    public function doWarningOfPartnershipIfDolibarrBacklinkNotfound($maxpercall = 0)
282
    {
283
        global $conf, $langs, $user;
284
285
        $managedfor = getDolGlobalString('PARTNERSHIP_IS_MANAGED_FOR');
286
287
        $partnership = new Partnership($this->db);
288
        if (empty($maxpercall)) {
289
            $maxpercall = getDolGlobalInt('PARTNERSHIP_MAX_WARNING_BACKLINK_PER_CALL', 10);
290
        }
291
292
        $langs->loadLangs(array("partnership", "member"));
293
294
        $error = 0;
295
        $erroremail = '';
296
        $this->output = '';
297
        $this->error = '';
298
        $partnershipsprocessed = array();
299
        $emailnotfound = '';
300
        $websitenotfound = '';
301
302
        /*$gracedelay = getDolGlobalInt('PARTNERSHIP_NBDAYS_AFTER_MEMBER_EXPIRATION_BEFORE_CANCEL');
303
        if ($gracedelay < 1) {
304
            $this->error = 'BadValueForDelayBeforeCancelCheckSetup';
305
            return -1;
306
        }*/
307
308
        $fk_partner = ($managedfor == 'member') ? 'fk_member' : 'fk_soc';
309
310
        dol_syslog(get_class($this) . "::doWarningOfPartnershipIfDolibarrBacklinkNotfound Warning of partnership");
311
312
        $now = dol_now();
313
        //$datetotest = dol_time_plus_duree($now, -1 * abs($gracedelay), 'd');
314
315
        $this->db->begin();
316
317
        $sql = "SELECT p.rowid, p.status, p." . $fk_partner;
318
        $sql .= ", p.url_to_check, p.last_check_backlink";
319
        $sql .= ', partner.url, partner.email';
320
        $sql .= " FROM " . MAIN_DB_PREFIX . "partnership as p";
321
        if ($managedfor == 'member') {
322
            $sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "adherent as partner on (partner.rowid = p.fk_member)";
323
        } else {
324
            $sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "societe as partner on (partner.rowid = p.fk_soc)";
325
        }
326
        $sql .= " WHERE p." . $fk_partner . " > 0";
327
        $sql .= " AND p.status = " . ((int) $partnership::STATUS_APPROVED); // Only accepted and not yet canceled
328
        $sql .= " AND (p.last_check_backlink IS NULL OR p.last_check_backlink <= '" . $this->db->idate($now - 24 * 3600) . "')"; // Never more than 1 check every day to check that website contains a referral link.
329
        $sql .= $this->db->order('p.rowid', 'ASC');
330
        // Limit is managed into loop later
331
332
        $resql = $this->db->query($sql);
333
        if ($resql) {
334
            $numofexpiredmembers = $this->db->num_rows($resql);
335
            $somethingdoneonpartnership = 0;
336
            $ifetchpartner = 0;
337
            while ($ifetchpartner < $numofexpiredmembers) {
338
                $ifetchpartner++;
339
340
                $obj = $this->db->fetch_object($resql);
341
                if ($obj) {
342
                    if (!empty($partnershipsprocessed[$obj->rowid])) {
343
                        continue;
344
                    }
345
346
                    if ($somethingdoneonpartnership >= $maxpercall) {
347
                        dol_syslog("We reach the limit of " . $maxpercall . " partnership processed, so we quit loop for this batch doWarningOfPartnershipIfDolibarrBacklinkNotfound to avoid to reach email quota.", LOG_WARNING);
348
                        break;
349
                    }
350
351
                    $backlinkfound = 0;
352
353
                    $object = new Partnership($this->db);
354
                    $object->fetch($obj->rowid);
355
356
                    if ($managedfor == 'member') {
357
                        $fk_partner = $object->fk_member;
358
                    } else {
359
                        $fk_partner = $object->fk_soc;
360
                    }
361
362
                    $website = (empty($obj->url_to_check) ? $obj->url : $obj->url_to_check);
363
364
                    if (empty($website)) {
365
                        $websitenotfound .= ($websitenotfound ? ', ' : '') . 'Website not found for id="' . $fk_partner . '"' . "\n";
366
                    } else {
367
                        $backlinkfound = $this->checkDolibarrBacklink($website);
368
                    }
369
370
                    if (!$backlinkfound) {
371
                        $tmpcount = $object->count_last_url_check_error + 1;
372
373
                        $nbminbacklinkerrorforcancel = (int) getDolGlobalString('PARTNERSHIP_MIN_BACKLINK_ERROR_FOR_CANCEL', 3);
374
                        $nbmaxbacklinkerrorforcancel = (int) getDolGlobalString('PARTNERSHIP_MAX_BACKLINK_ERROR_FOR_CANCEL', (int) $nbminbacklinkerrorforcancel + 2);
375
376
                        // If $nbminbacklinkerrorforemail = 0, no autoemail
377
                        if ($nbminbacklinkerrorforcancel > 0) {
378
                            if ($tmpcount > $nbminbacklinkerrorforcancel && $tmpcount <= $nbmaxbacklinkerrorforcancel) { // Send Warning Email
379
                                if (!empty($obj->email)) {
380
                                    $emailnotfound .= ($emailnotfound ? ', ' : '') . 'Email not found for id="' . $fk_partner . '"' . "\n";
381
                                } else {
382
                                    // Example: 'SendingEmailOnPartnershipWillSoonBeCanceled'
383
                                    $labeltemplate = '(' . getDolGlobalString('PARTNERSHIP_SENDMAIL_IF_NO_LINK', 'SendingEmailOnPartnershipWillSoonBeCanceled') . ')';
384
385
                                    dol_syslog("Now we will send an email to partner id=" . $fk_partner . " with label " . $labeltemplate);
386
387
                                    // Send deployment email
388
                                    $formmail = new FormMail($this->db);
389
390
                                    // Define output language
391
                                    $outputlangs = $langs;
392
                                    $newlang = '';
393
                                    if (getDolGlobalInt('MAIN_MULTILANGS') && empty($newlang) && GETPOST('lang_id', 'aZ09')) {
394
                                        $newlang = GETPOST('lang_id', 'aZ09');
395
                                    }
396
                                    if (!empty($newlang)) {
397
                                        $outputlangs = new Translate("", $conf);
398
                                        $outputlangs->setDefaultLang($newlang);
399
                                        $outputlangs->loadLangs(array('main', 'member', 'partnership'));
400
                                    }
401
402
                                    $arraydefaultmessage = $formmail->getEMailTemplate($this->db, 'partnership_send', $user, $outputlangs, 0, 1, $labeltemplate);
403
404
                                    $substitutionarray = getCommonSubstitutionArray($outputlangs, 0, null, $object);
405
                                    complete_substitutions_array($substitutionarray, $outputlangs, $object);
406
407
                                    $subject = make_substitutions($arraydefaultmessage->topic, $substitutionarray, $outputlangs);
408
                                    $msg     = make_substitutions($arraydefaultmessage->content, $substitutionarray, $outputlangs);
409
                                    $from = dol_string_nospecial($conf->global->MAIN_INFO_SOCIETE_NOM, ' ', array(",")) . ' <' . getDolGlobalString('MAIN_INFO_SOCIETE_MAIL') . '>';
410
411
                                    $sendto = $obj->email;
412
413
                                    $trackid = 'par' . $object->id;
414
                                    $sendcontext = 'standard';
415
416
                                    $cmail = new CMailFile($subject, $sendto, $from, $msg, array(), array(), array(), '', '', 0, 1, '', '', $trackid, '', $sendcontext);
417
418
                                    $result = $cmail->sendfile();
419
420
                                    if (!$result || !empty($cmail->error) || !empty($cmail->errors)) {
421
                                        $erroremail .= ($erroremail ? ', ' : '') . $cmail->error;
422
                                        $this->errors[] = $cmail->error;
423
                                        if (is_array($cmail->errors) && count($cmail->errors) > 0) {
424
                                            $this->errors += $cmail->errors;
425
                                        }
426
                                    } else {
427
                                        // Initialisation of datas of object to call trigger
428
                                        if (is_object($object)) {
429
                                            $actiontypecode = 'AC_OTH_AUTO'; // Event insert into agenda automatically
430
                                            $attachedfiles = array();
431
432
                                            if ($managedfor != 'member') {
433
                                                $object->socid = $fk_partner; // To link to a company
434
                                            }
435
                                            $object->actiontypecode = $actiontypecode; // Type of event ('AC_OTH', 'AC_OTH_AUTO', 'AC_XXX'...)
436
                                            $object->actionmsg = $arraydefaultmessage->topic . "\n" . $arraydefaultmessage->content; // Long text
437
                                            $object->actionmsg2 = $langs->transnoentities("PartnershipSentByEMail", $object->ref);
438
                                            ; // Short text ($langs->transnoentities('MailSentByTo')...);
439
                                            if (getDolGlobalString('MAIN_MAIL_REPLACE_EVENT_TITLE_BY_EMAIL_SUBJECT')) {
440
                                                $object->actionmsg2     = $subject; // Short text
441
                                            }
442
443
                                            $object->trackid = $trackid;
0 ignored issues
show
Bug Best Practice introduced by
The property trackid does not exist on Dolibarr\Code\Partnerships\Classes\Partnership. Since you implemented __set, consider adding a @property annotation.
Loading history...
444
                                            $object->fk_element = $object->id;
445
                                            $object->elementtype = $object->element;
0 ignored issues
show
Bug Best Practice introduced by
The property elementtype does not exist on Dolibarr\Code\Partnerships\Classes\Partnership. Since you implemented __set, consider adding a @property annotation.
Loading history...
446
                                            if (is_array($attachedfiles) && count($attachedfiles) > 0) {
447
                                                $object->attachedfiles = $attachedfiles;
0 ignored issues
show
Bug Best Practice introduced by
The property attachedfiles does not exist on Dolibarr\Code\Partnerships\Classes\Partnership. Since you implemented __set, consider adding a @property annotation.
Loading history...
448
                                            }
449
450
                                            $object->email_from = $from;
0 ignored issues
show
Bug Best Practice introduced by
The property email_from does not exist on Dolibarr\Code\Partnerships\Classes\Partnership. Since you implemented __set, consider adding a @property annotation.
Loading history...
451
                                            $object->email_subject = $subject;
0 ignored issues
show
Bug Best Practice introduced by
The property email_subject does not exist on Dolibarr\Code\Partnerships\Classes\Partnership. Since you implemented __set, consider adding a @property annotation.
Loading history...
452
                                            $object->email_to = $sendto;
0 ignored issues
show
Bug Best Practice introduced by
The property email_to does not exist on Dolibarr\Code\Partnerships\Classes\Partnership. Since you implemented __set, consider adding a @property annotation.
Loading history...
453
                                            $object->email_subject = $subject;
454
455
                                            $triggersendname = 'PARTNERSHIP_SENTBYMAIL';
456
                                            // Call of triggers (you should have set $triggersendname to execute trigger)
457
                                            if (!empty($triggersendname)) {
458
                                                $result = $object->call_trigger($triggersendname, $user);
459
                                                if ($result < 0) {
460
                                                    $error++;
461
                                                }
462
                                            }
463
                                            // End call of triggers
464
                                        }
465
                                    }
466
                                }
467
                            } elseif ($tmpcount > $nbmaxbacklinkerrorforcancel) { // Cancel Partnership
468
                                $object->status = $object::STATUS_CANCELED;
469
                                $object->reason_decline_or_cancel = $langs->trans('BacklinkNotFoundOnPartnerWebsite');
470
                            }
471
                        }
472
473
                        $object->count_last_url_check_error = $tmpcount;
474
                    } else {
475
                        $object->count_last_url_check_error = 0;
476
                        $object->reason_decline_or_cancel = '';
477
                    }
478
479
                    $partnershipsprocessed[$object->id] = $object->ref;
480
481
                    $object->last_check_backlink = $now;
482
483
                    $object->update($user);
484
                }
485
            }
486
        } else {
487
            $error++;
488
            $this->error = $this->db->lasterror();
489
        }
490
491
        if (!$error) {
492
            $this->db->commit();
493
            $this->output = "";
494
        } else {
495
            $this->db->rollback();
496
            $this->output = "Rollback after error\n";
497
        }
498
        $this->output .= $numofexpiredmembers . ' partnership checked' . "\n";
499
        if ($erroremail) {
500
            $this->output .= '. Got errors when sending some email : ' . $erroremail . "\n";
501
        }
502
        if ($emailnotfound) {
503
            $this->output .= '. Email not found for some partner : ' . $emailnotfound . "\n";
504
        }
505
        if ($websitenotfound) {
506
            $this->output .= '. Website not found for some partner : ' . $websitenotfound . "\n";
507
        }
508
        $this->output .= "\nSQL used to find partnerships to scan: " . $sql;
509
510
        return ($error ? 1 : 0);
511
    }
512
513
    /**
514
     * Action to check if Dolibarr backlink not found on partner website
515
     *
516
     * @param   string  $website        Partner's website URL
517
     * @return  int                     0 if KO, 1 if OK
518
     */
519
    private function checkDolibarrBacklink($website = null)
520
    {
521
        global $conf;
522
523
        $found      = 0;
524
        $error      = 0;
525
        $webcontent = '';
526
527
        // $website = 'https://nextgestion.com/'; // For Test
528
        $tmpgeturl = getURLContent($website, 'GET', '', 1, array(), array('http', 'https'), 0);
529
        if ($tmpgeturl['curl_error_no']) {
530
            $error++;
531
            dol_syslog('Error getting ' . $website . ': ' . $tmpgeturl['curl_error_msg']);
532
        } elseif ($tmpgeturl['http_code'] != '200') {
533
            $error++;
534
            dol_syslog('Error getting ' . $website . ': ' . $tmpgeturl['curl_error_msg']);
535
        } else {
536
            $urlContent = $tmpgeturl['content'];
537
            $dom = new DOMDocument();
0 ignored issues
show
Bug introduced by
The type Dolibarr\Code\Partnerships\Classes\DOMDocument was not found. Did you mean DOMDocument? If so, make sure to prefix the type with \.
Loading history...
538
            @$dom->loadHTML($urlContent);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition for loadHTML(). This can introduce security issues, and is generally not recommended. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unhandled  annotation

538
            /** @scrutinizer ignore-unhandled */ @$dom->loadHTML($urlContent);

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
539
540
            $xpath = new DOMXPath($dom);
0 ignored issues
show
Bug introduced by
The type Dolibarr\Code\Partnerships\Classes\DOMXPath was not found. Did you mean DOMXPath? If so, make sure to prefix the type with \.
Loading history...
541
            $hrefs = $xpath->evaluate("//a");
542
543
            for ($i = 0; $i < $hrefs->length; $i++) {
544
                $href = $hrefs->item($i);
545
                $url = $href->getAttribute('href');
546
                $url = filter_var($url, FILTER_SANITIZE_URL);
547
                if (!filter_var($url, FILTER_VALIDATE_URL) === false) {
548
                    $webcontent .= $url;
549
                }
550
            }
551
        }
552
553
        if ($webcontent && getDolGlobalString('PARTNERSHIP_BACKLINKS_TO_CHECK') && preg_match('/' . getDolGlobalString('PARTNERSHIP_BACKLINKS_TO_CHECK') . '/', $webcontent)) {
554
            $found = 1;
555
        }
556
557
        return $found;
558
    }
559
}
560