Source: Campaigns/campaigns.js

/**
 * @class
 * @classdesc Plugin used to manage campaigns marketing (which can be the origin of visits)
 * @name Campaigns
 * @memberof ATInternet.Tracker.Plugins
 * @type {function}
 * @param parent {object} Instance of the Tag used
 * @public
 */
window['ATInternet']['Tracker']['Plugins']['Campaigns'] = function (parent) {
    "use strict";

    parent.setConfig('visitLifetime', dfltGlobalCfg.visitLifetime, true);
    parent.setConfig('redirectionLifetime', dfltGlobalCfg.redirectionLifetime, true);
    var confCampaigns = {},
        _set_cookie_method,
        _get_cookie_method;
    parent.configPlugin('Campaigns', dfltPluginCfg || {}, function (newConf) {
        confCampaigns = newConf;
    });

    // Input values
    var _in_atredir_gopc,
        _in_atredir_gopc_err,
        _in_atredir_camp,
        _in_atsession_histo_camp,
        _in_atreman_camp,
        _in_atreman_date,
        _in_url_xtor,
        _in_url_xtdt,
        _in_url_xts,
        _in_tag_forcedCampaign;
    // Context values
    var _isRedirection,
        _isGopc,
        _isGopcErr;

    /**
     * Defines labels to use for unique persistence
     * @memberof ATInternet.Tracker.Plugins.Campaigns#
     * @function
     * @private
     */
    var _defineUniquePersistence = function () {
        _set_cookie_method = 'set' + (confCampaigns.domainAttribution ? '' : 'Private');
        _get_cookie_method = 'get' + (confCampaigns.domainAttribution ? '' : 'Private');
    };

    /**
     * Helper to use the exec method of the plugin manager
     * @memberof ATInternet.Tracker.Plugins.Campaigns#
     * @function
     * @param plugin {string}
     * @param method {string}
     * @param params {Array}
     * @returns {*}
     * @private
     */
    var _pluginCall = function (plugin, method, params) {
        var ret = null;
        parent['plugins']['exec'](plugin, method, params, function (data) {
            ret = data;
        });
        return ret;
    };

    /**
     * Helper to use the plugin Cookies
     * @memberof ATInternet.Tracker.Plugins.Campaigns#
     * @function
     * @param method {string}
     * @param params {Array}
     * @returns {*}
     * @private
     */
    var _pluginCookie = function (method, params) {
        return _pluginCall('Cookies', method, params);
    };

    /**
     * Helper to use the plugin Utils
     * @memberof ATInternet.Tracker.Plugins.Campaigns#
     * @function
     * @param method {string}
     * @param params {Array}
     * @returns {*}
     * @private
     */
    var _pluginUtils = function (method, params) {
        return _pluginCall('Utils', method, params);
    };

    /**
     * Retrieve raw data (in the url, cookies or configuration) for the campaigns processing.
     * @memberof ATInternet.Tracker.Plugins.Campaigns#
     * @function
     * @private
     */
    var _retrieveInputValues = function () {
        // Get redirection cookies
        _in_atredir_gopc = _pluginCookie(_get_cookie_method, [['atredir', 'gopc']]);
        _in_atredir_gopc_err = _pluginCookie(_get_cookie_method, [['atredir', 'gopc_err']]);
        _in_atredir_camp = _pluginCookie(_get_cookie_method, [['atredir', 'camp']]);
        // Burn after reading
        _pluginCookie('del', [['atredir', 'gopc']]);
        _pluginCookie('del', [['atredir', 'gopc_err']]);
        _pluginCookie('del', [['atredir', 'camp']]);
        // Get campaigns historic
        _in_atsession_histo_camp = _pluginCookie(_get_cookie_method, [['atsession', 'histo_camp']]);
        // Get persistent cookies
        _in_atreman_camp = _pluginCookie(_get_cookie_method, [['atreman', 'camp']]);
        _in_atreman_date = _pluginCookie(_get_cookie_method, [['atreman', 'date']]);
        // Get parameters from querystring
        var href = _pluginUtils('getLocation', []);
        _in_url_xtor = _pluginUtils('getQueryStringValue', ['xtor', href]);
        _in_url_xtdt = _pluginUtils('getQueryStringValue', ['xtdt', href]);
        _in_url_xts = _pluginUtils('getQueryStringValue', ['xts', href]);
        // Get forced campaign from context
        _in_tag_forcedCampaign = parent.getContext("forcedCampaign");
    };

    /**
     * Deduct context from raw information : html/javascript redirection, GOPC and GOPC_ERR
     * @memberof ATInternet.Tracker.Plugins.Campaigns#
     * @function
     * @private
     */
    var _processContextValues = function () {
        _isRedirection = !!parent.getConfig('redirect');
        _isGopc = (_in_url_xtor && _in_url_xtdt && _in_url_xts) ? true : false;
        if (_isGopc) {
            var nowInMin = (new Date()).getTime() / 60000;
            _isGopcErr = ((!_isRedirection && (_in_url_xts !== parent['getConfig']('site'))) || (nowInMin - _in_url_xtdt < 0) || (nowInMin - _in_url_xtdt >= parent.getConfig('visitLifetime'))) ? true : false;
        }
    };

    /**
     * Check if a cookie is present and with type object, if not it creates it and return true,
     * if present but with another type it returns false
     * @memberof ATInternet.Tracker.Plugins.Campaigns#
     * @function
     * @param name {string} Name of the cookie you need to check
     * @param options {object} Options of the cookie in the case of creation
     * @returns {*} Returns true if the cookie has been created
     * @private
     */
    var _checkCookie = function (name, options) {
        var temp = _pluginCookie(_get_cookie_method, [name]);
        if (temp !== null) {
            return (typeof temp === 'object' && !(temp instanceof Array));
        }
        else {
            _pluginCookie(_set_cookie_method, [name, {}, options]);
            return true;
        }
    };

    /**
     * Checks if a persistent campaign should be add to the next (page's) hit and do it if necessary
     * @memberof ATInternet.Tracker.Plugins.Campaigns#
     * @function
     * @private
     */
    var _setHitPersistentCampaign = function () {
        if (!_isRedirection && _in_atreman_camp) {
            _setContext('xtor', _in_atreman_camp);
            var currentDate = (new Date()).getTime() / (1000 * 3600);
            var temp = Math.floor(currentDate - _in_atreman_date);
            _setContext('roinbh', (temp >= 0 ? temp : 0));
        }
    };

    /**
     * Transmit campaigns during HTML/Javascript redirection if necessary (config => 'redirect: true')
     * @memberof ATInternet.Tracker.Plugins.Campaigns#
     * @function
     * @private
     */
    var _setRedirectionCampaign = function () {
        var campaign = _in_tag_forcedCampaign || _in_atredir_camp || _in_url_xtor;
        if (_isRedirection && campaign && _checkCookie('atredir', {
                path: '/',
                end: parent.getConfig('redirectionLifetime')
            })) {
            _pluginCookie(_set_cookie_method, [
                ['atredir', 'camp'],
                campaign
            ]);
            _pluginCookie(_set_cookie_method, [
                ['atredir', 'gopc'],
                (_in_tag_forcedCampaign ? false : _in_atredir_camp ? _in_atredir_gopc : _isGopc ? true : false)
            ]);
            _pluginCookie(_set_cookie_method, [
                ['atredir', 'gopc_err'],
                (_in_tag_forcedCampaign ? false : _in_atredir_camp ? _in_atredir_gopc_err : _isGopcErr ? true : false)
            ]);
        }
    };

    /**
     * Stores the campaign which should become the persistent campaign and add it to the historic if necessary
     * @memberof ATInternet.Tracker.Plugins.Campaigns#
     * @function
     * @private
     */
    var _setAtreman = function () {
        if (!_isRedirection) {
            var xto = undefined;
            if (_in_atredir_camp) {
                xto = _in_tag_forcedCampaign || _in_atredir_camp;
            }
            else {
                xto = _in_tag_forcedCampaign || _in_url_xtor || xto;
            }
            if (xto && !(
                    (!_in_tag_forcedCampaign && !_in_atredir_camp && _isGopc && _isGopcErr) ||
                    (!_in_tag_forcedCampaign && _in_atredir_camp && _in_atredir_gopc && _in_atredir_gopc_err)
                )) {
                if ((!_in_atsession_histo_camp || (_in_atsession_histo_camp instanceof Array && _in_atsession_histo_camp.indexOf(xto) < 0)) && _checkCookie('atsession', {
                        path: '/',
                        session: parent.getConfig('visitLifetime') * 60
                    })) {
                    _pluginCookie(_set_cookie_method, [
                        ['atsession', 'histo_camp'],
                        (_in_atsession_histo_camp && _in_atsession_histo_camp.push(xto) ? _in_atsession_histo_camp : [xto])
                    ]);
                }
                if ((!_in_atreman_camp || confCampaigns.lastPersistence) && _checkCookie('atreman', {
                        path: '/',
                        session: (confCampaigns.lifetime * 24 * 60 * 60)
                    })) {
                    _pluginCookie(_set_cookie_method, [
                        ['atreman', 'camp'],
                        xto
                    ]);
                    _pluginCookie(_set_cookie_method, [
                        ['atreman', 'date'],
                        (new Date().getTime() / (3600 * 1000))
                    ]);
                }
            }
        }
    };

    /**
     * Add a new campaign in the next hit (checking which campaign should be used for that -> xtor_url xtoforce atredir_camp)
     * @memberof ATInternet.Tracker.Plugins.Campaigns#
     * @function
     * @private
     */
    var _setXto = function () {
        if (!_isRedirection) {
            var xto = undefined;
            if (_in_atredir_camp) {
                if (_in_atredir_gopc) {
                    xto = _in_tag_forcedCampaign || xto;
                }
                else {
                    xto = _in_tag_forcedCampaign || _in_atredir_camp;
                }
            }
            else if (_isGopc) {
                xto = _in_tag_forcedCampaign || xto;
            }
            else {
                xto = _in_tag_forcedCampaign || _in_url_xtor || xto;
            }
            if (_in_atsession_histo_camp && _in_atsession_histo_camp instanceof Array && _in_atsession_histo_camp.indexOf(xto) > -1) {
                xto = undefined;
            }
            if (xto) {
                _setContext('xto', xto);
            }
        }
    };

    /**
     * Checks if there was an error during a GOPC and add the concerned campaign to the next hit if it's the case
     * @memberof ATInternet.Tracker.Plugins.Campaigns#
     * @function
     * @private
     */
    var _setPgt = function () {
        if (!_isRedirection && !_in_tag_forcedCampaign) {
            var pgt;
            if (_in_atredir_camp) {
                if (_in_atredir_gopc_err) {
                    pgt = _in_atredir_camp;
                }
            }
            else if (_isGopcErr) {
                pgt = _in_url_xtor;
            }
            if (pgt) {
                _setContext('pgt', pgt);
            }
        }
    };

    /**
     * Set a parameter with its value in campaigns context
     * @memberof ATInternet.Tracker.Plugins.Campaigns#
     * @function
     * @param param {string} Name of the parameter to register
     * @param value {string} Value of the parameter to register
     * @private
     */
    var _setContext = function (param, value) {
        var _context = parent.getContext('campaigns') || {};
        _context[param] = value;
        parent.setContext('campaigns', _context);
    };

    /**
     * Launch campaigns automatic processing
     * @memberof ATInternet.Tracker.Plugins.Campaigns#
     * @function
     * @private
     */
    var _run = function (msg) {
        _launchProcess();
        parent.emit('Campaigns:' + msg, {lvl: 'INFO'});
    };

    /**
     * Launch each task to do when automatic processing is triggered
     * @memberof ATInternet.Tracker.Plugins.Campaigns#
     * @function
     * @private
     */
    var _launchProcess = function () {
        _defineUniquePersistence();
        _retrieveInputValues();
        _processContextValues();
        _setRedirectionCampaign();
        _setHitPersistentCampaign();
        _setXto();
        _setPgt();
        _setAtreman();
    };

    /**
     * Init method, check dependencies and launch the campaigns plugin when all dependencies are present
     * @memberof ATInternet.Tracker.Plugins.Campaigns#
     * @function
     * @private
     */
    var _init = function () {
        var dependencies = ['Cookies', 'Utils'];
        if (ATInternet.Utils.arrayIndexOf(parent['getConfig']('plgs'), 'BackwardCompat') === -1) {
            parent['plugins']['waitForDependencies'](dependencies, function () {
                _run('process2:done');
            });
        }
        else {
            // Refresh New Cookies if necessary
            parent.onTrigger('BackCampaigns:process2:done', function (event, data) {
                parent['plugins']['waitForDependencies'](dependencies, function () {
                    _run('process1:done');
                });
            }, true);
        }
    };

    _init();

    // For unit tests on private elements !!!
    /* @if test */
    var self = this;
    self['_init'] = _init;
    self['_retrieveInputValues'] = _retrieveInputValues;
    self['_processContextValues'] = _processContextValues;
    self['_setContext'] = _setContext;
    self['_run'] = _run;
    self['_setHitPersistentCampaign'] = _setHitPersistentCampaign;
    self['_setRedirectionCampaign'] = _setRedirectionCampaign;
    self['_setXto'] = _setXto;
    self['_setPgt'] = _setPgt;
    self['_setAtreman'] = _setAtreman;
    self['_checkCookie'] = _checkCookie;
    self['_VISIT_LIFETIME'] = parent.getConfig('visitLifetime');
    self['_CAMPAIGNS_LIFETIME'] = confCampaigns.lifetime;
    self['_CAMPAIGNS_LAST_PERSISTENCE'] = confCampaigns.lastPersistence;
    self['getThemAll'] = function () {
        self['_in_atredir_gopc'] = _in_atredir_gopc;
        self['_in_atredir_gopc_err'] = _in_atredir_gopc_err;
        self['_in_atredir_camp'] = _in_atredir_camp;
        self['_in_atsession_histo_camp'] = _in_atsession_histo_camp;
        self['_in_atreman_camp'] = _in_atreman_camp;
        self['_in_atreman_date'] = _in_atreman_date;
        self['_in_url_xtor'] = _in_url_xtor;
        self['_in_url_xtdt'] = _in_url_xtdt;
        self['_in_url_xts'] = _in_url_xts;
        self['_in_tag_forcedCampaign'] = _in_tag_forcedCampaign;
        self['_isRedirection'] = _isRedirection;
        self['_isGopc'] = _isGopc;
        self['_isGopcErr'] = _isGopcErr;
    };
    self['setInternalVar'] = function (name, val) {
        if (name === '_in_atredir_gopc') _in_atredir_gopc = val;
        else if (name === '_in_atredir_gopc_err') _in_atredir_gopc_err = val;
        else if (name === '_in_atredir_camp') _in_atredir_camp = val;
        else if (name === '_in_atsession_histo_camp') _in_atsession_histo_camp = val;
        else if (name === '_in_atreman_camp') _in_atreman_camp = val;
        //else if (name === '_in_atreman_date') _in_atreman_date = val;
        else if (name === '_in_url_xtor') _in_url_xtor = val;
        else if (name === '_in_url_xtdt') _in_url_xtdt = val;
        //else if (name === '_in_url_xts') _in_url_xts = val;
        else if (name === '_in_tag_forcedCampaign') _in_tag_forcedCampaign = val;
        //else if (name === '_isRedirection') _isRedirection = val;
        else if (name === '_isGopc') _isGopc = val;
        else if (name === '_isGopcErr') _isGopcErr = val;
    };
    /* @endif */
};

window['ATInternet']['Tracker']['addPlugin']('Campaigns');