<?php
/**
 * Newsletter module
 * 
 * Script to send the newsletter to stored emails addresses.
 * Should be called using a cronjob
 * 
 * @package linea21\modules\newsletter
 * @author $Author$ - linea21 <info@linea21.com>
 * @version $Id$ 
 * @access public
 * @license http://opensource.org/licenses/gpl-3.0.html
 */

include_once('../config/define.php');
include_once('../class/class.newsletter.php');
include_once('../newsletter/'.SQL . '.inc.php');
include_once('../languages/' . U_L . '/lang_newsletter.' . CHARSET . '.php');

@set_time_limit(0); // suppression du timeout

// necessary for cron / CLI call
chdir (__DIR__);

// if called from command-line (cron)
// Crontab syntax
// * * * * * /usr/bin/php -q /var/www/linea21/admin/send.php token=mySecretToken
// * * * * * /usr/bin/php /home/simon/www/linea21_dev/admin/cron.php token=6255533e95978ff87c168b71e413frd4
// OR
// * * * * * curl -s http://yourinstall.com/admin/cron.php
// * * * * * /usr/bin/curl http://localhost/linea21_dev/admin/cron.php?token=6255533e95978ff87c168b71e413frd4
if (PHP_SAPI === 'cli') {

	// we get the given token
	parse_str($argv[1], $_GET);
	$source = 'cron_call';

} else {
	$source = $_SERVER["REQUEST_URI"];
}

// we check if the given token is correct
// else we quit
if(!isset($_GET['token']) || $_GET['token'] != SECRET_KEY) die('Invalid token!');


// sélection des newsletters à envoyer
$newsletters = $GLOBALS['sql_object']->DBSelect(SQL_GetNewsletter2Send());

// we follow up, if there is at least one newsletter to send
if(isset($newsletters[0]['newsletter_id'])) {
	
	// récupération des emails
	$emails_batch = $GLOBALS['sql_object']->DBSelect(SQL_GetEmails4Sending());
	
	// we follow up, if there is at least one email address stored in database
	if(isset($emails_batch[0]['emailcol_id'])) {
		
		$newsletter_object = new newsletter;
		
		$path = $newsletter_object->URI_TEMPLATE;
		
		// html
		$template_html = file_get_contents(override($path . '.html'));
		// text
		$template_txt = file_get_contents(override($path . '.txt'));
		logfile(LOG_MAILING, array('[newsletter-start]', 'batch mode', 'calling ' . __FILE__ ));
		require(override("../mail/send_newsletter.php"));
		logfile(LOG_MAILING, array('[newsletter-stop]'));
	}
	
}
?>