Create static pages NOTE: gatsby does automatically build pages from **top level** `/pages`, folder but in ocular we keep those pages in the installed structure so gatsby can't see them
354104
function addToRelativeLinks({
  source,
  target,
  rootFolder,
  edge,
  relativeLinks
}) {
  // what we are doing here: for each markdown file, we create a mapping of different ways to
  // link to another markdown file that we will honor.

  // let's suppose that we want to go from a file:
  // - physical location: /docs/my-files/source.md, slug: /docs/chapter-1/source
  // to this file:
  // - phyiscal location: /docs/developer-guide/target.md, slug: /docs/advanced-usage/api-reference/target

  // by default, '../../advanced-usage/api/reference/target' would work (target file slug, relative to original slug)
  // '/docs/advanced-usage/api-reference/target' would also work (absolute target slug)
  // however, on github, those links wouldn't work as there is no phyiscal file behind that link.
  // in github however: '/docs/developer-guide/target.md' (file name relative to root) or
  // '../developer-guide/target.md' (relative file name) would work. Those links wouldn't work on the gatsby rendered
  // page however (until that).

  // we are creating a mapping so that ANY OF THESE 4 SYNTAXES would be honored.
  // So, authors can use links that refer to physical files, and gatsby will render a link that works - the same link
  // can work on github and gatsby

  // note that often, the physical location and the slug are the same!
  // However there is no guarantee that this will be the case.

  if (!source || !target) {
    log.log(
      { color: COLOR.YELLOW },
      `couldn't add relative link for: ${JSON.stringify({ source, target })}`
    )();
    return {};
  }

  const relativeToCurrentFile = path.relative(
    edge.node.fileAbsolutePath,
    source
  );
  const relativeToRootFolder = rootFolder && path.relative(rootFolder, source);
  const relativeToCurrentSlug = path.relative(edge.node.fields.path, target);

  const absoluteTarget = `/${target}`;

  return {
    ...relativeLinks,
    [relativeToCurrentFile]: absoluteTarget,
    [relativeToCurrentFile]: absoluteTarget,
    [relativeToRootFolder]: absoluteTarget,
    [relativeToCurrentSlug]: absoluteTarget,
    [target]: absoluteTarget
  };
}
323095
function build(hasSeparateGlobals) {
                    var root = new output.NavigationItem('Index', 'index.html');
                    if (entryPoint == project) {
                        var globals = new output.NavigationItem('Globals', hasSeparateGlobals ? 'globals.html' : 'index.html', root);
                        globals.isGlobals = true;
                    }
                    var modules = [];
                    project.getReflectionsByKind(td.models.ReflectionKind.SomeModule).forEach(function (someModule) {
                        var target = someModule.parent;
                        var inScope = (someModule == entryPoint);
                        while (target) {
                            if (target.kindOf(td.models.ReflectionKind.ExternalModule))
                                return;
                            if (entryPoint == target)
                                inScope = true;
                            target = target.parent;
                        }
                        if (inScope) {
                            modules.push(someModule);
                        }
                    });
                    if (modules.length < 10) {
                        buildGroups(modules, root);
                    }
                    else {
                        buildGroups(entryPoint.getChildrenByKind(td.models.ReflectionKind.SomeModule), root, buildChildren);
                    }
                    return root;
                }
1258926
private function create_pages() {
        // Set up generator.
        $pagegenerator = $this->generator->get_plugin_generator('mod_page');

        // Create pages.
        $number = self::$parampages[$this->size];
        $this->log('createpages', $number, true);
        for ($i = 0; $i < $number; $i++) {
            $record = array('course' => $this->course);
            $options = array('section' => $this->get_target_section());
            $pagegenerator->create_instance($record, $options);
            $this->dot($i, $number);
        }

        $this->end_log();
    }
616248
function pageDefaults() {
  return {
    path: canonicalPath(),
    referrer: document.referrer,
    search: location.search,
    title: document.title,
    url: canonicalUrl(location.search)
  };
}
436466
protected function createPages()
    {
        $this->setCliMessage('Creating pages...');

        $pages = array();

        $pages[] = array(
            'title' => 'Contact us',
            'description' => 'Contact information',
        );

        $pages[] = array(
            'title' => 'Help',
            'description' => 'Help information. Coming soon...',
        );

        foreach ($pages as $page) {

            $page += array(
                'status' => 1,
                'user_id' => $this->context['user_id'],
                'store_id' => $this->context['store_id']
            );

            $this->getPageModel()->add($page);
        }
    }
