~ubuntu-branches/ubuntu/maverick/adblock-plus/maverick-updates

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
/* ***** BEGIN LICENSE BLOCK *****
 * Version: MPL 1.1
 *
 * The contents of this file are subject to the Mozilla Public License Version
 * 1.1 (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 * http://www.mozilla.org/MPL/
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * The Original Code is Adblock Plus.
 *
 * The Initial Developer of the Original Code is
 * Wladimir Palant.
 * Portions created by the Initial Developer are Copyright (C) 2006-2010
 * the Initial Developer. All Rights Reserved.
 *
 * Contributor(s):
 *
 * ***** END LICENSE BLOCK ***** */

let newInstall = true;
let editMode = true;
let autoAdd = false;
let source = null;
let result = null;
let initialized = false;

/**
 * Suppresses window resizing while the window is loading or if the window is loaded in a browser tab.
 * @type Boolean
 */
let suppressResize = true;

let closing = false;
let subscriptionListLoading = false;
let appLocale = "en-US";

let adblockID = "{34274bf4-1d97-a289-e984-17e546307e4f}";
let filtersetG = "filtersetg@updater";

function init()
{
  if (window.arguments  && window.arguments.length)
  {
    // In K-Meleon we might get the arguments wrapped
    for (var i = 0; i < window.arguments.length; i++)
      if (window.arguments[i] && "wrappedJSObject" in window.arguments[i])
        window.arguments[i] = window.arguments[i].wrappedJSObject;

    newInstall = false;
    [source, result] = window.arguments;
    if (window.arguments.length > 2 && window.arguments[2])
      window.hasSubscription = window.arguments[2];
  }

  if (!result)
  {
    result = {};
    autoAdd = true;
  }
  if (!source)
  {
    editMode = false;
    source = {title: "", url: "", disabled: false, external: false, autoDownload: true, mainSubscriptionTitle: null, mainSubscriptionURL: null};
  }
  else
  {
    if (typeof source.mainSubscriptionURL == "undefined")
      source.mainSubscriptionURL = source.mainSubscriptionTitle = null;
  }

  E("description-newInstall").hidden = !newInstall;
  if (newInstall)
    document.documentElement.setAttribute("newInstall", "true");

  E("subscriptionsBox").hidden = E("all-subscriptions-container").hidden
    = E("subscriptionInfo").hidden = editMode;

  E("fromWebText").hidden = !editMode || source instanceof abp.Subscription;
  E("editText").hidden = !(source instanceof abp.Subscription) || source instanceof abp.ExternalSubscription;
  E("externalText").hidden = !(source instanceof abp.ExternalSubscription);
  E("differentSubscription").hidden = !editMode;
  document.documentElement.getButton("extra2").hidden = editMode;

  setCustomSubscription(source.title, source.url,
                        source.mainSubscriptionTitle, source.mainSubscriptionURL);

  if (source instanceof abp.Subscription)
  {
    document.title = document.documentElement.getAttribute("edittitle");
    document.documentElement.getButton("accept").setAttribute("label", document.documentElement.getAttribute("buttonlabelacceptedit"))
  }

  if (source instanceof abp.ExternalSubscription)
  {
    E("location").setAttribute("disabled", "true");
    E("autoDownload").setAttribute("disabled", "true");
    E("autoDownload").checked = true;
  }
  else
    E("autoDownload").checked = source.autoDownload;

  // Find filter subscription suggestion based on user's browser locale
  try
  {
    appLocale = Cc["@mozilla.org/chrome/chrome-registry;1"].getService(Ci.nsIXULChromeRegistry).getSelectedLocale("adblockplus");
  }
  catch (e)
  {
    Cu.reportError(e);
  }

  initialized = true;

  if (!editMode)
  {
    let list = E("subscriptions");
    let items = list.menupopup.childNodes;
    let selectedItem = null;
    let selectedPrefix = null;
    let matchCount = 0;
    for (let i = 0; i < items.length; i++)
    {
      let item = items[i];
      let prefixes = item.getAttribute("_prefixes");
      if (!prefixes)
        continue;
  
      if (!selectedItem)
        selectedItem = item;
  
      let prefix = checkPrefixMatch(prefixes, appLocale);
      if (prefix)
      {
        item.setAttribute("class", "localeMatch");
        if (!selectedPrefix || selectedPrefix.length < prefix.length)
        {
          selectedItem = item;
          selectedPrefix = prefix;
          matchCount = 1;
        }
        else if (selectedPrefix && selectedPrefix.length == prefix.length)
        {
          matchCount++;

          // If multiple items have a matching prefix of the same length:
          // Select one of the items randomly, probability should be the same
          // for all items. So we replace the previous match here with
          // probability 1/N (N being the number of matches).
          if (Math.random() * matchCount < 1)
          {
            selectedItem = item;
            selectedPrefix = prefix;
          }
        }
      }
    }
    list.selectedItem = selectedItem;

    // Warn if Adblock or Filterset.G Updater are installed
    if (isExtensionActive(adblockID))
      E("adblock-warning").hidden = false;
  
    if (isExtensionActive(filtersetG))
      E("filtersetg-warning").hidden = false;
  
    if ("Filterset.G" in filterStorage.knownSubscriptions &&
        !filterStorage.knownSubscriptions["Filterset.G"].disabled)
    {
      E("filtersetg-warning").hidden = false;
    }
  }

  // Only resize if we are a chrome window (not loaded into a browser tab)
  if (window.QueryInterface(Ci.nsIInterfaceRequestor).getInterface(Ci.nsIWebNavigation).QueryInterface(Ci.nsIDocShellTreeItem).itemType == Ci.nsIDocShellTreeItem.typeChrome)
    suppressResize = false;
}

