partnershiputils.class.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441
  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. /**
  18. * \file partnership/class/partnershiputils.class.php
  19. * \ingroup partnership
  20. * \brief Class with utilities
  21. */
  22. //require_once(DOL_DOCUMENT_ROOT."/core/class/commonobject.class.php");
  23. //require_once(DOL_DOCUMENT_ROOT."/societe/class/societe.class.php");
  24. require_once DOL_DOCUMENT_ROOT.'/comm/action/class/actioncomm.class.php';
  25. require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
  26. require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  27. require_once DOL_DOCUMENT_ROOT.'/core/lib/geturl.lib.php';
  28. require_once DOL_DOCUMENT_ROOT.'/partnership/lib/partnership.lib.php';
  29. require_once DOL_DOCUMENT_ROOT.'/partnership/class/partnership.class.php';
  30. require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php';
  31. require_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent.class.php';
  32. /**
  33. * Class with cron tasks of Partnership module
  34. */
  35. class PartnershipUtils
  36. {
  37. public $db; //!< To store db handler
  38. public $error; //!< To return error code (or message)
  39. public $errors = array(); //!< To return several error codes (or messages)
  40. public $output; // To store output of some cron methods
  41. /**
  42. * Constructor
  43. *
  44. * @param DoliDb $db Database handler
  45. */
  46. public function __construct($db)
  47. {
  48. $this->db = $db;
  49. return 1;
  50. }
  51. /**
  52. * 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)
  53. *
  54. * CAN BE A CRON TASK
  55. *
  56. * @return int 0 if OK, <>0 if KO (this function is used also by cron so only 0 is OK)
  57. */
  58. public function doCancelStatusOfMemberPartnership()
  59. {
  60. global $conf, $langs, $user;
  61. $managedfor = getDolGlobalString('PARTNERSHIP_IS_MANAGED_FOR', 'thirdparty');
  62. if ($managedfor != 'member') {
  63. return 0; // If option 'PARTNERSHIP_IS_MANAGED_FOR' = 'thirdparty', this cron job does nothing.
  64. }
  65. $partnership = new Partnership($this->db);
  66. $MAXPERCALL = (empty($conf->global->PARTNERSHIP_MAX_EXPIRATION_CANCEL_PER_CALL) ? 25 : $conf->global->PARTNERSHIP_MAX_EXPIRATION_CANCEL_PER_CALL); // Limit to 25 per call
  67. $langs->loadLangs(array("partnership", "member"));
  68. $error = 0;
  69. $erroremail = '';
  70. $this->output = '';
  71. $this->error = '';
  72. $partnershipsprocessed = array();
  73. $gracedelay = $conf->global->PARTNERSHIP_NBDAYS_AFTER_MEMBER_EXPIRATION_BEFORE_CANCEL;
  74. if ($gracedelay < 1) {
  75. $this->error = 'BadValueForDelayBeforeCancelCheckSetup';
  76. return -1;
  77. }
  78. dol_syslog(get_class($this)."::doCancelStatusOfMemberPartnership cancel expired partnerships with grace delay of ".$gracedelay);
  79. $now = dol_now();
  80. $datetotest = dol_time_plus_duree($now, -1 * abs($gracedelay), 'd');
  81. $this->db->begin();
  82. $sql = "SELECT p.rowid, p.fk_member, p.status";
  83. $sql .= ", d.datefin, d.fk_adherent_type, dty.subscription";
  84. $sql .= " FROM ".MAIN_DB_PREFIX."partnership as p";
  85. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."adherent as d on (d.rowid = p.fk_member)";
  86. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."adherent_type as dty on (dty.rowid = d.fk_adherent_type)";
  87. $sql .= " WHERE fk_member > 0";
  88. $sql .= " AND (d.datefin < '".$this->db->idate($datetotest)."' AND dty.subscription = 1)";
  89. $sql .= " AND p.status = ".((int) $partnership::STATUS_APPROVED); // Only accepted not yet canceled
  90. $sql .= $this->db->order('d.rowid', 'ASC');
  91. // Limit is managed into loop later
  92. $resql = $this->db->query($sql);
  93. if ($resql) {
  94. $numofexpiredmembers = $this->db->num_rows($resql);
  95. $somethingdoneonpartnership = 0;
  96. $ifetchpartner = 0;
  97. while ($ifetchpartner < $numofexpiredmembers) {
  98. $ifetchpartner++;
  99. $obj = $this->db->fetch_object($resql);
  100. if ($obj) {
  101. if (!empty($partnershipsprocessed[$obj->rowid])) continue;
  102. if ($somethingdoneonpartnership >= $MAXPERCALL) {
  103. 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);
  104. break;
  105. }
  106. $object = new Partnership($this->db);
  107. $object->fetch($obj->rowid);
  108. // Get expiration date
  109. $expirationdate = $obj->datefin;
  110. if ($expirationdate && $expirationdate < $now) { // If contract expired (we already had a test into main select, this is a security)
  111. $somethingdoneonpartnership++;
  112. $result = $object->cancel($user, 0);
  113. // $conf->global->noapachereload = null;
  114. if ($result < 0) {
  115. $error++;
  116. $this->error = $object->error;
  117. if (is_array($object->errors) && count($object->errors)) {
  118. if (is_array($this->errors)) $this->errors = array_merge($this->errors, $object->errors);
  119. else $this->errors = $object->errors;
  120. }
  121. } else {
  122. $partnershipsprocessed[$object->id] = $object->ref;
  123. // Send an email to inform member
  124. $labeltemplate = '(SendingEmailOnPartnershipCanceled)';
  125. dol_syslog("Now we will send an email to member id=".$object->fk_member." with label ".$labeltemplate);
  126. // Send deployment email
  127. include_once DOL_DOCUMENT_ROOT.'/core/class/html.formmail.class.php';
  128. include_once DOL_DOCUMENT_ROOT.'/core/class/CMailFile.class.php';
  129. $formmail = new FormMail($this->db);
  130. // Define output language
  131. $outputlangs = $langs;
  132. $newlang = '';
  133. if (getDolGlobalInt('MAIN_MULTILANGS') && empty($newlang) && GETPOST('lang_id', 'aZ09')) $newlang = GETPOST('lang_id', 'aZ09');
  134. if (!empty($newlang)) {
  135. $outputlangs = new Translate("", $conf);
  136. $outputlangs->setDefaultLang($newlang);
  137. $outputlangs->loadLangs(array('main', 'member', 'partnership'));
  138. }
  139. $arraydefaultmessage = $formmail->getEMailTemplate($this->db, 'partnership_send', $user, $outputlangs, 0, 1, $labeltemplate);
  140. $substitutionarray = getCommonSubstitutionArray($outputlangs, 0, null, $object);
  141. complete_substitutions_array($substitutionarray, $outputlangs, $object);
  142. $subject = make_substitutions($arraydefaultmessage->topic, $substitutionarray, $outputlangs);
  143. $msg = make_substitutions($arraydefaultmessage->content, $substitutionarray, $outputlangs);
  144. $from = dol_string_nospecial($conf->global->MAIN_INFO_SOCIETE_NOM, ' ', array(",")).' <'.$conf->global->MAIN_INFO_SOCIETE_MAIL.'>';
  145. $adherent = new Adherent($this->db);
  146. $adherent->fetch($object->fk_member);
  147. $to = $adherent->email;
  148. $cmail = new CMailFile($subject, $to, $from, $msg, array(), array(), array(), '', '', 0, 1);
  149. $result = $cmail->sendfile();
  150. if (!$result || $cmail->error) {
  151. $erroremail .= ($erroremail ? ', ' : '').$cmail->error;
  152. $this->errors[] = $cmail->error;
  153. if (is_array($cmail->errors) && count($cmail->errors) > 0) $this->errors += $cmail->errors;
  154. }
  155. }
  156. }
  157. }
  158. }
  159. } else {
  160. $error++;
  161. $this->error = $this->db->lasterror();
  162. }
  163. if (!$error) {
  164. $this->db->commit();
  165. $this->output = $numofexpiredmembers.' expired partnership members found'."\n";
  166. if ($erroremail) $this->output .= '. Got errors when sending some email : '.$erroremail;
  167. } else {
  168. $this->db->rollback();
  169. $this->output = "Rollback after error\n";
  170. $this->output .= $numofexpiredmembers.' expired partnership members found'."\n";
  171. if ($erroremail) $this->output .= '. Got errors when sending some email : '.$erroremail;
  172. }
  173. return ($error ? 1 : 0);
  174. }
  175. /**
  176. * 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)
  177. *
  178. * CAN BE A CRON TASK
  179. *
  180. * @return int 0 if OK, <>0 if KO (this function is used also by cron so only 0 is OK)
  181. */
  182. public function doWarningOfPartnershipIfDolibarrBacklinkNotfound()
  183. {
  184. global $conf, $langs, $user;
  185. $managedfor = getDolGlobalString('PARTNERSHIP_IS_MANAGED_FOR');
  186. $partnership = new Partnership($this->db);
  187. $MAXPERCALL = (empty($conf->global->PARTNERSHIP_MAX_WARNING_BACKLINK_PER_CALL) ? 10 : $conf->global->PARTNERSHIP_MAX_WARNING_BACKLINK_PER_CALL); // Limit to 10 per call
  188. $langs->loadLangs(array("partnership", "member"));
  189. $error = 0;
  190. $erroremail = '';
  191. $this->output = '';
  192. $this->error = '';
  193. $partnershipsprocessed = array();
  194. $gracedelay = $conf->global->PARTNERSHIP_NBDAYS_AFTER_MEMBER_EXPIRATION_BEFORE_CANCEL;
  195. if ($gracedelay < 1) {
  196. $this->error = 'BadValueForDelayBeforeCancelCheckSetup';
  197. return -1;
  198. }
  199. $fk_partner = ($managedfor == 'member') ? 'fk_member' : 'fk_soc';
  200. dol_syslog(get_class($this)."::doWarningOfPartnershipIfDolibarrBacklinkNotfound Warning of partnership");
  201. $now = dol_now();
  202. $datetotest = dol_time_plus_duree($now, -1 * abs($gracedelay), 'd');
  203. $this->db->begin();
  204. $sql = "SELECT p.rowid, p.status, p.".$fk_partner;
  205. $sql .= ", p.last_check_backlink";
  206. $sql .= ', partner.url, partner.email';
  207. $sql .= " FROM ".MAIN_DB_PREFIX."partnership as p";
  208. if ($managedfor == 'member') {
  209. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."adherent as partner on (partner.rowid = p.fk_member)";
  210. } else {
  211. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as partner on (partner.rowid = p.fk_soc)";
  212. }
  213. $sql .= " WHERE 1 = 1";
  214. $sql .= " AND p.".$fk_partner." > 0";
  215. $sql .= " AND p.status = ".((int) $partnership::STATUS_APPROVED); // Only accepted not yet canceled
  216. $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.
  217. $sql .= $this->db->order('p.rowid', 'ASC');
  218. // Limit is managed into loop later
  219. $resql = $this->db->query($sql);
  220. if ($resql) {
  221. $numofexpiredmembers = $this->db->num_rows($resql);
  222. $somethingdoneonpartnership = 0;
  223. $ifetchpartner = 0;
  224. $websitenotfound = '';
  225. while ($ifetchpartner < $numofexpiredmembers) {
  226. $ifetchpartner++;
  227. $obj = $this->db->fetch_object($resql);
  228. if ($obj) {
  229. if (!empty($partnershipsprocessed[$obj->rowid])) continue;
  230. if ($somethingdoneonpartnership >= $MAXPERCALL) {
  231. 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);
  232. break;
  233. }
  234. $backlinkfound = 0;
  235. $object = new Partnership($this->db);
  236. $object->fetch($obj->rowid);
  237. if ($managedfor == 'member') {
  238. $fk_partner = $object->fk_member;
  239. } else {
  240. $fk_partner = $object->fk_soc;
  241. }
  242. $website = $obj->url;
  243. if (empty($website)) {
  244. $websitenotfound .= ($websitenotfound ? ', ' : '').'Website not found for id="'.$fk_partner.'"'."\n";
  245. } else {
  246. $backlinkfound = $this->checkDolibarrBacklink($website);
  247. }
  248. if (!$backlinkfound) {
  249. $tmpcount = $object->count_last_url_check_error + 1;
  250. if ($tmpcount > 2 && $tmpcount <= 4) { // Send Warning Email
  251. if (!empty($obj->email)) {
  252. $emailnotfound .= ($emailnotfound ? ', ' : '').'Email not found for id="'.$fk_partner.'"'."\n";
  253. } else {
  254. $labeltemplate = '(SendingEmailOnPartnershipWillSoonBeCanceled)';
  255. dol_syslog("Now we will send an email to partner id=".$fk_partner." with label ".$labeltemplate);
  256. // Send deployment email
  257. include_once DOL_DOCUMENT_ROOT.'/core/class/html.formmail.class.php';
  258. include_once DOL_DOCUMENT_ROOT.'/core/class/CMailFile.class.php';
  259. $formmail = new FormMail($this->db);
  260. // Define output language
  261. $outputlangs = $langs;
  262. $newlang = '';
  263. if (getDolGlobalInt('MAIN_MULTILANGS') && empty($newlang) && GETPOST('lang_id', 'aZ09')) $newlang = GETPOST('lang_id', 'aZ09');
  264. if (!empty($newlang)) {
  265. $outputlangs = new Translate("", $conf);
  266. $outputlangs->setDefaultLang($newlang);
  267. $outputlangs->loadLangs(array('main', 'member', 'partnership'));
  268. }
  269. $arraydefaultmessage = $formmail->getEMailTemplate($this->db, 'partnership_send', $user, $outputlangs, 0, 1, $labeltemplate);
  270. $substitutionarray = getCommonSubstitutionArray($outputlangs, 0, null, $object);
  271. complete_substitutions_array($substitutionarray, $outputlangs, $object);
  272. $subject = make_substitutions($arraydefaultmessage->topic, $substitutionarray, $outputlangs);
  273. $msg = make_substitutions($arraydefaultmessage->content, $substitutionarray, $outputlangs);
  274. $from = dol_string_nospecial($conf->global->MAIN_INFO_SOCIETE_NOM, ' ', array(",")).' <'.$conf->global->MAIN_INFO_SOCIETE_MAIL.'>';
  275. $to = $obj->email;
  276. $cmail = new CMailFile($subject, $to, $from, $msg, array(), array(), array(), '', '', 0, 1);
  277. $result = $cmail->sendfile();
  278. if (!$result || $cmail->error) {
  279. $erroremail .= ($erroremail ? ', ' : '').$cmail->error;
  280. $this->errors[] = $cmail->error;
  281. if (is_array($cmail->errors) && count($cmail->errors) > 0) $this->errors += $cmail->errors;
  282. }
  283. }
  284. } elseif ($tmpcount > 4) { // Cancel Partnership
  285. $object->status = $object::STATUS_CANCELED;
  286. $object->reason_decline_or_cancel = $langs->trans('BacklinkNotFoundOnPartnerWebsite');
  287. }
  288. $object->count_last_url_check_error = $tmpcount;
  289. } else {
  290. $object->count_last_url_check_error = 0;
  291. $object->reason_decline_or_cancel = '';
  292. }
  293. $partnershipsprocessed[$object->id] = $object->ref;
  294. $object->last_check_backlink = $this->db->idate($now);
  295. $object->update($user);
  296. }
  297. }
  298. } else {
  299. $error++;
  300. $this->error = $this->db->lasterror();
  301. }
  302. if (!$error) {
  303. $this->db->commit();
  304. $this->output = $numofexpiredmembers.' partnership checked'."\n";
  305. if ($erroremail) $this->output .= '. Got errors when sending some email : '.$erroremail."\n";
  306. if ($emailnotfound) $this->output .= '. Email not found for some partner : '.$emailnotfound."\n";
  307. if ($websitenotfound) $this->output .= '. Website not found for some partner : '.$websitenotfound."\n";
  308. } else {
  309. $this->db->rollback();
  310. $this->output = "Rollback after error\n";
  311. $this->output .= $numofexpiredmembers.' partnership checked'."\n";
  312. if ($erroremail) $this->output .= '. Got errors when sending some email : '.$erroremail."\n";
  313. if ($emailnotfound) $this->output .= '. Email not found for some partner : '.$emailnotfound."\n";
  314. if ($websitenotfound) $this->output .= '. Website not found for some partner : '.$websitenotfound."\n";
  315. }
  316. return ($error ? 1 : 0);
  317. }
  318. /**
  319. * Action to check if Dolibarr backlink not found on partner website
  320. *
  321. * @param $website Website Partner's website
  322. * @return int 0 if KO, 1 if OK
  323. */
  324. private function checkDolibarrBacklink($website = null)
  325. {
  326. global $conf, $langs, $user;
  327. $found = 0;
  328. $error = 0;
  329. $webcontent = '';
  330. // $website = 'https://nextgestion.com/'; // For Test
  331. $tmpgeturl = getURLContent($website, 'GET', '', 1, array(), array('http', 'https'), 0);
  332. if ($tmpgeturl['curl_error_no']) {
  333. $error++;
  334. dol_syslog('Error getting '.$website.': '.$tmpgeturl['curl_error_msg']);
  335. } elseif ($tmpgeturl['http_code'] != '200') {
  336. $error++;
  337. dol_syslog('Error getting '.$website.': '.$tmpgeturl['curl_error_msg']);
  338. } else {
  339. $urlContent = $tmpgeturl['content'];
  340. $dom = new DOMDocument();
  341. @$dom->loadHTML($urlContent);
  342. $xpath = new DOMXPath($dom);
  343. $hrefs = $xpath->evaluate("//a");
  344. for ($i = 0; $i < $hrefs->length; $i++) {
  345. $href = $hrefs->item($i);
  346. $url = $href->getAttribute('href');
  347. $url = filter_var($url, FILTER_SANITIZE_URL);
  348. if (!filter_var($url, FILTER_VALIDATE_URL) === false) {
  349. $webcontent .= $url;
  350. }
  351. }
  352. }
  353. if ($webcontent && !empty($conf->global->PARTNERSHIP_BACKLINKS_TO_CHECK) && preg_match('/'.$conf->global->PARTNERSHIP_BACKLINKS_TO_CHECK.'/', $webcontent)) {
  354. $found = 1;
  355. }
  356. return $found;
  357. }
  358. }