1112651
protected function buildPages()
    {
        $this->sort = [];

        /** @var Config $config */
        $config = $this->grav['config'];

        /** @var Language $language */
        $language = $this->grav['language'];

        /** @var UniformResourceLocator $locator */
        $locator = $this->grav['locator'];

        $pages_dir = $locator->findResource('page://');

        if ($config->get('system.cache.enabled')) {
            /** @var Cache $cache */
            $cache = $this->grav['cache'];
            /** @var Taxonomy $taxonomy */
            $taxonomy = $this->grav['taxonomy'];

            // how should we check for last modified? Default is by file
            switch ($this->check_method) {
                case 'none':
                case 'off':
                    $hash = 0;
                    break;
                case 'folder':
                    $hash = Folder::lastModifiedFolder($pages_dir);
                    break;
                case 'hash':
                    $hash = Folder::hashAllFiles($pages_dir);
                    break;
                default:
                    $hash = Folder::lastModifiedFile($pages_dir);
            }

            $this->pages_cache_id = md5($pages_dir . $hash . $language->getActive() . $config->checksum());

            list($this->instances, $this->routes, $this->children, $taxonomy_map, $this->sort) = $cache->fetch($this->pages_cache_id);
            if (!$this->instances) {
                $this->grav['debugger']->addMessage('Page cache missed, rebuilding pages..');

                // recurse pages and cache result
                $this->resetPages($pages_dir);

            } else {
                // If pages was found in cache, set the taxonomy
                $this->grav['debugger']->addMessage('Page cache hit.');
                $taxonomy->taxonomy($taxonomy_map);
            }
        } else {
            $this->recurse($pages_dir);
            $this->buildRoutes();
        }
    }
436550
function(next) {
            
                    
            // Stylesheet and JavaScript files are listed in the config
            config.headerScripts.stylesheets.forEach(function(cssentry) {
                config.akashacmsEPUB.manifest.push({
                    id: cssentry.id,
                    type: "text/css",
                    href: rewriteURL(akasha, config, { rendered_url: config.akashacmsEPUB.bookmetadata.opf }, cssentry.href, false)  // MAP this URL
                });
            });
        
            config.headerScripts.javaScriptTop.concat(config.headerScripts.javaScriptBottom).forEach(function(jsentry) {
                config.akashacmsEPUB.manifest.push({
                    id: jsentry.id,
                    type: "application/javascript",
                    href: rewriteURL(akasha, config, { rendered_url: config.akashacmsEPUB.bookmetadata.opf }, jsentry.href, false)  // MAP this URL
                });
            });
            
            // There had formerly been a list of allowed file extensions in globfs.operate
            //
            // Turns out to have been too restrictive because those who wanted to
            // include other kinds of files weren't free to do so.
            //
            // The purpose here is to add manifest entries for files that aren't documents
            // and aren't already in the manifest for any other reason.
            
            var assetNum = 0;
            globfs.operate(config.root_assets.concat(config.root_docs), [ "**/*" ],
                function(basedir, fpath, fini) {
                    
                    // logger.trace('asset file '+ path.join(basedir, fpath));
                    
                    fs.stat(path.join(basedir, fpath), function(err, stats) {
                        if (err || !stats) {
                            // Shouldn't get this, because globfs will only give us
                            // files which exist
                            logger.error('ERROR '+ basedir +' '+ fpath +' '+ err);
                            fini();
                        } else if (stats.isDirectory()) {
                            // Skip directories
                            // logger.trace('isDirectory '+ basedir +' '+ fpath);
                            fini();
                        } else {
                            // logger.trace('regular file '+ basedir +' '+ fpath);
                            akasha.readDocumentEntry(fpath, function(err, docEntry) {
                            
                                if (docEntry) {
                                    // If there's a docEntry, we need to override the fpath
                                    // with the filename it renders to.  This is to properly
                                    // detect files that are already in the manifest.
                                    
                                    // logger.trace('docEntry '+ basedir +' '+ fpath);
                                    fpath = docEntry.renderedFileName;
                                }
                                // Detect any files that are already in manifest
                                // Only add to manifest stuff which isn't already there
                                var inManifest = false;
                                config.akashacmsEPUB.manifest.forEach(function(item) {
                                    if (item.href === fpath) {
                                        inManifest = true;
                                    }
                                });
                                if (!inManifest) {
                                    // We're not using the mime library for some
                                    // file extensions because it gives
                                    // incorrect values for the .otf and .ttf files
                                    
                                    // logger.trace('assetManifestEntries '+ basedir +' '+ fpath);
                                    var mimetype;
                                    if (fpath.match(/\.ttf$/i)) mimetype = "application/vnd.ms-opentype";
                                    else if (fpath.match(/\.otf$/i)) mimetype = "application/vnd.ms-opentype";
                                    else mimetype = mime.lookup(fpath);
                                    
                                    config.akashacmsEPUB.manifest.push({
                                        id: "asset" + assetNum++,
                                        type: mimetype,
                                        href: rewriteURL(akasha, config, {
                                            rendered_url: config.akashacmsEPUB.bookmetadata.opf
                                        }, fpath, false)
                                    });
                                }
                                fini();
                            });
                        }
                    });
                },
                next);
        }
