Page callback
Entry point for all AJAX requests
426049
public function responseAjax()
    {
        if (!$this->isAjax()) {
            $this->response->outputError403();
        }

        $action = $this->getPosted('action');

        if (empty($action)) {
            $this->outputJson(array('error' => $this->text('Unknown action')));
        }

        $this->outputJson(call_user_func(array($this, $action)));
    }
372227
function pageLoadLoop() {
        var index;
        clearTimeout(pageLoadTID);
        if (pageLoadQueue.length > 0) {
            // found a page to load
            index = pageLoadQueue.shift();
            // page exists and not reached max errors?
            if (pages[index]) {
                api.loadPage(index, function loadPageCallback(pageIsLoading) {
                    if (pageIsLoading === false) {
                        // don't wait if the page is not loading
                        pageLoadLoop();
                    } else {
                        pageLoadTID = setTimeout(pageLoadLoop, PAGE_LOAD_INTERVAL);
                    }
                });
            } else {
                pageLoadLoop();
            }
        } else {
            stopPageLoadLoop();
        }
    }
153585
function jsonp(req) {
    var sUrl = req.url,
        inData = req.data,
        callback = req.callback;
    if (!sUrl || typeof sUrl != 'string') throw new Error('invalid URL');
    if (inData && (typeof inData === 'undefined' ? 'undefined' : _typeof(inData)) != 'object') throw new Error('invalid input argument (data)');
    if (typeof callback != 'function') throw new Error('input argument (callback) should be a function');

    var id = newJsonPid_();
    if (sUrl.indexOf('?') > 0) sUrl += '&';else sUrl += '?';
    sUrl += 'callback=TRIGGER__%5B' + id + '%5D'; // encodeURIComponent('[' + id + ']')

    if (inData) {
      Object.keys(inData).forEach(function (sKey) {
        var item = inData[sKey];
        sUrl += '&' + sKey + '=' + encodeURIComponent(item + '');
      });
    }

    var head = document.head || document.getElementsByTagName('head')[0] || document.documentElement;
    var script = document.createElement('script');
    script.async = 'async';
    if (req.scriptCharset) script.charset = req.scriptCharset;
    script.src = sUrl;
    script.onload = script.onreadystatechange = function () {
      if (!script.readyState || /loaded|complete/.test(script.readyState)) {
        script.onload = script.onreadystatechange = null; // handle memory leak in IE
        if (head && script.parentNode) // remove the script node
          head.removeChild(script);

        script = undefined; // dereference the script
        setTimeout(function () {
          var fn = window.TRIGGER__[id];
          if (fn) {
            delete window.TRIGGER__[id];
            if (req.notifyError) callback(null); // null means failed, fn not removed in TRIGGER__[id]() yet
          }
        }, 0);
      }
    };
    head.insertBefore(script, head.firstChild);

    window.TRIGGER__[id] = function (json) {
      var fn = window.TRIGGER__[id];
      if (fn) {
        delete window.TRIGGER__[id]; // unregist callback: TRIGGER__[xxx]
        callback(json);
      }
    };
  }
1255132
function startModulesAfterPageLoad( lo ) {
  // header hooks
  if ( ( lo != null ) && ( lo.header != null ) && ( lo.header.modules != null ) ) {
    for ( var i = 0; i < lo.header.modules.length; i++ ) {
      startModuleAfterPageLoad( lo.header.modules[i] );
    }
  }
  // footer hooks
  if ( ( lo != null ) && ( lo.footer != null ) && ( lo.footer.modules != null ) ) {
    for ( var i = 0; i < lo.footer.modules.length; i++ ) {
      startModuleAfterPageLoad( lo.footer.modules[i] );
    }
  }
  ajaxOngoing--;
}
31366
function ( callback ) {
					self.api.call( _.extend( params, continueParams ), function ( err, data, next ) {
						if ( err ) {
							callback( err );
						} else {
							// append batch data
							const batchData = ( typeof key === 'function' ) ? key( data ) : data[ key ];

							res = res.concat( batchData );

							// more pages?
							continueParams = next;
							callback( next ? null : true );
						}
					} );
				}
