Source: IdentifiedVisitor/identifiedvisitor.js

/**
 * @class
 * @classdesc Plugin used to manage identified visitors
 * @name IdentifiedVisitor
 * @memberOf ATInternet.Tracker.Plugins
 * @type {function}
 * @param parent {object} Instance of the Tag used
 * @public
 */
window['ATInternet']['Tracker']['Plugins']['IdentifiedVisitor'] = function (parent) {
    "use strict";
    var self = this;
    // Global configuration, cookie and query values
    var _cookie_textual = null;
    var _cookie_numeric = null;
    var _cookie_category = null;
    var _cookie_vrn = null;
    var _query_textual = '';
    var _query_numeric = '';
    var _cookie_redirect_textual = null;
    var _cookie_redirect_numeric = null;
    var _set_cookie_method = '';
    var _get_cookie_method = '';
    var conf = {};
    // Set specific plugin configuration
    // If global configuration already exists, set only undefined properties
    parent.configPlugin('IdentifiedVisitor', dfltPluginCfg || {}, function (newConf) {
        conf = newConf;
    });
    parent.setConfig('redirectionLifetime', dfltGlobalCfg.redirectionLifetime, true);

    /**
     * Check if current page is a redirection one
     * @memberof ATInternet.Tracker.Plugins.IdentifiedVisitor#
     * @function
     * @return {boolean}
     * @private
     */
    var _isRedirection = function () {
        return !!parent.getConfig('redirect');
    };

    /**
     * Define domain attribution for the numsite
     * @memberof ATInternet.Tracker.Plugins.IdentifiedVisitor#
     * @function
     * @private
     */
    var _setDomainAttribution = function () {
        _set_cookie_method = 'set' + (conf.domainAttribution ? '' : 'Private');
        _get_cookie_method = 'get' + (conf.domainAttribution ? '' : 'Private');
    };

    /**
     * Helper to use the exec method of the plugin manager
     * @memberof ATInternet.Tracker.Plugins.IdentifiedVisitor#
     * @function
     * @param plugin {string} Plugin to use
     * @param method {string} Method to call
     * @param params {Array} Arguments to give
     * @return {*}
     * @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 Utils
     * @memberof ATInternet.Tracker.Plugins.IdentifiedVisitor#
     * @function
     * @param method {string} Method to call
     * @param params {Array} Arguments to give
     * @return {*}
     * @private
     */
    var _pluginUtils = function (method, params) {
        return _pluginCall('Utils', method, params);
    };

    /**
     * Helper to use the plugin Cookies
     * @memberof ATInternet.Tracker.Plugins.IdentifiedVisitor#
     * @function
     * @param method {string} Method to call
     * @param params {Array} Arguments to give
     * @return {*}
     * @private
     */
    var _pluginCookie = function (method, params) {
        var ret = null;
        parent['plugins']['exec']('Cookies', method, params, function (data) {
            ret = data;
        });
        return ret;
    };

    /**
     * Get identified visitor values in the query string
     * @memberof ATInternet.Tracker.Plugins.IdentifiedVisitor#
     * @function
     * @private
     */
    var _getQueryValues = function () {
        var href = _pluginUtils('getLocation', []);
        _query_textual = _pluginUtils('getQueryStringValue', ['xtat', href]);
        _query_numeric = _pluginUtils('getQueryStringValue', ['xtan', href]);
    };

    /**
     * Get identified visitor values in the cookie from a redirection
     * @memberof ATInternet.Tracker.Plugins.IdentifiedVisitor#
     * @function
     * @private
     */
    var _getCookieRedirectValues = function () {
        _cookie_redirect_textual = _pluginCookie(_get_cookie_method, [['atredir', 'at']]);
        _cookie_redirect_numeric = _pluginCookie(_get_cookie_method, [['atredir', 'an']]);
        // Burn after reading
        _pluginCookie('del', [['atredir', 'at']]);
        _pluginCookie('del', [['atredir', 'an']]);
    };

    /**
     * Set identified visitor values in a cookie for redirection
     * @memberof ATInternet.Tracker.Plugins.IdentifiedVisitor#
     * @function
     * @private
     */
    var _setCookieRedirectValues = function () {
        if ((_query_textual || _query_numeric) && _checkCookie('atredir', {
                path: '/',
                end: parent.getConfig('redirectionLifetime')
            })) {
            if (_query_numeric) {
                _pluginCookie(_set_cookie_method, [
                    ['atredir', 'an'],
                    _query_numeric
                ]);
            }
            if (_query_textual) {
                _pluginCookie(_set_cookie_method, [
                    ['atredir', 'at'],
                    _query_textual
                ]);
            }
        }
    };

    /**
     * get identified visitor and new visitor (vrn) values from the persistent cookie
     * @memberof ATInternet.Tracker.Plugins.IdentifiedVisitor#
     * @function
     * @private
     */
    var _getCookieValues = function () {
        _cookie_textual = _pluginCookie(_get_cookie_method, [
            ['atidvisitor', 'at']
        ]);
        _cookie_numeric = _pluginCookie(_get_cookie_method, [
            ['atidvisitor', 'an']
        ]);
        _cookie_category = _pluginCookie(_get_cookie_method, [
            ['atidvisitor', 'ac']
        ]);
        _cookie_vrn = _pluginCookie(_get_cookie_method, [
            ['atidvisitor', 'vrn']
        ]);
    };

    /**
     * Check if a cookie exists with 'object' type, if not, method creates cookie and returns true
     * If exists but with another type, method returns false
     * @memberof ATInternet.Tracker.Plugins.IdentifiedVisitor#
     * @function
     * @param name {string} Name of the cookie
     * @param options {object} Options of the cookie in the case of creation
     * @return boolean {boolean} Returns true if the cookie already exist or has been created, false if any problem
     * @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;
        }
    };

    /**
     * Run the automatic process
     * @memberof ATInternet.Tracker.Plugins.IdentifiedVisitor#
     * @function
     * @private
     */
    var _run = function () {
        _setDomainAttribution(); //commun
        _getQueryValues(); //commun
        if (_isRedirection()) {
            _setCookieRedirectValues(); //redirect
        }
        else {
            _getCookieRedirectValues(); //pas redirect
            _getCookieValues(); //pas redirect
            _setParams(); //pas redirect
            _setVrnValue(); // pas redirect
        }
        parent.emit('IdentifiedVisitor:Ready', {
            lvl: 'INFO',
            details: {
                cookieRedirectTextual: _cookie_redirect_textual,
                cookieRedirectNumeric: _cookie_redirect_numeric,
                cookieTextual: _cookie_textual,
                cookieNumeric: _cookie_numeric,
                cookieCategory: _cookie_category,
                cookieVrn: _cookie_vrn
            }
        });
    };

    /**
     * Set the identified visitor in buffer and cookie
     * @memberof ATInternet.Tracker.Plugins.IdentifiedVisitor#
     * @function
     * @private
     */
    var _setParams = function () {

        //Function used to build object from string value
        var _processValue = function (obj, str) {
            if (/-/.test(str)) {
                obj.category = str.split('-')[0];
                obj.id = str.split('-')[1];
            }
            else {
                obj.id = str;
            }
        };

        //Numeric identifier processing
        var numObj = {category: '', id: ''};
        var numStr = _query_numeric || _cookie_redirect_numeric;
        _processValue(numObj, numStr);

        //Textual identifier processing
        var textObj = {category: '', id: ''};
        var textStr = _query_textual || _cookie_redirect_textual;
        _processValue(textObj, textStr);

        //Set textual identifier
        if (textObj.id) {
            if (textObj.category) {
                _set('ac', textObj.category);
            }
            _set('at', textObj.id);
        }
        else if (_cookie_textual) {
            parent.setParam('at', _cookie_textual, {'hitType': ['all'], permanent: true});
        }

        //Set numeric identifier depending on priority
        if (numObj.id) {
            if (numObj.category) {
                _set('ac', numObj.category);
            }
            _set('an', numObj.id);
        }
        else if (_cookie_numeric) {
            parent.setParam('anc', _cookie_category + '-' + _cookie_numeric, {'hitType': ['all'], permanent: true});
        }
    };

    /**
     * Set new visitor (vrn) in cookie and page context
     * @memberof ATInternet.Tracker.Plugins.IdentifiedVisitor#
     * @function
     * @private
     */
    var _setVrnValue = function () {
        var regVal = '-' +  parent.getConfig('site') + '-';
        var regExp = new RegExp(regVal);
        if(!regExp.test(_cookie_vrn)) {
            _cookie_vrn = (_cookie_vrn||'') + regVal;
            _setCookie('vrn', _cookie_vrn);
            _addPageContext();
        }
    };

    /**
     * Add a new visitor property in the page context
     * @memberof ATInternet.Tracker.Plugins.IdentifiedVisitor#
     * @function
     * @private
     */
    var _addPageContext = function () {
        var contextPageObject = parent['getContext']('page') || {};
        contextPageObject.vrn = 1;
        parent['setContext']('page', contextPageObject);
    };

    /**
     * Check dependencies and launch the automatic process when all dependencies are present
     * @memberof ATInternet.Tracker.Plugins.IdentifiedVisitor#
     * @function
     * @private
     */
    var _init = function () {
        var dependencies = ['Cookies', 'Utils'];
        parent['plugins']['waitForDependencies'](dependencies, _run);
    };

    /**
     * Check/create/write a property in the cookie session (create it if necessary)
     * @memberof ATInternet.Tracker.Plugins.IdentifiedVisitor#
     * @function
     * @param key {string} Property name
     * @param value {string} Value for the property
     * @private
     */
    var _setCookie = function (key, value) {
        if (_checkCookie('atidvisitor', {path: '/', session: conf.lifetime * 24 * 60 * 60})) {
            _pluginCookie(_set_cookie_method, [
                ['atidvisitor', key],
                value
            ]);
        }
    };

    /**
     * Add the key/value to the next hits, and check/create the session cookie to update the property in it
     * @memberof ATInternet.Tracker.Plugins.IdentifiedVisitor#
     * @function
     * @param key {string} Property to set
     * @param value {string} Value to set for the property
     * @private
     */
    var _set = function (key, value) {
        parent.setParam(key, value, {'hitType': ['all'], permanent: true});
        _setCookie(key, value);
    };

    // Launch process
    _init();

    /**
     * [Object added by plugin {@link ATInternet.Tracker.Plugins.IdentifiedVisitor IdentifiedVisitor}] Tags to identify a visitor.
     * @name identifiedVisitor
     * @memberof ATInternet.Tracker.Tag
     * @inner
     * @type {object}
     * @property {function} set Tag helper, see details here {@link ATInternet.Tracker.Tag#identifiedVisitor.set}
     * @property {function} unset Tag helper, see details here {@link ATInternet.Tracker.Tag#identifiedVisitor.unset}
     * @public
     */
    parent['identifiedVisitor'] = {};

    /**
     * [Helper added by plugin {@link ATInternet.Tracker.Plugins.IdentifiedVisitor IdentifiedVisitor}] Set an identified visitor
     * @alias identifiedVisitor.set
     * @memberof! ATInternet.Tracker.Tag#
     * @function
     * @param tagObject {object} 2 properties : id, category
     * @example
     * <pre><code class="javascript">
     *  tag.identifiedVisitor.set({
     *      id:'id123', // or a numeric value, id:123456
     *      category:'123'
     *  });
     *  </code></pre>
     * @public
     */
    parent['identifiedVisitor']['set'] = self['set'] = function(tagObject){
        var identifier = tagObject['id'], category = tagObject['category'];
        if(typeof identifier === 'number') {
            _set('an', identifier.toString());
        }
        else {
            _set('at', identifier);
        }
        if(typeof category !== 'undefined') {
            _set('ac', category);
        }
        /* @if debug */
        parent.debug('IdentifiedVisitor:identifiedVisitor:set', 'DEBUG', 'method ended', tagObject);
        /* @endif */
    };

    /**
     * [Helper added by plugin {@link ATInternet.Tracker.Plugins.IdentifiedVisitor IdentifiedVisitor}] Unset an identified visitor (delete all cookies and parameters from buffer)
     * @alias identifiedVisitor.unset
     * @memberof! ATInternet.Tracker.Tag#
     * @function
     * @public
     */
    parent['identifiedVisitor']['unset'] = self['unset'] = function(){
        var delParams = function(tab, str) {
            for (var i = 0; i < tab.length; i++) {
                parent['exec']('Cookies', 'set', [['atidvisitor', tab[i], {path: '/'}], undefined]);
                parent['delParam'](tab[i]);
            }
            parent['delParam'](str);
        };
        delParams(['an','at','ac'],'anc');
        /* @if debug */
        parent.debug('IdentifiedVisitor:identifiedVisitor:unset', 'DEBUG', 'method ended');
        /* @endif */
    };

    // For unit tests on private elements !!!
    /* @if test */
    self._IDENTIFIEDVISITOR_LIFETIME = conf.lifetime;
    self.getAllParams = function () {
        self._cookie_textual = _cookie_textual;
        self._cookie_numeric = _cookie_numeric;
        self._cookie_category = _cookie_category;
        self._cookie_vrn = _cookie_vrn;
        self._query_textual = _query_textual;
        self._query_numeric = _query_numeric;
        self._cookie_redirect_textual = _cookie_redirect_textual;
        self._cookie_redirect_numeric = _cookie_redirect_numeric;
    };
    self._set_cookie_method = _set_cookie_method;
    self._get_cookie_method = _get_cookie_method;
    self._setDomainAttribution = _setDomainAttribution;
    self._pluginCall = _pluginCall;
    self._pluginUtils = _pluginUtils;
    self._pluginCookie = _pluginCookie;
    self._getQueryValues = _getQueryValues;
    self._getCookieRedirectValues = _getCookieRedirectValues;
    self._setCookieRedirectValues = _setCookieRedirectValues;
    self._getCookieValues = _getCookieValues;
    self._checkCookie = _checkCookie;
    self._run = _run;
    self._setParams = _setParams;
    self._setVrnValue = _setVrnValue;
    self._addPageContext = _addPageContext;
    self._init = _init;
    self._set = _set;
    self._setCookie = _setCookie;
    /* @endif */
};
window['ATInternet']['Tracker']['addPlugin']('IdentifiedVisitor');