WIP: try-catch JavaScript-exceptions in banner-codes
[openx] / jquery.openx.js
1 /*
2  * (C) Copyright 2012 juplo (http://juplo.de/).
3  *
4  * All rights reserved. This program and the accompanying materials
5  * are made available under the terms of the GNU Lesser General Public License
6  * (LGPL) version 3.0 which accompanies this distribution, and is available at
7  * http://www.gnu.org/licenses/lgpl-3.0.html
8  *
9  * This library 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 GNU
12  * Lesser General Public License for more details.
13  *
14  * Contributors:
15  * - Kai Moritz
16  */
17
18 /*
19  * See http://coding.smashingmagazine.com/2011/10/11/essential-jquery-plugin-patterns/
20  * for detailed explanations for the applied best practices.
21  *
22  * The semicolon guides our code for poorly written concatenated scripts.
23  */
24 ;(function( $, window, document, undefined ) {
25
26   var
27
28   settings, _options, domain, id, node,
29
30   count = 0,
31   slots = {},
32   min_width = {},
33   max_width = {},
34   is_pagewidth = {},
35   pagewidth,
36   rendered = {},
37   visible = {},
38   rendering = false,
39   resize_timer,
40   queue = [],
41   output = [];
42
43
44   /*
45    * Configuration-Options for jQuery.openx
46    *
47    * Since the domain-name of the ad-server is the only required parameter,
48    * jQuery.openx for convenience can be configured with only that one
49    * parameter. For example: "jQuery.openx('openx.example.org');". If more
50    * configuration-options are needed, they must be specified as an object.
51    * For example: "jQuery.openx({'server': 'openx.example.org', ... });".
52    *
53    *
54    * Server-Settings:
55    *
56    * server:        string  Name of the server, without protocol or port. For
57    *                        example "openx.example.org". This option is
58    *                        REQUIRED.
59    * protocol:              Optional parameter.
60    *                http:   All connections to the ad-server are made via HTTP.
61    *                https:  All connections to the ad-server are made via HTTPS.
62    *                        If empty, document.location.protocol will be used.
63    * http_port:     number  Port-Number for HTTP-connections to the ad-server
64    *                        (only needed, when it is not the default-value 80).
65    * https_port:            Port-Number for HTTPS-connections to the ad-server
66    *                        (only needed, when it is not the default-value 443).
67    *
68    *
69    * Seldom needed special Server-Settings (these parameters are only needed,
70    * if the default delivery-configration of the OpenX-Server was changed):
71    *
72    * path:          string  Path to delivery-scripts. DEFAULT: "/www/delivery".
73    * fl:            string  Flash-Include-Script. DEFAULT: "fl.js".
74    *
75    *
76    * Delivery-Options (for details and explanations see the see:
77    * http://www.openx.com/docs/2.8/userguide/single%20page%20call):
78    *
79    * block:         1       Don't show the banner again on the same page.
80    *                0       A Banner might be shown multiple times on the same
81    *                        page (DEFAULT).
82    * blockcampaign: 1       Don't show a banner from the same campaign again on
83    *                        the same page.
84    *                0       A Banner from the same campaign might be shown
85    *                        muliple times on the same page (DEFAULT).
86    * target:        string  The value is addes as the HTML TARGET attribute in
87    *                        the ad code. Examples for sensible values: "_blank",
88    *                        "_top".
89    * withtext:      1       Show text below banner. Enter this text in the
90    *                        Banner properties page.
91    *                0       Ignore the text-field from the banner-properties
92                             (DEFAULT).
93    * charset:       string  Charset used, when delivering the banner-codes.
94    *                        If empty, the charset is guessed by OpenX. Examples
95    *                        for sensible values: "UTF-8", "ISO-8859-1".
96    *
97    *
98    * Other settings:
99    *
100    * source:        array   An optional array of JavaScript-Objects, that
101    *                        define prefixes and suffixes, that should be
102    *                        added to source-tag defined in OA_source. Each
103    *                        object can (should) specify the properties "min"
104    *                        and "max". OA_source will only be altered, when
105    *                        min <= page-width <= max is true. If this is the
106    *                        case, the property "prefix" will be prepended to
107    *                        OA_source and the property "suffix" will be
108    *                        appended.
109    * selector:      string  A selector for selecting the DOM-elements, that
110    *                        should display ad-banners. DEFAULT: ".oa".
111    *                        See: http://api.jquery.com/category/selectors/
112    * min_prefix:    string  Prefix for the encoding of the minmal width as
113    *                        CSS-class. DEFAULT: "min_".
114    * max_prefix:    string  Prefix for the encoding of the maximal width as
115    *                        CSS-class. DEFAULT: "max_".
116    * pw_marker:     string  CSS-class, that marks the encoded maximal and minmal
117    *                        width as page width. DEFAULT: "pw".
118    * resize_delay:  number  Number of milliseconds to wait, before a
119    *                        recalculation of the visible ads is scheduled.
120    *                        If the value is choosen to small, a recalculation
121    *                        might be scheduled, while resizing is still in
122    *                        progress. DEFAULT: 500.
123    * debug:         boolean Turn on/off console-debugging. DEFAULT: false.
124    */
125   $.openx = function( options ) {
126
127     if (domain) {
128       if (console.error) {
129         console.error('jQuery.openx was already initialized!');
130         console.log('Configured options: ', _options);
131       }
132       return;
133     }
134
135     /** Enable convenient-configuration */
136     if (typeof(options) == 'string')
137       options = { 'server': options };
138
139     _options = options;
140
141     if (!options.server) {
142       if (console.error) {
143         console.error('Required option "server" is missing!');
144         console.log('options: ', options);
145       }
146       return;
147     }
148
149     settings = $.extend(
150       {
151         'protocol': document.location.protocol,
152         'delivery': '/www/delivery',
153         'fl': 'fl.js',
154         'selector': '.oa',
155         'min_prefix': 'min_',
156         'max_prefix': 'max_',
157         'pw_marker': 'pw',
158         'resize_delay': 500,
159         'debug': false
160       },
161       options
162       );
163
164     domain = settings.protocol + '//';
165     domain += settings.server;
166     if (settings.protocol === 'http:' && settings.http_port)
167       domain += ':' + settings.http_port;
168     if (settings.protocol === 'https:' && settings.https_port)
169       domain += ':' + settings.https_port;
170
171     if (settings.debug && console.debug)
172       console.debug('Ad-Server: ' + domain);
173
174     /**
175      * Without this option, jQuery appends an timestamp to every URL, that
176      * is fetched via $.getScript(). This can mess up badly written
177      * third-party-ad-scripts, that assume that the called URL's are not
178      * altered.
179      */
180     $.ajaxSetup({ 'cache': true });
181
182     /**
183      * jQuery.openx only works with "named zones", because it does not know,
184      * which zones belong to which website. For mor informations about
185      * "named zones" see:
186      * http://www.openx.com/docs/2.8/userguide/single%20page%20call
187      *
188      * For convenience, jQuery.openx only fetches banners, that are really
189      * included in the actual page. This way, you can configure jQuery.openx
190      * with all zones available for your website - for example in a central
191      * template - and does not have to worry about performance penalties due
192      * to unnecessarily fetched banners.
193      */
194     for(name in OA_zones) {
195       $(settings.selector).each(function() {
196         var
197         id,
198         classes,
199         i,
200         min = new RegExp('^' + settings.min_prefix + '([0-9]+)$'),
201         max = new RegExp('^' + settings.max_prefix + '([0-9]+)$'),
202         match;
203         if (this.id === name) {
204           id = 'oa_' + ++count;
205           slots[id] = this;
206           min_width[id] = 0;
207           max_width[id] = Number.MAX_VALUE;
208           is_pagewidth[id] = false;
209           classes = this.className.split(/\s+/);
210           for (i=0; i<classes.length; i++) {
211             match = min.exec(classes[i]);
212             if (match)
213               min_width[id] = +match[1];
214             match = max.exec(classes[i]);
215             if (match)
216               max_width[id] = +match[1];
217             is_pagewidth[id] = classes[i] === settings.pw_marker;
218           }
219           rendered[id] = false;
220           visible[id] = false;
221           if (settings.debug && console.debug)
222             console.debug(
223                 'Slot ' + count + ': ' + this.id
224                 + (is_pagewidth[id] ? ', pagewidth: ' : ', width: ')
225                 + min_width[id]
226                 + (max_width[id] != Number.MAX_VALUE ? '-' + max_width[id] : '')
227                 );
228         }
229       });
230     }
231
232     /** Cleanup data for responsive source-tag's */
233     for (i=0; i<settings.source.length; i++) {
234       if (!settings.source[i].min) settings.source[i].min = 0;
235       if (!settings.source[i].max) settings.source[i].max = Number.MAX_VALUE;
236       if (!settings.source[i].prefix) settings.source[i].prefix = '';
237       if (!settings.source[i].suffix) settings.source[i].suffix = '';
238     }
239
240     /** Add resize-event */
241     $(window).resize(function() {
242       clearTimeout(resize_timer);
243       resize_timer = setTimeout(recalculate_visible , settings.resize_timeout);
244     });
245
246     /** Fetch the JavaScript for Flash and schedule the initial fetch */
247     $.getScript(domain + settings.delivery + '/' + settings.fl, recalculate_visible);
248
249   }
250
251   function recalculate_visible() {
252
253     pagewidth = $(document).width();
254     if (settings.debug && console.debug)
255       console.debug('Scheduling recalculation of visible banners for width ' + pagewidth);
256     if (!rendering)
257       fetch_ads();
258     
259   }
260
261   function fetch_ads() {
262
263     /** Guide rendering-process for early restarts */
264     rendering = true;
265
266     if (settings.debug && console.debug)
267       console.debug('Starting recalculation of visible banners for width ' + pagewidth);
268
269     var
270     name,
271     width,
272     i,
273     source_prefix = '',
274     source_suffix = '',
275     src = domain + settings.delivery + '/spc.php';
276
277     /** Order banners for all zones that were found on the page */
278     src += '?zones=';
279     for(id in slots) {
280       width =
281           is_pagewidth[id]
282           ? pagewidth
283           : Math.round($(slots[id]).parent().width());
284       visible[id] = width >= min_width[id] && width <= max_width[id];
285       if (visible[id]) {
286         if (!rendered[id]) {
287           queue.push(id);
288           src += escape(id + '=' + OA_zones[slots[id].id] + "|");
289           rendered[id] = true;
290           if (settings.debug && console.debug)
291             console.debug('Fetching banner ' + slots[id].id);
292         }
293         else {
294           /** Unhide already fetched visible banners */
295           if (settings.debug && console.debug)
296             console.debug('Unhiding already fetched banner ' + slots[id].id);
297           $(slots[id]).slideDown();
298         }
299       }
300       else {
301         /** Hide unvisible banners */
302         if (settings.debug && console.debug)
303           console.debug('Hiding banner ' + slots[id].id);
304         $(slots[id]).hide();
305       }
306     }
307     src += '&nz=1'; // << We want to fetch named zones!
308
309     /**
310      * These are some additions to the URL of spc.php, that are originally
311      * made in spcjs.php
312      */
313     src += '&r=' + Math.floor(Math.random()*99999999);
314     if (window.location)   src += "&loc=" + escape(window.location);
315     if (document.referrer) src += "&referer=" + escape(document.referrer);
316
317     /** Add the configured options */
318     if (settings.block === 1)
319       src += '&block=1';
320     if (settings.blockcampaign === 1)
321       src += '&blockcampaign=1';
322     if (settings.target)
323       src += '&target=' + settings.target;
324     if (settings.withtext === 1)
325       src += '&withtext=1';
326     if (settings.charset)
327       src += '&charset=' + settings.charset;
328
329     /** Calculate responsive source-tag's */
330     for (i=0; i<settings.source.length; i++) {
331       if (pagewidth >= settings.source[i].min
332           && pagewidth <= settings.source[i].max
333           ) {
334         source_prefix = settings.source[i].prefix + source_prefix;
335         source_suffix = source_suffix + settings.source[i].suffix;
336       }
337     }
338
339     /** Add the source-code - if present */
340     if (typeof OA_source !== 'undefined'
341         || source_prefix != ''
342         || source_suffix != ''
343         ) {
344       if (settings.debug && console.debug)
345         console.debug('OA_source: ' + source_prefix + OA_source + source_suffix);
346       src += "&source=" + escape(source_prefix + OA_source + source_suffix);
347     }
348
349     /** Signal, that this task is done / in progress */
350     pagewidth = undefined;
351
352     /** Fetch data from OpenX and schedule the render-preparation */
353     $.getScript(src, init_ads);
354
355   }
356
357   function init_ads() {
358
359     var i, id, ads = [];
360     for (i=0; i<queue.length; i++) {
361       id = queue[i];
362       if (typeof(OA_output[id]) != 'undefined' && OA_output[id] != '')
363         ads.push(id);
364     }
365     queue = ads;
366
367     document.write = document_write;
368     document.writeln = document_write;
369
370     render_ads();
371
372   }
373
374   function render_ads() {
375
376     while (queue.length > 0) {
377
378       var result, src, inline;
379
380       id = queue.shift();
381       node = $(slots[id]);
382
383       if (settings.debug && console.debug)
384         console.debug('Rendering banner ' + slots[id].id);
385
386       node.slideDown();
387
388       // node.append(id + ": " + node.attr('class'));
389
390       /**
391        * If output was added via document.write(), this output must be
392        * rendered before other banner-code from the OpenX-server is rendered!
393        */
394       insert_output();
395
396       while ((result = /<script/i.exec(OA_output[id])) != null) {
397         node.append(OA_output[id].slice(0,result.index));
398         /** Strip all text before "<script" from OA_output[id] */
399         OA_output[id] = OA_output[id].slice(result.index,OA_output[id].length);
400         result = /^([^>]*)>([\s\S]*?)<\\?\/script>/i.exec(OA_output[id]);
401         if (result == null) {
402           /** Invalid syntax in delivered banner-code: ignoring the rest of this banner-code! */
403           // alert(OA_output[id]);
404           OA_output[id] = "";
405         }
406         else {
407           /** Remember iinline-code, if present */
408           src = result[1] + ' ' // << simplifies the following regular expression: the string ends with a space in any case, so that the src-URL cannot be followed by the end of the string emediately!
409           inline = result[2];
410           /** Strip all text up to and including "</script>" from OA_output[id] */
411           OA_output[id] = OA_output[id].slice(result[0].length,OA_output[id].length);
412           result = /src\s*=\s*['"]?([^'"]*)['"]?\s/i.exec(src);
413           if (result == null) {
414             /** script-tag with inline-code: execute inline-code! */
415             result = /^\s*<.*$/m.exec(inline);
416             if (result != null) {
417               /** Remove leading HTML-comments, because IE will stumble otherwise */
418               inline = inline.slice(result[0].length,inline.length);
419             }
420             try {
421               $.globalEval(inline);
422             }
423             catch(e) {
424               if (console.error)
425                 console.error('Error while executing inline script-code: ' + e.message);
426             }
427             insert_output(); // << The executed inline-code might have called document.write()!
428           }
429           else {
430             /** script-tag with src-URL! */
431             if (OA_output[id].length > 0)
432               /** The banner-code was not rendered completely yet! */
433               queue.unshift(id);
434             /** Load the script and halt all work until the script is loaded and executed... */
435             $.getScript(result[1], render_ads); // << jQuery.getScript() generates onload-Handler for _all_ browsers ;)
436             return;
437           }
438         }
439       }
440
441       node.append(OA_output[id]);
442       OA_output[id] = "";
443     }
444
445     /** All entries from OA_output were rendered */
446
447     id = undefined;
448     node = undefined;
449     rendering = false;
450
451     if (settings.debug && console.debug)
452       console.debug('Recalculation of visible banners done!');
453
454     /** Restart rendering, if new task was queued */
455     if (pagewidth)
456       fetch_ads();
457
458   }
459
460   /** This function is used to overwrite document.write and document.writeln */
461   function document_write() {
462
463     if (id == undefined)
464       return;
465
466     for (var i=0; i<arguments.length; i++)
467       output.push(arguments[i]);
468
469     if (id != queue[0])
470       /**
471        * Re-Add the last banner-code to the working-queue, because included
472        * scripts had added markup via document.write(), which is not
473        * proccessed yet.
474        * Otherwise the added markup would be falsely rendered together with
475        * the markup from the following banner-code.
476        */
477       queue.unshift(id);
478
479   }
480
481   /**
482    * This function prepends the collected output from calls to
483    * document_write() to the current banner-code.
484    */
485   function insert_output() {
486
487     if (output.length > 0) {
488       output.push(OA_output[id]);
489       OA_output[id] = "";
490       for (i=0; i<output.length; i++)
491         OA_output[id] += output[i];
492       output = [];
493     }
494
495   }
496
497 })( jQuery, window, document );
498
499 var OA_output = {}; // << Needed, because IE will complain loudly otherwise!