1147734
function(callback) {
      var t = this,
          dirs = [],
          pages = [],
          thisAppName = UI.Server.currentServer.thisAppName;
      callback = callback || function(){};

      // Synchronize the virtual /app directory
      if (t.get('path') === '/app') {
        for (var appName in UI.Server.currentServer.apps) {
          // Don't add me to the /app directory if I'm an app
          if (appName !== thisAppName) {
            var app = UI.Server.currentServer.apps[appName];
            dirs.push({
              id: appName,
              label: app.label || app.description || appName,
              path: Path.join(app.moduleDir, 'site_db', t.CONST.objectClass)
            });
          }
        }

        // Trim directory branches that have no contents
        t.trimDirs(dirs, function(error, trimmed) {
          if (error) {
            callback(error);
          }
          t.set({
            leaves: pages,
            branches: trimmed
          });
          return callback();
        });
        return;
      }

      // Get the directory at this level
      FS.readdir(t.dirPath, function(error, fileNames) {

        // Process errors
        if (error) {
          console.error('TreeProbe readdir error', error);
          return callback(error);
        }

        // Don't show the main 404 page (it's too confusing)
        if (t.CONST.objectClass === 'Page') {
          fileNames = _.reject(fileNames, function(name){
            return name === '404.json';
          });
        }

        // Perform a stat on all files for meta-info
        t.statFiles(fileNames, function(error, fileStats) {

          // Process errors
          if (error) {
            console.error('TreeProbe statFiles error', error);
            return callback(error);
          }

          // Process each file, recording directories and pages
          for (var i = 0, l = fileStats.length; i < l; i++) {
            var name = fileNames[i],
                stat = fileStats[i],
                id = Path.basename(name, '.json'),
                page = {id:id};

            if (stat.isDirectory()) {
              page.path = Path.join(t.dirPath, name);
              dirs.push(page);
            }
            else if (stat.isFile() && Path.extname(name).toLowerCase() === '.json') {
              pages.push(page);
            }
            else {
              console.error('Not a file or directory: ' + name);
            }
          }

          // Read each page for the display label and description
          t.readPages(pages, function(error) {

            // Process errors
            if (error) {
              console.error('PagesProbe readPages error', error);
              return callback(error);
            }

            // Add the virtual /app directory to the root
            if (t.dirPath === t.rootPath) {
              dirs.push({
                id:'app',
                label: t.CONST.appLabel,
                description: t.CONST.appDescription,
                path: Path.dirname(t.dirPath)
              });
            }

            // Trim directory branches that have no contents
            t.trimDirs(dirs, function(error, trimmed) {
              if (error) {
                callback(error);
              }

              t.set({
                leaves: pages,
                branches: trimmed
              });
              return callback();
            });
          });

        });
      });

    }
873417
function (requested) {
    // No postMessage? Don't render – the event-stream will handle it.
    if (!window.postMessage) { return; }

    // Inform other pages event streaming render to reload
    if (requested) {
      sendReload();
      jsbin.state.hasBody = false;
    }
    getPreparedCode().then(function (source) {
      var includeJsInRealtime = jsbin.settings.includejs;

      // Tell the iframe to reload
      var visiblePanels = jsbin.panels.getVisible();
      var outputPanelOpen = visiblePanels.indexOf(jsbin.panels.panels.live) > -1;
      var consolePanelOpen = visiblePanels.indexOf(jsbin.panels.panels.console) > -1;
      if (!outputPanelOpen && !consolePanelOpen) {
        return;
      }
      // this is a flag that helps detect crashed runners
      if (jsbin.settings.includejs) {
        store.sessionStorage.setItem('runnerPending', 1);
      }

      renderer.postMessage('render', {
        source: source,
        options: {
          injectCSS: jsbin.state.hasBody && jsbin.panels.focused.id === 'css',
          requested: requested,
          debug: jsbin.settings.debug,
          includeJsInRealtime: jsbin.settings.includejs,
        },
      });

      jsbin.state.hasBody = true;

    });
  }
716546
function start_html() {
        global $OUTPUT;

        // Render button to allow user to reset table preferences.
        echo $this->render_reset_button();

        // Do we need to print initial bars?
        $this->print_initials_bar();

        // Paging bar
        if ($this->use_pages) {
            $pagingbar = new paging_bar($this->totalrows, $this->currpage, $this->pagesize, $this->baseurl);
            $pagingbar->pagevar = $this->request[TABLE_VAR_PAGE];
            echo $OUTPUT->render($pagingbar);
        }

        if (in_array(TABLE_P_TOP, $this->showdownloadbuttonsat)) {
            echo $this->download_buttons();
        }

        $this->wrap_html_start();
        // Start of main data table

        echo html_writer::start_tag('div', array('class' => 'no-overflow'));
        echo html_writer::start_tag('table', $this->attributes);

    }
