Always do these actions when publishing a page

@param {String} url
@param {String} uri
@param {Object} data
@param {Object} locals
@param {Object} site
@return {Promise}
506311
function publishPageAtUrl(url, uri, data, locals, site) { // eslint-disable-line
  if (data._dynamic) {
    locals.isDynamicPublishUrl = true;
    return data;
  }

  // set the publishUrl for component's model.js files that
  // may want to know about the URL of the page
  locals.publishUrl = url;

  return bluebird.resolve({ url })
    .then(metaObj => storeUrlHistory(metaObj, uri, url))
    .then(metaObj => addRedirects(metaObj, uri))
    .then(metaObj => addToMeta(metaObj, site.assignToMetaOnPublish, uri, data));
}
560160
function( url ) {
        var _this = this,
            callbackName,
            callback,
            readySource,
            options,
            urlParts,
            filename,
            lastDot;


        if( url ) {
            urlParts = url.split( '/' );
            filename = urlParts[ urlParts.length - 1 ];
            lastDot  = filename.lastIndexOf( '.' );
            if ( lastDot > -1 ) {
                urlParts[ urlParts.length - 1 ] = filename.slice( 0, lastDot );
            }
        }

        callback = function( data ){
            if( typeof (data) === "string" ) {
                data = $.parseXml( data );
            }
            var $TileSource = $.TileSource.determineType( _this, data, url );
            if ( !$TileSource ) {
                /**
                 * Raised when an error occurs loading a TileSource.
                 *
                 * @event open-failed
                 * @memberof OpenSeadragon.TileSource
                 * @type {object}
                 * @property {OpenSeadragon.TileSource} eventSource - A reference to the TileSource which raised the event.
                 * @property {String} message
                 * @property {String} source
                 * @property {?Object} userData - Arbitrary subscriber-defined object.
                 */
                _this.raiseEvent( 'open-failed', { message: "Unable to load TileSource", source: url } );
                return;
            }

            options = $TileSource.prototype.configure.apply( _this, [ data, url ]);
            if (options.ajaxWithCredentials === undefined) {
                options.ajaxWithCredentials = _this.ajaxWithCredentials;
            }

            readySource = new $TileSource( options );
            _this.ready = true;
            /**
             * Raised when a TileSource is opened and initialized.
             *
             * @event ready
             * @memberof OpenSeadragon.TileSource
             * @type {object}
             * @property {OpenSeadragon.TileSource} eventSource - A reference to the TileSource which raised the event.
             * @property {Object} tileSource
             * @property {?Object} userData - Arbitrary subscriber-defined object.
             */
            _this.raiseEvent( 'ready', { tileSource: readySource } );
        };

        if( url.match(/\.js$/) ){
            //TODO: Its not very flexible to require tile sources to end jsonp
            //      request for info  with a url that ends with '.js' but for
            //      now it's the only way I see to distinguish uniformly.
            callbackName = url.split('/').pop().replace('.js', '');
            $.jsonp({
                url: url,
                async: false,
                callbackName: callbackName,
                callback: callback
            });
        } else {
            // request info via xhr asynchronously.
            $.makeAjaxRequest( {
                url: url,
                withCredentials: this.ajaxWithCredentials,
                headers: this.ajaxHeaders,
                success: function( xhr ) {
                    var data = processResponse( xhr );
                    callback( data );
                },
                error: function ( xhr, exc ) {
                    var msg;

                    /*
                        IE < 10 will block XHR requests to different origins. Any property access on the request
                        object will raise an exception which we'll attempt to handle by formatting the original
                        exception rather than the second one raised when we try to access xhr.status
                     */
                    try {
                        msg = "HTTP " + xhr.status + " attempting to load TileSource";
                    } catch ( e ) {
                        var formattedExc;
                        if ( typeof ( exc ) == "undefined" || !exc.toString ) {
                            formattedExc = "Unknown error";
                        } else {
                            formattedExc = exc.toString();
                        }

                        msg = formattedExc + " attempting to load TileSource";
                    }

                    /***
                     * Raised when an error occurs loading a TileSource.
                     *
                     * @event open-failed
                     * @memberof OpenSeadragon.TileSource
                     * @type {object}
                     * @property {OpenSeadragon.TileSource} eventSource - A reference to the TileSource which raised the event.
                     * @property {String} message
                     * @property {String} source
                     * @property {?Object} userData - Arbitrary subscriber-defined object.
                     */
                    _this.raiseEvent( 'open-failed', {
                        message: msg,
                        source: url
                    });
                }
            });
        }

    }