function checkPrefixMatch(prefixes, appLocale)
{
  if (!prefixes)
    return null;

  for each (let prefix in prefixes.split(/,/))
    if (new RegExp("^" + prefix + "\\b").test(appLocale))
      return prefix;

  return null;
}

function collapseElements()
{
  if (!suppressResize && window.windowState == Ci.nsIDOMChromeWindow.STATE_NORMAL)
  {
    let diff = 0;
    for (let i = 0; i < arguments.length; i++)
      diff -= arguments[i].boxObject.height;
    window.resizeBy(0, diff);
    window.moveBy(0, -diff/2);
  }
  for (let i = 0; i < arguments.length; i++)
    arguments[i].hidden = true;
}

function showElements()
{
  for (let i = 0; i < arguments.length; i++)
    arguments[i].hidden = false;

  let scrollBox = E("content-scroll").boxObject;
  if (!suppressResize && window.windowState == Ci.nsIDOMChromeWindow.STATE_NORMAL && scrollBox instanceof Ci.nsIScrollBoxObject)
  {
    // Force reflow
    for (let i = 0; i < arguments.length; i++)
      arguments[i].boxObject.height;

    let scrollHeight = {};
    scrollBox.getScrolledSize({}, scrollHeight);
    if (scrollHeight.value > scrollBox.height)
    {
      let diff = scrollHeight.value - scrollBox.height;
      window.resizeBy(0, diff);
      window.moveBy(0, -diff/2);
    }
  }
}

function onSelectionChange()
{
  if (!initialized)
    return;

  let selectedSubscription = E("subscriptions").value;

  // Show/hide extra UI widgets for custom subscriptions, resize window appropriately
  let container = E("all-subscriptions-container");
  let inputFields = E("differentSubscription");
  if (container.hidden && !selectedSubscription)
    showElements(container, inputFields);
  else if (!container.hidden && selectedSubscription)
    collapseElements(container, inputFields);

  // Make sure to hide "Add different subscription button" if we are already in that mode
  document.documentElement.getButton("extra2").hidden = !selectedSubscription;

  if (!selectedSubscription)
  {
    loadSubscriptionList();
    E("title").focus();
  }

  updateSubscriptionInfo();
}

function updateSubscriptionInfo()
{
  let selectedSubscription = E("subscriptions").selectedItem;
  if (!selectedSubscription.value)
    selectedSubscription = E("all-subscriptions").selectedItem;

  E("subscriptionInfo").setAttribute("invisible", !selectedSubscription);
  if (selectedSubscription)
  {
    let url = selectedSubscription.getAttribute("_url");
    let homePage = selectedSubscription.getAttribute("_homepage")

    let viewLink = E("view-list");
    viewLink.setAttribute("_url", url);
    viewLink.setAttribute("tooltiptext", url);

    let homePageLink = E("visit-homepage");
    homePageLink.hidden = !homePage;
    if (homePage)
    {
      homePageLink.setAttribute("_url", homePage);
      homePageLink.setAttribute("tooltiptext", homePage);
    }
  }
}

function reloadSubscriptionList()
{
  subscriptionListLoading = false;
  loadSubscriptionList();
}

function loadSubscriptionList()
{
  if (subscriptionListLoading)
    return;

  E("all-subscriptions-container").selectedIndex = 0;

  let request = new XMLHttpRequest();
  let errorHandler = function()
  {
    E("all-subscriptions-container").selectedIndex = 2;
  };
  let successHandler = function()
  {
    if (!request.responseXML || request.responseXML.documentElement.localName != "subscriptions")
    {
      errorHandler();
      return;
    }

    try
    {
      processSubscriptionList(request.responseXML);
    }
    catch (e)
    {
      Cu.reportError(e);
      errorHandler();
    }
  };

  request.open("GET", abp.prefs.subscriptions_listurl);
  request.onerror = errorHandler;
  request.onload = successHandler;
  request.send(null);

  subscriptionListLoading = true;
}