1267929
function createMozBuildFiles() {
  const builds = {};

  getFiles()
    .filter(file => file.match(/.js$/))
    .filter(file => {
      if (file.match(/\/workers\.js/)) {
        return true;
      }

     // We exclude worker files because they are bundled and we include
     // worker/index.js files because are required by the debugger app in order
     // to communicate with the worker.
     if (file.match(/\/workers/)) {
       return file.match(/workers\/(\w|-)*\/index.js/);
     }

     return !file.match(/(test|types|packages)/)

   })
    .forEach(file => {
      // console.log(file)
      let dir = path.dirname(file);
      builds[dir] = builds[dir] || { files: [], dirs: [] };

      // Add the current file to its parent dir moz.build
      builds[dir].files.push(path.basename(file));

      // There should be a moz.build in every folder between the root and this
      // file. Climb up the folder hierarchy and make sure a each folder of the
      // chain is listing in its parent dir moz.build.
      while (path.dirname(dir) != ".") {
        const parentDir = path.dirname(dir);
        const dirName = path.basename(dir);

        builds[parentDir] = builds[parentDir] || { files: [], dirs: [] };
        if (!builds[parentDir].dirs.includes(dirName)) {
          builds[parentDir].dirs.push(dirName);
        }
        dir = parentDir;
      }
    });

  Object.keys(builds).forEach(build => {
    const { files, dirs } = builds[build];

    const buildPath = path.join(mcDebuggerPath, build);
    shell.mkdir("-p", buildPath);

    // Files and folders should be alphabetically sorted in moz.build
    const fileStr = files
      .sort((a, b) => (a.toLowerCase() < b.toLowerCase() ? -1 : 1))
      .map(file => `    '${file}',`)
      .join("\n");

    const dirStr = dirs
      .sort((a, b) => (a.toLowerCase() < b.toLowerCase() ? -1 : 1))
      .map(dir => `    '${dir}',`)
      .join("\n");

    const src = MOZ_BUILD_TEMPLATE.replace("__DIRS__", dirStr).replace(
      "__FILES__",
      fileStr
    );

    fs.writeFileSync(path.join(buildPath, "moz.build"), src);
  });
}
182328
function Page(page) {
  if (!page) page = {};
  for (var key in page) this[key] = page[key];
  if (!this.hasOwnProperty('idx')) this.idx = 0;
  if (!this.hasOwnProperty('total')) this.total = 1;
  if (!this.hasOwnProperty('current')) {
    this.current = this.total;
  }
}
875973
function addPagesTooling( api ) {
   let pagesTooling;
   Object.defineProperty( api, 'pages', {
      get() {
         if( !pagesTooling ) {
            pagesTooling = createPagesTooling( api );
            pagesTooling.enable();
            api.destroy = () => {
               pagesTooling.disable();
            };
         }
         return pagesTooling;
      }
   } );
}
575698
def urls_from_file_tree(template_dir):
    """"""
    urls = []  # keep a list of of all the files/paths

    # Should be somethign like:
    # /path/to/myproject/templates/staticflatpages
    root_dir = join(template_dir, 'staticflatpages')

    for root, dirs, files in walk(template_dir):
        # Only do this for the ``staticflatpages`` directory or sub-directories
        if "staticflatpages" in root:
            root = root.replace(root_dir, '')
            for f in files:
                path = join(root, f)
                path = _format_as_url(path)
                urls.append(path)
    return urls
