Converted to PSR-2

This commit is contained in:
helpfulrobot 2015-11-21 19:25:41 +13:00
parent 2f0cbfe4f6
commit ced8128190
26 changed files with 4223 additions and 4033 deletions

View File

@ -5,8 +5,8 @@
* *
* @package docsviewer * @package docsviewer
*/ */
class DocumentationHelper { class DocumentationHelper
{
/** /**
* String helper for cleaning a file name to a readable version. * String helper for cleaning a file name to a readable version.
* *
@ -14,7 +14,8 @@ class DocumentationHelper {
* *
* @return string $name output * @return string $name output
*/ */
public static function clean_page_name($name) { public static function clean_page_name($name)
{
$name = self::trim_extension_off($name); $name = self::trim_extension_off($name);
$name = self::trim_sort_number($name); $name = self::trim_sort_number($name);
@ -30,13 +31,14 @@ class DocumentationHelper {
* *
* @return string $name output * @return string $name output
*/ */
public static function clean_page_url($name) { public static function clean_page_url($name)
{
$name = str_replace(array(' '), '_', $name); $name = str_replace(array(' '), '_', $name);
$name = self::trim_extension_off($name); $name = self::trim_extension_off($name);
$name = self::trim_sort_number($name); $name = self::trim_sort_number($name);
if(preg_match('/^[\/]?index[\/]?/', $name)) { if (preg_match('/^[\/]?index[\/]?/', $name)) {
return ''; return '';
} }
@ -50,7 +52,8 @@ class DocumentationHelper {
* *
* @return string * @return string
*/ */
public static function trim_sort_number($name) { public static function trim_sort_number($name)
{
$name = preg_replace("/^[0-9]*[_-]+/", '', $name); $name = preg_replace("/^[0-9]*[_-]+/", '', $name);
return $name; return $name;
@ -65,9 +68,10 @@ class DocumentationHelper {
* *
* @return string * @return string
*/ */
public static function trim_extension_off($name) { public static function trim_extension_off($name)
if(strrpos($name,'.') !== false) { {
return substr($name, 0, strrpos($name,'.')); if (strrpos($name, '.') !== false) {
return substr($name, 0, strrpos($name, '.'));
} }
return $name; return $name;
@ -80,9 +84,10 @@ class DocumentationHelper {
* *
* @return string * @return string
*/ */
public static function get_extension($name) { public static function get_extension($name)
if(preg_match('/\.[a-z]+$/', $name)) { {
return substr($name, strrpos($name,'.') + 1); if (preg_match('/\.[a-z]+$/', $name)) {
return substr($name, strrpos($name, '.') + 1);
} }
return null; return null;

View File

@ -27,8 +27,8 @@
* @package framework * @package framework
* @subpackage manifest * @subpackage manifest
*/ */
class DocumentationManifest { class DocumentationManifest
{
/** /**
* @config * @config
* *
@ -78,7 +78,8 @@ class DocumentationManifest {
* @param bool $includeTests Include tests in the manifest. * @param bool $includeTests Include tests in the manifest.
* @param bool $forceRegen Force the manifest to be regenerated. * @param bool $forceRegen Force the manifest to be regenerated.
*/ */
public function __construct($forceRegen = false) { public function __construct($forceRegen = false)
{
$this->cacheKey = 'manifest'; $this->cacheKey = 'manifest';
$this->forceRegen = $forceRegen; $this->forceRegen = $forceRegen;
$this->registeredEntities = new ArrayList(); $this->registeredEntities = new ArrayList();
@ -97,23 +98,24 @@ class DocumentationManifest {
* Either manually registered through the YAML syntax or automatically * Either manually registered through the YAML syntax or automatically
* loaded through investigating the file system for `docs` folder. * loaded through investigating the file system for `docs` folder.
*/ */
public function setupEntities() { public function setupEntities()
if($this->registeredEntities->Count() > 0) { {
if ($this->registeredEntities->Count() > 0) {
return; return;
} }
if(Config::inst()->get('DocumentationManifest', 'automatic_registration')) { if (Config::inst()->get('DocumentationManifest', 'automatic_registration')) {
$this->populateEntitiesFromInstall(); $this->populateEntitiesFromInstall();
} }
$registered = Config::inst()->get('DocumentationManifest', 'register_entities'); $registered = Config::inst()->get('DocumentationManifest', 'register_entities');
foreach($registered as $details) { foreach ($registered as $details) {
// validate the details provided through the YAML configuration // validate the details provided through the YAML configuration
$required = array('Path', 'Title'); $required = array('Path', 'Title');
foreach($required as $require) { foreach ($required as $require) {
if(!isset($details[$require])) { if (!isset($details[$require])) {
throw new Exception("$require is a required key in DocumentationManifest.register_entities"); throw new Exception("$require is a required key in DocumentationManifest.register_entities");
} }
} }
@ -124,7 +126,7 @@ class DocumentationManifest {
$key = (isset($details['Key'])) ? $details['Key'] : $details['Title']; $key = (isset($details['Key'])) ? $details['Key'] : $details['Title'];
if(!$path || !is_dir($path)) { if (!$path || !is_dir($path)) {
throw new Exception($details['Path'] . ' is not a valid documentation directory'); throw new Exception($details['Path'] . ' is not a valid documentation directory');
} }
@ -134,11 +136,11 @@ class DocumentationManifest {
$langs = scandir($path); $langs = scandir($path);
if($langs) { if ($langs) {
$possible = i18n::get_common_languages(true); $possible = i18n::get_common_languages(true);
foreach($langs as $k => $lang) { foreach ($langs as $k => $lang) {
if(isset($possible[$lang])) { if (isset($possible[$lang])) {
$entity = Injector::inst()->create( $entity = Injector::inst()->create(
'DocumentationEntity', $key 'DocumentationEntity', $key
); );
@ -149,11 +151,11 @@ class DocumentationManifest {
$entity->setVersion($version); $entity->setVersion($version);
$entity->setBranch($branch); $entity->setBranch($branch);
if(isset($details['Stable'])) { if (isset($details['Stable'])) {
$entity->setIsStable($details['Stable']); $entity->setIsStable($details['Stable']);
} }
if(isset($details['DefaultEntity'])) { if (isset($details['DefaultEntity'])) {
$entity->setIsDefaultEntity($details['DefaultEntity']); $entity->setIsDefaultEntity($details['DefaultEntity']);
} }
@ -164,8 +166,9 @@ class DocumentationManifest {
} }
} }
public function getRealPath($path) { public function getRealPath($path)
if(substr($path, 0, 1) != '/') { {
if (substr($path, 0, 1) != '/') {
$path = Controller::join_links(BASE_PATH, $path); $path = Controller::join_links(BASE_PATH, $path);
} }
@ -175,7 +178,8 @@ class DocumentationManifest {
/** /**
* @return ArrayList * @return ArrayList
*/ */
public function getEntities() { public function getEntities()
{
return $this->registeredEntities; return $this->registeredEntities;
} }
@ -185,24 +189,25 @@ class DocumentationManifest {
* *
* @return void * @return void
*/ */
public function populateEntitiesFromInstall() { public function populateEntitiesFromInstall()
if($this->automaticallyPopulated) { {
if ($this->automaticallyPopulated) {
// already run // already run
return; return;
} }
foreach(scandir(BASE_PATH) as $key => $entity) { foreach (scandir(BASE_PATH) as $key => $entity) {
if($key == "themes") { if ($key == "themes") {
continue; continue;
} }
$dir = Controller::join_links(BASE_PATH, $entity); $dir = Controller::join_links(BASE_PATH, $entity);
if(is_dir($dir)) { if (is_dir($dir)) {
// check to see if it has docs // check to see if it has docs
$docs = Controller::join_links($dir, 'docs'); $docs = Controller::join_links($dir, 'docs');
if(is_dir($docs)) { if (is_dir($docs)) {
$entities[] = array( $entities[] = array(
'Path' => $docs, 'Path' => $docs,
'Title' => DocumentationHelper::clean_page_name($entity), 'Title' => DocumentationHelper::clean_page_name($entity),
@ -224,7 +229,8 @@ class DocumentationManifest {
/** /**
* *
*/ */
protected function init() { protected function init()
{
if (!$this->forceRegen && $data = $this->cache->load($this->cacheKey)) { if (!$this->forceRegen && $data = $this->cache->load($this->cacheKey)) {
$this->pages = $data['pages']; $this->pages = $data['pages'];
$this->redirects = $data['redirects']; $this->redirects = $data['redirects'];
@ -240,7 +246,8 @@ class DocumentationManifest {
* *
* @return array * @return array
*/ */
public function getPages() { public function getPages()
{
if (!$this->inited) { if (!$this->inited) {
$this->init(); $this->init();
} }
@ -248,8 +255,9 @@ class DocumentationManifest {
return $this->pages; return $this->pages;
} }
public function getRedirects() { public function getRedirects()
if(!$this->inited) { {
if (!$this->inited) {
$this->init(); $this->init();
} }
@ -261,19 +269,20 @@ class DocumentationManifest {
* *
* @return DocumentationPage * @return DocumentationPage
*/ */
public function getPage($url) { public function getPage($url)
{
$pages = $this->getPages(); $pages = $this->getPages();
$url = $this->normalizeUrl($url); $url = $this->normalizeUrl($url);
if(!isset($pages[$url])) { if (!isset($pages[$url])) {
return null; return null;
} }
$record = $pages[$url]; $record = $pages[$url];
foreach($this->getEntities() as $entity) { foreach ($this->getEntities() as $entity) {
if(strpos($record['filepath'], $entity->getPath()) !== false) { if (strpos($record['filepath'], $entity->getPath()) !== false) {
$page = Injector::inst()->create( $page = Injector::inst()->create(
$record['type'], $record['type'],
$entity, $entity,
@ -292,11 +301,12 @@ class DocumentationManifest {
* @param type $url * @param type $url
* @return string * @return string
*/ */
public function getRedirect($url) { public function getRedirect($url)
{
$pages = $this->getRedirects(); $pages = $this->getRedirects();
$url = $this->normalizeUrl($url); $url = $this->normalizeUrl($url);
if(isset($pages[$url])) { if (isset($pages[$url])) {
return $pages[$url]; return $pages[$url];
} }
} }
@ -306,7 +316,8 @@ class DocumentationManifest {
* *
* @param bool $cache * @param bool $cache
*/ */
public function regenerate($cache = true) { public function regenerate($cache = true)
{
$finder = new DocumentationManifestFileFinder(); $finder = new DocumentationManifestFileFinder();
$finder->setOptions(array( $finder->setOptions(array(
'dir_callback' => array($this, 'handleFolder'), 'dir_callback' => array($this, 'handleFolder'),
@ -314,7 +325,7 @@ class DocumentationManifest {
)); ));
$this->redirects = array(); $this->redirects = array();
foreach($this->getEntities() as $entity) { foreach ($this->getEntities() as $entity) {
$this->entity = $entity; $this->entity = $entity;
$this->handleFolder('', $this->entity->getPath(), 0); $this->handleFolder('', $this->entity->getPath(), 0);
@ -324,8 +335,8 @@ class DocumentationManifest {
// groupds // groupds
$grouped = array(); $grouped = array();
foreach($this->pages as $url => $page) { foreach ($this->pages as $url => $page) {
if(!isset($grouped[$page['entitypath']])) { if (!isset($grouped[$page['entitypath']])) {
$grouped[$page['entitypath']] = array(); $grouped[$page['entitypath']] = array();
} }
@ -334,13 +345,13 @@ class DocumentationManifest {
$this->pages = array(); $this->pages = array();
foreach($grouped as $entity) { foreach ($grouped as $entity) {
uasort($entity, function($a, $b) { uasort($entity, function ($a, $b) {
// ensure parent directories are first // ensure parent directories are first
$a['filepath'] = str_replace('index.md', '', $a['filepath']); $a['filepath'] = str_replace('index.md', '', $a['filepath']);
$b['filepath'] = str_replace('index.md', '', $b['filepath']); $b['filepath'] = str_replace('index.md', '', $b['filepath']);
if(strpos($b['filepath'], $a['filepath']) === 0) { if (strpos($b['filepath'], $a['filepath']) === 0) {
return -1; return -1;
} }
@ -373,7 +384,8 @@ class DocumentationManifest {
* @param string $link * @param string $link
* @return string * @return string
*/ */
protected function stripLinkBase($link) { protected function stripLinkBase($link)
{
return ltrim(str_replace( return ltrim(str_replace(
Config::inst()->get('DocumentationViewer', 'link_base'), Config::inst()->get('DocumentationViewer', 'link_base'),
'', '',
@ -387,7 +399,8 @@ class DocumentationManifest {
* @param string $basename * @param string $basename
* @param string $path * @param string $path
*/ */
protected function addPage($page, $basename, $path) { protected function addPage($page, $basename, $path)
{
$link = $this->stripLinkBase($page->Link()); $link = $this->stripLinkBase($page->Link());
$this->pages[$link] = array( $this->pages[$link] = array(
@ -406,7 +419,8 @@ class DocumentationManifest {
* @param string $from * @param string $from
* @param string $to * @param string $to
*/ */
protected function addRedirect($from, $to) { protected function addRedirect($from, $to)
{
$fromLink = $this->stripLinkBase($from); $fromLink = $this->stripLinkBase($from);
$toLink = $this->stripLinkBase($to); $toLink = $this->stripLinkBase($to);
$this->redirects[$fromLink] = $toLink; $this->redirects[$fromLink] = $toLink;
@ -415,7 +429,8 @@ class DocumentationManifest {
/** /**
* *
*/ */
public function handleFolder($basename, $path, $depth) { public function handleFolder($basename, $path, $depth)
{
$folder = Injector::inst()->create( $folder = Injector::inst()->create(
'DocumentationFolder', $this->entity, $basename, $path 'DocumentationFolder', $this->entity, $basename, $path
); );
@ -426,7 +441,7 @@ class DocumentationManifest {
// Add alternative link // Add alternative link
$shortLink = $folder->Link(true); $shortLink = $folder->Link(true);
if($shortLink != $fullLink) { if ($shortLink != $fullLink) {
$this->addRedirect($shortLink, $fullLink); $this->addRedirect($shortLink, $fullLink);
} }
} }
@ -443,7 +458,8 @@ class DocumentationManifest {
* @param string $path * @param string $path
* @param int $depth * @param int $depth
*/ */
public function handleFile($basename, $path, $depth) { public function handleFile($basename, $path, $depth)
{
$page = Injector::inst()->create( $page = Injector::inst()->create(
'DocumentationPage', 'DocumentationPage',
$this->entity, $basename, $path $this->entity, $basename, $path
@ -458,7 +474,7 @@ class DocumentationManifest {
// If this is a stable version, add the short link // If this is a stable version, add the short link
$shortLink = $page->Link(true); $shortLink = $page->Link(true);
if($fullLink != $shortLink) { if ($fullLink != $shortLink) {
$this->addRedirect($shortLink, $fullLink); $this->addRedirect($shortLink, $fullLink);
} }
} }
@ -471,7 +487,8 @@ class DocumentationManifest {
* *
* @return ArrayList * @return ArrayList
*/ */
public function generateBreadcrumbs($record, $base) { public function generateBreadcrumbs($record, $base)
{
$output = new ArrayList(); $output = new ArrayList();
$parts = explode('/', trim($record->getRelativeLink(), '/')); $parts = explode('/', trim($record->getRelativeLink(), '/'));
@ -484,8 +501,8 @@ class DocumentationManifest {
$progress = $base->Link(); $progress = $base->Link();
foreach($parts as $part) { foreach ($parts as $part) {
if($part) { if ($part) {
$progress = Controller::join_links($progress, $part, '/'); $progress = Controller::join_links($progress, $part, '/');
$output->push(new ArrayData(array( $output->push(new ArrayData(array(
@ -509,21 +526,22 @@ class DocumentationManifest {
* *
* @return ArrayData * @return ArrayData
*/ */
public function getNextPage($filepath, $entityBase) { public function getNextPage($filepath, $entityBase)
{
$grabNext = false; $grabNext = false;
$fallback = null; $fallback = null;
foreach($this->getPages() as $url => $page) { foreach ($this->getPages() as $url => $page) {
if($grabNext && strpos($page['filepath'], $entityBase) !== false) { if ($grabNext && strpos($page['filepath'], $entityBase) !== false) {
return new ArrayData(array( return new ArrayData(array(
'Link' => $url, 'Link' => $url,
'Title' => $page['title'] 'Title' => $page['title']
)); ));
} }
if($filepath == $page['filepath']) { if ($filepath == $page['filepath']) {
$grabNext = true; $grabNext = true;
} else if(!$fallback && strpos($page['filepath'], $filepath) !== false) { } elseif (!$fallback && strpos($page['filepath'], $filepath) !== false) {
$fallback = new ArrayData(array( $fallback = new ArrayData(array(
'Link' => $url, 'Link' => $url,
'Title' => $page['title'], 'Title' => $page['title'],
@ -532,7 +550,7 @@ class DocumentationManifest {
} }
} }
if(!$grabNext) { if (!$grabNext) {
return $fallback; return $fallback;
} }
@ -550,12 +568,13 @@ class DocumentationManifest {
* *
* @return ArrayData * @return ArrayData
*/ */
public function getPreviousPage($filepath, $entityPath) { public function getPreviousPage($filepath, $entityPath)
{
$previousUrl = $previousPage = null; $previousUrl = $previousPage = null;
foreach($this->getPages() as $url => $page) { foreach ($this->getPages() as $url => $page) {
if($filepath == $page['filepath']) { if ($filepath == $page['filepath']) {
if($previousUrl) { if ($previousUrl) {
return new ArrayData(array( return new ArrayData(array(
'Link' => $previousUrl, 'Link' => $previousUrl,
'Title' => $previousPage['title'] 'Title' => $previousPage['title']
@ -563,7 +582,7 @@ class DocumentationManifest {
} }
} }
if(strpos($page['filepath'], $entityPath) !== false) { if (strpos($page['filepath'], $entityPath) !== false) {
$previousUrl = $url; $previousUrl = $url;
$previousPage = $page; $previousPage = $page;
} }
@ -577,11 +596,12 @@ class DocumentationManifest {
* *
* @return string * @return string
*/ */
public function normalizeUrl($url) { public function normalizeUrl($url)
{
$url = trim($url, '/') .'/'; $url = trim($url, '/') .'/';
// if the page is the index page then hide it from the menu // if the page is the index page then hide it from the menu
if(strpos(strtolower($url), '/index.md/')) { if (strpos(strtolower($url), '/index.md/')) {
$url = substr($url, 0, strpos($url, "index.md/")); $url = substr($url, 0, strpos($url, "index.md/"));
} }
@ -597,8 +617,9 @@ class DocumentationManifest {
* *
* @return ArrayList * @return ArrayList
*/ */
public function getChildrenFor($entityPath, $recordPath = null) { public function getChildrenFor($entityPath, $recordPath = null)
if(!$recordPath) { {
if (!$recordPath) {
$recordPath = $entityPath; $recordPath = $entityPath;
} }
@ -606,35 +627,33 @@ class DocumentationManifest {
$base = Config::inst()->get('DocumentationViewer', 'link_base'); $base = Config::inst()->get('DocumentationViewer', 'link_base');
$entityPath = $this->normalizeUrl($entityPath); $entityPath = $this->normalizeUrl($entityPath);
$recordPath = $this->normalizeUrl($recordPath); $recordPath = $this->normalizeUrl($recordPath);
$recordParts = explode(DIRECTORY_SEPARATOR, trim($recordPath,'/')); $recordParts = explode(DIRECTORY_SEPARATOR, trim($recordPath, '/'));
$currentRecordPath = end($recordParts); $currentRecordPath = end($recordParts);
$depth = substr_count($entityPath, '/'); $depth = substr_count($entityPath, '/');
foreach($this->getPages() as $url => $page) { foreach ($this->getPages() as $url => $page) {
$pagePath = $this->normalizeUrl($page['filepath']); $pagePath = $this->normalizeUrl($page['filepath']);
// check to see if this page is under the given path // check to see if this page is under the given path
if(strpos($pagePath, $entityPath) === false) { if (strpos($pagePath, $entityPath) === false) {
continue; continue;
} }
// only pull it up if it's one more level depth // only pull it up if it's one more level depth
if(substr_count($pagePath, DIRECTORY_SEPARATOR) == ($depth + 1)) { if (substr_count($pagePath, DIRECTORY_SEPARATOR) == ($depth + 1)) {
$pagePathParts = explode(DIRECTORY_SEPARATOR, trim($pagePath,'/')); $pagePathParts = explode(DIRECTORY_SEPARATOR, trim($pagePath, '/'));
$currentPagePath = end($pagePathParts); $currentPagePath = end($pagePathParts);
if($currentPagePath == $currentRecordPath) { if ($currentPagePath == $currentRecordPath) {
$mode = 'current'; $mode = 'current';
} } elseif (strpos($recordPath, $pagePath) !== false) {
else if(strpos($recordPath, $pagePath) !== false) {
$mode = 'section'; $mode = 'section';
} } else {
else {
$mode = 'link'; $mode = 'link';
} }
$children = new ArrayList(); $children = new ArrayList();
if($mode == 'section' || $mode == 'current') { if ($mode == 'section' || $mode == 'current') {
$children = $this->getChildrenFor($pagePath, $recordPath); $children = $this->getChildrenFor($pagePath, $recordPath);
} }
@ -656,12 +675,13 @@ class DocumentationManifest {
* *
* @return ArrayList * @return ArrayList
*/ */
public function getAllVersionsOfEntity(DocumentationEntity $entity) { public function getAllVersionsOfEntity(DocumentationEntity $entity)
{
$all = new ArrayList(); $all = new ArrayList();
foreach($this->getEntities() as $check) { foreach ($this->getEntities() as $check) {
if($check->getKey() == $entity->getKey()) { if ($check->getKey() == $entity->getKey()) {
if($check->getLanguage() == $entity->getLanguage()) { if ($check->getLanguage() == $entity->getLanguage()) {
$all->push($check); $all->push($check);
} }
} }
@ -675,11 +695,12 @@ class DocumentationManifest {
* *
* @return DocumentationEntity * @return DocumentationEntity
*/ */
public function getStableVersion(DocumentationEntity $entity) { public function getStableVersion(DocumentationEntity $entity)
foreach($this->getEntities() as $check) { {
if($check->getKey() == $entity->getKey()) { foreach ($this->getEntities() as $check) {
if($check->getLanguage() == $entity->getLanguage()) { if ($check->getKey() == $entity->getKey()) {
if($check->getIsStable()) { if ($check->getLanguage() == $entity->getLanguage()) {
if ($check->getIsStable()) {
return $check; return $check;
} }
} }
@ -694,16 +715,17 @@ class DocumentationManifest {
* *
* @return ArrayList * @return ArrayList
*/ */
public function getVersions($entity) { public function getVersions($entity)
if(!$entity) { {
if (!$entity) {
return null; return null;
} }
$output = new ArrayList(); $output = new ArrayList();
foreach($this->getEntities() as $check) { foreach ($this->getEntities() as $check) {
if($check->getKey() == $entity->getKey()) { if ($check->getKey() == $entity->getKey()) {
if($check->getLanguage() == $entity->getLanguage()) { if ($check->getLanguage() == $entity->getLanguage()) {
$same = ($check->getVersion() == $entity->getVersion()); $same = ($check->getVersion() == $entity->getVersion());
$output->push(new ArrayData(array( $output->push(new ArrayData(array(
@ -712,7 +734,6 @@ class DocumentationManifest {
'LinkingMode' => ($same) ? 'current' : 'link', 'LinkingMode' => ($same) ? 'current' : 'link',
'IsStable' => $check->getIsStable() 'IsStable' => $check->getIsStable()
))); )));
} }
} }
} }
@ -723,11 +744,12 @@ class DocumentationManifest {
/** /**
* Returns a sorted array of all the unique versions registered * Returns a sorted array of all the unique versions registered
*/ */
public function getAllVersions() { public function getAllVersions()
{
$versions = array(); $versions = array();
foreach($this->getEntities() as $entity) { foreach ($this->getEntities() as $entity) {
if($entity->getVersion()) { if ($entity->getVersion()) {
$versions[$entity->getVersion()] = $entity->getVersion(); $versions[$entity->getVersion()] = $entity->getVersion();
} else { } else {
$versions['0.0'] = _t('DocumentationManifest.MASTER', 'Master'); $versions['0.0'] = _t('DocumentationManifest.MASTER', 'Master');

View File

@ -1,7 +1,7 @@
<?php <?php
class DocumentationManifestFileFinder extends SS_FileFinder { class DocumentationManifestFileFinder extends SS_FileFinder
{
/** /**
* @var array * @var array
*/ */
@ -23,16 +23,16 @@ class DocumentationManifestFileFinder extends SS_FileFinder {
/** /**
* *
*/ */
public function acceptDir($basename, $pathname, $depth) { public function acceptDir($basename, $pathname, $depth)
{
$ignored = Config::inst()->get('DocumentationManifestFileFinder', 'ignored_files'); $ignored = Config::inst()->get('DocumentationManifestFileFinder', 'ignored_files');
if($ignored) { if ($ignored) {
if(in_array(strtolower($basename), $ignored)) { if (in_array(strtolower($basename), $ignored)) {
return false; return false;
} }
} }
return true; return true;
} }
} }

View File

@ -7,8 +7,8 @@
* *
* @package docsviewer * @package docsviewer
*/ */
class DocumentationParser { class DocumentationParser
{
const CODE_BLOCK_BACKTICK = 1; const CODE_BLOCK_BACKTICK = 1;
const CODE_BLOCK_COLON = 2; const CODE_BLOCK_COLON = 2;
@ -41,8 +41,9 @@ class DocumentationParser {
* *
* @return String * @return String
*/ */
public static function parse(DocumentationPage $page, $baselink = null) { public static function parse(DocumentationPage $page, $baselink = null)
if(!$page || (!$page instanceof DocumentationPage)) { {
if (!$page || (!$page instanceof DocumentationPage)) {
return false; return false;
} }
@ -65,7 +66,8 @@ class DocumentationParser {
return $text; return $text;
} }
public static function rewrite_code_blocks($md) { public static function rewrite_code_blocks($md)
{
$started = false; $started = false;
$inner = false; $inner = false;
$mode = false; $mode = false;
@ -75,74 +77,88 @@ class DocumentationParser {
$lines = explode("\n", $md); $lines = explode("\n", $md);
$output = array(); $output = array();
foreach($lines as $i => $line) { foreach ($lines as $i => $line) {
if($debug) var_dump('Line '. ($i + 1) . ' '. $line); if ($debug) {
var_dump('Line '. ($i + 1) . ' '. $line);
}
// if line just contains whitespace, continue down the page. // if line just contains whitespace, continue down the page.
// Prevents code blocks with leading tabs adding an extra line. // Prevents code blocks with leading tabs adding an extra line.
if(preg_match('/^\s$/', $line) && !$started) { if (preg_match('/^\s$/', $line) && !$started) {
continue; continue;
} }
if(!$started && preg_match('/^[\t]*:::\s*(.*)/', $line, $matches)) { if (!$started && preg_match('/^[\t]*:::\s*(.*)/', $line, $matches)) {
// first line with custom formatting // first line with custom formatting
if($debug) var_dump('Starts a new block with :::'); if ($debug) {
var_dump('Starts a new block with :::');
}
$started = true; $started = true;
$mode = self::CODE_BLOCK_COLON; $mode = self::CODE_BLOCK_COLON;
$output[$i] = sprintf('```%s', (isset($matches[1])) ? trim($matches[1]) : ""); $output[$i] = sprintf('```%s', (isset($matches[1])) ? trim($matches[1]) : "");
} elseif (!$started && preg_match('/^\t*```\s*(.*)/', $line, $matches)) {
} else if(!$started && preg_match('/^\t*```\s*(.*)/', $line, $matches)) { if ($debug) {
if($debug) var_dump('Starts a new block with ```'); var_dump('Starts a new block with ```');
}
$started = true; $started = true;
$mode = self::CODE_BLOCK_BACKTICK; $mode = self::CODE_BLOCK_BACKTICK;
$output[$i] = sprintf('```%s', (isset($matches[1])) ? trim($matches[1]) : ""); $output[$i] = sprintf('```%s', (isset($matches[1])) ? trim($matches[1]) : "");
} else if($started && $mode == self::CODE_BLOCK_BACKTICK) { } elseif ($started && $mode == self::CODE_BLOCK_BACKTICK) {
// inside a backtick fenced box // inside a backtick fenced box
if(preg_match('/^\t*```\s*/', $line, $matches)) { if (preg_match('/^\t*```\s*/', $line, $matches)) {
if($debug) var_dump('End a block with ```'); if ($debug) {
var_dump('End a block with ```');
}
// end of the backtick fenced box. Unset the line that contains the backticks // end of the backtick fenced box. Unset the line that contains the backticks
$end = true; $end = true;
} else {
if ($debug) {
var_dump('Still in a block with ```');
} }
else {
if($debug) var_dump('Still in a block with ```');
// still inside the line. // still inside the line.
if(!$started) { if (!$started) {
$output[$i - 1] = '```'; $output[$i - 1] = '```';
} }
$output[$i] = $line; $output[$i] = $line;
$inner = true; $inner = true;
} }
} else if(preg_match('/^[\ ]{0,3}?[\t](.*)/', $line, $matches)) { } elseif (preg_match('/^[\ ]{0,3}?[\t](.*)/', $line, $matches)) {
// inner line of block, or first line of standard markdown code block // inner line of block, or first line of standard markdown code block
// regex removes first tab (any following tabs are part of the code). // regex removes first tab (any following tabs are part of the code).
if(!$started) { if (!$started) {
if($debug) var_dump('Start code block because of tab. No fence'); if ($debug) {
var_dump('Start code block because of tab. No fence');
}
$output[$i - 1] = '```'; $output[$i - 1] = '```';
} else { } else {
if($debug) var_dump('Content is still tabbed so still inner'); if ($debug) {
var_dump('Content is still tabbed so still inner');
}
} }
$output[$i] = $matches[1]; $output[$i] = $matches[1];
$inner = true; $inner = true;
$started = true; $started = true;
} else if($started && $inner && trim($line) === "") { } elseif ($started && $inner && trim($line) === "") {
if($debug) var_dump('Inner line of code block'); if ($debug) {
var_dump('Inner line of code block');
}
// still inside a colon based block, if the line is only whitespace // still inside a colon based block, if the line is only whitespace
// then continue with with it. We can continue with it for now as // then continue with with it. We can continue with it for now as
// it'll be tidied up later in the $end section. // it'll be tidied up later in the $end section.
$inner = true; $inner = true;
$output[$i] = $line; $output[$i] = $line;
} else if($started && $inner) { } elseif ($started && $inner) {
// line contains something other than whitespace, or tabbed. E.g // line contains something other than whitespace, or tabbed. E.g
// > code // > code
// > \n // > \n
@ -152,7 +168,7 @@ class DocumentationParser {
// and include this line. The edge case where this will fail is // and include this line. The edge case where this will fail is
// new the following segment contains a code block as well as it // new the following segment contains a code block as well as it
// will not open. // will not open.
if($debug) { if ($debug) {
var_dump('Contains something that isnt code. So end the code.'); var_dump('Contains something that isnt code. So end the code.');
} }
@ -163,8 +179,10 @@ class DocumentationParser {
$output[$i] = $line; $output[$i] = $line;
} }
if($end) { if ($end) {
if($debug) var_dump('End of code block'); if ($debug) {
var_dump('End of code block');
}
$output = self::finalize_code_output($i, $output); $output = self::finalize_code_output($i, $output);
// reset state // reset state
@ -172,12 +190,11 @@ class DocumentationParser {
} }
} }
if($started) { if ($started) {
$output = self::finalize_code_output($i+1, $output); $output = self::finalize_code_output($i+1, $output);
} }
return implode("\n", $output); return implode("\n", $output);
} }
/** /**
@ -188,18 +205,19 @@ class DocumentationParser {
* *
* @return array * @return array
*/ */
private static function finalize_code_output($i, $output) { private static function finalize_code_output($i, $output)
if(isset($output[$i]) && trim($output[$i])) { {
if (isset($output[$i]) && trim($output[$i])) {
$output[$i] .= "\n```\n"; $output[$i] .= "\n```\n";
} } else {
else {
$output[$i] = "```"; $output[$i] = "```";
} }
return $output; return $output;
} }
public static function rewrite_image_links($md, $page) { public static function rewrite_image_links($md, $page)
{
// Links with titles // Links with titles
$re = '/ $re = '/
! !
@ -212,15 +230,15 @@ class DocumentationParser {
/x'; /x';
preg_match_all($re, $md, $images); preg_match_all($re, $md, $images);
if($images) { if ($images) {
foreach($images[0] as $i => $match) { foreach ($images[0] as $i => $match) {
$title = $images[1][$i]; $title = $images[1][$i];
$url = $images[2][$i]; $url = $images[2][$i];
// Don't process absolute links (based on protocol detection) // Don't process absolute links (based on protocol detection)
$urlParts = parse_url($url); $urlParts = parse_url($url);
if($urlParts && isset($urlParts['scheme'])) { if ($urlParts && isset($urlParts['scheme'])) {
continue; continue;
} }
@ -230,7 +248,7 @@ class DocumentationParser {
); );
// if the image starts with a slash, it's absolute // if the image starts with a slash, it's absolute
if(substr($url, 0, 1) == '/') { if (substr($url, 0, 1) == '/') {
$relativeUrl = str_replace(BASE_PATH, '', Controller::join_links( $relativeUrl = str_replace(BASE_PATH, '', Controller::join_links(
$page->getEntity()->getPath(), $page->getEntity()->getPath(),
$url $url
@ -240,7 +258,7 @@ class DocumentationParser {
} }
// Resolve relative paths // Resolve relative paths
while(strpos($relativeUrl, '/..') !== FALSE) { while (strpos($relativeUrl, '/..') !== false) {
$relativeUrl = preg_replace('/\w+\/\.\.\//', '', $relativeUrl); $relativeUrl = preg_replace('/\w+\/\.\.\//', '', $relativeUrl);
} }
@ -278,7 +296,8 @@ class DocumentationParser {
* @param DocumentationPage $page * @param DocumentationPage $page
* @return String * @return String
*/ */
public static function rewrite_api_links($md, $page) { public static function rewrite_api_links($md, $page)
{
// Links with titles // Links with titles
$re = '/ $re = '/
`? `?
@ -291,8 +310,8 @@ class DocumentationParser {
`? `?
/x'; /x';
preg_match_all($re, $md, $linksWithTitles); preg_match_all($re, $md, $linksWithTitles);
if($linksWithTitles) { if ($linksWithTitles) {
foreach($linksWithTitles[0] as $i => $match) { foreach ($linksWithTitles[0] as $i => $match) {
$title = $linksWithTitles[1][$i]; $title = $linksWithTitles[1][$i];
$subject = $linksWithTitles[2][$i]; $subject = $linksWithTitles[2][$i];
@ -320,8 +339,8 @@ class DocumentationParser {
`? `?
/x'; /x';
preg_match_all($re, $md, $links); preg_match_all($re, $md, $links);
if($links) { if ($links) {
foreach($links[0] as $i => $match) { foreach ($links[0] as $i => $match) {
$subject = $links[1][$i]; $subject = $links[1][$i];
$url = sprintf( $url = sprintf(
self::$api_link_base, self::$api_link_base,
@ -344,7 +363,8 @@ class DocumentationParser {
/** /**
* *
*/ */
public static function rewrite_heading_anchors($md, $page) { public static function rewrite_heading_anchors($md, $page)
{
$re = '/^\#+(.*)/m'; $re = '/^\#+(.*)/m';
$md = preg_replace_callback($re, array('DocumentationParser', '_rewrite_heading_anchors_callback'), $md); $md = preg_replace_callback($re, array('DocumentationParser', '_rewrite_heading_anchors_callback'), $md);
@ -354,16 +374,18 @@ class DocumentationParser {
/** /**
* *
*/ */
public static function _rewrite_heading_anchors_callback($matches) { public static function _rewrite_heading_anchors_callback($matches)
{
$heading = $matches[0]; $heading = $matches[0];
$headingText = $matches[1]; $headingText = $matches[1];
if(preg_match('/\{\#.*\}/', $headingText)) return $heading; if (preg_match('/\{\#.*\}/', $headingText)) {
return $heading;
if(!isset(self::$heading_counts[$headingText])) {
self::$heading_counts[$headingText] = 1;
} }
else {
if (!isset(self::$heading_counts[$headingText])) {
self::$heading_counts[$headingText] = 1;
} else {
self::$heading_counts[$headingText]++; self::$heading_counts[$headingText]++;
$headingText .= "-" . self::$heading_counts[$headingText]; $headingText .= "-" . self::$heading_counts[$headingText];
} }
@ -376,12 +398,13 @@ class DocumentationParser {
* *
* @return String * @return String
*/ */
public static function generate_html_id($title) { public static function generate_html_id($title)
{
$t = $title; $t = $title;
$t = str_replace('&amp;','-and-',$t); $t = str_replace('&amp;', '-and-', $t);
$t = str_replace('&','-and-',$t); $t = str_replace('&', '-and-', $t);
$t = preg_replace('/[^A-Za-z0-9]+/','-',$t); $t = preg_replace('/[^A-Za-z0-9]+/', '-', $t);
$t = preg_replace('/-+/','-',$t); $t = preg_replace('/-+/', '-', $t);
$t = trim($t, '-'); $t = trim($t, '-');
$t = strtolower($t); $t = strtolower($t);
@ -396,7 +419,8 @@ class DocumentationParser {
* *
* @return String Markdown * @return String Markdown
*/ */
public static function rewrite_relative_links($md, $page) { public static function rewrite_relative_links($md, $page)
{
$baselink = $page->getEntity()->Link(); $baselink = $page->getEntity()->Link();
$re = '/ $re = '/
@ -414,46 +438,49 @@ class DocumentationParser {
// For "sapphire/en/current/topics/templates", this would be "templates" // For "sapphire/en/current/topics/templates", this would be "templates"
$relativePath = dirname($page->getRelativePath()); $relativePath = dirname($page->getRelativePath());
if(strpos($page->getRelativePath(), 'index.md')) { if (strpos($page->getRelativePath(), 'index.md')) {
$relativeLink = $page->getRelativeLink(); $relativeLink = $page->getRelativeLink();
} else { } else {
$relativeLink = dirname($page->getRelativeLink()); $relativeLink = dirname($page->getRelativeLink());
} }
if($relativePath == '.') { if ($relativePath == '.') {
$relativePath = ''; $relativePath = '';
} }
if($relativeLink == ".") { if ($relativeLink == ".") {
$relativeLink = ''; $relativeLink = '';
} }
// file base link // file base link
$fileBaseLink = Director::makeRelative(dirname($page->getPath())); $fileBaseLink = Director::makeRelative(dirname($page->getPath()));
if($matches) { if ($matches) {
foreach($matches[0] as $i => $match) { foreach ($matches[0] as $i => $match) {
$title = $matches[2][$i]; $title = $matches[2][$i];
$url = $matches[3][$i]; $url = $matches[3][$i];
// Don't process API links // Don't process API links
if(preg_match('/^api:/', $url)) continue; if (preg_match('/^api:/', $url)) {
continue;
}
// Don't process absolute links (based on protocol detection) // Don't process absolute links (based on protocol detection)
$urlParts = parse_url($url); $urlParts = parse_url($url);
if($urlParts && isset($urlParts['scheme'])) continue; if ($urlParts && isset($urlParts['scheme'])) {
continue;
}
// for images we need to use the file base path // for images we need to use the file base path
if(preg_match('/_images/', $url)) { if (preg_match('/_images/', $url)) {
$relativeUrl = Controller::join_links( $relativeUrl = Controller::join_links(
Director::absoluteBaseURL(), Director::absoluteBaseURL(),
$fileBaseLink, $fileBaseLink,
$url $url
); );
} } else {
else {
// Rewrite public URL // Rewrite public URL
if(preg_match('/^\//', $url)) { if (preg_match('/^\//', $url)) {
// Absolute: Only path to module base // Absolute: Only path to module base
$relativeUrl = Controller::join_links($baselink, $url, '/'); $relativeUrl = Controller::join_links($baselink, $url, '/');
} else { } else {
@ -463,7 +490,7 @@ class DocumentationParser {
} }
// Resolve relative paths // Resolve relative paths
while(strpos($relativeUrl, '..') !== FALSE) { while (strpos($relativeUrl, '..') !== false) {
$relativeUrl = preg_replace('/[-\w]+\/\.\.\//', '', $relativeUrl); $relativeUrl = preg_replace('/[-\w]+\/\.\.\//', '', $relativeUrl);
} }
@ -487,17 +514,18 @@ class DocumentationParser {
* *
* @param DocumentationPage * @param DocumentationPage
*/ */
public static function retrieve_meta_data(DocumentationPage &$page) { public static function retrieve_meta_data(DocumentationPage &$page)
if($md = $page->getMarkdown()) { {
if ($md = $page->getMarkdown()) {
$matches = preg_match_all('/ $matches = preg_match_all('/
(?<key>[A-Za-z0-9_-]+): (?<key>[A-Za-z0-9_-]+):
\s* \s*
(?<value>.*) (?<value>.*)
/x', $md, $meta); /x', $md, $meta);
if($matches) { if ($matches) {
foreach($meta['key'] as $index => $key) { foreach ($meta['key'] as $index => $key) {
if(isset($meta['value'][$index])) { if (isset($meta['value'][$index])) {
$page->setMetaData($key, $meta['value'][$index]); $page->setMetaData($key, $meta['value'][$index]);
} }
} }

View File

@ -9,8 +9,8 @@
* @package docsviewer * @package docsviewer
*/ */
class DocumentationPermalinks { class DocumentationPermalinks
{
/** /**
* @var array * @var array
*/ */
@ -30,11 +30,11 @@ class DocumentationPermalinks {
* *
* @param array * @param array
*/ */
public static function add($map = array()) { public static function add($map = array())
if(ArrayLib::is_associative($map)) { {
if (ArrayLib::is_associative($map)) {
self::$mapping = array_merge(self::$mapping, $map); self::$mapping = array_merge(self::$mapping, $map);
} } else {
else {
user_error("DocumentationPermalinks::add() requires an associative array", E_USER_ERROR); user_error("DocumentationPermalinks::add() requires an associative array", E_USER_ERROR);
} }
} }
@ -44,7 +44,8 @@ class DocumentationPermalinks {
* *
* @return string|false * @return string|false
*/ */
public static function map($url) { public static function map($url)
{
return (isset(self::$mapping[$url])) ? self::$mapping[$url] : false; return (isset(self::$mapping[$url])) ? self::$mapping[$url] : false;
} }
} }

View File

@ -31,8 +31,8 @@ require_once 'Zend/Search/Lucene.php';
* @package docsviewer * @package docsviewer
*/ */
class DocumentationSearch { class DocumentationSearch
{
/** /**
* @var bool - Is search enabled * @var bool - Is search enabled
*/ */
@ -82,11 +82,13 @@ class DocumentationSearch {
*/ */
private $modules, $versions; private $modules, $versions;
public function setModules($modules) { public function setModules($modules)
{
$this->modules = $modules; $this->modules = $modules;
} }
public function setVersions($versions) { public function setVersions($versions)
{
$this->versions = $versions; $this->versions = $versions;
} }
@ -95,7 +97,8 @@ class DocumentationSearch {
* *
* @param string * @param string
*/ */
public function setQuery($query) { public function setQuery($query)
{
$this->query = $query; $this->query = $query;
} }
@ -104,7 +107,8 @@ class DocumentationSearch {
* *
* @return string * @return string
*/ */
public function getQuery() { public function getQuery()
{
return $this->query; return $this->query;
} }
@ -114,7 +118,8 @@ class DocumentationSearch {
* *
* @param Controller * @param Controller
*/ */
public function setOutputController($controller) { public function setOutputController($controller)
{
$this->outputController = $controller; $this->outputController = $controller;
} }
@ -129,10 +134,11 @@ class DocumentationSearch {
/** /**
* @return string * @return string
*/ */
public static function get_index_location() { public static function get_index_location()
{
$location = Config::inst()->get('DocumentationSearch', 'index_location'); $location = Config::inst()->get('DocumentationSearch', 'index_location');
if(!$location) { if (!$location) {
return Controller::join_links(TEMP_FOLDER, 'RebuildLuceneDocsIndex'); return Controller::join_links(TEMP_FOLDER, 'RebuildLuceneDocsIndex');
} }
@ -142,8 +148,8 @@ class DocumentationSearch {
/** /**
* Perform a search query on the index * Perform a search query on the index
*/ */
public function performSearch() { public function performSearch()
{
try { try {
$index = Zend_Search_Lucene::open(self::get_index_location()); $index = Zend_Search_Lucene::open(self::get_index_location());
@ -153,20 +159,20 @@ class DocumentationSearch {
$term = Zend_Search_Lucene_Search_QueryParser::parse($this->getQuery()); $term = Zend_Search_Lucene_Search_QueryParser::parse($this->getQuery());
$query->addSubquery($term, true); $query->addSubquery($term, true);
if($this->modules) { if ($this->modules) {
$moduleQuery = new Zend_Search_Lucene_Search_Query_MultiTerm(); $moduleQuery = new Zend_Search_Lucene_Search_Query_MultiTerm();
foreach($this->modules as $module) { foreach ($this->modules as $module) {
$moduleQuery->addTerm(new Zend_Search_Lucene_Index_Term($module, 'Entity')); $moduleQuery->addTerm(new Zend_Search_Lucene_Index_Term($module, 'Entity'));
} }
$query->addSubquery($moduleQuery, true); $query->addSubquery($moduleQuery, true);
} }
if($this->versions) { if ($this->versions) {
$versionQuery = new Zend_Search_Lucene_Search_Query_MultiTerm(); $versionQuery = new Zend_Search_Lucene_Search_Query_MultiTerm();
foreach($this->versions as $version) { foreach ($this->versions as $version) {
$versionQuery->addTerm(new Zend_Search_Lucene_Index_Term($version, 'Version')); $versionQuery->addTerm(new Zend_Search_Lucene_Index_Term($version, 'Version'));
} }
@ -178,8 +184,7 @@ class DocumentationSearch {
$this->results = $index->find($query); $this->results = $index->find($query);
error_reporting($er); error_reporting($er);
$this->totalResults = $index->numDocs(); $this->totalResults = $index->numDocs();
} } catch (Zend_Search_Lucene_Exception $e) {
catch(Zend_Search_Lucene_Exception $e) {
user_error($e .'. Ensure you have run the rebuld task (/dev/tasks/RebuildLuceneDocsIndex)', E_USER_ERROR); user_error($e .'. Ensure you have run the rebuld task (/dev/tasks/RebuildLuceneDocsIndex)', E_USER_ERROR);
} }
} }
@ -187,7 +192,8 @@ class DocumentationSearch {
/** /**
* @return ArrayData * @return ArrayData
*/ */
public function getSearchResults($request) { public function getSearchResults($request)
{
$pageLength = (isset($_GET['length'])) ? (int) $_GET['length'] : 10; $pageLength = (isset($_GET['length'])) ? (int) $_GET['length'] : 10;
$data = array( $data = array(
@ -210,9 +216,9 @@ class DocumentationSearch {
$start = ($request->requestVar('start')) ? (int)$request->requestVar('start') : 0; $start = ($request->requestVar('start')) ? (int)$request->requestVar('start') : 0;
$query = ($request->requestVar('q')) ? $request->requestVar('q') : ''; $query = ($request->requestVar('q')) ? $request->requestVar('q') : '';
$currentPage = floor( $start / $pageLength ) + 1; $currentPage = floor($start / $pageLength) + 1;
$totalPages = ceil(count($this->results) / $pageLength ); $totalPages = ceil(count($this->results) / $pageLength);
if ($totalPages == 0) { if ($totalPages == 0) {
$totalPages = 1; $totalPages = 1;
@ -224,9 +230,9 @@ class DocumentationSearch {
$results = new ArrayList(); $results = new ArrayList();
if($this->results) { if ($this->results) {
foreach($this->results as $k => $hit) { foreach ($this->results as $k => $hit) {
if($k < ($currentPage-1)*$pageLength || $k >= ($currentPage*$pageLength)) { if ($k < ($currentPage-1)*$pageLength || $k >= ($currentPage*$pageLength)) {
continue; continue;
} }
@ -237,9 +243,9 @@ class DocumentationSearch {
$obj = new ArrayData(array( $obj = new ArrayData(array(
'Title' => DBField::create_field('Varchar', $doc->getFieldValue('Title')), 'Title' => DBField::create_field('Varchar', $doc->getFieldValue('Title')),
'BreadcrumbTitle' => DBField::create_field('HTMLText', $doc->getFieldValue('BreadcrumbTitle')), 'BreadcrumbTitle' => DBField::create_field('HTMLText', $doc->getFieldValue('BreadcrumbTitle')),
'Link' => DBField::create_field('Varchar',$doc->getFieldValue('Link')), 'Link' => DBField::create_field('Varchar', $doc->getFieldValue('Link')),
'Language' => DBField::create_field('Varchar',$doc->getFieldValue('Language')), 'Language' => DBField::create_field('Varchar', $doc->getFieldValue('Language')),
'Version' => DBField::create_field('Varchar',$doc->getFieldValue('Version')), 'Version' => DBField::create_field('Varchar', $doc->getFieldValue('Version')),
'Entity' => DBField::create_field('Varchar', $doc->getFieldValue('Entity')), 'Entity' => DBField::create_field('Varchar', $doc->getFieldValue('Entity')),
'Content' => DBField::create_field('HTMLText', $content), 'Content' => DBField::create_field('HTMLText', $content),
'Score' => $hit->score, 'Score' => $hit->score,
@ -260,21 +266,21 @@ class DocumentationSearch {
$data['EndResult'] = $start + count($results); $data['EndResult'] = $start + count($results);
// Pagination links // Pagination links
if($currentPage > 1) { if ($currentPage > 1) {
$data['PrevUrl'] = DBField::create_field('Text', $data['PrevUrl'] = DBField::create_field('Text',
$this->buildQueryUrl(array('start' => ($currentPage - 2) * $pageLength)) $this->buildQueryUrl(array('start' => ($currentPage - 2) * $pageLength))
); );
} }
if($currentPage < $totalPages) { if ($currentPage < $totalPages) {
$data['NextUrl'] = DBField::create_field('Text', $data['NextUrl'] = DBField::create_field('Text',
$this->buildQueryUrl(array('start' => $currentPage * $pageLength)) $this->buildQueryUrl(array('start' => $currentPage * $pageLength))
); );
} }
if($totalPages > 1) { if ($totalPages > 1) {
// Always show a certain number of pages at the start // Always show a certain number of pages at the start
for ( $i = 1; $i <= $totalPages; $i++ ) { for ($i = 1; $i <= $totalPages; $i++) {
$obj = new DataObject(); $obj = new DataObject();
$obj->IsEllipsis = false; $obj->IsEllipsis = false;
$obj->PageNumber = $i; $obj->PageNumber = $i;
@ -283,7 +289,9 @@ class DocumentationSearch {
)); ));
$obj->Current = false; $obj->Current = false;
if ( $i == $currentPage ) $obj->Current = true; if ($i == $currentPage) {
$obj->Current = true;
}
$data['SearchPages']->push($obj); $data['SearchPages']->push($obj);
} }
} }
@ -296,13 +304,20 @@ class DocumentationSearch {
* *
* @return string * @return string
*/ */
private function buildQueryUrl($params) { private function buildQueryUrl($params)
{
$url = parse_url($_SERVER['REQUEST_URI']); $url = parse_url($_SERVER['REQUEST_URI']);
if ( ! array_key_exists('query', $url) ) $url['query'] = ''; if (! array_key_exists('query', $url)) {
$url['query'] = '';
}
parse_str($url['query'], $url['query']); parse_str($url['query'], $url['query']);
if ( ! is_array($url['query']) ) $url['query'] = array(); if (! is_array($url['query'])) {
$url['query'] = array();
}
// Remove 'start parameter if it exists // Remove 'start parameter if it exists
if ( array_key_exists('start', $url['query']) ) unset( $url['query']['start'] ); if (array_key_exists('start', $url['query'])) {
unset($url['query']['start']);
}
// Add extra parameters from argument // Add extra parameters from argument
$url['query'] = array_merge($url['query'], $params); $url['query'] = array_merge($url['query'], $params);
$url['query'] = http_build_query($url['query']); $url['query'] = http_build_query($url['query']);
@ -314,7 +329,8 @@ class DocumentationSearch {
/** /**
* @return int * @return int
*/ */
public function getTotalResults() { public function getTotalResults()
{
return (int) $this->totalResults; return (int) $this->totalResults;
} }
@ -323,16 +339,20 @@ class DocumentationSearch {
* *
* @return void * @return void
*/ */
public function optimizeIndex() { public function optimizeIndex()
{
$index = Zend_Search_Lucene::open(self::get_index_location()); $index = Zend_Search_Lucene::open(self::get_index_location());
if($index) $index->optimize(); if ($index) {
$index->optimize();
}
} }
/** /**
* @return String * @return String
*/ */
public function getTitle() { public function getTitle()
{
return ($this->outputController) ? $this->outputController->Title : _t('DocumentationSearch.SEARCH', 'Search'); return ($this->outputController) ? $this->outputController->Title : _t('DocumentationSearch.SEARCH', 'Search');
} }
@ -342,13 +362,13 @@ class DocumentationSearch {
* *
* @param array * @param array
*/ */
public static function set_meta_data($data) { public static function set_meta_data($data)
if(is_array($data)) { {
foreach($data as $key => $value) { if (is_array($data)) {
foreach ($data as $key => $value) {
self::$meta_data[strtolower($key)] = $value; self::$meta_data[strtolower($key)] = $value;
} }
} } else {
else {
user_error("set_meta_data must be passed an array", E_USER_ERROR); user_error("set_meta_data must be passed an array", E_USER_ERROR);
} }
} }
@ -358,7 +378,8 @@ class DocumentationSearch {
* *
* @return array * @return array
*/ */
public static function get_meta_data() { public static function get_meta_data()
{
$data = self::$meta_data; $data = self::$meta_data;
$defaults = array( $defaults = array(
@ -369,8 +390,10 @@ class DocumentationSearch {
'Author' => 'SilverStripe' 'Author' => 'SilverStripe'
); );
foreach($defaults as $key => $value) { foreach ($defaults as $key => $value) {
if(isset($data[$key])) $defaults[$key] = $data[$key]; if (isset($data[$key])) {
$defaults[$key] = $data[$key];
}
} }
return $defaults; return $defaults;
@ -380,12 +403,13 @@ class DocumentationSearch {
* Renders the search results into a template. Either the search results * Renders the search results into a template. Either the search results
* template or the Atom feed. * template or the Atom feed.
*/ */
public function renderResults() { public function renderResults()
if(!$this->results && $this->query) { {
if (!$this->results && $this->query) {
$this->performSearch(); $this->performSearch();
} }
if(!$this->outputController) { if (!$this->outputController) {
return user_error('Call renderResults() on a DocumentationViewer instance.', E_USER_ERROR); return user_error('Call renderResults() on a DocumentationViewer instance.', E_USER_ERROR);
} }
@ -393,7 +417,7 @@ class DocumentationSearch {
$data = $this->getSearchResults($request); $data = $this->getSearchResults($request);
$templates = array('DocumentationViewer_search'); $templates = array('DocumentationViewer_search');
if($request->requestVar('format') && $request->requestVar('format') == "atom") { if ($request->requestVar('format') && $request->requestVar('format') == "atom") {
// alter the fields for the opensearch xml. // alter the fields for the opensearch xml.
$title = ($title = $this->getTitle()) ? ' - '. $title : ""; $title = ($title = $this->getTitle()) ? ' - '. $title : "";

View File

@ -7,24 +7,26 @@
* @package docsviewer * @package docsviewer
*/ */
class DocumentationOpenSearchController extends Controller { class DocumentationOpenSearchController extends Controller
{
private static $allowed_actions = array( private static $allowed_actions = array(
'description' 'description'
); );
public function index() { public function index()
{
return $this->httpError(404); return $this->httpError(404);
} }
public function description() { public function description()
{
$viewer = new DocumentationViewer(); $viewer = new DocumentationViewer();
if(!$viewer->canView()) { if (!$viewer->canView()) {
return Security::permissionFailure($this); return Security::permissionFailure($this);
} }
if(!Config::inst()->get('DocumentationSearch', 'enabled')) { if (!Config::inst()->get('DocumentationSearch', 'enabled')) {
return $this->httpError('404'); return $this->httpError('404');
} }

View File

@ -12,8 +12,8 @@
* @package docsviewer * @package docsviewer
*/ */
class DocumentationViewer extends Controller { class DocumentationViewer extends Controller
{
/** /**
* @var array * @var array
*/ */
@ -82,10 +82,11 @@ class DocumentationViewer extends Controller {
/** /**
* *
*/ */
public function init() { public function init()
{
parent::init(); parent::init();
if(!$this->canView()) { if (!$this->canView()) {
return Security::permissionFailure($this); return Security::permissionFailure($this);
} }
Requirements::javascript('//use.typekit.net/emt4dhq.js'); Requirements::javascript('//use.typekit.net/emt4dhq.js');
@ -111,18 +112,21 @@ class DocumentationViewer extends Controller {
* *
* @return bool * @return bool
*/ */
public function canView() { public function canView()
{
return (Director::isDev() || Director::is_cli() || return (Director::isDev() || Director::is_cli() ||
!$this->config()->get('check_permission') || !$this->config()->get('check_permission') ||
Permission::check($this->config()->get('check_permission')) Permission::check($this->config()->get('check_permission'))
); );
} }
public function hasAction($action) { public function hasAction($action)
{
return true; return true;
} }
public function checkAccessAction($action) { public function checkAccessAction($action)
{
return true; return true;
} }
@ -136,9 +140,10 @@ class DocumentationViewer extends Controller {
* *
* @return SS_HTTPResponse * @return SS_HTTPResponse
*/ */
public function handleAction($request, $action) { public function handleAction($request, $action)
{
// if we submitted a form, let that pass // if we submitted a form, let that pass
if(!$request->isGET()) { if (!$request->isGET()) {
return parent::handleAction($request, $action); return parent::handleAction($request, $action);
} }
@ -148,7 +153,7 @@ class DocumentationViewer extends Controller {
// If the current request has an extension attached to it, strip that // If the current request has an extension attached to it, strip that
// off and redirect the user to the page without an extension. // off and redirect the user to the page without an extension.
// //
if(DocumentationHelper::get_extension($url)) { if (DocumentationHelper::get_extension($url)) {
$this->response = new SS_HTTPResponse(); $this->response = new SS_HTTPResponse();
$this->response->redirect( $this->response->redirect(
DocumentationHelper::trim_extension_off($url) .'/', DocumentationHelper::trim_extension_off($url) .'/',
@ -168,19 +173,18 @@ class DocumentationViewer extends Controller {
Config::inst()->get('DocumentationViewer', 'link_base'), '/' Config::inst()->get('DocumentationViewer', 'link_base'), '/'
); );
if($base && strpos($url, $base) !== false) { if ($base && strpos($url, $base) !== false) {
$url = substr( $url = substr(
ltrim($url, '/'), ltrim($url, '/'),
strlen($base) strlen($base)
); );
} else { } else {
} }
// //
// Handle any permanent redirections that the developer has defined. // Handle any permanent redirections that the developer has defined.
// //
if($link = DocumentationPermalinks::map($url)) { if ($link = DocumentationPermalinks::map($url)) {
// the first param is a shortcode for a page so redirect the user to // the first param is a shortcode for a page so redirect the user to
// the short code. // the short code.
$this->response = new SS_HTTPResponse(); $this->response = new SS_HTTPResponse();
@ -199,16 +203,16 @@ class DocumentationViewer extends Controller {
// //
$languages = i18n::get_common_languages(); $languages = i18n::get_common_languages();
if(!$lang = $request->param('Lang')) { if (!$lang = $request->param('Lang')) {
$lang = $request->param('Action'); $lang = $request->param('Action');
$action = $request->param('ID'); $action = $request->param('ID');
} else { } else {
$action = $request->param('Action'); $action = $request->param('Action');
} }
if(!$lang) { if (!$lang) {
return $this->redirect($this->Link('en')); return $this->redirect($this->Link('en'));
} else if(!isset($languages[$lang])) { } elseif (!isset($languages[$lang])) {
return $this->httpError(404); return $this->httpError(404);
} }
@ -216,7 +220,7 @@ class DocumentationViewer extends Controller {
$allowed = $this->config()->allowed_actions; $allowed = $this->config()->allowed_actions;
if(in_array($action, $allowed)) { if (in_array($action, $allowed)) {
// //
// if it's one of the allowed actions such as search or all then the // if it's one of the allowed actions such as search or all then the
// URL must be prefixed with one of the allowed languages. // URL must be prefixed with one of the allowed languages.
@ -236,7 +240,7 @@ class DocumentationViewer extends Controller {
// return $redirect->redirect($cleaned, 302); // return $redirect->redirect($cleaned, 302);
// } // }
if($record = $this->getManifest()->getPage($url)) { if ($record = $this->getManifest()->getPage($url)) {
$this->record = $record; $this->record = $record;
$this->init(); $this->init();
@ -247,11 +251,11 @@ class DocumentationViewer extends Controller {
)); ));
return new SS_HTTPResponse($body, 200); return new SS_HTTPResponse($body, 200);
} else if($redirect = $this->getManifest()->getRedirect($url)) { } elseif ($redirect = $this->getManifest()->getRedirect($url)) {
$response = new SS_HTTPResponse(); $response = new SS_HTTPResponse();
$to = Controller::join_links(Director::baseURL(), $base, $redirect); $to = Controller::join_links(Director::baseURL(), $base, $redirect);
return $response->redirect($to, 301); return $response->redirect($to, 301);
} else if(!$url || $url == $lang) { } elseif (!$url || $url == $lang) {
$body = $this->renderWith(array( $body = $this->renderWith(array(
"DocumentationViewer_DocumentationFolder", "DocumentationViewer_DocumentationFolder",
"DocumentationViewer" "DocumentationViewer"
@ -270,7 +274,8 @@ class DocumentationViewer extends Controller {
* *
* @return SS_HTTPResponse * @return SS_HTTPResponse
*/ */
public function httpError($status, $message = null) { public function httpError($status, $message = null)
{
$this->init(); $this->init();
$class = get_class($this); $class = get_class($this);
@ -284,8 +289,9 @@ class DocumentationViewer extends Controller {
/** /**
* @return DocumentationManifest * @return DocumentationManifest
*/ */
public function getManifest() { public function getManifest()
if(!$this->manifest) { {
if (!$this->manifest) {
$flush = SapphireTest::is_running_test() || (isset($_GET['flush'])); $flush = SapphireTest::is_running_test() || (isset($_GET['flush']));
$this->manifest = new DocumentationManifest($flush); $this->manifest = new DocumentationManifest($flush);
@ -297,8 +303,9 @@ class DocumentationViewer extends Controller {
/** /**
* @return string * @return string
*/ */
public function getLanguage() { public function getLanguage()
if(!$lang = $this->request->param('Lang')) { {
if (!$lang = $this->request->param('Lang')) {
$lang = $this->request->param('Action'); $lang = $this->request->param('Action');
} }
@ -313,24 +320,25 @@ class DocumentationViewer extends Controller {
* *
* @return DataObject * @return DataObject
*/ */
public function getMenu() { public function getMenu()
{
$entities = $this->getManifest()->getEntities(); $entities = $this->getManifest()->getEntities();
$output = new ArrayList(); $output = new ArrayList();
$record = $this->getPage(); $record = $this->getPage();
$current = $this->getEntity(); $current = $this->getEntity();
foreach($entities as $entity) { foreach ($entities as $entity) {
$checkLang = $entity->getLanguage(); $checkLang = $entity->getLanguage();
$checkVers = $entity->getVersion(); $checkVers = $entity->getVersion();
// only show entities with the same language or any entity that // only show entities with the same language or any entity that
// isn't registered under any particular language (auto detected) // isn't registered under any particular language (auto detected)
if($checkLang && $checkLang !== $this->getLanguage()) { if ($checkLang && $checkLang !== $this->getLanguage()) {
continue; continue;
} }
if($current && $checkVers) { if ($current && $checkVers) {
if($entity->getVersion() !== $current->getVersion()) { if ($entity->getVersion() !== $current->getVersion()) {
continue; continue;
} }
} }
@ -338,7 +346,7 @@ class DocumentationViewer extends Controller {
$mode = 'link'; $mode = 'link';
$children = new ArrayList(); $children = new ArrayList();
if($entity->hasRecord($record) || $entity->getIsDefaultEntity()) { if ($entity->hasRecord($record) || $entity->getIsDefaultEntity()) {
$mode = 'current'; $mode = 'current';
// add children // add children
@ -346,7 +354,7 @@ class DocumentationViewer extends Controller {
$entity->getPath(), ($record) ? $record->getPath() : $entity->getPath() $entity->getPath(), ($record) ? $record->getPath() : $entity->getPath()
); );
} else { } else {
if($current && $current->getKey() == $entity->getKey()) { if ($current && $current->getKey() == $entity->getKey()) {
continue; continue;
} }
} }
@ -372,7 +380,8 @@ class DocumentationViewer extends Controller {
* *
* @return HTMLText * @return HTMLText
*/ */
public function getContent() { public function getContent()
{
$page = $this->getPage(); $page = $this->getPage();
$html = $page->getHTML(); $html = $page->getHTML();
$html = $this->replaceChildrenCalls($html); $html = $this->replaceChildrenCalls($html);
@ -380,7 +389,8 @@ class DocumentationViewer extends Controller {
return $html; return $html;
} }
public function replaceChildrenCalls($html) { public function replaceChildrenCalls($html)
{
$codes = new ShortcodeParser(); $codes = new ShortcodeParser();
$codes->register('CHILDREN', array($this, 'includeChildren')); $codes->register('CHILDREN', array($this, 'includeChildren'));
@ -390,8 +400,9 @@ class DocumentationViewer extends Controller {
/** /**
* Short code parser * Short code parser
*/ */
public function includeChildren($args) { public function includeChildren($args)
if(isset($args['Folder'])) { {
if (isset($args['Folder'])) {
$children = $this->getManifest()->getChildrenFor( $children = $this->getManifest()->getChildrenFor(
Controller::join_links(dirname($this->record->getPath()), $args['Folder']) Controller::join_links(dirname($this->record->getPath()), $args['Folder'])
); );
@ -401,12 +412,12 @@ class DocumentationViewer extends Controller {
); );
} }
if(isset($args['Exclude'])) { if (isset($args['Exclude'])) {
$exclude = explode(',', $args['Exclude']); $exclude = explode(',', $args['Exclude']);
foreach($children as $k => $child) { foreach ($children as $k => $child) {
foreach($exclude as $e) { foreach ($exclude as $e) {
if($child->Link == Controller::join_links($this->record->Link(), strtolower($e), '/')) { if ($child->Link == Controller::join_links($this->record->Link(), strtolower($e), '/')) {
unset($children[$k]); unset($children[$k]);
} }
} }
@ -421,12 +432,13 @@ class DocumentationViewer extends Controller {
/** /**
* @return ArrayList * @return ArrayList
*/ */
public function getChildren() { public function getChildren()
if($this->record instanceof DocumentationFolder) { {
if ($this->record instanceof DocumentationFolder) {
return $this->getManifest()->getChildrenFor( return $this->getManifest()->getChildrenFor(
$this->record->getPath() $this->record->getPath()
); );
} else if($this->record) { } elseif ($this->record) {
return $this->getManifest()->getChildrenFor( return $this->getManifest()->getChildrenFor(
dirname($this->record->getPath()) dirname($this->record->getPath())
); );
@ -440,8 +452,9 @@ class DocumentationViewer extends Controller {
* *
* @return ArrayList * @return ArrayList
*/ */
public function getBreadcrumbs() { public function getBreadcrumbs()
if($this->record) { {
if ($this->record) {
return $this->getManifest()->generateBreadcrumbs( return $this->getManifest()->generateBreadcrumbs(
$this->record, $this->record,
$this->record->getEntity() $this->record->getEntity()
@ -452,21 +465,24 @@ class DocumentationViewer extends Controller {
/** /**
* @return DocumentationPage * @return DocumentationPage
*/ */
public function getPage() { public function getPage()
{
return $this->record; return $this->record;
} }
/** /**
* @return DocumentationEntity * @return DocumentationEntity
*/ */
public function getEntity() { public function getEntity()
{
return ($this->record) ? $this->record->getEntity() : null; return ($this->record) ? $this->record->getEntity() : null;
} }
/** /**
* @return ArrayList * @return ArrayList
*/ */
public function getVersions() { public function getVersions()
{
return $this->getManifest()->getVersions($this->getEntity()); return $this->getManifest()->getVersions($this->getEntity());
} }
@ -475,14 +491,16 @@ class DocumentationViewer extends Controller {
* *
* @return string * @return string
*/ */
public function getTitle() { public function getTitle()
{
return ($this->record) ? $this->record->getTitle() : null; return ($this->record) ? $this->record->getTitle() : null;
} }
/** /**
* @return string * @return string
*/ */
public function AbsoluteLink($action) { public function AbsoluteLink($action)
{
return Controller::join_links( return Controller::join_links(
Director::absoluteBaseUrl(), Director::absoluteBaseUrl(),
$this->Link($action) $this->Link($action)
@ -494,7 +512,8 @@ class DocumentationViewer extends Controller {
* *
* @return string * @return string
*/ */
public function Link($action = '') { public function Link($action = '')
{
$link = Controller::join_links( $link = Controller::join_links(
Config::inst()->get('DocumentationViewer', 'link_base'), Config::inst()->get('DocumentationViewer', 'link_base'),
$this->getLanguage(), $this->getLanguage(),
@ -511,14 +530,15 @@ class DocumentationViewer extends Controller {
* *
* @return GroupedList * @return GroupedList
*/ */
public function AllPages() { public function AllPages()
{
$pages = $this->getManifest()->getPages(); $pages = $this->getManifest()->getPages();
$output = new ArrayList(); $output = new ArrayList();
foreach($pages as $url => $page) { foreach ($pages as $url => $page) {
$first = strtoupper(trim(substr($page['title'], 0, 1))); $first = strtoupper(trim(substr($page['title'], 0, 1)));
if($first) { if ($first) {
$output->push(new ArrayData(array( $output->push(new ArrayData(array(
'Link' => $url, 'Link' => $url,
'Title' => $page['title'], 'Title' => $page['title'],
@ -536,8 +556,9 @@ class DocumentationViewer extends Controller {
* *
* @return Form * @return Form
*/ */
public function DocumentationSearchForm() { public function DocumentationSearchForm()
if(!Config::inst()->get('DocumentationSearch','enabled')) { {
if (!Config::inst()->get('DocumentationSearch', 'enabled')) {
return false; return false;
} }
@ -568,7 +589,8 @@ class DocumentationViewer extends Controller {
* @param string link * @param string link
* @param array options ('rewritetrunktomaster') * @param array options ('rewritetrunktomaster')
*/ */
public static function set_edit_link($module, $link, $options = array()) { public static function set_edit_link($module, $link, $options = array())
{
self::$edit_links[$module] = array( self::$edit_links[$module] = array(
'url' => $link, 'url' => $link,
'options' => $options 'options' => $options
@ -580,29 +602,28 @@ class DocumentationViewer extends Controller {
* *
* @return string * @return string
*/ */
public function getEditLink() { public function getEditLink()
{
$page = $this->getPage(); $page = $this->getPage();
if($page) { if ($page) {
$entity = $page->getEntity(); $entity = $page->getEntity();
if($entity && isset(self::$edit_links[strtolower($entity->title)])) { if ($entity && isset(self::$edit_links[strtolower($entity->title)])) {
// build the edit link, using the version defined // build the edit link, using the version defined
$url = self::$edit_links[strtolower($entity->title)]; $url = self::$edit_links[strtolower($entity->title)];
$version = $entity->getVersion(); $version = $entity->getVersion();
if($entity->getBranch()){ if ($entity->getBranch()) {
$version = $entity->getBranch(); $version = $entity->getBranch();
} }
if($version == "trunk" && (isset($url['options']['rewritetrunktomaster']))) { if ($version == "trunk" && (isset($url['options']['rewritetrunktomaster']))) {
if($url['options']['rewritetrunktomaster']) { if ($url['options']['rewritetrunktomaster']) {
$version = "master"; $version = "master";
} }
} }
@ -632,7 +653,8 @@ class DocumentationViewer extends Controller {
* *
* @return DocumentationPage * @return DocumentationPage
*/ */
public function getNextPage() { public function getNextPage()
{
return ($this->record) return ($this->record)
? $this->getManifest()->getNextPage( ? $this->getManifest()->getNextPage(
$this->record->getPath(), $this->getEntity()->getPath()) $this->record->getPath(), $this->getEntity()->getPath())
@ -645,7 +667,8 @@ class DocumentationViewer extends Controller {
* *
* @return DocumentationPage * @return DocumentationPage
*/ */
public function getPreviousPage() { public function getPreviousPage()
{
return ($this->record) return ($this->record)
? $this->getManifest()->getPreviousPage( ? $this->getManifest()->getPreviousPage(
$this->record->getPath(), $this->getEntity()->getPath()) $this->record->getPath(), $this->getEntity()->getPath())
@ -655,10 +678,11 @@ class DocumentationViewer extends Controller {
/** /**
* @return string * @return string
*/ */
public function getGoogleAnalyticsCode() { public function getGoogleAnalyticsCode()
{
$code = $this->config()->get('google_analytics_code'); $code = $this->config()->get('google_analytics_code');
if($code) { if ($code) {
return $code; return $code;
} }
} }
@ -666,11 +690,13 @@ class DocumentationViewer extends Controller {
/** /**
* @return string * @return string
*/ */
public function getDocumentationTitle() { public function getDocumentationTitle()
{
return $this->config()->get('documentation_title'); return $this->config()->get('documentation_title');
} }
public function getDocumentationBaseHref() { public function getDocumentationBaseHref()
{
return Config::inst()->get('DocumentationViewer', 'link_base'); return Config::inst()->get('DocumentationViewer', 'link_base');
} }
} }

View File

@ -1,20 +1,20 @@
<?php <?php
class DocumentationSearchExtension extends Extension { class DocumentationSearchExtension extends Extension
{
/** /**
* Return an array of folders and titles * Return an array of folders and titles
* *
* @return array * @return array
*/ */
public function getSearchedEntities() { public function getSearchedEntities()
{
$entities = array(); $entities = array();
if(!empty($_REQUEST['Entities'])) { if (!empty($_REQUEST['Entities'])) {
if(is_array($_REQUEST['Entities'])) { if (is_array($_REQUEST['Entities'])) {
$entities = Convert::raw2att($_REQUEST['Entities']); $entities = Convert::raw2att($_REQUEST['Entities']);
} } else {
else {
$entities = explode(',', Convert::raw2att($_REQUEST['Entities'])); $entities = explode(',', Convert::raw2att($_REQUEST['Entities']));
$entities = array_combine($entities, $entities); $entities = array_combine($entities, $entities);
} }
@ -28,15 +28,15 @@ class DocumentationSearchExtension extends Extension {
* *
* @return array * @return array
*/ */
public function getSearchedVersions() { public function getSearchedVersions()
{
$versions = array(); $versions = array();
if(!empty($_REQUEST['Versions'])) { if (!empty($_REQUEST['Versions'])) {
if(is_array($_REQUEST['Versions'])) { if (is_array($_REQUEST['Versions'])) {
$versions = Convert::raw2att($_REQUEST['Versions']); $versions = Convert::raw2att($_REQUEST['Versions']);
$versions = array_combine($versions, $versions); $versions = array_combine($versions, $versions);
} } else {
else {
$version = Convert::raw2att($_REQUEST['Versions']); $version = Convert::raw2att($_REQUEST['Versions']);
$versions[$version] = $version; $versions[$version] = $version;
} }
@ -50,10 +50,11 @@ class DocumentationSearchExtension extends Extension {
* *
* @return HTMLText|null * @return HTMLText|null
*/ */
public function getSearchQuery() { public function getSearchQuery()
if(isset($_REQUEST['Search'])) { {
if (isset($_REQUEST['Search'])) {
return DBField::create_field('HTMLText', $_REQUEST['Search']); return DBField::create_field('HTMLText', $_REQUEST['Search']);
} else if(isset($_REQUEST['q'])) { } elseif (isset($_REQUEST['q'])) {
return DBField::create_field('HTMLText', $_REQUEST['q']); return DBField::create_field('HTMLText', $_REQUEST['q']);
} }
} }
@ -61,7 +62,8 @@ class DocumentationSearchExtension extends Extension {
/** /**
* Past straight to results, display and encode the query. * Past straight to results, display and encode the query.
*/ */
public function getSearchResults() { public function getSearchResults()
{
$query = $this->getSearchQuery(); $query = $this->getSearchQuery();
$search = new DocumentationSearch(); $search = new DocumentationSearch();
@ -79,15 +81,16 @@ class DocumentationSearchExtension extends Extension {
* *
* @return Form * @return Form
*/ */
public function AdvancedSearchForm() { public function AdvancedSearchForm()
{
return new DocumentationAdvancedSearchForm($this->owner); return new DocumentationAdvancedSearchForm($this->owner);
} }
/** /**
* @return bool * @return bool
*/ */
public function getAdvancedSearchEnabled() { public function getAdvancedSearchEnabled()
{
return Config::inst()->get("DocumentationSearch", 'advanced_search_enabled'); return Config::inst()->get("DocumentationSearch", 'advanced_search_enabled');
} }
} }

View File

@ -25,12 +25,13 @@
* *
* @package docsviewer * @package docsviewer
*/ */
class DocumentationStaticPublisherExtension extends Extension { class DocumentationStaticPublisherExtension extends Extension
{
public function alterExportUrls(&$urls) { public function alterExportUrls(&$urls)
{
$manifest = new DocumentationManifest(true); $manifest = new DocumentationManifest(true);
foreach($manifest->getPages() as $url => $page) { foreach ($manifest->getPages() as $url => $page) {
$urls[$url] = $url; $urls[$url] = $url;
} }
} }

View File

@ -7,37 +7,37 @@
* @return false|ArrayData * @return false|ArrayData
*/ */
class DocumentationViewerVersionWarning extends Extension { class DocumentationViewerVersionWarning extends Extension
{
public function VersionWarning() { public function VersionWarning()
{
$page = $this->owner->getPage(); $page = $this->owner->getPage();
if(!$page) { if (!$page) {
return false; return false;
} }
$entity = $page->getEntity(); $entity = $page->getEntity();
if(!$entity) { if (!$entity) {
return false; return false;
} }
$versions = $this->owner->getManifest()->getAllVersionsOfEntity($entity); $versions = $this->owner->getManifest()->getAllVersionsOfEntity($entity);
if($entity->getIsStable()) { if ($entity->getIsStable()) {
return false; return false;
} }
$stable = $this->owner->getManifest()->getStableVersion($entity); $stable = $this->owner->getManifest()->getStableVersion($entity);
$compare = $entity->compare($stable); $compare = $entity->compare($stable);
if($entity->getVersion() == "master" || $compare > 0) { if ($entity->getVersion() == "master" || $compare > 0) {
return $this->owner->customise(new ArrayData(array( return $this->owner->customise(new ArrayData(array(
'FutureRelease' => true, 'FutureRelease' => true,
'StableVersion' => DBField::create_field('HTMLText', $stable->getVersion()) 'StableVersion' => DBField::create_field('HTMLText', $stable->getVersion())
))); )));
} } else {
else {
return $this->owner->customise(new ArrayData(array( return $this->owner->customise(new ArrayData(array(
'OutdatedRelease' => true, 'OutdatedRelease' => true,
'StableVersion' => DBField::create_field('HTMLText', $stable->getVersion()) 'StableVersion' => DBField::create_field('HTMLText', $stable->getVersion())

View File

@ -3,9 +3,10 @@
/** /**
* @package docsviewer * @package docsviewer
*/ */
class DocumentationAdvancedSearchForm extends Form { class DocumentationAdvancedSearchForm extends Form
{
public function __construct($controller) { public function __construct($controller)
{
$versions = $controller->getManifest()->getAllVersions(); $versions = $controller->getManifest()->getAllVersions();
$entities = $controller->getManifest()->getEntities(); $entities = $controller->getManifest()->getEntities();
@ -17,13 +18,13 @@ class DocumentationAdvancedSearchForm extends Form {
// if we haven't gone any search limit then we're searching everything // if we haven't gone any search limit then we're searching everything
$searchedEntities = $controller->getSearchedEntities(); $searchedEntities = $controller->getSearchedEntities();
if(count($searchedEntities) < 1) { if (count($searchedEntities) < 1) {
$searchedEntities = $entities; $searchedEntities = $entities;
} }
$searchedVersions = $controller->getSearchedVersions(); $searchedVersions = $controller->getSearchedVersions();
if(count($searchedVersions) < 1) { if (count($searchedVersions) < 1) {
$searchedVersions = $versions; $searchedVersions = $versions;
} }

View File

@ -1,10 +1,9 @@
<?php <?php
class DocumentationSearchForm extends Form { class DocumentationSearchForm extends Form
{
public function __construct($controller) { public function __construct($controller)
{
$fields = new FieldList( $fields = new FieldList(
TextField::create('q', _t('DocumentationViewer.SEARCH', 'Search'), '') TextField::create('q', _t('DocumentationViewer.SEARCH', 'Search'), '')
->setAttribute('placeholder', _t('DocumentationViewer.SEARCH', 'Search')) ->setAttribute('placeholder', _t('DocumentationViewer.SEARCH', 'Search'))
@ -12,7 +11,7 @@ class DocumentationSearchForm extends Form {
$page = $controller->getPage(); $page = $controller->getPage();
if($page){ if ($page) {
$versions = HiddenField::create( $versions = HiddenField::create(
'Versions', 'Versions',
_t('DocumentationViewer.VERSIONS', 'Versions'), _t('DocumentationViewer.VERSIONS', 'Versions'),

View File

@ -16,8 +16,8 @@
* @subpackage models * @subpackage models
*/ */
class DocumentationEntity extends ViewableData { class DocumentationEntity extends ViewableData
{
/** /**
* The key to match entities with that is not localized. For instance, you * The key to match entities with that is not localized. For instance, you
* may have three entities (en, de, fr) that you want to display a nice * may have three entities (en, de, fr) that you want to display a nice
@ -79,7 +79,8 @@ class DocumentationEntity extends ViewableData {
/** /**
* *
*/ */
public function __construct($key) { public function __construct($key)
{
$this->key = DocumentationHelper::clean_page_url($key); $this->key = DocumentationHelper::clean_page_url($key);
} }
@ -89,8 +90,9 @@ class DocumentationEntity extends ViewableData {
* *
* @return string * @return string
*/ */
public function getTitle() { public function getTitle()
if(!$this->title) { {
if (!$this->title) {
$this->title = DocumentationHelper::clean_page_name($this->key); $this->title = DocumentationHelper::clean_page_name($this->key);
} }
@ -101,7 +103,8 @@ class DocumentationEntity extends ViewableData {
* @param string $title * @param string $title
* @return this * @return this
*/ */
public function setTitle($title) { public function setTitle($title)
{
$this->title = $title; $this->title = $title;
return $this; return $this;
@ -116,8 +119,9 @@ class DocumentationEntity extends ViewableData {
* This might omit the version number if this is the default version. * This might omit the version number if this is the default version.
* @return string * @return string
*/ */
public function Link($short = false) { public function Link($short = false)
if($this->getIsDefaultEntity()) { {
if ($this->getIsDefaultEntity()) {
$base = Controller::join_links( $base = Controller::join_links(
Config::inst()->get('DocumentationViewer', 'link_base'), Config::inst()->get('DocumentationViewer', 'link_base'),
$this->getLanguage(), $this->getLanguage(),
@ -134,7 +138,7 @@ class DocumentationEntity extends ViewableData {
$base = ltrim(str_replace('//', '/', $base), '/'); $base = ltrim(str_replace('//', '/', $base), '/');
if($short && $this->stable) { if ($short && $this->stable) {
return $base; return $base;
} }
@ -148,7 +152,8 @@ class DocumentationEntity extends ViewableData {
/** /**
* @return string * @return string
*/ */
public function __toString() { public function __toString()
{
return sprintf('DocumentationEntity: %s)', $this->getPath()); return sprintf('DocumentationEntity: %s)', $this->getPath());
} }
@ -157,8 +162,9 @@ class DocumentationEntity extends ViewableData {
* *
* @return boolean * @return boolean
*/ */
public function hasRecord($page) { public function hasRecord($page)
if(!$page) { {
if (!$page) {
return false; return false;
} }
@ -168,7 +174,8 @@ class DocumentationEntity extends ViewableData {
/** /**
* @param boolean $bool * @param boolean $bool
*/ */
public function setIsDefaultEntity($bool) { public function setIsDefaultEntity($bool)
{
$this->defaultEntity = $bool; $this->defaultEntity = $bool;
return $this; return $this;
@ -177,21 +184,24 @@ class DocumentationEntity extends ViewableData {
/** /**
* @return boolean * @return boolean
*/ */
public function getIsDefaultEntity() { public function getIsDefaultEntity()
{
return $this->defaultEntity; return $this->defaultEntity;
} }
/** /**
* @return string * @return string
*/ */
public function getKey() { public function getKey()
{
return $this->key; return $this->key;
} }
/** /**
* @return string * @return string
*/ */
public function getLanguage() { public function getLanguage()
{
return $this->language; return $this->language;
} }
@ -200,7 +210,8 @@ class DocumentationEntity extends ViewableData {
* *
* @return this * @return this
*/ */
public function setLanguage($language) { public function setLanguage($language)
{
$this->language = $language; $this->language = $language;
return $this; return $this;
@ -209,7 +220,8 @@ class DocumentationEntity extends ViewableData {
/** /**
* @param string * @param string
*/ */
public function setVersion($version) { public function setVersion($version)
{
$this->version = $version; $this->version = $version;
return $this; return $this;
@ -218,14 +230,16 @@ class DocumentationEntity extends ViewableData {
/** /**
* @return float * @return float
*/ */
public function getVersion() { public function getVersion()
{
return $this->version; return $this->version;
} }
/** /**
* @param string * @param string
*/ */
public function setBranch($branch) { public function setBranch($branch)
{
$this->branch = $branch; $this->branch = $branch;
return $this; return $this;
@ -234,14 +248,16 @@ class DocumentationEntity extends ViewableData {
/** /**
* @return float * @return float
*/ */
public function getBranch() { public function getBranch()
{
return $this->branch; return $this->branch;
} }
/** /**
* @return string * @return string
*/ */
public function getPath() { public function getPath()
{
return $this->path; return $this->path;
} }
@ -250,7 +266,8 @@ class DocumentationEntity extends ViewableData {
* *
* @return this * @return this
*/ */
public function setPath($path) { public function setPath($path)
{
$this->path = $path; $this->path = $path;
return $this; return $this;
@ -259,7 +276,8 @@ class DocumentationEntity extends ViewableData {
/** /**
* @param boolean * @param boolean
*/ */
public function setIsStable($stable) { public function setIsStable($stable)
{
$this->stable = $stable; $this->stable = $stable;
return $this; return $this;
@ -268,7 +286,8 @@ class DocumentationEntity extends ViewableData {
/** /**
* @return boolean * @return boolean
*/ */
public function getIsStable() { public function getIsStable()
{
return $this->stable; return $this->stable;
} }
@ -282,14 +301,16 @@ class DocumentationEntity extends ViewableData {
* @param string $version * @param string $version
* @return int * @return int
*/ */
public function compare(DocumentationEntity $other) { public function compare(DocumentationEntity $other)
{
return version_compare($this->getVersion(), $other->getVersion()); return version_compare($this->getVersion(), $other->getVersion());
} }
/** /**
* @return array * @return array
*/ */
public function toMap() { public function toMap()
{
return array( return array(
'Key' => $this->key, 'Key' => $this->key,
'Path' => $this->getPath(), 'Path' => $this->getPath(),

View File

@ -8,13 +8,13 @@
* @package docsviewer * @package docsviewer
* @subpackage model * @subpackage model
*/ */
class DocumentationFolder extends DocumentationPage { class DocumentationFolder extends DocumentationPage
{
/** /**
* @return string * @return string
*/ */
public function getTitle() { public function getTitle()
{
return $this->getTitleFromFolder(); return $this->getTitleFromFolder();
} }
} }

View File

@ -10,8 +10,8 @@
* @package docsviewer * @package docsviewer
* @subpackage model * @subpackage model
*/ */
class DocumentationPage extends ViewableData { class DocumentationPage extends ViewableData
{
/** /**
* @var string * @var string
*/ */
@ -41,7 +41,8 @@ class DocumentationPage extends ViewableData {
* @param string $filename * @param string $filename
* @param string $path * @param string $path
*/ */
public function __construct(DocumentationEntity $entity, $filename, $path) { public function __construct(DocumentationEntity $entity, $filename, $path)
{
$this->filename = $filename; $this->filename = $filename;
$this->path = $path; $this->path = $path;
$this->entity = $entity; $this->entity = $entity;
@ -50,7 +51,8 @@ class DocumentationPage extends ViewableData {
/** /**
* @return string * @return string
*/ */
public function getExtension() { public function getExtension()
{
return DocumentationHelper::get_extension($this->filename); return DocumentationHelper::get_extension($this->filename);
} }
@ -59,7 +61,8 @@ class DocumentationPage extends ViewableData {
* *
* @return string * @return string
*/ */
public function getBreadcrumbTitle($divider = ' - ') { public function getBreadcrumbTitle($divider = ' - ')
{
$pathParts = explode('/', trim($this->getRelativePath(), '/')); $pathParts = explode('/', trim($this->getRelativePath(), '/'));
// from the page from this // from the page from this
@ -72,13 +75,13 @@ class DocumentationPage extends ViewableData {
'DocumentationHelper', 'clean_page_name' 'DocumentationHelper', 'clean_page_name'
), $pathParts); ), $pathParts);
$titleParts = array_filter($titleParts, function($val) { $titleParts = array_filter($titleParts, function ($val) {
if($val) { if ($val) {
return $val; return $val;
} }
}); });
if($this->getTitle()) { if ($this->getTitle()) {
array_unshift($titleParts, $this->getTitle()); array_unshift($titleParts, $this->getTitle());
} }
@ -88,28 +91,31 @@ class DocumentationPage extends ViewableData {
/** /**
* @return DocumentationEntity * @return DocumentationEntity
*/ */
public function getEntity() { public function getEntity()
{
return $this->entity; return $this->entity;
} }
/** /**
* @return string * @return string
*/ */
public function getTitle() { public function getTitle()
if($this->title) { {
if ($this->title) {
return $this->title; return $this->title;
} }
$page = DocumentationHelper::clean_page_name($this->filename); $page = DocumentationHelper::clean_page_name($this->filename);
if($page == "Index") { if ($page == "Index") {
return $this->getTitleFromFolder(); return $this->getTitleFromFolder();
} }
return $page; return $page;
} }
public function getTitleFromFolder() { public function getTitleFromFolder()
{
$folder = $this->getPath(); $folder = $this->getPath();
$entity = $this->getEntity()->getPath(); $entity = $this->getEntity()->getPath();
@ -117,7 +123,7 @@ class DocumentationPage extends ViewableData {
// if it's the root of the entity then we want to use the entity name // if it's the root of the entity then we want to use the entity name
// otherwise we'll get 'En' for the entity folder // otherwise we'll get 'En' for the entity folder
if($folder == $entity) { if ($folder == $entity) {
return $this->getEntity()->getTitle(); return $this->getEntity()->getTitle();
} else { } else {
$path = explode(DIRECTORY_SEPARATOR, trim($folder, DIRECTORY_SEPARATOR)); $path = explode(DIRECTORY_SEPARATOR, trim($folder, DIRECTORY_SEPARATOR));
@ -130,7 +136,8 @@ class DocumentationPage extends ViewableData {
/** /**
* @return string * @return string
*/ */
public function getSummary() { public function getSummary()
{
return $this->summary; return $this->summary;
} }
@ -141,7 +148,8 @@ class DocumentationPage extends ViewableData {
* *
* @return string * @return string
*/ */
public function getMarkdown($removeMetaData = false) { public function getMarkdown($removeMetaData = false)
{
try { try {
if ($md = file_get_contents($this->getPath())) { if ($md = file_get_contents($this->getPath())) {
$this->populateMetaDataFromText($md, $removeMetaData); $this->populateMetaDataFromText($md, $removeMetaData);
@ -150,22 +158,22 @@ class DocumentationPage extends ViewableData {
} }
$this->read = true; $this->read = true;
} } catch (InvalidArgumentException $e) {
catch(InvalidArgumentException $e) {
} }
return false; return false;
} }
public function setMetaData($key, $value) { public function setMetaData($key, $value)
{
$key = strtolower($key); $key = strtolower($key);
$this->$key = $value; $this->$key = $value;
} }
public function getIntroduction() { public function getIntroduction()
if(!$this->read) { {
if (!$this->read) {
$this->getMarkdown(); $this->getMarkdown();
} }
@ -179,7 +187,8 @@ class DocumentationPage extends ViewableData {
* *
* @return string * @return string
*/ */
public function getHTML() { public function getHTML()
{
$html = DocumentationParser::parse( $html = DocumentationParser::parse(
$this, $this,
$this->entity->Link() $this->entity->Link()
@ -195,10 +204,11 @@ class DocumentationPage extends ViewableData {
* *
* @return string * @return string
*/ */
public function getRelativeLink() { public function getRelativeLink()
{
$path = $this->getRelativePath(); $path = $this->getRelativePath();
$url = explode('/', $path); $url = explode('/', $path);
$url = implode('/', array_map(function($a) { $url = implode('/', array_map(function ($a) {
return DocumentationHelper::clean_page_url($a); return DocumentationHelper::clean_page_url($a);
}, $url)); }, $url));
@ -213,15 +223,16 @@ class DocumentationPage extends ViewableData {
* *
* @return string * @return string
*/ */
public function getRelativePath() { public function getRelativePath()
{
return str_replace($this->entity->getPath(), '', $this->getPath()); return str_replace($this->entity->getPath(), '', $this->getPath());
} }
/** /**
* @return string * @return string
*/ */
public function getPath() { public function getPath()
{
return $this->path; return $this->path;
} }
@ -233,7 +244,8 @@ class DocumentationPage extends ViewableData {
* This might omit the version number if this is the default version. * This might omit the version number if this is the default version.
* @return string * @return string
*/ */
public function Link($short = false) { public function Link($short = false)
{
return ltrim(Controller::join_links( return ltrim(Controller::join_links(
$this->entity->Link($short), $this->entity->Link($short),
$this->getRelativeLink() $this->getRelativeLink()
@ -247,21 +259,22 @@ class DocumentationPage extends ViewableData {
* @param DocumentationPage $md * @param DocumentationPage $md
* @param bool $remove * @param bool $remove
*/ */
public function populateMetaDataFromText(&$md, $removeMetaData = false) { public function populateMetaDataFromText(&$md, $removeMetaData = false)
if($md) { {
if ($md) {
// get the text up to the first whiteline // get the text up to the first whiteline
$extPattern = "/^(.+)\n(\r)*\n/Uis"; $extPattern = "/^(.+)\n(\r)*\n/Uis";
$matches = preg_match($extPattern, $md, $block); $matches = preg_match($extPattern, $md, $block);
if($matches && $block[1]) { if ($matches && $block[1]) {
$metaDataFound = false; $metaDataFound = false;
// find the key/value pairs // find the key/value pairs
$intPattern = '/(?<key>[A-Za-z][A-Za-z0-9_-]+)[\t]*:[\t]*(?<value>[^:\n\r\/]+)/x'; $intPattern = '/(?<key>[A-Za-z][A-Za-z0-9_-]+)[\t]*:[\t]*(?<value>[^:\n\r\/]+)/x';
$matches = preg_match_all($intPattern, $block[1], $meta); $matches = preg_match_all($intPattern, $block[1], $meta);
foreach($meta['key'] as $index => $key) { foreach ($meta['key'] as $index => $key) {
if(isset($meta['value'][$index])) { if (isset($meta['value'][$index])) {
// check if a property exists for this key // check if a property exists for this key
if (property_exists(get_class(), $key)) { if (property_exists(get_class(), $key)) {
$this->$key = $meta['value'][$index]; $this->$key = $meta['value'][$index];
@ -279,11 +292,13 @@ class DocumentationPage extends ViewableData {
} }
} }
public function getVersion() { public function getVersion()
{
return $this->entity->getVersion(); return $this->entity->getVersion();
} }
public function __toString() { public function __toString()
{
return sprintf(get_class($this) .': %s)', $this->getPath()); return sprintf(get_class($this) .': %s)', $this->getPath());
} }
} }

View File

@ -1,14 +1,14 @@
<?php <?php
class DocumentationBuild extends BuildTask { class DocumentationBuild extends BuildTask
{
public function run($request) { public function run($request)
{
$manifest = new DocumentationManifest(true); $manifest = new DocumentationManifest(true);
echo "<pre>"; echo "<pre>";
print_r($manifest->getPages()); print_r($manifest->getPages());
echo "</pre>"; echo "</pre>";
die();; die();
;
} }
} }

View File

@ -9,18 +9,20 @@
* @subpackage tasks * @subpackage tasks
*/ */
class RebuildLuceneDocsIndex extends BuildTask { class RebuildLuceneDocsIndex extends BuildTask
{
protected $title = "Rebuild Documentation Search Indexes"; protected $title = "Rebuild Documentation Search Indexes";
protected $description = " protected $description = "
Rebuilds the indexes used for the search engine in the docsviewer."; Rebuilds the indexes used for the search engine in the docsviewer.";
public function run($request) { public function run($request)
{
$this->rebuildIndexes(); $this->rebuildIndexes();
} }
public function rebuildIndexes($quiet = false) { public function rebuildIndexes($quiet = false)
{
require_once 'Zend/Search/Lucene.php'; require_once 'Zend/Search/Lucene.php';
ini_set("memory_limit", -1); ini_set("memory_limit", -1);
@ -35,8 +37,8 @@ class RebuildLuceneDocsIndex extends BuildTask {
echo "Building index in ". DocumentationSearch::get_index_location() . PHP_EOL; echo "Building index in ". DocumentationSearch::get_index_location() . PHP_EOL;
if($lockFileFresh && !isset($_REQUEST['flush'])) { if ($lockFileFresh && !isset($_REQUEST['flush'])) {
if(!$quiet) { if (!$quiet) {
echo "Index recently rebuilt. If you want to force reindex use ?flush=1"; echo "Index recently rebuilt. If you want to force reindex use ?flush=1";
} }
@ -46,15 +48,13 @@ class RebuildLuceneDocsIndex extends BuildTask {
try { try {
$index = Zend_Search_Lucene::open(DocumentationSearch::get_index_location()); $index = Zend_Search_Lucene::open(DocumentationSearch::get_index_location());
$index->removeReference(); $index->removeReference();
} } catch (Zend_Search_Lucene_Exception $e) {
catch (Zend_Search_Lucene_Exception $e) {
user_error($e); user_error($e);
} }
try { try {
$index = Zend_Search_Lucene::create(DocumentationSearch::get_index_location()); $index = Zend_Search_Lucene::create(DocumentationSearch::get_index_location());
} } catch (Zend_Search_Lucene_Exception $c) {
catch(Zend_Search_Lucene_Exception $c) {
user_error($c); user_error($c);
} }
@ -62,16 +62,16 @@ class RebuildLuceneDocsIndex extends BuildTask {
$manifest = new DocumentationManifest(true); $manifest = new DocumentationManifest(true);
$pages = $manifest->getPages(); $pages = $manifest->getPages();
if($pages) { if ($pages) {
$count = 0; $count = 0;
// iconv complains about all the markdown formatting // iconv complains about all the markdown formatting
// turn off notices while we parse // turn off notices while we parse
if(!Director::is_cli()) { if (!Director::is_cli()) {
echo "<ul>"; echo "<ul>";
} }
foreach($pages as $url => $record) { foreach ($pages as $url => $record) {
$count++; $count++;
$page = $manifest->getPage($url); $page = $manifest->getPage($url);
@ -107,8 +107,8 @@ class RebuildLuceneDocsIndex extends BuildTask {
$boost = Config::inst()->get('DocumentationSearch', 'boost_by_path'); $boost = Config::inst()->get('DocumentationSearch', 'boost_by_path');
foreach($boost as $pathExpr => $boost) { foreach ($boost as $pathExpr => $boost) {
if(preg_match($pathExpr, $page->getRelativePath())) { if (preg_match($pathExpr, $page->getRelativePath())) {
$doc->boost = $boost; $doc->boost = $boost;
} }
} }
@ -116,16 +116,19 @@ class RebuildLuceneDocsIndex extends BuildTask {
error_reporting(E_ALL ^ E_NOTICE); error_reporting(E_ALL ^ E_NOTICE);
$index->addDocument($doc); $index->addDocument($doc);
if(!$quiet) { if (!$quiet) {
if(Director::is_cli()) echo " * adding ". $page->getPath() ."\n"; if (Director::is_cli()) {
else echo "<li>adding ". $page->getPath() ."</li>\n"; echo " * adding ". $page->getPath() ."\n";
} else {
echo "<li>adding ". $page->getPath() ."</li>\n";
}
} }
} }
} }
$index->commit(); $index->commit();
if(!$quiet) { if (!$quiet) {
echo "complete."; echo "complete.";
} }
} }

View File

@ -4,15 +4,17 @@
* @package docsviewer * @package docsviewer
* @subpackage tests * @subpackage tests
*/ */
class DocumentationHelperTests extends SapphireTest { class DocumentationHelperTests extends SapphireTest
{
public function testCleanName() { public function testCleanName()
{
$this->assertEquals("File path", DocumentationHelper::clean_page_name( $this->assertEquals("File path", DocumentationHelper::clean_page_name(
'00_file-path.md' '00_file-path.md'
)); ));
} }
public function testCleanUrl() { public function testCleanUrl()
{
$this->assertEquals("some_path", DocumentationHelper::clean_page_url( $this->assertEquals("some_path", DocumentationHelper::clean_page_url(
'Some Path' 'Some Path'
)); ));
@ -22,7 +24,8 @@ class DocumentationHelperTests extends SapphireTest {
)); ));
} }
public function testTrimSortNumber() { public function testTrimSortNumber()
{
$this->assertEquals('file', DocumentationHelper::trim_sort_number( $this->assertEquals('file', DocumentationHelper::trim_sort_number(
'0_file' '0_file'
)); ));
@ -36,7 +39,8 @@ class DocumentationHelperTests extends SapphireTest {
)); ));
} }
public function testTrimExtension() { public function testTrimExtension()
{
$this->assertEquals('file', DocumentationHelper::trim_extension_off( $this->assertEquals('file', DocumentationHelper::trim_extension_off(
'file.md' 'file.md'
)); ));
@ -46,7 +50,8 @@ class DocumentationHelperTests extends SapphireTest {
)); ));
} }
public function testGetExtension() { public function testGetExtension()
{
$this->assertEquals('md', DocumentationHelper::get_extension( $this->assertEquals('md', DocumentationHelper::get_extension(
'file.md' 'file.md'
)); ));

View File

@ -4,11 +4,12 @@
* @package docsviewer * @package docsviewer
* @subpackage tests * @subpackage tests
*/ */
class DocumentationManifestTests extends SapphireTest { class DocumentationManifestTests extends SapphireTest
{
private $manifest; private $manifest;
public function setUp() { public function setUp()
{
parent::setUp(); parent::setUp();
Config::nest(); Config::nest();
@ -57,7 +58,8 @@ class DocumentationManifestTests extends SapphireTest {
$this->manifest = new DocumentationManifest(true); $this->manifest = new DocumentationManifest(true);
} }
public function tearDown() { public function tearDown()
{
parent::tearDown(); parent::tearDown();
Config::unnest(); Config::unnest();
@ -67,7 +69,8 @@ class DocumentationManifestTests extends SapphireTest {
/** /**
* Check that the manifest matches what we'd expect. * Check that the manifest matches what we'd expect.
*/ */
public function testRegenerate() { public function testRegenerate()
{
$match = array( $match = array(
'de/testdocs/2.3/', 'de/testdocs/2.3/',
'de/testdocs/2.3/german/', 'de/testdocs/2.3/german/',
@ -100,7 +103,8 @@ class DocumentationManifestTests extends SapphireTest {
$this->assertEquals($match, array_keys($this->manifest->getPages())); $this->assertEquals($match, array_keys($this->manifest->getPages()));
} }
public function testGetNextPage() { public function testGetNextPage()
{
// get next page at the end of one subfolder goes back up to the top // get next page at the end of one subfolder goes back up to the top
// most directory // most directory
$this->assertStringEndsWith('2.3/test/', $this->manifest->getNextPage( $this->assertStringEndsWith('2.3/test/', $this->manifest->getNextPage(
@ -129,7 +133,8 @@ class DocumentationManifestTests extends SapphireTest {
)); ));
} }
public function testGetPreviousPage() { public function testGetPreviousPage()
{
// goes right into subfolders // goes right into subfolders
$this->assertContains('subfolder/subsubfolder/subsubpage', $this->manifest->getPreviousPage( $this->assertContains('subfolder/subsubfolder/subsubpage', $this->manifest->getPreviousPage(
DOCSVIEWER_PATH . '/tests/docs/en/test.md', DOCSVIEWER_PATH . '/tests/docs/en/test.md',
@ -149,15 +154,18 @@ class DocumentationManifestTests extends SapphireTest {
)); ));
} }
public function testGetPage() { public function testGetPage()
{
$this->markTestIncomplete(); $this->markTestIncomplete();
} }
public function testGenerateBreadcrumbs() { public function testGenerateBreadcrumbs()
{
$this->markTestIncomplete(); $this->markTestIncomplete();
} }
public function testGetChildrenFor() { public function testGetChildrenFor()
{
$expected = array( $expected = array(
array('Title' => 'Test', 'LinkingMode' => 'link') array('Title' => 'Test', 'LinkingMode' => 'link')
); );
@ -178,7 +186,8 @@ class DocumentationManifestTests extends SapphireTest {
)); ));
} }
public function testGetAllVersions() { public function testGetAllVersions()
{
$expected = array( $expected = array(
'2.3' => '2.3', '2.3' => '2.3',
'2.4' => '2.4', '2.4' => '2.4',
@ -189,7 +198,8 @@ class DocumentationManifestTests extends SapphireTest {
$this->assertEquals($expected, $this->manifest->getAllVersions()); $this->assertEquals($expected, $this->manifest->getAllVersions());
} }
public function testGetAllEntityVersions() { public function testGetAllEntityVersions()
{
$expected = array( $expected = array(
'Version' => '2.3', 'Version' => '2.3',
'Version' => '2.4', 'Version' => '2.4',
@ -205,7 +215,8 @@ class DocumentationManifestTests extends SapphireTest {
$this->assertEquals(1, $this->manifest->getAllVersionsOfEntity($entity)->count()); $this->assertEquals(1, $this->manifest->getAllVersionsOfEntity($entity)->count());
} }
public function testGetStableVersion() { public function testGetStableVersion()
{
$this->markTestIncomplete(); $this->markTestIncomplete();
} }
} }

View File

@ -4,11 +4,12 @@
* @package docsviewer * @package docsviewer
* @subpackage tests * @subpackage tests
*/ */
class DocumentationPageTest extends SapphireTest { class DocumentationPageTest extends SapphireTest
{
protected $entity; protected $entity;
public function setUp() { public function setUp()
{
parent::setUp(); parent::setUp();
$this->entity = new DocumentationEntity('doctest'); $this->entity = new DocumentationEntity('doctest');
@ -26,13 +27,15 @@ class DocumentationPageTest extends SapphireTest {
$manifest = new DocumentationManifest(true); $manifest = new DocumentationManifest(true);
} }
public function tearDown() { public function tearDown()
{
parent::tearDown(); parent::tearDown();
Config::unnest(); Config::unnest();
} }
public function testGetLink() { public function testGetLink()
{
$page = new DocumentationPage( $page = new DocumentationPage(
$this->entity, $this->entity,
'test.md', 'test.md',
@ -61,7 +64,8 @@ class DocumentationPageTest extends SapphireTest {
$this->assertEquals('dev/docs/en/doctest/2.4/sort/basic/', $page->Link()); $this->assertEquals('dev/docs/en/doctest/2.4/sort/basic/', $page->Link());
} }
public function testGetBreadcrumbTitle() { public function testGetBreadcrumbTitle()
{
$page = new DocumentationPage( $page = new DocumentationPage(
$this->entity, $this->entity,
'test.md', 'test.md',
@ -85,6 +89,5 @@ class DocumentationPageTest extends SapphireTest {
); );
$this->assertEquals('Sort - Doctest', $page->getBreadcrumbTitle()); $this->assertEquals('Sort - Doctest', $page->getBreadcrumbTitle());
} }
} }

View File

@ -4,17 +4,19 @@
* @package docsviewer * @package docsviewer
* @subpackage tests * @subpackage tests
*/ */
class DocumentationParserTest extends SapphireTest { class DocumentationParserTest extends SapphireTest
{
protected $entity, $entityAlt, $page, $subPage, $subSubPage, $filePage, $metaDataPage, $indexPage; protected $entity, $entityAlt, $page, $subPage, $subSubPage, $filePage, $metaDataPage, $indexPage;
public function tearDown() { public function tearDown()
{
parent::tearDown(); parent::tearDown();
Config::unnest(); Config::unnest();
} }
public function setUp() { public function setUp()
{
parent::setUp(); parent::setUp();
Config::nest(); Config::nest();
@ -73,7 +75,8 @@ class DocumentationParserTest extends SapphireTest {
$manifest = new DocumentationManifest(true); $manifest = new DocumentationManifest(true);
} }
public function testRewriteCodeBlocks() { public function testRewriteCodeBlocks()
{
$codePage = new DocumentationPage( $codePage = new DocumentationPage(
$this->entityAlt, $this->entityAlt,
'CodeSnippets.md', 'CodeSnippets.md',
@ -161,7 +164,8 @@ HTML;
$this->assertContains($expected, $result, 'Backtick with newlines'); $this->assertContains($expected, $result, 'Backtick with newlines');
} }
public function testRelativeLinks() { public function testRelativeLinks()
{
// index.md // index.md
$result = DocumentationParser::rewrite_relative_links( $result = DocumentationParser::rewrite_relative_links(
$this->indexPage->getMarkdown(), $this->indexPage->getMarkdown(),
@ -266,7 +270,8 @@ HTML;
); );
} }
public function testGenerateHtmlId() { public function testGenerateHtmlId()
{
$this->assertEquals('title-one', DocumentationParser::generate_html_id('title one')); $this->assertEquals('title-one', DocumentationParser::generate_html_id('title one'));
$this->assertEquals('title-one', DocumentationParser::generate_html_id('Title one')); $this->assertEquals('title-one', DocumentationParser::generate_html_id('Title one'));
$this->assertEquals('title-and-one', DocumentationParser::generate_html_id('Title &amp; One')); $this->assertEquals('title-and-one', DocumentationParser::generate_html_id('Title &amp; One'));
@ -277,8 +282,8 @@ HTML;
public function testImageRewrites() { public function testImageRewrites()
{
$result = DocumentationParser::rewrite_image_links( $result = DocumentationParser::rewrite_image_links(
$this->subPage->getMarkdown(), $this->subPage->getMarkdown(),
$this->subPage $this->subPage
@ -310,7 +315,8 @@ HTML;
); );
} }
public function testApiLinks() { public function testApiLinks()
{
$result = DocumentationParser::rewrite_api_links( $result = DocumentationParser::rewrite_api_links(
$this->page->getMarkdown(), $this->page->getMarkdown(),
$this->page $this->page
@ -326,7 +332,8 @@ HTML;
); );
} }
public function testHeadlineAnchors() { public function testHeadlineAnchors()
{
$result = DocumentationParser::rewrite_heading_anchors( $result = DocumentationParser::rewrite_heading_anchors(
$this->page->getMarkdown(), $this->page->getMarkdown(),
$this->page $this->page
@ -357,18 +364,19 @@ HTML;
$this->assertContains('## Heading duplicate {#heading-duplicate}', $result); $this->assertContains('## Heading duplicate {#heading-duplicate}', $result);
$this->assertContains('## Heading duplicate {#heading-duplicate-2}', $result); $this->assertContains('## Heading duplicate {#heading-duplicate-2}', $result);
$this->assertContains('## Heading duplicate {#heading-duplicate-3}', $result); $this->assertContains('## Heading duplicate {#heading-duplicate-3}', $result);
} }
public function testRetrieveMetaData() { public function testRetrieveMetaData()
{
DocumentationParser::retrieve_meta_data($this->metaDataPage); DocumentationParser::retrieve_meta_data($this->metaDataPage);
$this->assertEquals('Dr. Foo Bar.', $this->metaDataPage->author); $this->assertEquals('Dr. Foo Bar.', $this->metaDataPage->author);
$this->assertEquals("Foo Bar's Test page.", $this->metaDataPage->getTitle()); $this->assertEquals("Foo Bar's Test page.", $this->metaDataPage->getTitle());
} }
public function testRewritingRelativeLinksToFiles() { public function testRewritingRelativeLinksToFiles()
{
$parsed = DocumentationParser::parse($this->filePage); $parsed = DocumentationParser::parse($this->filePage);
$this->assertContains( $this->assertContains(

View File

@ -4,9 +4,10 @@
* @package docsviewer * @package docsviewer
* @subpackage tests * @subpackage tests
*/ */
class DocumentationPermalinksTest extends FunctionalTest { class DocumentationPermalinksTest extends FunctionalTest
{
public function testSavingAndAccessingMapping() { public function testSavingAndAccessingMapping()
{
// basic test // basic test
DocumentationPermalinks::add(array( DocumentationPermalinks::add(array(
'foo' => 'en/framework/subfolder/foo', 'foo' => 'en/framework/subfolder/foo',
@ -26,7 +27,8 @@ class DocumentationPermalinksTest extends FunctionalTest {
* Tests to make sure short codes get translated to full paths. * Tests to make sure short codes get translated to full paths.
* *
*/ */
public function testRedirectingMapping() { public function testRedirectingMapping()
{
DocumentationPermalinks::add(array( DocumentationPermalinks::add(array(
'foo' => 'en/framework/subfolder/foo', 'foo' => 'en/framework/subfolder/foo',
'bar' => 'en/cms/bar' 'bar' => 'en/cms/bar'

View File

@ -5,9 +5,10 @@
* @subpackage tests * @subpackage tests
*/ */
class DocumentationSearchTest extends FunctionalTest { class DocumentationSearchTest extends FunctionalTest
{
public function setUp() { public function setUp()
{
parent::setUp(); parent::setUp();
Config::nest(); Config::nest();
@ -35,13 +36,15 @@ class DocumentationSearchTest extends FunctionalTest {
$this->manifest = new DocumentationManifest(true); $this->manifest = new DocumentationManifest(true);
} }
public function tearDown() { public function tearDown()
{
parent::tearDown(); parent::tearDown();
Config::unnest(); Config::unnest();
} }
public function testOpenSearchControllerAccessible() { public function testOpenSearchControllerAccessible()
{
$c = new DocumentationOpenSearchController(); $c = new DocumentationOpenSearchController();
$response = $c->handleRequest(new SS_HTTPRequest('GET', ''), DataModel::inst()); $response = $c->handleRequest(new SS_HTTPRequest('GET', ''), DataModel::inst());
$this->assertEquals(404, $response->getStatusCode()); $this->assertEquals(404, $response->getStatusCode());

View File

@ -8,13 +8,14 @@
* @subpackage tests * @subpackage tests
*/ */
class DocumentationViewerTest extends FunctionalTest { class DocumentationViewerTest extends FunctionalTest
{
protected $autoFollowRedirection = false; protected $autoFollowRedirection = false;
protected $manifest; protected $manifest;
public function setUp() { public function setUp()
{
parent::setUp(); parent::setUp();
Config::nest(); Config::nest();
@ -65,7 +66,8 @@ class DocumentationViewerTest extends FunctionalTest {
$this->manifest = new DocumentationManifest(true); $this->manifest = new DocumentationManifest(true);
} }
public function tearDown() { public function tearDown()
{
parent::tearDown(); parent::tearDown();
Config::unnest(); Config::unnest();
@ -74,7 +76,8 @@ class DocumentationViewerTest extends FunctionalTest {
/** /**
* This tests that all the locations will exist if we access it via the urls. * This tests that all the locations will exist if we access it via the urls.
*/ */
public function testLocationsExists() { public function testLocationsExists()
{
$this->autoFollowRedirection = false; $this->autoFollowRedirection = false;
$response = $this->get('dev/docs/en/doc_test/2.3/subfolder/'); $response = $this->get('dev/docs/en/doc_test/2.3/subfolder/');
@ -141,7 +144,8 @@ class DocumentationViewerTest extends FunctionalTest {
} }
public function testGetMenu() { public function testGetMenu()
{
$v = new DocumentationViewer(); $v = new DocumentationViewer();
// check with children // check with children
$response = $v->handleRequest(new SS_HTTPRequest('GET', 'en/doc_test/2.3/'), DataModel::inst()); $response = $v->handleRequest(new SS_HTTPRequest('GET', 'en/doc_test/2.3/'), DataModel::inst());
@ -174,7 +178,8 @@ class DocumentationViewerTest extends FunctionalTest {
public function testGetLanguage() { public function testGetLanguage()
{
$v = new DocumentationViewer(); $v = new DocumentationViewer();
$response = $v->handleRequest(new SS_HTTPRequest('GET', 'en/doc_test/2.3/'), DataModel::inst()); $response = $v->handleRequest(new SS_HTTPRequest('GET', 'en/doc_test/2.3/'), DataModel::inst());
@ -185,7 +190,8 @@ class DocumentationViewerTest extends FunctionalTest {
} }
public function testAccessingAll() { public function testAccessingAll()
{
$response = $this->get('dev/docs/en/all/'); $response = $this->get('dev/docs/en/all/');
// should response with the documentation index // should response with the documentation index
@ -210,6 +216,5 @@ class DocumentationViewerTest extends FunctionalTest {
// accessing all without a language should fail // accessing all without a language should fail
$response = $this->get('dev/docs/all/'); $response = $this->get('dev/docs/all/');
$this->assertEquals(404, $response->getStatusCode()); $this->assertEquals(404, $response->getStatusCode());
} }
} }

View File

@ -4,13 +4,14 @@
* @package docsviewer * @package docsviewer
* @subpackage tests * @subpackage tests
*/ */
class DocumentationViewerVersionWarningTest extends SapphireTest { class DocumentationViewerVersionWarningTest extends SapphireTest
{
protected $autoFollowRedirection = false; protected $autoFollowRedirection = false;
private $manifest; private $manifest;
public function setUp() { public function setUp()
{
parent::setUp(); parent::setUp();
Config::nest(); Config::nest();
@ -54,14 +55,15 @@ class DocumentationViewerVersionWarningTest extends SapphireTest {
$this->manifest = new DocumentationManifest(true); $this->manifest = new DocumentationManifest(true);
} }
public function tearDown() { public function tearDown()
{
parent::tearDown(); parent::tearDown();
Config::unnest(); Config::unnest();
} }
public function testVersionWarning() { public function testVersionWarning()
{
$v = new DocumentationViewer(); $v = new DocumentationViewer();
// the current version is set to 2.4, no notice should be shown on that page // the current version is set to 2.4, no notice should be shown on that page