dolibarr  19.0.0-dev
partnershiputils.class.php
Go to the documentation of this file.
1 <?php
2 /* Copyright (C) 2021 NextGestion <contact@nextgestion.com>
3  *
4  * This program is free software; you can redistribute it and/or modify
5  * it under the terms of the GNU General Public License as published by
6  * the Free Software Foundation; either version 3 of the License, or
7  * (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program. If not, see <https://www.gnu.org/licenses/>.
16  */
17 
24 //require_once(DOL_DOCUMENT_ROOT."/core/class/commonobject.class.php");
25 //require_once(DOL_DOCUMENT_ROOT."/societe/class/societe.class.php");
26 require_once DOL_DOCUMENT_ROOT.'/comm/action/class/actioncomm.class.php';
27 require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
28 require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
29 require_once DOL_DOCUMENT_ROOT.'/core/lib/geturl.lib.php';
30 require_once DOL_DOCUMENT_ROOT.'/partnership/lib/partnership.lib.php';
31 require_once DOL_DOCUMENT_ROOT.'/partnership/class/partnership.class.php';
32 require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php';
33 require_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent.class.php';
34 
39 {
40  public $db;
41  public $error;
42  public $errors = array();
43 
44  public $output; // To store output of some cron methods
45 
46 
52  public function __construct($db)
53  {
54  $this->db = $db;
55  return 1;
56  }
57 
66  {
67  global $conf, $langs, $user;
68 
69  $managedfor = getDolGlobalString('PARTNERSHIP_IS_MANAGED_FOR', 'thirdparty');
70 
71  if ($managedfor != 'member') {
72  return 0; // If option 'PARTNERSHIP_IS_MANAGED_FOR' = 'thirdparty', this cron job does nothing.
73  }
74 
75  $partnership = new Partnership($this->db);
76  $MAXPERCALL = (empty($conf->global->PARTNERSHIP_MAX_EXPIRATION_CANCEL_PER_CALL) ? 25 : $conf->global->PARTNERSHIP_MAX_EXPIRATION_CANCEL_PER_CALL); // Limit to 25 per call
77 
78  $langs->loadLangs(array("partnership", "member"));
79 
80  $error = 0;
81  $erroremail = '';
82  $this->output = '';
83  $this->error = '';
84  $partnershipsprocessed = array();
85 
86  $gracedelay = $conf->global->PARTNERSHIP_NBDAYS_AFTER_MEMBER_EXPIRATION_BEFORE_CANCEL;
87  if ($gracedelay < 1) {
88  $this->error = 'BadValueForDelayBeforeCancelCheckSetup';
89  return -1;
90  }
91 
92  dol_syslog(get_class($this)."::doCancelStatusOfMemberPartnership cancel expired partnerships with grace delay of ".$gracedelay);
93 
94  $now = dol_now();
95  $datetotest = dol_time_plus_duree($now, -1 * abs($gracedelay), 'd');
96 
97  $this->db->begin();
98 
99  $sql = "SELECT p.rowid, p.fk_member, p.status";
100  $sql .= ", d.datefin, d.fk_adherent_type, dty.subscription";
101  $sql .= " FROM ".MAIN_DB_PREFIX."partnership as p";
102  $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."adherent as d on (d.rowid = p.fk_member)";
103  $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."adherent_type as dty on (dty.rowid = d.fk_adherent_type)";
104  $sql .= " WHERE fk_member > 0";
105  $sql .= " AND (d.datefin < '".$this->db->idate($datetotest)."' AND dty.subscription = 1)";
106  $sql .= " AND p.status = ".((int) $partnership::STATUS_APPROVED); // Only accepted not yet canceled
107  $sql .= $this->db->order('d.rowid', 'ASC');
108  // Limit is managed into loop later
109 
110  $resql = $this->db->query($sql);
111  if ($resql) {
112  $numofexpiredmembers = $this->db->num_rows($resql);
113 
114  $somethingdoneonpartnership = 0;
115  $ifetchpartner = 0;
116  while ($ifetchpartner < $numofexpiredmembers) {
117  $ifetchpartner++;
118 
119  $obj = $this->db->fetch_object($resql);
120  if ($obj) {
121  if (!empty($partnershipsprocessed[$obj->rowid])) continue;
122 
123  if ($somethingdoneonpartnership >= $MAXPERCALL) {
124  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);
125  break;
126  }
127 
128  $object = new Partnership($this->db);
129  $object->fetch($obj->rowid);
130 
131  // Get expiration date
132  $expirationdate = $obj->datefin;
133 
134  if ($expirationdate && $expirationdate < $now) { // If contract expired (we already had a test into main select, this is a security)
135  $somethingdoneonpartnership++;
136 
137  $result = $object->cancel($user, 0);
138  // $conf->global->noapachereload = null;
139  if ($result < 0) {
140  $error++;
141  $this->error = $object->error;
142  if (is_array($object->errors) && count($object->errors)) {
143  if (is_array($this->errors)) $this->errors = array_merge($this->errors, $object->errors);
144  else $this->errors = $object->errors;
145  }
146  } else {
147  $partnershipsprocessed[$object->id] = $object->ref;
148 
149  // Send an email to inform member
150  $labeltemplate = '(SendingEmailOnPartnershipCanceled)';
151 
152  dol_syslog("Now we will send an email to member id=".$object->fk_member." with label ".$labeltemplate);
153 
154  // Send deployment email
155  include_once DOL_DOCUMENT_ROOT.'/core/class/html.formmail.class.php';
156  include_once DOL_DOCUMENT_ROOT.'/core/class/CMailFile.class.php';
157  $formmail = new FormMail($this->db);
158 
159  // Define output language
160  $outputlangs = $langs;
161  $newlang = '';
162  if (getDolGlobalInt('MAIN_MULTILANGS') && empty($newlang) && GETPOST('lang_id', 'aZ09')) $newlang = GETPOST('lang_id', 'aZ09');
163  if (!empty($newlang)) {
164  $outputlangs = new Translate("", $conf);
165  $outputlangs->setDefaultLang($newlang);
166  $outputlangs->loadLangs(array('main', 'member', 'partnership'));
167  }
168 
169  $arraydefaultmessage = $formmail->getEMailTemplate($this->db, 'partnership_send', $user, $outputlangs, 0, 1, $labeltemplate);
170 
171  $substitutionarray = getCommonSubstitutionArray($outputlangs, 0, null, $object);
172  complete_substitutions_array($substitutionarray, $outputlangs, $object);
173 
174  $subject = make_substitutions($arraydefaultmessage->topic, $substitutionarray, $outputlangs);
175  $msg = make_substitutions($arraydefaultmessage->content, $substitutionarray, $outputlangs);
176  $from = dol_string_nospecial($conf->global->MAIN_INFO_SOCIETE_NOM, ' ', array(",")).' <'.$conf->global->MAIN_INFO_SOCIETE_MAIL.'>';
177 
178  $adherent = new Adherent($this->db);
179  $adherent->fetch($object->fk_member);
180  $to = $adherent->email;
181 
182  $cmail = new CMailFile($subject, $to, $from, $msg, array(), array(), array(), '', '', 0, 1);
183  $result = $cmail->sendfile();
184  if (!$result || $cmail->error) {
185  $erroremail .= ($erroremail ? ', ' : '').$cmail->error;
186  $this->errors[] = $cmail->error;
187  if (is_array($cmail->errors) && count($cmail->errors) > 0) $this->errors += $cmail->errors;
188  }
189  }
190  }
191  }
192  }
193  } else {
194  $error++;
195  $this->error = $this->db->lasterror();
196  }
197 
198  if (!$error) {
199  $this->db->commit();
200  $this->output = $numofexpiredmembers.' expired partnership members found'."\n";
201  if ($erroremail) $this->output .= '. Got errors when sending some email : '.$erroremail;
202  } else {
203  $this->db->rollback();
204  $this->output = "Rollback after error\n";
205  $this->output .= $numofexpiredmembers.' expired partnership members found'."\n";
206  if ($erroremail) $this->output .= '. Got errors when sending some email : '.$erroremail;
207  }
208 
209  return ($error ? 1 : 0);
210  }
211 
212 
221  {
222  global $conf, $langs, $user;
223 
224  $managedfor = getDolGlobalString('PARTNERSHIP_IS_MANAGED_FOR');
225 
226  $partnership = new Partnership($this->db);
227  $MAXPERCALL = (empty($conf->global->PARTNERSHIP_MAX_WARNING_BACKLINK_PER_CALL) ? 10 : $conf->global->PARTNERSHIP_MAX_WARNING_BACKLINK_PER_CALL); // Limit to 10 per call
228 
229  $langs->loadLangs(array("partnership", "member"));
230 
231  $error = 0;
232  $erroremail = '';
233  $this->output = '';
234  $this->error = '';
235  $partnershipsprocessed = array();
236 
237  $gracedelay = $conf->global->PARTNERSHIP_NBDAYS_AFTER_MEMBER_EXPIRATION_BEFORE_CANCEL;
238  if ($gracedelay < 1) {
239  $this->error = 'BadValueForDelayBeforeCancelCheckSetup';
240  return -1;
241  }
242 
243  $fk_partner = ($managedfor == 'member') ? 'fk_member' : 'fk_soc';
244 
245  dol_syslog(get_class($this)."::doWarningOfPartnershipIfDolibarrBacklinkNotfound Warning of partnership");
246 
247  $now = dol_now();
248  $datetotest = dol_time_plus_duree($now, -1 * abs($gracedelay), 'd');
249 
250  $this->db->begin();
251 
252  $sql = "SELECT p.rowid, p.status, p.".$fk_partner;
253  $sql .= ", p.last_check_backlink";
254 
255  $sql .= ', partner.url, partner.email';
256 
257  $sql .= " FROM ".MAIN_DB_PREFIX."partnership as p";
258 
259  if ($managedfor == 'member') {
260  $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."adherent as partner on (partner.rowid = p.fk_member)";
261  } else {
262  $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as partner on (partner.rowid = p.fk_soc)";
263  }
264 
265  $sql .= " WHERE 1 = 1";
266  $sql .= " AND p.".$fk_partner." > 0";
267  $sql .= " AND p.status = ".((int) $partnership::STATUS_APPROVED); // Only accepted not yet canceled
268  $sql .= " AND (p.last_check_backlink IS NULL OR p.last_check_backlink <= '".$this->db->idate($now - 7 * 24 * 3600)."')"; // Every week, check that website contains a link to dolibarr.
269  $sql .= $this->db->order('p.rowid', 'ASC');
270  // Limit is managed into loop later
271 
272  $resql = $this->db->query($sql);
273  if ($resql) {
274  $numofexpiredmembers = $this->db->num_rows($resql);
275  $somethingdoneonpartnership = 0;
276  $ifetchpartner = 0;
277  $websitenotfound = '';
278  while ($ifetchpartner < $numofexpiredmembers) {
279  $ifetchpartner++;
280 
281  $obj = $this->db->fetch_object($resql);
282  if ($obj) {
283  if (!empty($partnershipsprocessed[$obj->rowid])) continue;
284 
285  if ($somethingdoneonpartnership >= $MAXPERCALL) {
286  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);
287  break;
288  }
289 
290  $backlinkfound = 0;
291 
292  $object = new Partnership($this->db);
293  $object->fetch($obj->rowid);
294 
295  if ($managedfor == 'member') {
296  $fk_partner = $object->fk_member;
297  } else {
298  $fk_partner = $object->fk_soc;
299  }
300 
301  $website = $obj->url;
302 
303  if (empty($website)) {
304  $websitenotfound .= ($websitenotfound ? ', ' : '').'Website not found for id="'.$fk_partner.'"'."\n";
305  } else {
306  $backlinkfound = $this->checkDolibarrBacklink($website);
307  }
308 
309  if (!$backlinkfound) {
310  $tmpcount = $object->count_last_url_check_error + 1;
311 
312  if ($tmpcount > 2 && $tmpcount <= 4) { // Send Warning Email
313  if (!empty($obj->email)) {
314  $emailnotfound .= ($emailnotfound ? ', ' : '').'Email not found for id="'.$fk_partner.'"'."\n";
315  } else {
316  $labeltemplate = '(SendingEmailOnPartnershipWillSoonBeCanceled)';
317 
318  dol_syslog("Now we will send an email to partner id=".$fk_partner." with label ".$labeltemplate);
319 
320  // Send deployment email
321  include_once DOL_DOCUMENT_ROOT.'/core/class/html.formmail.class.php';
322  include_once DOL_DOCUMENT_ROOT.'/core/class/CMailFile.class.php';
323  $formmail = new FormMail($this->db);
324 
325  // Define output language
326  $outputlangs = $langs;
327  $newlang = '';
328  if (getDolGlobalInt('MAIN_MULTILANGS') && empty($newlang) && GETPOST('lang_id', 'aZ09')) $newlang = GETPOST('lang_id', 'aZ09');
329  if (!empty($newlang)) {
330  $outputlangs = new Translate("", $conf);
331  $outputlangs->setDefaultLang($newlang);
332  $outputlangs->loadLangs(array('main', 'member', 'partnership'));
333  }
334 
335  $arraydefaultmessage = $formmail->getEMailTemplate($this->db, 'partnership_send', $user, $outputlangs, 0, 1, $labeltemplate);
336 
337  $substitutionarray = getCommonSubstitutionArray($outputlangs, 0, null, $object);
338  complete_substitutions_array($substitutionarray, $outputlangs, $object);
339 
340  $subject = make_substitutions($arraydefaultmessage->topic, $substitutionarray, $outputlangs);
341  $msg = make_substitutions($arraydefaultmessage->content, $substitutionarray, $outputlangs);
342  $from = dol_string_nospecial($conf->global->MAIN_INFO_SOCIETE_NOM, ' ', array(",")).' <'.$conf->global->MAIN_INFO_SOCIETE_MAIL.'>';
343 
344  $to = $obj->email;
345 
346  $cmail = new CMailFile($subject, $to, $from, $msg, array(), array(), array(), '', '', 0, 1);
347  $result = $cmail->sendfile();
348  if (!$result || $cmail->error) {
349  $erroremail .= ($erroremail ? ', ' : '').$cmail->error;
350  $this->errors[] = $cmail->error;
351  if (is_array($cmail->errors) && count($cmail->errors) > 0) $this->errors += $cmail->errors;
352  }
353  }
354  } elseif ($tmpcount > 4) { // Cancel Partnership
355  $object->status = $object::STATUS_CANCELED;
356  $object->reason_decline_or_cancel = $langs->trans('BacklinkNotFoundOnPartnerWebsite');
357  }
358 
359  $object->count_last_url_check_error = $tmpcount;
360  } else {
361  $object->count_last_url_check_error = 0;
362  $object->reason_decline_or_cancel = '';
363  }
364 
365  $partnershipsprocessed[$object->id] = $object->ref;
366 
367  $object->last_check_backlink = $this->db->idate($now);
368 
369  $object->update($user);
370  }
371  }
372  } else {
373  $error++;
374  $this->error = $this->db->lasterror();
375  }
376 
377  if (!$error) {
378  $this->db->commit();
379  $this->output = $numofexpiredmembers.' partnership checked'."\n";
380  if ($erroremail) $this->output .= '. Got errors when sending some email : '.$erroremail."\n";
381  if ($emailnotfound) $this->output .= '. Email not found for some partner : '.$emailnotfound."\n";
382  if ($websitenotfound) $this->output .= '. Website not found for some partner : '.$websitenotfound."\n";
383  } else {
384  $this->db->rollback();
385  $this->output = "Rollback after error\n";
386  $this->output .= $numofexpiredmembers.' partnership checked'."\n";
387  if ($erroremail) $this->output .= '. Got errors when sending some email : '.$erroremail."\n";
388  if ($emailnotfound) $this->output .= '. Email not found for some partner : '.$emailnotfound."\n";
389  if ($websitenotfound) $this->output .= '. Website not found for some partner : '.$websitenotfound."\n";
390  }
391 
392  return ($error ? 1 : 0);
393  }
394 
401  private function checkDolibarrBacklink($website = null)
402  {
403  global $conf, $langs, $user;
404 
405  $found = 0;
406  $error = 0;
407  $webcontent = '';
408 
409  // $website = 'https://nextgestion.com/'; // For Test
410  $tmpgeturl = getURLContent($website, 'GET', '', 1, array(), array('http', 'https'), 0);
411  if ($tmpgeturl['curl_error_no']) {
412  $error++;
413  dol_syslog('Error getting '.$website.': '.$tmpgeturl['curl_error_msg']);
414  } elseif ($tmpgeturl['http_code'] != '200') {
415  $error++;
416  dol_syslog('Error getting '.$website.': '.$tmpgeturl['curl_error_msg']);
417  } else {
418  $urlContent = $tmpgeturl['content'];
419  $dom = new DOMDocument();
420  @$dom->loadHTML($urlContent);
421 
422  $xpath = new DOMXPath($dom);
423  $hrefs = $xpath->evaluate("//a");
424 
425  for ($i = 0; $i < $hrefs->length; $i++) {
426  $href = $hrefs->item($i);
427  $url = $href->getAttribute('href');
428  $url = filter_var($url, FILTER_SANITIZE_URL);
429  if (!filter_var($url, FILTER_VALIDATE_URL) === false) {
430  $webcontent .= $url;
431  }
432  }
433  }
434 
435  if ($webcontent && !empty($conf->global->PARTNERSHIP_BACKLINKS_TO_CHECK) && preg_match('/'.$conf->global->PARTNERSHIP_BACKLINKS_TO_CHECK.'/', $webcontent)) {
436  $found = 1;
437  }
438 
439  return $found;
440  }
441 }
Class to manage members of a foundation.
Class to send emails (with attachments or not) Usage: $mailfile = new CMailFile($subject,...
Classe permettant la generation du formulaire html d'envoi de mail unitaire Usage: $formail = new For...
Class for Partnership.
Class with cron tasks of Partnership module.
doWarningOfPartnershipIfDolibarrBacklinkNotfound()
Action executed by scheduler to check if Dolibarr backlink not found on partner website.
$db
To store db handler.
checkDolibarrBacklink($website=null)
Action to check if Dolibarr backlink not found on partner website.
__construct($db)
Constructor.
$errors
To return several error codes (or messages)
$error
To return error code (or message)
doCancelStatusOfMemberPartnership()
Action executed by scheduler to cancel status of partnership when subscription is expired + x days.
Class to manage translations.
if(isModEnabled('facture') && $user->hasRight('facture', 'lire')) if((isModEnabled('fournisseur') &&empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD) && $user->hasRight("fournisseur", "facture", "lire"))||(isModEnabled('supplier_invoice') && $user->hasRight("supplier_invoice", "lire"))) if(isModEnabled('don') && $user->hasRight('don', 'lire')) if(isModEnabled('tax') &&!empty($user->rights->tax->charges->lire)) if(isModEnabled('facture') &&isModEnabled('commande') && $user->hasRight("commande", "lire") &&empty($conf->global->WORKFLOW_DISABLE_CREATE_INVOICE_FROM_ORDER)) $sql
Social contributions to pay.
Definition: index.php:746
dol_time_plus_duree($time, $duration_value, $duration_unit, $ruleforendofmonth=0)
Add a delay to a date.
Definition: date.lib.php:122
dol_string_nospecial($str, $newstr='_', $badcharstoreplace='', $badcharstoremove='', $keepspaces=0)
Clean a string from all punctuation characters to use it as a ref or login.
dol_now($mode='auto')
Return date for now.
getDolGlobalInt($key, $default=0)
Return dolibarr global constant int value.
complete_substitutions_array(&$substitutionarray, $outputlangs, $object=null, $parameters=null, $callfunc="completesubstitutionarray")
Complete the $substitutionarray with more entries coming from external module that had set the "subst...
make_substitutions($text, $substitutionarray, $outputlangs=null, $converttextinhtmlifnecessary=0)
Make substitution into a text string, replacing keys with vals from $substitutionarray (oldval=>newva...
GETPOST($paramname, $check='alphanohtml', $method=0, $filter=null, $options=null, $noreplace=0)
Return value of a param into GET or POST supervariable.
getCommonSubstitutionArray($outputlangs, $onlykey=0, $exclude=null, $object=null, $include=null)
Return array of possible common substitutions.
getDolGlobalString($key, $default='')
Return dolibarr global constant string value.
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.
getURLContent($url, $postorget='GET', $param='', $followlocation=1, $addheaders=array(), $allowedschemes=array('http', 'https'), $localurl=0, $ssl_verifypeer=-1)
Function to get a content from an URL (use proxy if proxy defined).
Definition: geturl.lib.php:41
if(!defined( 'CSRFCHECK_WITH_TOKEN'))