1306153
function(){
		STATIC_FILES.forEach(function(file){
			addFile(fs.createReadStream(__dirname + '/templates/' + file), { name: file });
		});
	}
1171933
function Pages(pages) {
  this.pages = [];
  if (typeof pages === 'undefined') return;
  if (!Array.isArray(pages)) {
    throw new TypeError('expected pages to be an Array');
  }
  this.addPages(pages);
}
596520
function setRefs(allPages, pages) {
            if (!pages) {
                pages = allPages;
            }

            for (var index = 0; index < pages.length; index++) {
                var stateRef;

                if (pages[index].stateRef) {
                    stateRef = stateRefSearch(allPages, pages[index].stateRef);

                    if (null !== stateRef) {
                        pages[index] = merge({}, stateRef, pages[index]);
                    }
                }

                if (pages[index].pages) {
                    pages[index].pages = setRefs(allPages, pages[index].pages);
                }
            }

            return pages;
        }
995719
def import_pages(import_data, parent_page):
    
    pages_by_original_path = {}
    pages_by_original_id = {}

    # First create the base Page records; these contain no foreign keys, so this allows us to
    # build a complete mapping from old IDs to new IDs before we go on to importing the
    # specific page models, which may require us to rewrite page IDs within foreign keys / rich
    # text / streamfields.
    page_content_type = ContentType.objects.get_for_model(Page)
    for (i, page_record) in enumerate(import_data['pages']):
        # build a base Page instance from the exported content (so that we pick up its title and other
        # core attributes)
        page = Page.from_serializable_data(page_record['content'])
        original_path = page.path
        original_id = page.id

        # clear id and treebeard-related fields so that they get reassigned when we save via add_child
        page.id = None
        page.path = None
        page.depth = None
        page.numchild = 0
        page.url_path = None
        page.content_type = page_content_type
        if i == 0:
            parent_page.add_child(instance=page)
        else:
            # Child pages are created in the same sibling path order as the
            # source tree because the export is ordered by path
            parent_path = original_path[:-(Page.steplen)]
            pages_by_original_path[parent_path].add_child(instance=page)

        pages_by_original_path[original_path] = page
        pages_by_original_id[original_id] = page

    for (i, page_record) in enumerate(import_data['pages']):
        # Get the page model of the source page by app_label and model name
        # The content type ID of the source page is not in general the same
        # between the source and destination sites but the page model needs
        # to exist on both.
        # Raises LookupError exception if there is no matching model
        model = apps.get_model(page_record['app_label'], page_record['model'])

        specific_page = model.from_serializable_data(page_record['content'], check_fks=False, strict_fks=False)
        base_page = pages_by_original_id[specific_page.id]
        specific_page.page_ptr = base_page
        specific_page.__dict__.update(base_page.__dict__)
        specific_page.content_type = ContentType.objects.get_for_model(model)
        update_page_references(specific_page, pages_by_original_id)
        specific_page.save()

    return len(import_data['pages'])