1193633
function(eventObj, callback) {
    var url = eventObj.url;
    var params = eventObj.params;
    if (eventObj.httpVerb === POST_METHOD) {
      var req = new XMLHttpRequest();
      req.open(POST_METHOD, url, true);
      req.setRequestHeader('Content-Type', 'application/json');
      req.onreadystatechange = function() {
        if (req.readyState === READYSTATE_COMPLETE && callback && typeof callback === 'function') {
          try {
            callback(params);
          } catch (e) {
            // TODO: Log this somehow (consider adding a logger to the EventDispatcher interface)
          }
        }
      };
      req.send(JSON.stringify(params));
    } else {
      // add param for cors headers to be sent by the log endpoint
      url += '?wxhr=true';
      if (params) {
        url += '&' + toQueryString(params);
      }

      var req = new XMLHttpRequest();
      req.open(GET_METHOD, url, true);
      req.onreadystatechange = function() {
        if (req.readyState === READYSTATE_COMPLETE && callback && typeof callback === 'function') {
          try {
            callback();
          } catch (e) {
            // TODO: Log this somehow (consider adding a logger to the EventDispatcher interface)
          }
        }
      };
      req.send();
    }
  }
1035081
function(pages, callback) {
      var t = this,
          didError = false,
          numLeft = pages.length;

      // Callback early if no pages to read
      if (pages.length === 0) {
        return callback();
      }

      // Read and parse each file for the title/description
      pages.forEach(function(page, index) {

        // Read the file
        var fullPath = Path.join(t.dirPath, page.id + '.json');
        FS.readFile(fullPath, 'utf8', function(error, file) {

          // Process a stat error
          if (error) {
            didError = true;
            return callback(error);
          }

          // Parse the JSON
          var parsed = null;
          try {
            parsed = JSON.parse(file);
          }
          catch (e) {
            didError = true;
            console.error('JSON error parsing page: ' + fullPath, e);
            return callback(e);
          }

          // Do nothing if a prior error callback happened
          if (didError) {
            return;
          }

          // Set the page title and description
          if (parsed.title) {
            page.label = parsed.title;
          }
          if (parsed.description) {
            page.description = parsed.description;
          }

          // Add a file watcher if not already watching
          if (!t.fileWatchers[page.id]) {
            t.fileWatchers[page.id] = new FS.watch(fullPath, {persistent:false}, function(type){
              t.sync();
            });
          }

          // Callback if all page reads are complete
          if (--numLeft === 0) {
            callback(null);
          }
        });
      });
    }
731383
function callbackWrapper() {
					callback && callback.apply( this, arguments );

					// Removed the just loaded script from the queue.
					pending.shift();

					loadNext.call( that );
				}
201413
function(callback)
    {
        if (this._limit != null && this.offset >= this._limit)
        {
            return callback(null, null);
        }

        var self = this;
        var _next = function(err)
        {       
            if (err)
            {
                return callback(err);
            }
        
            if (self.pos < self.data.length)
            {
                var itemData = self.data[self.pos];
                self.pos++;
                self.offset++;
                var cls = self.itemCls;
                callback(null, new cls(self.api, itemData, true));
            }
            else
            {
                callback(null, null);
            }
        };
        
        if (this.data == null || this.pos >= this.data.length && this.truncated)
        {
            this.loadNextPage(_next);
        }
        else
        {
            process.nextTick(_next);
        }
    }
560202
function() {
		// if running in Node.js, don't setup.
		if (isNode()) {
			return;
		}

		var document = getDocument(),
			window = getGlobal();

		this._value = getCurrentUrl();

		// Intercept routable links.
		domEvents.addDelegateListener(document.documentElement, "click", "a", this.anchorClickHandler);
		var originalMethods = this.originalMethods = {};
		var dispatchHandlers = this.dispatchHandlers;

		// Rewrites original `pushState`/`replaceState` methods on `history`
		// and keeps pointer to original methods.
		canReflect.eachKey(methodsToOverwrite, function(method) {
			this.originalMethods[method] = window.history[method];
			window.history[method] = function(state, title, url) {

				// Avoid doubled history states (with pushState).
				var absolute = url.indexOf("http") === 0;
				var location = LOCATION();
				var searchHash = location.search + location.hash;

				// If url differs from current call original history method and update `route` state.
				if ((!absolute && url !== location.pathname + searchHash) ||
					(absolute && url !== location.href + searchHash)) {
					originalMethods[method].apply(window.history, arguments);
					dispatchHandlers();
				}
			};
		}, this);

		// Bind dispatchHandlers to the `popstate` event, so they will fire
		// when `history.back()` or `history.forward()` methods are called.
		domEvents.addEventListener(window, "popstate", this.dispatchHandlers);
	}
564188
public function hookCallback()
    {
        $name = $this->getModel()->getName();

        // Check Ajax referer
        check_ajax_referer($name, 'nonce');

        // Call custom callback function
        $data = $this->callback();

        // Build JSON data
        wp_send_json_success($data);

        // Stops everything
        wp_die();
    }