function processSubscriptionList(doc)
{
  let list = E("all-subscriptions");
  while (list.firstChild)
    list.removeChild(list.firstChild);

  addSubscriptions(list, doc.documentElement, 0, null, null);
  E("all-subscriptions-container").selectedIndex = 1;
}

function addSubscriptions(list, parent, level, parentTitle, parentURL)
{
  for (let i = 0; i < parent.childNodes.length; i++)
  {
    let node = parent.childNodes[i];
    if (node.nodeType != Node.ELEMENT_NODE || node.localName != "subscription")
      continue;

    if (node.getAttribute("type") != "ads" || node.getAttribute("deprecated") == "true")
      continue;

    let variants = node.getElementsByTagName("variants");
    if (!variants.length || !variants[0].childNodes.length)
      continue;
    variants = variants[0].childNodes;

    let isFirst = true;
    let mainTitle = null;
    let mainURL = null;
    for (let j = 0; j < variants.length; j++)
    {
      let variant = variants[j];
      if (variant.nodeType != Node.ELEMENT_NODE || variant.localName != "variant")
        continue;

      let item = document.createElement("richlistitem");
      item.setAttribute("_title", variant.getAttribute("title"));
      item.setAttribute("_url", variant.getAttribute("url"));
      if (parentTitle && parentURL && variant.getAttribute("complete") != "true")
      {
        item.setAttribute("_supplementForTitle", parentTitle);
        item.setAttribute("_supplementForURL", parentURL);
      }
      item.setAttribute("tooltiptext", variant.getAttribute("url"));
      item.setAttribute("_homepage", node.getAttribute("homepage"));

      let title = document.createElement("description");
      if (isFirst)
      {
        if (checkPrefixMatch(node.getAttribute("prefixes"), appLocale))
          title.setAttribute("class", "title localeMatch");
        else
          title.setAttribute("class", "title");
        title.textContent = node.getAttribute("title");
        mainTitle = variant.getAttribute("title");
        mainURL = variant.getAttribute("url");
        isFirst = false;
      }
      title.setAttribute("flex", "1");
      title.style.marginLeft = (20 * level) + "px";
      item.appendChild(title);
  
      let variantTitle = document.createElement("description");
      variantTitle.setAttribute("class", "variant");
      variantTitle.textContent = variant.getAttribute("title");
      variantTitle.setAttribute("crop", "end");
      item.appendChild(variantTitle);

      list.appendChild(item);
    }

    let supplements = node.getElementsByTagName("supplements");
    if (supplements.length)
      addSubscriptions(list, supplements[0], level + 1, mainTitle, mainURL);
  }
}

function onAllSelectionChange()
{
  let selectedItem = E("all-subscriptions").selectedItem;
  if (!selectedItem)
    return;

  setCustomSubscription(selectedItem.getAttribute("_title"), selectedItem.getAttribute("_url"),
                        selectedItem.getAttribute("_supplementForTitle"), selectedItem.getAttribute("_supplementForURL"));

  updateSubscriptionInfo();
}

function setCustomSubscription(title, url, mainSubscriptionTitle, mainSubscriptionURL)
{
  E("title").value = title;
  E("location").value = url;

  let messageElement = E("supplementMessage");
  let addMainCheckbox = E("addMainSubscription");
  if (mainSubscriptionURL && !hasSubscription(mainSubscriptionURL))
  {
    if (messageElement.hidden)
      showElements(messageElement, addMainCheckbox);

    let beforeLink, afterLink;
    if (/(.*)\?1\?(.*)/.test(messageElement.getAttribute("_textTemplate")))
      [beforeLink, afterLink] = [RegExp.$1, RegExp.$2, RegExp.$3];
    else
      [beforeLink, afterLink] = [messageElement.getAttribute("_textTemplate"), ""];

    while (messageElement.firstChild)
      messageElement.removeChild(messageElement.firstChild);
    messageElement.appendChild(document.createTextNode(beforeLink));
    let link = document.createElement("label");
    link.className = "text-link";
    link.setAttribute("tooltiptext", mainSubscriptionURL);
    link.addEventListener("click", function() abp.loadInBrowser(mainSubscriptionURL), false);
    link.textContent = mainSubscriptionTitle;
    messageElement.appendChild(link);
    messageElement.appendChild(document.createTextNode(afterLink));
    
    addMainCheckbox.value = mainSubscriptionURL;
    addMainCheckbox.setAttribute("_mainSubscriptionTitle", mainSubscriptionTitle)
    addMainCheckbox.label = addMainCheckbox.getAttribute("_labelTemplate").replace(/\?1\?/g, mainSubscriptionTitle);
    addMainCheckbox.accessKey = addMainCheckbox.accessKey;
  }
  else if (!messageElement.hidden)
    collapseElements(messageElement, addMainCheckbox);
}