1332666
function initAppDir (config, module, appDir, appSubDir) {
    // if called without sub dir then start with app dir
    if (!appSubDir) {
        appSubDir = appDir
    }
    // debug
    debug('initAppDir %s', appSubDir)
    // get relative path from app base to directory which determines
    // where in the routes tree this directory sits
    var rel = path.relative(appDir, appSubDir)
    // get route node from relative path
    var route = routeFromRel(module.routes, rel)
    // prevent infinite loops
    if (route.loaded) {
        return
    }
    // mark route as loaded
    route.loaded = true
    // directory names map
    var dirNames = {}
    // list of all sub-directories in directory
    var dirs = []
    // list of all files in directory
    var files = []
    // iterate over file names in directory
    _.each(fs.readdirSync(appSubDir), file => {
        // get absolute file
        var absFile = appSubDir+'/'+file
        // get stat of file to check if it is dir or file
        var stat = fs.statSync(absFile)
        // file
        if (stat.isFile()) {
            files.push(absFile)
        }
        // directory
        else if (stat.isDirectory()) {
            // add name to map for doing conflict checking
            dirNames[file] = true
            // add abs path to list for recursive loading
            dirs.push(absFile)
        }
        // ignore anything else
        else {
            debug('initAppDir: ignoring %s', absFile)
        }
    })
    // recursively process all sub-directories - go depth first so that routes
    // for sub-dirs are added before wildcard path param matching rules
    _.each(dirs, dir => {
        initAppDir(config, module, appDir, dir)
    })
    // regular expression for matching controller files
    var controllerRegEx = /controller\.js$/
    // regular expression for matching model files
    var modelRegEx = /model\.js$/
    // regular expression for matching template files extname starts with .
    config.handlebars.templateRegExp = new RegExp('\\'+config.handlebars.ext+'$')
    // ImmutableCoreController for node - multiple files will be merged
    route.controller = {}
    // ImmutableCoreModel for node - multiple files will be merged
    route.model = {}
    // list of templates indexed by name. name of template file indicates path
    // that it should be served on. if path does not have a controller then
    // a default controller will be created.
    route.templates = {}
    // get mapping of templates by path
    route.templatesInverse = {}
    // require all controller and model files for route
    _.each(files, file => {
        // get type
        var type
        // controllers must be named controller.js
        if (file.match(controllerRegEx)) {
            // require controller file
            var controller = require(path.relative(__dirname, file))
            // require defined
            assert.ok(defined(controller), `nothing exported for ${file}`)
            // throw error if controller instantiated
            assert.ok(!controller.ImmutableCoreController, `controller must be plain object ${file}`)
            // merge controller spec
            _.merge(route.controller, controller)
        }
        // models must be named model.js
        else if (file.match(modelRegEx)) {
            // require model file
            var model = require(path.relative(__dirname, file))
            // require defined
            assert.ok(defined(model), `nothing exported for ${file}`)
            // throw error if controller instantiated
            assert.ok(!model.ImmutableCoreModel, `model must be plain object ${file}`)
            // merge model spec
            _.merge(route.model, model)
        }
        // template files must end in hbs
        else if (file.match(config.handlebars.templateRegExp)) {
            // get only the file name
            file = path.basename(file)
            // remove extension from file
            file = file.replace(config.handlebars.templateRegExp, '')
            // template path used in render call is relative path from app
            // base (if any) and the file name without the extensions
            var templatePath = (rel.length ? rel+'/' : '') + file
            // split file name on dot - if template name has a dot then the
            // part after the dot must be the role that the template is for
            var fileParts = file.split('.')
            // if there is only a single part then not a role specific template
            if (fileParts.length === 1) {
                // if entry does not exist for template name then create it
                if (!defined(route.templates[file])) {
                    route.templates[file] = {
                        role: {},
                    }
                }
                // store template name and template path under default all role
                route.templates[file].role.all = templatePath
                // create inverse entry keyed by full path
                route.templatesInverse[templatePath] = {
                    name: file,
                    role: 'all',
                }
            }
            // it there are two parts they must be name.role
            else if (fileParts.length === 2) {
                var name = fileParts[0]
                var role = fileParts[1]
                // if entry does not exist for template name then create it
                if (!defined(route.templates[name])) {
                    route.templates[name] = {
                        role: {},
                    }
                }
                // store template name and template path
                route.templates[name].role[role] = templatePath
                // create inverse entry keyed by full path
                route.templatesInverse[templatePath] = {
                    name: name,
                    role: role,
                }
            }
            // if there are not 1 or 2 parts this is an error
            else {
                throw new Error('invalid template file name '+file)
            }
        }
        // otherwise ignore file
        else {
            return
        }
    })
    // if controller name is not set construct from module name
    if (!defined(route.controller.name)) {
        // get controller name as app + path
        route.controller.name = changeCase.camelCase(module.name)
            + changeCase.pascalCase(rel.length ? rel : 'Index')
    }
    // if controller path is not set use current relative path
    if (!defined(route.controller.path)) {
        route.controller.path = rel
    }
}
1334071
function(page) {
      var t = this,
          newPages = t.pages.slice(0);
      newPages.push(page);
      t.tour.set('pages', newPages);
      t.tour.isDirty = true;
      t.setDirty(true);
      t.loadForm();
    }