1233029
function(path, callbackSuccess, callbackError) {
  var xhr = new XMLHttpRequest();
  xhr.onreadystatechange = function() {
    if (xhr.readyState === 4) {
      if (xhr.status >= 200 && xhr.status < 300) {
        callbackSuccess(xhr.responseText);
      } else {
        callbackError();
      }
    }
  };
  xhr.open('GET', path, false);
  try {
    xhr.send();
  } catch (e) {
    callbackError();
  }
}
6667
function processWebRequest(routeInfo, callbacks) {
    var appName = routeInfo.appName;
    var serverOnly = !!routeInfo.query.server;
    var page = injector.loadModule('app/' + appName + '/pages/' + routeInfo.name + '.page');

    // get the callbacks
    var serverPreprocessing = callbacks.serverPreprocessing || function () { return false; };
    var appAddToModel = callbacks.addToModel || function () {};
    var pageCacheService = callbacks.pageCacheService || defaultPageCache;
    var initialModel, cacheKey;

    return getInitialModel(routeInfo, page)
        .then(function (model) {
            initialModel = model || {};

            // if the server pre-processing returns true, then return without doing anything
            // this is because the pre-processor sent a reply to the user already
            if (serverPreprocessing(routeInfo, page, model)) {
                return true;
            }

            //TODO: may be weird edge cases with this. need to test more to ensure performance and uniqueness
            // but note that we have an hour default timeout for the redis cache just in case
            // and we have the redis LRU config set up so the least recently used will get pushed out
            cacheKey = utensils.checksum(routeInfo.lang + '||' + routeInfo.appName + '||' +
                routeInfo.url + '||' + JSON.stringify(model));

            return pageCacheService.get({ key: cacheKey });
        })
        .then(function (cachedPage) {
            if (cachedPage === true) { return null; }
            if (cachedPage && !serverOnly) { return cachedPage; }

            // allow the app level to modify the model before rendering
            appAddToModel(initialModel, routeInfo);

            // finally use the client side plugin to do the rendering
            return clientPlugin.renderPage(routeInfo, page, initialModel, inlineCssCache[appName + '||' + routeInfo.name]);
        })
        .then(function (renderedPage) {
            if (!serverOnly && renderedPage) {
                pageCacheService.set({ key: cacheKey, value: renderedPage });
            }

            return renderedPage;
        });
}
1159692
function (callback) {
    var APIController = require('./controllers/api'),
      DefaultController = require('./controllers/index'),
      PackController = require('./controllers/pack'),
      CardController = require('./controllers/card'),
      WebHookController = require('./controllers/webhook'),
      ProxyController = require('./controllers/proxy'),
      JsonParser = BodyParser.json({strict: false});
    
    // Disable caching middleware.  
    var nocache = function (req, res, next) {
      res.header('Cache-Control', 'private, no-cache, no-store, must-revalidate');
      res.header('Expires', '-1');
      res.header('Pragma', 'no-cache');
      next();
    };
    
    // Setup routes late to give implementers routes higher priority and allow middleware as well.
    App.get('/api/count', nocache, APIController.count);
    App.get('/api/cards', nocache, APIController.cards);
    App.get('/api/card', nocache, APIController.card);
    
    App.post('/api/card/state/save', APIController.saveState);
    App.post('/api/card/state/clear', APIController.clearState);
    App.post('/api/card/analytics', APIController.recordAnalyticEvents);

    // Proxy
    App.post('/proxy/:pack/:card', ProxyController.post);

    // Web Hooks
    App.post('/webhook/:pack/:card', WebHookController.process);

    // Card Routes
    App.post('/:pack/:card', JsonParser, CardController.post);
    App.get('/:pack/:card', CardController.get);
    
    App.get('/:pack', PackController);
    App.get('/', DefaultController);

    var exit = function () {
      HashDo.db.disconnect(function () {
        process.exit(0);
      });
    };
    
    // Gracefully disconnect from the database on expected exit.
    process.on('SIGINT', exit);
    process.on('SIGTERM', exit);
    
    // Global error handler (always exit for programmatic errors).
    process.on('uncaughtException', function (err) {
      console.error('FATAL: ', err.message);
      console.error(err.stack);
      process.exit(1);
    });
    
    // Connect to the database and start server on successful connection.
    HashDo.db.connect(function (err) {
      if (err) {
        console.error('FATAL: Could not connect to database.', err);
        process.exit(1);
      }
      else {
        console.log('WEB: Starting web server on port %d...', process.env.PORT);
        
        App.listen(process.env.PORT, function () {
          console.log();
          console.log('Let\'s #Do');
          
          callback && callback();
        });
      }
    });
  }