function selectCustomSubscription()
{
  let list = E("subscriptions")
  list.selectedItem = list.menupopup.lastChild;
}

function validateURL(url)
{
  url = url.replace(/^\s+/, "").replace(/\s+$/, "");

  // Is this a file path?
  try {
    let file = Cc["@mozilla.org/file/local;1"].createInstance(Ci.nsILocalFile);
    file.initWithPath(url);
    return Cc["@mozilla.org/network/io-service;1"].getService(Ci.nsIIOService).newFileURI(file).spec;
  } catch (e) {}

  // Is this a valid URL?
  let uri = abp.makeURL(url);
  if (uri)
    return uri.spec;

  return null;
}

function addSubscription()
{
  let list = E("subscriptions");
  let url;
  let title;
  let autoDownload;
  if (list.value)
  {
    url = list.value;
    title = list.label;
    autoDownload = true;
  }
  else
  {
    url = E("location").value;
    if (!(source instanceof abp.ExternalSubscription))
      url = validateURL(url);
    if (!url)
    {
      abp.alert(window, abp.getString("subscription_invalid_location"));
      E("location").focus();
      return false;
    }

    title = E("title").value.replace(/^\s+/, "").replace(/\s+$/, "");
    if (!title)
      title = url;

    autoDownload = E("autoDownload").checked;
  }

  result.url = url;
  result.title = title;
  result.autoDownload = autoDownload;
  result.disabled = source.disabled;

  let addMainCheckbox = E("addMainSubscription")
  if (!addMainCheckbox.hidden && addMainCheckbox.checked)
  {
    result.mainSubscriptionTitle = addMainCheckbox.getAttribute("_mainSubscriptionTitle");
    result.mainSubscriptionURL = addMainCheckbox.value;
  }

  if (autoAdd)
  {
    abp.addSubscription(result.url, result.title, result.autoDownload, result.disabled);
    if ("mainSubscriptionURL" in result)
      abp.addSubscription(result.mainSubscriptionURL, result.mainSubscriptionTitle, result.autoDownload, result.disabled);
  }

  closing = true;
  return true;
}

function hasSubscription(url)
{
  return abp.filterStorage.subscriptions.some(function(subscription) subscription instanceof abp.DownloadableSubscription && subscription.url == url);
}

function checkUnload()
{
  if (newInstall && !closing)
    return abp.getString("subscription_notAdded_warning");

  return undefined;
}

function onDialogCancel()
{
  let message = checkUnload();
  if (!message)
    return true;

  message += " " + abp.getString("subscription_notAdded_warning_addendum");
  closing = abp.confirm(window, message);
  return closing;
}

function uninstallExtension(id)
{
  let extensionManager = Cc["@mozilla.org/extensions/manager;1"].getService(Ci.nsIExtensionManager);
  if (extensionManager.getItemForID(id))
  {
    let location = extensionManager.getInstallLocation(id);
    if (location && !location.canAccess)
    {
      // Cannot uninstall, need to disable
      extensionManager.disableItem(id);
    }
    else
    {
      extensionManager.uninstallItem(id);
    }
  }
}

function isExtensionActive(id)
{
  if (!("@mozilla.org/extensions/manager;1" in Cc))
    return false;

  let extensionManager = Cc["@mozilla.org/extensions/manager;1"].getService(Ci.nsIExtensionManager);

  // First check whether the extension is installed
  if (!extensionManager.getItemForID(id))
    return false;

  let ds = extensionManager.datasource;
  let rdfService = Cc["@mozilla.org/rdf/rdf-service;1"].getService(Ci.nsIRDFService);
  let source = rdfService.GetResource("urn:mozilla:item:" + id);

  // Check whether extension is disabled
  let link = rdfService.GetResource("http://www.mozilla.org/2004/em-rdf#isDisabled");
  let target = ds.GetTarget(source, link, true);
  if (target instanceof Ci.nsIRDFLiteral && target.Value == "true")
    return false;

  // Check whether an operation is pending for the extension
  link = rdfService.GetResource("http://www.mozilla.org/2004/em-rdf#opType");
  if (ds.GetTarget(source, link, false))
    return false;

  return true;
}

function uninstallAdblock()
{
  uninstallExtension(adblockID);
  E("adblock-warning").hidden = true;
}

function uninstallFiltersetG()
{
  // Disable further updates
  abp.denyFiltersetG = true;

  // Uninstall extension
  uninstallExtension(filtersetG);

  // Remove filter subscription
  if ("Filterset.G" in filterStorage.knownSubscriptions)
    filterStorage.removeSubscription(filterStorage.knownSubscriptions["Filterset.G"]);

  E("filtersetg-warning").hidden = true;
}