1240940
function buildHttpURL(uri) {
    var port     = weinre_port
    var pathname = weinre_pathname

    if (pathname == "/index.html") pathname = "/"

    if (weinre_protocol == "file:") {
        return uri
    }

    else if (weinre_protocol == "http:") {
        if (port != "") port = ":" + port

        return weinre_protocol + "//" + weinre_host + port + pathname + uri
    }

    else if (weinre_protocol == "https:") {
        if (port != "") port = ":" + port

        return weinre_protocol + "//" + weinre_host + port + pathname + uri
    }
}
706634
function put(uri, data, locals) {
  var model = files.getLayoutModules(getLayoutName(uri)),
    callHooks = _.get(locals, 'hooks') !== 'false',
    result;

  if (model && _.isFunction(model.save) && callHooks) {
    result = models.put(model, uri, data, locals);
  } else {
    result = dbOps.putDefaultBehavior(uri, data);
  }

  return result;
}
1296962
function inetChecksite(url, callback) {

  return new Promise((resolve) => {
    process.nextTick(() => {

      let result = {
        url: url,
        ok: false,
        status: 404,
        ms: -1
      };
      if (url) {
        url = url.toLowerCase();
        let t = Date.now();
        if (_linux || _freebsd || _openbsd || _darwin || _sunos) {
          let args = ' -I --connect-timeout 5 -m 5 ' + url + ' 2>/dev/null | head -n 1 | cut -d " " -f2';
          let cmd = 'curl';
          exec(cmd + args, function (error, stdout) {
            let statusCode = parseInt(stdout.toString());
            result.status = statusCode || 404;
            result.ok = !error && (statusCode === 200 || statusCode === 301 || statusCode === 302 || statusCode === 304);
            result.ms = (result.ok ? Date.now() - t : -1);
            if (callback) { callback(result); }
            resolve(result);
          });
        }
        if (_windows) {   // if this is stable, this can be used for all OS types
          const http = (url.startsWith('https:') ? require('https') : require('http'));
          try {
            http.get(url, (res) => {
              const statusCode = res.statusCode;

              result.status = statusCode || 404;
              result.ok = (statusCode === 200 || statusCode === 301 || statusCode === 302 || statusCode === 304);

              if (statusCode !== 200) {
                res.resume();
                result.ms = (result.ok ? Date.now() - t : -1);
                if (callback) { callback(result); }
                resolve(result);
              } else {
                res.on('data', () => { });
                res.on('end', () => {
                  result.ms = (result.ok ? Date.now() - t : -1);
                  if (callback) { callback(result); }
                  resolve(result);
                });
              }
            }).on('error', () => {
              if (callback) { callback(result); }
              resolve(result);
            });
          } catch (err) {
            if (callback) { callback(result); }
            resolve(result);
          }
        }
      } else {
        if (callback) { callback(result); }
        resolve(result);
      }
    });
  });
}
1057388
function xhrJson(method, url, options) {
		if (options && typeof options.data !== 'undefined') {
			options.data = JSON.stringify(options.data);
		}
		return xhr.apply(null, Array.prototype.slice.call(arguments)).then(function(result) {
			return JSON.parse(result.response || null);
		});
	}
1183539
function () {

      // helper method to assert if a given url is local
      function isLocal(url) {
        var loc = document.location,
            reg = new RegExp("^\\.|^\/(?!\/)|^[\\w]((?!://).)*$|" + loc.protocol + "//" + loc.host);
        return url.match(reg);
      }

      // gather all resources
      var scripts = document.getElementsByTagName("script"),
          links = document.getElementsByTagName("link"),
          uris = [];

      // track local js urls
      for (var i = 0; i < scripts.length; i++) {
        var script = scripts[i], src = script.getAttribute("src");
        if (src && isLocal(src))
          uris.push(src);
        if (src && src.match(/\blive.js#/)) {
          for (var type in active)
            active[type] = src.match("[#,|]" + type) != null
          if (src.match("notify")) 
            alert("Live.js is loaded.");
        }
      }
      if (!active.js) uris = [];
      if (active.html) uris.push(document.location.href);

      // track local css urls
      for (var i = 0; i < links.length && active.css; i++) {
        var link = links[i], rel = link.getAttribute("rel"), href = link.getAttribute("href", 2);
        if (href && rel && rel.match(new RegExp("stylesheet", "i")) && isLocal(href)) {
          uris.push(href);
          currentLinkElements[href] = link;
        }
      }

      // initialize the resources info
      for (var i = 0; i < uris.length; i++) {
        var url = uris[i];
        Live.getHead(url, function (url, info) {
          resources[url] = info;
        });
      }

      // add rule for morphing between old and new css files
      var head = document.getElementsByTagName("head")[0],
          style = document.createElement("style"),
          rule = "transition: all .3s ease-out;"
      css = [".livejs-loading * { ", rule, " -webkit-", rule, "-moz-", rule, "-o-", rule, "}"].join('');
      style.setAttribute("type", "text/css");
      head.appendChild(style);
      style.styleSheet ? style.styleSheet.cssText = css : style.appendChild(document.createTextNode(css));

      // yep
      loaded = true;
    }
458857
function request (url) {
  return new Promise((resolve, reject) => {
    const xhr = new XMLHttpRequest()

    xhr.open('GET', url)
    xhr.setRequestHeader('Content-Type', 'application/json')
    xhr.addEventListener('load', _ => {
      try {
        const response = JSON.parse(xhr.response)

        resolve(response)
      } catch (e) {
        reject(e)
      };
    })

    xhr.send(null)
  })
}
193257
function( url, data, noEvents ) {
            var state, href, hash, popstateEvent,
                isPopStateEvent = $.event.special.navigate.isPushStateEnabled();

            // Get the url as it would look squashed on to the current resolution url
            href = path.squash( url );

            // sort out what the hash sould be from the url
            hash = this.hash( url, href );

            // Here we prevent the next hash change or popstate event from doing any
            // history management. In the case of hashchange we don't swallow it
            // if there will be no hashchange fired (since that won't reset the value)
            // and will swallow the following hashchange
            if ( noEvents && hash !== path.stripHash(path.parseLocation().hash) ) {
                this.preventNextHashChange = noEvents;
            }

            // IMPORTANT in the case where popstate is supported the event will be triggered
            //      directly, stopping further execution - ie, interupting the flow of this
            //      method call to fire bindings at this expression. Below the navigate method
            //      there is a binding to catch this event and stop its propagation.
            //
            //      We then trigger a new popstate event on the window with a null state
            //      so that the navigate events can conclude their work properly
            //
            // if the url is a path we want to preserve the query params that are available on
            // the current url.
            this.preventHashAssignPopState = true;
            window.location.hash = hash;

            // If popstate is enabled and the browser triggers `popstate` events when the hash
            // is set (this often happens immediately in browsers like Chrome), then the
            // this flag will be set to false already. If it's a browser that does not trigger
            // a `popstate` on hash assignement or `replaceState` then we need avoid the branch
            // that swallows the event created by the popstate generated by the hash assignment
            // At the time of this writing this happens with Opera 12 and some version of IE
            this.preventHashAssignPopState = false;

            state = $.extend({
                url: href,
                hash: hash,
                title: document.title
            }, data);

            if ( isPopStateEvent ) {
                popstateEvent = new $.Event( "popstate" );
                popstateEvent.originalEvent = {
                    type: "popstate",
                    state: null
                };

                this.squash( url, state );

                // Trigger a new faux popstate event to replace the one that we
                // caught that was triggered by the hash setting above.
                if ( !noEvents ) {
                    this.ignorePopState = true;
                    $.mobile.window.trigger( popstateEvent );
                }
            }

            // record the history entry so that the information can be included
            // in hashchange event driven navigate events in a similar fashion to
            // the state that's provided by popstate
            this.history.add( state.url, state );
        }
1286401
function ajax(url, callback, data) {
  if (data) {
    var reqOptions = typeof url === 'string' ? { uri: url, body: data, json: true } : _extends({}, url, { body: data, json: true });
    _request2.default.post(reqOptions, function (err, res, body) {
      if (err) console.log(err);
      callback(err, body, res);
    });
  } else {
    (0, _request2.default)(url, function (err, res, body) {
      if (err) console.log(err);
      callback(err, body, res);
    });
  }
}
1167627
function redata(params, onUpdate) {
// console.log('redata()', params);
        // If should not reload the data.
        if (!shouldReload(params)) {
console.log('will not reload');
            // Inform any subscriber.
            onUpdate && onUpdate(ctx.lastData);

            // Resolve with last data.
            return Promise.resolve(ctx.lastData);
        }
console.log('will reload');
        // Data not valid, will load new data and subscribe to its updates.
        // Reset lastData, since it is no longer valid.
        ctx.lastData = { ...defaultInitialData };
// debugger;
        // Update any subscriber about new data.
        onUpdate && onUpdate(ctx.lastData);

        // Store promise reference in order to check which is the last one if multiple resolve.
        ctx.promise = load(ctx, loader, params, onUpdate);
// console.log('storing ctx promise', ctx.promise);
ctx.promise.loader = loader;
        return ctx.promise;
    }
575975
function xhr (url, responseType) {
  return new Promise((resolve, reject) => {
    var x = new XMLHttpRequest();

    if (responseType)
      x.responseType = responseType;

    x.open('get', url, true);

    x.onreadystatechange = function() {
      if (x.readyState === 4) { // `DONE`
        if (x.status === 200) {
          resolve(x.responseText);
        } else {
          reject(x.status);
        }
      }
    };
    x.send();
  });
}
9218
public function renderPageByUrl($uri, $url, $locale, $layout = null)
    {
        $page = null;
        if ($viewReference = $this->viewReferenceRepository->getReferenceByUrl($url, $locale)) {
            $page = $this->findPageByReference($viewReference);
            $this->checkPageValidity($page, ['url' => $url, 'locale' => $locale]);
            $page->setReference($viewReference);

            if ($page instanceof BasePage
                && $page->getSeo()
                && $page->getSeo()->getRedirectTo()
                && $page->getSeo()->getRedirectTo()->getLinkType() != Link::TYPE_NONE
                && !$this->session->get('victoire.edit_mode', false)) {
                $link = $page->getSeo()->getRedirectTo();

                return new RedirectResponse($this->container->get('victoire_widget.twig.link_extension')->victoireLinkUrl($link->getParameters()));
            }

            return $this->renderPage($page, $layout);
        } else {
            try {
                /** @var Error404 $error404 */
                $error404 = $this->entityManager->getRepository('VictoireSeoBundle:Error404')->findOneBy(['url' => $uri]);
                /** @var Redirection $redirection */
                $redirection = $this->entityManager->getRepository('VictoireSeoBundle:Redirection')->findOneBy(['url' => $uri]);

                $result = $this->redirectionHandler->handleError($redirection, $error404);

                if ($result instanceof Redirection) {
                    return new RedirectResponse($this->container->get('victoire_widget.twig.link_extension')->victoireLinkUrl(
                        $result->getLink()->getParameters()
                    ), Response::HTTP_MOVED_PERMANENTLY);
                } elseif ($result->getRedirection()) {
                    return new RedirectResponse($this->container->get('victoire_widget.twig.link_extension')->victoireLinkUrl(
                        $result->getRedirection()->getLink()->getParameters()
                    ));
                }
            } catch (NoResultException $e) {
                $error = new Error404();

                $error->setUrl($uri);
                $error->setType($this->redirectionHandler->handleErrorExtension(pathinfo($uri, PATHINFO_EXTENSION)));

                $this->entityManager->persist($error);
                $this->entityManager->flush();
            }

            throw new NotFoundHttpException(sprintf('Page not found (url: "%s", locale: "%s")', $url, $locale));
        }
    }
1245175
function post($url, $data, $callback = null)
    {
        $ret = new CoURLResult($url, $callback, $this->handle);
        $ret->method = self::METHOD_POST;
        $ret->data = $data;
        $this->requests[$ret->id] = $ret;
        return $ret;
    }
318763
function(site, file) {
			if (!site) {
				var d = new Deferred();
				d.resolve(false);
				return d;
			}
			return this.getURLOnSite(site, file).then(function(url) {
				return url !== null;
			});
		}
830615
function (url) {
        var self = this;
        this.searching = true;
        this.loadingError = false;
        return $http.get(url)
          .success(function (res) {
            self.searching = false;
            return res.data;
          })
          .error(function () {
            self.searching = false;
            self.loadingError = true;
            return false;
          });
      }
980834
function resetUriRouteHandlers() {
  /**
   * URIs can point to many different things, and this list will probably grow.
   * @type {[{when: RegExp, html: function, json: function}]}
   */
  uriRoutes = [
    // assume published
    {
      when: /\/_pages\//,
      default: assumePublishedUnlessEditing(renderPage),
      json: assumePublishedUnlessEditing(getDBObject)
    },
    // assume published
    {
      when: /\/_components\//,
      default: assumePublishedUnlessEditing(renderComponent),
      json: assumePublishedUnlessEditing(components.get)
    },
    // uris are not published, they only exist
    {
      when: /\/_uris\//,
      isUri: true,
      html: renderUri,
      json: db.get
    }];
}