Code cleanup and fix compatibility for ss 3.2

This commit is contained in:
Damian Mooyman 2014-08-22 16:36:42 +12:00
parent 095a97018e
commit 66e51bb5a4
16 changed files with 841 additions and 1024 deletions

View File

@ -3,15 +3,15 @@
language: php
php:
- 5.3
- 5.4
env:
- DB=MYSQL CORE_RELEASE=3.1
- DB=PGSQL CORE_RELEASE=master
- DB=MYSQL CORE_RELEASE=master
matrix:
include:
- php: 5.4
env: DB=MYSQL CORE_RELEASE=master
env: DB=PGSQL CORE_RELEASE=master
before_script:
- git clone git://github.com/silverstripe-labs/silverstripe-travis-support.git ~/travis-support
@ -19,4 +19,4 @@ before_script:
- cd ~/builds/ss
script:
- phpunit blog/tests/
- vendor/bin/phpunit blog/tests

View File

@ -0,0 +1,4 @@
<?php
// 0.8 version for framework 3.2
Deprecation::notification_version('0.8.0', 'blog');

View File

@ -1,4 +1,5 @@
<?php
/**
* An individual blog entry page type.
*
@ -24,14 +25,6 @@ class BlogEntry extends Page {
private static $plural_name = 'Blog Entry Pages';
private static $has_one = array();
private static $has_many = array();
private static $many_many = array();
private static $belongs_many_many = array();
private static $defaults = array(
"ProvideComments" => true,
'ShowInMenus' => false
@ -41,7 +34,7 @@ class BlogEntry extends Page {
* Is WYSIWYG editing allowed?
* @var boolean
*/
static $allow_wysiwyg_editing = true;
public static $allow_wysiwyg_editing = true;
/**
* Overload so that the default date is today.
@ -49,41 +42,55 @@ class BlogEntry extends Page {
public function populateDefaults(){
parent::populateDefaults();
$this->setField('Date', date('Y-m-d H:i:s', strtotime('now')));
$this->setField('Date', SS_DateTime::now()->getValue());
}
function getCMSFields() {
public function getCMSFields() {
Requirements::javascript('blog/javascript/bbcodehelp.js');
Requirements::themedCSS('bbcodehelp');
Requirements::themedCSS('bbcodehelp', 'blog');
$firstName = Member::currentUser() ? Member::currentUser()->FirstName : '';
$codeparser = new BBCodeParser();
SiteTree::disableCMSFieldsExtensions();
$fields = parent::getCMSFields();
SiteTree::enableCMSFieldsExtensions();
if(!self::$allow_wysiwyg_editing) {
$fields->removeFieldFromTab("Root.Main","Content");
$fields->addFieldToTab("Root.Main", new TextareaField("Content", _t("BlogEntry.CN", "Content"), 20));
// Add fields prior to extension
$this->beforeUpdateCMSFields(function($fields) {
// Disable HTML editing if wysiwyg is disabled
if(!BlogEntry::$allow_wysiwyg_editing) {
$fields->FieldList('Content', TextareaField::create("Content", _t("BlogEntry.CN", "Content"), 20));
}
$fields->addFieldToTab("Root.Main", $dateField = new DatetimeField("Date", _t("BlogEntry.DT", "Date")),"Content");
// Date field
$dateField = DatetimeField::create("Date", _t("BlogEntry.DT", "Date"));;
$dateField->getDateField()->setConfig('showcalendar', true);
$dateField->getTimeField()->setConfig('timeformat', 'H:m:s');
$fields->addFieldToTab("Root.Main", new TextField("Author", _t("BlogEntry.AU", "Author"), $firstName),"Content");
$fields->addFieldToTab("Root.Main", $dateField, "Content");
if(!self::$allow_wysiwyg_editing) {
$fields->addFieldToTab("Root.Main", new LiteralField("BBCodeHelper", "<div id='BBCode' class='field'>" .
// Author field
$firstName = Member::currentUser() ? Member::currentUser()->FirstName : '';
$fields->addFieldToTab(
"Root.Main",
TextField::create("Author", _t("BlogEntry.AU", "Author"), $firstName),
"Content"
);
// BB code hints
if(!BlogEntry::$allow_wysiwyg_editing) {
$codeparser = BBCodeParser::create();
$hintField = new LiteralField(
"BBCodeHelper",
"<div id='BBCode' class='field'>" .
"<a id=\"BBCodeHint\" target='new'>" . _t("BlogEntry.BBH", "BBCode help") . "</a>" .
"<div id='BBTagsHolder' style='display:none;'>".$codeparser->useable_tagsHTML()."</div></div>"));
"<div id='BBTagsHolder' style='display:none;'>".$codeparser->useable_tagsHTML()."</div></div>"
);
$fields->addFieldToTab("Root.Main", $hintField);
}
$fields->addFieldToTab("Root.Main", new TextField("Tags", _t("BlogEntry.TS", "Tags (comma sep.)")),"Content");
// Tags
$fields->addFieldToTab(
"Root.Main",
TextField::create("Tags", _t("BlogEntry.TS", "Tags (comma sep.)")),
"Content"
);
});
$this->extend('updateCMSFields', $fields);
return $fields;
return parent::getCMSFields();
}
/**
@ -106,7 +113,6 @@ class BlogEntry extends Page {
* @return ArrayList List of ArrayData with Tag, Link, and URLTag keys
*/
public function TagsCollection() {
$tags = $this->TagNames();
$output = new ArrayList();
@ -123,11 +129,11 @@ class BlogEntry extends Page {
return $output;
}
function Content() {
public function Content() {
if(self::$allow_wysiwyg_editing) {
return $this->getField('Content');
} else {
$parser = new BBCodeParser($this->Content);
$parser = BBCodeParser::create($this->Content);
$content = new HTMLText('Content');
$content->value = $parser->parse();
return $content;
@ -136,86 +142,71 @@ class BlogEntry extends Page {
/**
* To be used by RSSFeed. If RSSFeed uses Content field, it doesn't pull in correctly parsed content.
*
* @return string
*/
function RSSContent() {
return $this->Content();
}
/**
* Get a bbcode parsed summary of the blog entry
* @deprecated
*/
function ParagraphSummary(){
user_error("BlogEntry::ParagraphSummary() is deprecated; use BlogEntry::Content()", E_USER_NOTICE);
$val = $this->Content();
$content = $val;
if(!($content instanceof HTMLText)) {
$content = new HTMLText('Content');
$content->value = $val;
}
return $content->FirstParagraph('html');
}
/**
* Get the bbcode parsed content
* @deprecated
*/
function ParsedContent() {
user_error("BlogEntry::ParsedContent() is deprecated; use BlogEntry::Content()", E_USER_NOTICE);
public function RSSContent() {
return $this->Content();
}
/**
* Link for editing this blog entry
*
* @return string Edit URL
*/
function EditURL() {
return ($this->getParent()) ? $this->getParent()->Link('post') . '/' . $this->ID . '/' : false;
public function EditURL() {
$parent = $this->getParent();
if($parent) {
return Controller::join_links($parent->Link('post'), $this->ID);
}
}
function IsOwner() {
if(method_exists($this->Parent(), 'IsOwner')) {
return $this->Parent()->IsOwner();
}
/**
* Returns true if the current user is an admin, or is the owner of this blog
* {@see BlogHolder::IsOwner}
*
* @return bool
*/
public function IsOwner() {
$parent = $this->Parent();
return $parent && $parent->hasMethod('IsOwner') && $parent->IsOwner();
}
/**
* Call this to enable WYSIWYG editing on your blog entries.
* By default the blog uses BBCode
*/
static function allow_wysiwyg_editing() {
public static function allow_wysiwyg_editing() {
self::$allow_wysiwyg_editing = true;
}
/**
* Get the previous blog entry from this section of blog pages.
* Get the next oldest blog entry from this section of blog pages.
*
* @return BlogEntry
*/
function PreviousBlogEntry() {
return DataObject::get_one(
'BlogEntry',
"\"SiteTree\".\"ParentID\" = '$this->ParentID' AND \"BlogEntry\".\"Date\" < '$this->Date'",
true,
'Date DESC'
);
public function PreviousBlogEntry() {
return BlogEntry::get()
->filter('ParentID', $this->ParentID)
->exclude('ID', $this->ID)
->filter('Date:LessThanOrEqual', $this->Date)
->sort('"BlogEntry"."Date" DESC')
->first();
}
/**
* Get the next blog entry from this section of blog pages.
* Get the next most recent blog entry from this section of blog pages.
*
* @return BlogEntry
*/
function NextBlogEntry() {
return DataObject::get_one(
'BlogEntry',
"\"SiteTree\".\"ParentID\" = '$this->ParentID' AND \"BlogEntry\".\"Date\" > '$this->Date'",
true,
'Date ASC'
);
public function NextBlogEntry() {
return BlogEntry::get()
->filter('ParentID', $this->ParentID)
->exclude('ID', $this->ID)
->filter('Date:GreaterThanOrEqual', $this->Date)
->sort('"BlogEntry"."Date" ASC')
->first();
}
/**
@ -223,7 +214,7 @@ class BlogEntry extends Page {
*
* @return BlogHolder
*/
function getBlogHolder() {
public function getBlogHolder() {
$holder = null;
if($this->ParentID && $this->Parent()->ClassName == 'BlogHolder') {
$holder = $this->Parent();
@ -236,13 +227,10 @@ class BlogEntry extends Page {
class BlogEntry_Controller extends Page_Controller {
private static $allowed_actions = array(
'index',
'unpublishPost',
'PageComments',
'SearchForm'
'unpublishPost'
);
function init() {
public function init() {
parent::init();
Requirements::themedCSS("blog", "blog");
@ -251,32 +239,19 @@ class BlogEntry_Controller extends Page_Controller {
/**
* Gets a link to unpublish the blog entry
*/
function unpublishPost() {
public function unpublishPost() {
if(!$this->IsOwner()) {
Security::permissionFailure(
$this,
'Unpublishing blogs is an administrator task. Please log in.'
);
} else {
$SQL_id = (int) $this->ID;
$page = DataObject::get_by_id('SiteTree', $SQL_id);
$page = BlogEntry::get()->byID($this->data()->ID);
$page->deleteFromStage('Live');
$page->flushCache();
$this->redirect($this->getParent()->Link());
return $this->redirect($this->getParent()->Link());
}
}
/**
* Temporary workaround for compatibility with 'comments' module
* (has been extracted from sapphire/trunk in 12/2010).
*
* @return Form
*/
function PageComments() {
if($this->hasMethod('CommentsForm')) return $this->CommentsForm();
else if(method_exists('Page_Controller', 'PageComments')) return parent::PageComments();
}
}

View File

@ -34,39 +34,36 @@ class BlogHolder extends BlogTree implements PermissionProvider {
'BlogEntry'
);
function getCMSFields() {
public function getCMSFields() {
$blogOwners = $this->blogOwners();
SiteTree::disableCMSFieldsExtensions();
$fields = parent::getCMSFields();
SiteTree::enableCMSFieldsExtensions();
$fields->addFieldToTab(
// Add holder fields prior to extensions being called
$this->beforeUpdateCMSFields(function($fields) use ($blogOwners) {
$fields->addFieldsToTab(
'Root.Main',
array(
DropdownField::create('OwnerID', 'Blog owner', $blogOwners->map('ID', 'Name')->toArray())
->setEmptyString('(None)')
->setHasEmptyDefault(true),
"Content"
);
$fields->addFieldToTab('Root.Main', new CheckboxField('AllowCustomAuthors', 'Allow non-admins to have a custom author field'), "Content");
$fields->addFieldToTab(
"Root.Main",
CheckboxField::create('AllowCustomAuthors', 'Allow non-admins to have a custom author field'),
CheckboxField::create("ShowFullEntry", "Show Full Entry")
->setDescription('Show full content in overviews rather than summary'),
->setDescription('Show full content in overviews rather than summary')
),
"Content"
);
});
$this->extend('updateCMSFields', $fields);
return $fields;
return parent::getCMSFields();
}
/**
* Get members who have BLOGMANAGEMENT and ADMIN permission
*
* @param array $sort
* @param string $direction
* @return SS_List
*/
function blogOwners($sort = array('FirstName'=>'ASC','Surname'=>'ASC'), $direction = null) {
public function blogOwners($sort = array('FirstName'=>'ASC','Surname'=>'ASC'), $direction = null) {
$members = Permission::get_members_by_permission(array('ADMIN', 'BLOGMANAGEMENT'));
$members->sort($sort);
@ -86,7 +83,7 @@ class BlogHolder extends BlogTree implements PermissionProvider {
/**
* Only display the blog entries that have the specified tag
*/
function ShowTag() {
public function ShowTag() {
if($this->request->latestParam('Action') == 'tag') {
return Convert::raw2xml(Director::urlParam('ID'));
}
@ -95,30 +92,30 @@ class BlogHolder extends BlogTree implements PermissionProvider {
/**
* Check if url has "/post"
*/
function isPost() {
public function isPost() {
return $this->request->latestParam('Action') == 'post';
}
/**
* Link for creating a new blog entry
*/
function postURL(){
public function postURL() {
return $this->Link('post');
}
/**
* Returns true if the current user is an admin, or is the owner of this blog
*
* @return Boolean
* @return bool
*/
function IsOwner() {
public function IsOwner() {
return (Permission::check('BLOGMANAGEMENT') || Permission::check('ADMIN'));
}
/**
* Create default blog setup
*/
function requireDefaultRecords() {
public function requireDefaultRecords() {
parent::requireDefaultRecords();
// Skip creation of default records
@ -179,7 +176,7 @@ class BlogHolder extends BlogTree implements PermissionProvider {
}
}
function providePermissions() {
public function providePermissions() {
return array("BLOGMANAGEMENT" => "Blog management");
}
}
@ -196,7 +193,7 @@ class BlogHolder_Controller extends BlogTree_Controller {
'BlogEntryForm' => 'BLOGMANAGEMENT',
);
function init() {
public function init() {
parent::init();
Requirements::themedCSS("bbcodehelp");
}
@ -204,14 +201,14 @@ class BlogHolder_Controller extends BlogTree_Controller {
/**
* Return list of usable tags for help
*/
function BBTags() {
public function BBTags() {
return BBCodeParser::usable_tags();
}
/**
* Post a new blog entry
*/
function post(){
public function post(){
if(!Permission::check('BLOGMANAGEMENT')) return Security::permissionFailure();
$page = $this->customise(array(
'Content' => false,
@ -223,62 +220,74 @@ class BlogHolder_Controller extends BlogTree_Controller {
/**
* A simple form for creating blog entries
*
* @return Form
*/
function BlogEntryForm() {
public function BlogEntryForm() {
if(!Permission::check('BLOGMANAGEMENT')) return Security::permissionFailure();
$id = 0;
if($this->request->latestParam('ID')) {
$id = (int) $this->request->latestParam('ID');
}
$codeparser = new BBCodeParser();
$codeparser = BBCodeParser::create();
$membername = Member::currentUser() ? Member::currentUser()->getName() : "";
if(BlogEntry::$allow_wysiwyg_editing) {
$contentfield = new HtmlEditorField("BlogPost", _t("BlogEntry.CN"));
$contentfield = HtmlEditorField::create("BlogPost", _t("BlogEntry.CN"));
} else {
$contentfield = new CompositeField(
new LiteralField("BBCodeHelper","<a id=\"BBCodeHint\" target='new'>"._t("BlogEntry.BBH")."</a><div class='clear'><!-- --></div>" ),
new TextareaField("BlogPost", _t("BlogEntry.CN"),20), // This is called BlogPost as the id #Content is generally used already
new LiteralField("BBCodeTags","<div id=\"BBTagsHolder\">".$codeparser->useable_tagsHTML()."</div>")
$contentfield = CompositeField::create(
LiteralField::create(
"BBCodeHelper",
"<a id=\"BBCodeHint\" target='new'>"._t("BlogEntry.BBH")."</a><div class='clear'><!-- --></div>"
),
TextareaField::create(
"BlogPost",
_t("BlogEntry.CN"),
20
), // This is called BlogPost as the id #Content is generally used already
LiteralField::create(
"BBCodeTags",
"<div id=\"BBTagsHolder\">".$codeparser->useable_tagsHTML()."</div>"
)
);
}
// Support for https://github.com/chillu/silverstripe-tagfield
if(class_exists('TagField')) {
$tagfield = new TagField('Tags', null, null, 'BlogEntry');
$tagfield = TagField::create('Tags', null, null, 'BlogEntry');
$tagfield->setSeparator(', ');
} else {
$tagfield = new TextField('Tags');
$tagfield = TextField::create('Tags');
}
$field = 'TextField';
if(!$this->AllowCustomAuthors && !Permission::check('ADMIN')) {
$field = 'ReadonlyField';
}
$fields = new FieldList(
new HiddenField("ID", "ID"),
new TextField("Title", _t('BlogHolder.SJ', "Subject")),
new $field("Author", _t('BlogEntry.AU'), $membername),
$fields = FieldList::create(
HiddenField::create("ID", "ID"),
TextField::create("Title", _t('BlogHolder.SJ', "Subject")),
$field::create("Author", _t('BlogEntry.AU'), $membername),
$contentfield,
$tagfield,
new LiteralField("Tagsnote"," <label id='tagsnote'>"._t('BlogHolder.TE', "For example: sport, personal, science fiction")."<br/>" .
_t('BlogHolder.SPUC', "Please separate tags using commas.")."</label>")
LiteralField::create(
"Tagsnote",
" <label id='tagsnote'>"._t('BlogHolder.TE', "For example: sport, personal, science fiction")."<br/>" .
_t('BlogHolder.SPUC', "Please separate tags using commas.")."</label>"
)
);
$submitAction = new FormAction('postblog', _t('BlogHolder.POST', 'Post blog entry'));
$submitAction = FormAction::create('postblog', _t('BlogHolder.POST', 'Post blog entry'));
$actions = new FieldList($submitAction);
$validator = new RequiredFields('Title','BlogPost');
$actions = FieldList::create($submitAction);
$validator = RequiredFields::create('Title','BlogPost');
$form = new Form($this, 'BlogEntryForm',$fields, $actions,$validator);
$form = Form::create($this, 'BlogEntryForm', $fields, $actions, $validator);
if($id != 0) {
$entry = DataObject::get_by_id('BlogEntry', $id);
$id = (int) $this->request->latestParam('ID');
if($id) {
$entry = BlogEntry::get()->byID($id);
if($entry->IsOwner()) {
$form->loadDataFrom($entry);
$form->Fields()->fieldByName('BlogPost')->setValue($entry->Content);
}
} else {
$form->loadDataFrom(array("Author" => Cookie::get("BlogHolder_Name")));
@ -287,22 +296,18 @@ class BlogHolder_Controller extends BlogTree_Controller {
return $form;
}
function postblog($data, $form) {
public function postblog($data, $form) {
if(!Permission::check('BLOGMANAGEMENT')) return Security::permissionFailure();
Cookie::set("BlogHolder_Name", $data['Author']);
$blogentry = false;
if(isset($data['ID']) && $data['ID']) {
$blogentry = DataObject::get_by_id("BlogEntry", $data['ID']);
if(!$blogentry->IsOwner()) {
unset($blogentry);
}
if(!empty($data['ID'])) {
$candidate = BlogEntry::get()->byID($data['ID']);
if($candidate->IsOwner()) $blogentry = $candidate;
}
if(!$blogentry) {
$blogentry = new BlogEntry();
}
if(!$blogentry) $blogentry = BlogEntry::create();
$form->saveInto($blogentry);
$blogentry->ParentID = $this->ID;
@ -313,8 +318,11 @@ class BlogHolder_Controller extends BlogTree_Controller {
$blogentry->Locale = $this->Locale;
}
$blogentry->writeToStage("Stage");
$oldMode = Versioned::get_reading_mode();
Versioned::reading_stage('Stage');
$blogentry->write();
$blogentry->publish("Stage", "Live");
Versioned::set_reading_mode($oldMode);
$this->redirect($this->Link());
}

View File

@ -4,14 +4,24 @@
* Adds author and "post date" fields.
*/
class BlogLeftMainExtension extends Extension {
function updateListView($listView) {
/**
* {@see CMSMain::ListViewForm}
*
* @param type $listView
* @return type
*/
public function updateListView($listView) {
$parentId = $listView->getController()->getRequest()->requestVar('ParentID');
$parent = ($parentId) ? Page::get()->byId($parentId) : new Page();
if(!$parentId) return;
// Only apply logic for this page type
if($parent && $parent instanceof BlogHolder) {
$parent = BlogHolder::get()->byId($parentId);
if(!$parent) return;
$gridField = $listView->Fields()->dataFieldByName('Page');
if($gridField) {
if(!$gridField) return;
// Sort by post date
$list = $gridField->getList();
$list = $list->leftJoin('BlogEntry', '"BlogEntry"."ID" = "SiteTree"."ID"');
@ -19,7 +29,8 @@ class BlogLeftMainExtension extends Extension {
// Change columns
$cols = $gridField->getConfig()->getComponentByType('GridFieldDataColumns');
if($cols) {
if(!$cols) return;
$fields = $cols->getDisplayFields($gridField);
$castings = $cols->getFieldCasting($gridField);
@ -34,6 +45,3 @@ class BlogLeftMainExtension extends Extension {
$cols->setFieldCasting($castings);
}
}
}
}
}

View File

@ -19,23 +19,22 @@ class BlogTree extends Page {
private static $plural_name = 'Blog Tree Pages';
// Default number of blog entries to show
static $default_entries_limit = 10;
/**
* Default number of blog entries to show
*
* @var int
* @config
*/
private static $default_entries_limit = 10;
private static $db = array(
'Name' => 'Varchar(255)',
'LandingPageFreshness' => 'Varchar',
);
private static $defaults = array(
);
private static $has_one = array();
private static $has_many = array();
private static $allowed_children = array(
'BlogTree', 'BlogHolder'
'BlogTree',
'BlogHolder'
);
/*
@ -48,8 +47,8 @@ class BlogTree extends Page {
* uses current
* @return BlogTree
*/
static function current($page = null) {
public static function current($page = null) {
// extract page from current request if not specified
if (!$page && Controller::has_curr()) {
$controller = Controller::curr();
if ($controller->hasMethod('data')) {
@ -62,21 +61,23 @@ class BlogTree extends Page {
if ($page instanceof BlogTree) return $page;
// If page is a virtual page use that
if($page instanceof VirtualPage && $page->CopyContentFrom() instanceof BlogTree) return $page;
if($page instanceof VirtualPage && $page->CopyContentFrom() instanceof BlogTree) {
return $page;
}
// Or, if we a a BlogEntry underneath a BlogTree, use our parent
if($page->is_a("BlogEntry")) {
$parent = $page->getParent();
if($parent instanceof BlogTree) return $parent;
if($page instanceof BlogEntry && $page->getParent() instanceof BlogTree) {
return $page->getParent();
}
}
// Try to find a top-level BlogTree
$top = DataObject::get_one('BlogTree', "\"ParentID\" = '0'");
$top = BlogTree::get()->filter("ParentID", 0)->first();
if($top) return $top;
// Try to find any BlogTree that is not inside another BlogTree
if($blogTrees=DataObject::get('BlogTree')) foreach($blogTrees as $tree) {
$blogTrees = BlogTree::get();
foreach($blogTrees as $tree) {
if(!($tree->getParent() instanceof BlogTree)) return $tree;
}
@ -84,20 +85,26 @@ class BlogTree extends Page {
return $blogTrees->first();
}
/* ----------- ACCESSOR OVERRIDES -------------- */
/**
* Calculates number of months of landing page freshness to show
*
* @return int Number of months, if filtered
*/
public function getLandingPageFreshnessMonths() {
$freshness = $this->LandingPageFreshness;
public function getLandingPageFreshness() {
$freshness = $this->getField('LandingPageFreshness');
// If we want to inherit freshness, try that first
if ($freshness == "INHERIT" && $this->getParent()) $freshness = $this->getParent()->LandingPageFreshness;
// If we don't have a parent, or the inherited result was still inherit, use default
if ($freshness == "INHERIT") $freshness = '';
// Substitute 'INHERIT' for parent freshness, if available
if ($freshness === "INHERIT") {
$freshness = (($parent = $this->getParent()) && $parent instanceof BlogTree)
? $parent->getLandingPageFreshnessMonths()
: null;
}
return $freshness;
}
/* ----------- CMS CONTROL -------------- */
function getSettingsFields() {
public function getSettingsFields() {
$fields = parent::getSettingsFields();
$fields->addFieldToTab(
@ -143,7 +150,11 @@ class BlogTree extends Page {
}
}
// Build a list of all IDs for BlogHolders that are children of us
/**
* Build a list of all IDs for BlogHolders that are children of us
*
* @return array
*/
public function BlogHolderIDs() {
$holderIDs = array();
$this->loadDescendantBlogHolderIDListInto($holderIDs);
@ -153,74 +164,64 @@ class BlogTree extends Page {
/**
* Get entries in this blog.
*
* @param string $limit A clause to insert into the limit clause.
* @param string $limit Page size of paginated list
* @param string $tag Only get blog entries with this tag
* @param string $date Only get blog entries on this date - either a year, or a year-month eg '2008' or '2008-02'
* @param callable $retrieveCallback A function to call with pagetype, filter and limit for custom blog
* sorting or filtering
* @param string $filter Filter condition
* @param array $filters A list of DataList compatible filters
* @param mixed $where Raw SQL WHERE condition(s)
* @return PaginatedList The list of entries in a paginated list
*/
public function Entries($limit = '', $tag = '', $date = '', $retrieveCallback = null, $filter = '') {
$tagCheck = '';
$dateCheck = '';
if($tag) {
$SQL_tag = Convert::raw2sql($tag);
$tagCheck = "AND \"BlogEntry\".\"Tags\" LIKE '%$SQL_tag%'";
}
if($date) {
// Some systems still use the / seperator for date presentation
if( strpos($date, '-') ) $seperator = '-';
elseif( strpos($date, '/') ) $seperator = '/';
if(isset($seperator) && !empty($seperator)) {
// The 2 in the explode argument will tell it to only create 2 elements
// i.e. in this instance the $year and $month fields respectively
list($year,$month) = explode( $seperator, $date, 2);
$year = (int)$year;
$month = (int)$month;
if($year && $month) {
if(method_exists(DB::getConn(), 'formattedDatetimeClause')) {
$db_date=DB::getConn()->formattedDatetimeClause('"BlogEntry"."Date"', '%m');
$dateCheck = "AND CAST($db_date AS " . DB::getConn()->dbDataType('unsigned integer') . ") = $month AND " . DB::getConn()->formattedDatetimeClause('"BlogEntry"."Date"', '%Y') . " = '$year'";
} else {
$dateCheck = "AND MONTH(\"BlogEntry\".\"Date\") = '$month' AND YEAR(\"BlogEntry\".\"Date\") = '$year'";
}
}
} else {
$year = (int) $date;
if($year) {
if(method_exists(DB::getConn(), 'formattedDatetimeClause')) {
$dateCheck = "AND " . DB::getConn()->formattedDatetimeClause('"BlogEntry"."Date"', '%Y') . " = '$year'";
} else {
$dateCheck = "AND YEAR(\"BlogEntry\".\"Date\") = '$year'";
}
}
}
}
// Build a list of all IDs for BlogHolders that are children of us
public function Entries($limit = '', $tag = '', $date = '', $filters = array(), $where = '') {
// Filter by all current blog holder parents, if any are available
$holderIDs = $this->BlogHolderIDs();
// If no BlogHolders, no BlogEntries. So return false
if(empty($holderIDs)) return false;
// Otherwise, do the actual query
if($filter) $filter .= ' AND ';
$filter .= '"SiteTree"."ParentID" IN (' . implode(',', $holderIDs) . ") $tagCheck $dateCheck";
// Build filtered list
$entries = BlogEntry::get()
->filter('ParentID', $holderIDs)
->sort($order = '"BlogEntry"."Date" DESC');
$order = '"BlogEntry"."Date" DESC';
// Apply where condition
if($where) $entries = $entries->where($where);
// By specifying a callback, you can alter the SQL, or sort on something other than date.
if($retrieveCallback) return call_user_func($retrieveCallback, 'BlogEntry', $filter, $limit, $order);
// Add tag condition
if($tag) $entries = $entries->filter('Tags:PartialMatch', $tag);
$entries = BlogEntry::get()->where($filter)->sort($order);
// Add date condition
if($date && preg_match('/^(?<year>\d+)([-\\/](?<month>\d+))?/', $date, $matches)) {
// Add year filter
$yearExpression = DB::get_conn()->formattedDatetimeClause('"BlogEntry"."Date"', '%Y');
$uintExpression = DB::get_schema()->dbDataType('unsigned integer');
$entries = $entries->where(array(
"CAST($yearExpression AS $uintExpression) = ?" => $matches['year']
));
// Add month filter
if(!empty($matches['month'])) {
$monthExpression = DB::get_conn()->formattedDatetimeClause('"BlogEntry"."Date"', '%m');
$entries = $entries->where(array(
"CAST($monthExpression AS $uintExpression) = ?" => $matches['month']
));
}
}
// Deprecate old $retrieveCallback parameter
if($filters && (is_string($filters) || is_callable($filters))) {
Deprecation::notice(
'0.8',
'$retrieveCallback parameter is deprecated. Use updateEntries in an extension instead.'
);
$callbackWhere = $entries->dataQuery()->query()->getWhere();
return call_user_func($filters, 'BlogEntry', $callbackWhere, $limit, $order);
}
// Apply filters
if($filters) $entries = $entries->filter($filters);
// Extension point
$this->extend('updateEntries', $entries, $limit, $tag, $date, $filters, $where);
// Paginate results
$list = new PaginatedList($entries, Controller::curr()->request);
$list->setPageLength($limit);
return $list;
@ -241,7 +242,7 @@ class BlogTree_Controller extends Page_Controller {
'SelectedAuthor' => 'Text'
);
function init() {
public function init() {
parent::init();
$this->IncludeBlogRSS();
@ -257,37 +258,28 @@ class BlogTree_Controller extends Page_Controller {
*/
public function BlogEntries($limit = null) {
require_once('Zend/Date.php');
$filter = array();
if($limit === null) $limit = BlogTree::$default_entries_limit;
// Defaults for limit
if($limit === null) $limit = BlogTree::config()->default_entries_limit;
// only use freshness if no action is present (might be displaying tags or rss)
if ($this->LandingPageFreshness && !$this->request->param('Action')) {
$d = new Zend_Date(SS_Datetime::now()->getValue());
$d->sub($this->LandingPageFreshness, Zend_Date::MONTH);
$date = $d->toString('YYYY-MM-dd');
$landingPageFreshness = $this->getLandingPageFreshnessMonths();
if ($landingPageFreshness && !$this->request->param('Action')) {
$date = new Zend_Date(SS_Datetime::now()->getValue());
$date->sub($landingPageFreshness, Zend_Date::MONTH);
$date = $date->toString('YYYY-MM-dd');
$filter = "\"BlogEntry\".\"Date\" > '$date'";
} else {
$filter = '';
}
// allow filtering by author field and some blogs have an authorID field which
// may allow filtering by id
if(isset($_GET['author']) && isset($_GET['authorID'])) {
$author = Convert::raw2sql($_GET['author']);
$id = Convert::raw2sql($_GET['authorID']);
$filter .= " \"BlogEntry\".\"Author\" LIKE '". $author . "' OR \"BlogEntry\".\"AuthorID\" = '". $id ."'";
}
else if(isset($_GET['author'])) {
$filter .= " \"BlogEntry\".\"Author\" LIKE '". Convert::raw2sql($_GET['author']) . "'";
}
else if(isset($_GET['authorID'])) {
$filter .= " \"BlogEntry\".\"AuthorID\" = '". Convert::raw2sql($_GET['authorID']). "'";
$filter["Date:GreaterThan"] = $date;
}
$date = $this->SelectedDate();
// Allow filtering by author field
if($author = $this->SelectedAuthor()) {
$filter['Author:PartialMatch'] = $author;
}
return $this->Entries($limit, $this->SelectedTag(), ($date) ? $date : '', null, $filter);
// Return filtered items
return $this->Entries($limit, $this->SelectedTag(), $this->SelectedDate(), $filter);
}
/**
@ -339,50 +331,33 @@ class BlogTree_Controller extends Page_Controller {
/**
* Return the selected date from the blog tree
*
* @return string
* @return string Date in format 'year-month', 'year', or false if not a date
*/
public function SelectedDate() {
if($this->request->latestParam('Action') == 'date') {
if($this->request->latestParam('Action') !== 'date') return false;
// Check year
$year = $this->request->latestParam('ID');
if(!is_numeric($year)) return false;
// Check month
$month = $this->request->latestParam('OtherID');
if(is_numeric($year) && is_numeric($month) && $month < 13) {
$date = $year .'-'. $month;
return $date;
if(is_numeric($month) && $month < 13) {
return $year . '-' . $month;
} else {
if(is_numeric($year)) return $year;
return $year;
}
}
return false;
}
/**
* @return string
*/
public function SelectedAuthor() {
if($this->request->getVar('author')) {
$hasAuthor = BlogEntry::get()->filter('Author', $this->request->getVar('author'))->Count();
return $hasAuthor
? $this->request->getVar('author')
: null;
} elseif($this->request->getVar('authorID')) {
$hasAuthor = BlogEntry::get()->filter('AuthorID', $this->request->getVar('authorID'))->Count();
if($hasAuthor) {
$member = Member::get()->byId($this->request->getVar('authorID'));
if($member) {
if($member->hasMethod('BlogAuthorTitle')) {
return $member->BlogAuthorTitle;
} else {
return $member->Title;
}
} else {
return null;
}
}
if($author = $this->request->getVar('author')) {
$hasAuthor = BlogEntry::get()
->filter('Author:PartialMatch', $author)
->Count();
if($hasAuthor) return $author;
}
}

View File

@ -8,7 +8,8 @@ require_once(BASE_PATH . '/blog/thirdparty/xmlrpc/xmlrpc_wrappers.php');
* MetaWeblogController provides the MetaWeblog API for SilverStripe blogs.
*/
class MetaWeblogController extends Controller {
function index($request) {
public function index($request) {
// Create an xmlrpc server, and set up the method calls
$service = new xmlrpc_server(array(
@ -34,7 +35,7 @@ class MetaWeblogController extends Controller {
/**
* Get a list of BlogHolders the user has access to.
*/
function getUsersBlogs($appkey, $username, $password) {
public function getUsersBlogs($appkey, $username, $password) {
$member = MemberAuthenticator::authenticate(array(
'Email' => $username,
'Password' => $password,
@ -43,7 +44,7 @@ class MetaWeblogController extends Controller {
// TODO Throw approriate error.
if(!$member) die();
$blogholders = DataObject::get('BlogHolder');
$blogholders = SearchForm::get();
$response = array();
@ -64,7 +65,7 @@ class MetaWeblogController extends Controller {
/**
* Get the most recent posts on a blog.
*/
function getRecentPosts($blogid, $username, $password, $numberOfPosts) {
public function getRecentPosts($blogid, $username, $password, $numberOfPosts) {
$member = MemberAuthenticator::authenticate(array(
'Email' => $username,
'Password' => $password,
@ -96,10 +97,8 @@ class MetaWeblogController extends Controller {
return $res;
}
function getCategories() {
public function getCategories() {
//TODO dummy function
return array();
}
}
?>

View File

@ -1,152 +0,0 @@
<?php
require_once("model/DB.php");
class TypoImport extends Controller {
/**
* Imports product status and price change updates.
*
*/
function testinstall() {
echo "Ok";
}
/**
* Imports blog entries and comments from a Potgres-based typo installation into a SilverStripe blog
*/
function import(){
// some of the guys in the contents table are articles, some are contents. Distinguished by type = "Article" or "Comment"
// fields are: id, title, author, body, body_html, extended, excerpt, keywords, created_at, updated_at, extended_html, user_id, permalink, guid, [13]
// text_filter_id, whiteboard, type, article_id, email, url, ip, blog_name, name, published, allow_pings, allow_comments, blog_id
// published_at, state, status_confirmed
$dbconn = pg_connect("host=orwell port=5432 dbname=typo_prod user=postgres password=possty");
// create a new blogholder and call it "imported blog"
$bholder = new BlogHolder();
$bholder->Title = "imported blog";
// write it!
$bholder->write();
$bholder->publish("Stage", "Live");
// get the typo articles
$result = pg_query($dbconn, "SELECT * FROM contents WHERE type='Article'");
while ($row = pg_fetch_row($result)) {
// title [1]
// author [2]
// body [3]
// body_html [4] (type rendered and cached the html here. This is the preferred blog entry content for migration)
// keywords (space separated) [7] (tags table is just a list of the unique variants of these keywords)
// created_at [8]
// permalink [12] (this is like the url in sitetree, prolly not needed)
// email [18] (address of the commenter)
// url [19] (url of the commenter)
$title = $row[1];
$author = $row[2];
$blog_entry = $row[4];
$keywords = $row[7];
$created_at = $row[8];
// sometimes it's empty. If it is, grab the body
if ($blog_entry == ""){
// use "body"
$blog_entry = $row[3];
}
echo "blog_entry: $blog_entry";
echo "<br />\n";
// put the typo blog entry in the SS database
$newEntry = new BlogEntry();
$newEntry->Title = $title;
$newEntry->Author = $author;
$newEntry->Content = $blog_entry;
$newEntry->Tags = $keywords;
$newEntry->Date = $created_at;
// tie each blog entry back to the blogholder we created initially
$newEntry->ParentID = $bholder->ID;
// write it!
$newEntry->write();
$newEntry->publish("Stage", "Live");
// grab the id so we can get the comments
$old_article_id = $row[0];
// get the comments
$result2 = pg_query($dbconn, "SELECT * FROM contents WHERE type = 'Comment' AND article_id = $old_article_id");
while ($row2 = pg_fetch_row($result2)) {
// grab the body_html
$comment = $row2[4];
// sometimes it's empty. If it is, grab the body
if ($comment == ""){
// use "body"
$comment = $row2[3];
}
$Cauthor = $row2[2];
$Ccreated_at = $row2[8];
// put the typo blog comment in the SS database
$newCEntry = new PageComment();
$newCEntry->Name = $Cauthor;
$newCEntry->Comment = $comment;
$newCEntry->Created = $created_at;
// need to grab the newly inserted blog entry's id
$newCEntry->ParentID = $newEntry->ID;
// write it!
$newCEntry->write();
echo "comment: $comment";
echo "<br />\n";
}
$newEntry->flushCache();
// fix up the specialchars
pg_query($dbconn, "UPDATE SiteTree SET Content = REPLACE(Content, \"&#215;\", \"x\")");
pg_query($dbconn, "UPDATE SiteTree SET Content = REPLACE(Content, \"&#8217;\", \"&rsquo;\")");
pg_query($dbconn, "UPDATE SiteTree SET Content = REPLACE(Content, \"&#8216;\", \"&lsquo;\")");
pg_query($dbconn, "UPDATE SiteTree SET Content = REPLACE(Content, \"&#151;\", \"&mdash;\")");
pg_query($dbconn, "UPDATE SiteTree SET Content = REPLACE(Content, \"&#8220;\", \"&ldquo;\")");
pg_query($dbconn, "UPDATE SiteTree SET Content = REPLACE(Content, \"&#8221;\", \"&rdquo;\")");
pg_query($dbconn, "UPDATE SiteTree SET Content = REPLACE(Content, \"&#8211;\", \"&ndash;\")");
pg_query($dbconn, "UPDATE SiteTree SET Content = REPLACE(Content, \"&#8212;\", \"&mdash;\")");
pg_query($dbconn, "UPDATE SiteTree SET Content = REPLACE(Content, \"&#8230;\", \"&hellip;\")");
pg_query($dbconn, "UPDATE SiteTree SET Content = REPLACE(Content, \"&#8482;\", \"&trade;\")");
pg_query($dbconn, "UPDATE SiteTree SET Content = REPLACE(Content, \"&#38;\", \"&amp;\")");
pg_query($dbconn, "UPDATE PageComment SET Comment = REPLACE(Comment, \"&#215;\", \"x\")");
pg_query($dbconn, "UPDATE PageComment SET Comment = REPLACE(Comment, \"&#8217;\", \"&rsquo;\")");
pg_query($dbconn, "UPDATE PageComment SET Comment = REPLACE(Comment, \"&#8216;\", \"&lsquo;\")");
pg_query($dbconn, "UPDATE PageComment SET Comment = REPLACE(Comment, \"&#151;\", \"&mdash;\")");
pg_query($dbconn, "UPDATE PageComment SET Comment = REPLACE(Comment, \"&#8220;\", \"&ldquo;\")");
pg_query($dbconn, "UPDATE PageComment SET Comment = REPLACE(Comment, \"&#8221;\", \"&rdquo;\")");
pg_query($dbconn, "UPDATE PageComment SET Comment = REPLACE(Comment, \"&#8211;\", \"&ndash;\")");
pg_query($dbconn, "UPDATE PageComment SET Comment = REPLACE(Comment, \"&#8212;\", \"&mdash;\")");
pg_query($dbconn, "UPDATE PageComment SET Comment = REPLACE(Comment, \"&#8230;\", \"&hellip;\")");
pg_query($dbconn, "UPDATE PageComment SET Comment = REPLACE(Comment, \"&#8482;\", \"&trade;\")");
pg_query($dbconn, "UPDATE PageComment SET Comment = REPLACE(Comment, \"&#38;\", \"&amp;\")");
}
pg_close($dbconn);
} // end function
} // end class
?>

View File

@ -1,6 +1,6 @@
<?php
if(class_exists('Widget')) {
if(!class_exists('Widget')) return;
/**
* Shows a widget with viewing blog entries
@ -25,7 +25,7 @@ if(class_exists('Widget')) {
private static $description =
'Show a list of months or years in which there are blog posts, and provide links to them.';
function getCMSFields() {
public function getCMSFields() {
$fields = parent::getCMSFields();
$fields->merge(
@ -47,7 +47,7 @@ if(class_exists('Widget')) {
return $fields;
}
function getDates() {
public function getDates() {
Requirements::themedCSS('archivewidget');
$results = new ArrayList();
@ -113,5 +113,3 @@ if(class_exists('Widget')) {
return $results;
}
}
}

View File

@ -1,6 +1,6 @@
<?php
if(class_exists('Widget')) {
if(!class_exists('Widget')) return;
/**
* Blog Management Widget
@ -16,8 +16,12 @@ if(class_exists('Widget')) {
private static $description =
"Provide a number of links useful for administering a blog. Only shown if the user is an admin.";
function CommentText() {
/**
* Get text of latest comment
*
* @return string
*/
public function CommentText() {
if(!class_exists('Comment')) return false;
$unmoderatedcount = DB::query("SELECT COUNT(*) FROM \"Comment\" WHERE \"Moderated\"=1")->value();
if($unmoderatedcount == 1) {
@ -29,8 +33,12 @@ if(class_exists('Widget')) {
}
}
function CommentLink() {
/**
* Link to edit comment
*
* @return string
*/
public function CommentLink() {
if(!Permission::check('BLOGMANAGEMENT') || !class_exists('Comment')) return false;
$unmoderatedcount = DB::query("SELECT COUNT(*) FROM \"Comment\" WHERE \"Moderated\"=1")->value();
@ -45,16 +53,14 @@ if(class_exists('Widget')) {
class BlogManagementWidget_Controller extends Widget_Controller {
function WidgetHolder() {
public function WidgetHolder() {
if(Permission::check("BLOGMANAGEMENT")) {
return $this->renderWith("WidgetHolder");
}
}
function PostLink() {
public function PostLink() {
$container = BlogTree::current();
return ($container && $container->ClassName != "BlogTree") ? $container->Link('post') : false;
}
}
}

View File

@ -1,6 +1,6 @@
<?php
if (class_exists('Widget')) {
if(!class_exists('Widget')) return;
/**
* Presents a list of items from an RSS feed url
@ -32,7 +32,7 @@ if (class_exists('Widget')) {
*
* @return string
*/
function getAbsoluteRssUrl() {
public function getAbsoluteRssUrl() {
$urlParts = parse_url($this->RssUrl);
if(!isset($urlParts['host']) || !$urlParts['host']) {
return Director::absoluteBaseURL() . $this->RssUrl;
@ -41,7 +41,7 @@ if (class_exists('Widget')) {
}
}
function getCMSFields() {
public function getCMSFields() {
$fields = parent::getCMSFields();
$fields->merge(
@ -60,11 +60,11 @@ if (class_exists('Widget')) {
return $fields;
}
function Title() {
return ($this->RSSTitle) ? $this->RSSTitle : _t('RSSWidget.DEFAULTTITLE', 'RSS Feed');
public function Title() {
return $this->RSSTitle ?: _t('RSSWidget.DEFAULTTITLE', 'RSS Feed');
}
function getFeedItems() {
public function getFeedItems() {
$output = new ArrayList();
// Protection against infinite loops when an RSS widget pointing to this page is added to this page
@ -105,5 +105,3 @@ if (class_exists('Widget')) {
}
}
}
}

View File

@ -1,6 +1,6 @@
<?php
if(class_exists('Widget')) {
if(!class_exists('Widget')) return;
/**
* A simple widget that just shows a link
@ -23,11 +23,9 @@ if(class_exists('Widget')) {
*
* @return string
*/
function getRSSLink() {
public function getRSSLink() {
Requirements::themedCSS('subscribersswidget');
$container = BlogTree::current();
if ($container) return $container->Link('rss');
}
}
}

View File

@ -1,6 +1,6 @@
<?php
if(class_exists('Widget')) {
if(!class_exists('Widget')) return;
/**
* A list of tags associated with blog posts
@ -62,8 +62,8 @@ if(class_exists('Widget')) {
return parent::getCMSFields();
}
function Title() {
return $this->Title ? $this->Title : _t('TagCloudWidget.DEFAULTTITLE', 'Tag Cloud');
public function Title() {
return $this->Title ?: _t('TagCloudWidget.DEFAULTTITLE', 'Tag Cloud');
}
/**
@ -79,7 +79,7 @@ if(class_exists('Widget')) {
*
* @return ArrayList
*/
function getTagsCollection() {
public function getTagsCollection() {
Requirements::themedCSS("tagcloud");
// Ensure there is a valid BlogTree with entries
@ -152,4 +152,3 @@ if(class_exists('Widget')) {
return $output;
}
}
}

View File

@ -13,13 +13,13 @@
"email": "carlos@silverstripe.com"
}
],
"require":
{
"silverstripe/cms": "~3.1"
"require": {
"silverstripe/cms": "~3.2"
},
"suggest":
{
"require-dev": {
"phpunit/PHPUnit": "~3.7@stable"
},
"suggest": {
"silverstripe/widgets": "Additional 'sidebar features', e.g. a list of recent posts and a tagcloud",
"silverstripe/comments": "Enable user comments on any page type, including blog posts",
"simplepie/simplepie": "Parse RSS feeds, required for the RSS widget"

View File

@ -72,11 +72,12 @@ class BlogTreeTest extends SapphireTest {
function testLandingPageFreshness() {
$node = $this->objFromFixture('BlogTree', 'root');
$this->assertEquals($node->LandingPageFreshness, '7 DAYS');
$this->assertEquals('7', $node->LandingPageFreshness);
$node = $this->objFromFixture('BlogTree', 'levela');
$this->assertEquals($node->LandingPageFreshness, '2 DAYS');
$this->assertEquals('2', $node->LandingPageFreshness);
$node = $this->objFromFixture('BlogTree', 'levelb');
$this->assertEquals($node->LandingPageFreshness, '7 DAYS');
$this->assertEquals('INHERIT', $node->LandingPageFreshness);
$this->assertEquals('7', $node->getLandingPageFreshnessMonths());
}
function testGettingAssociatedBlogTree() {

View File

@ -1,13 +1,13 @@
BlogTree:
root:
Title: Root BlogTree
LandingPageFreshness: 7 DAYS
LandingPageFreshness: 7
otherroot:
Title: Other root BlogTree
levela:
Title: Level A
Parent: =>BlogTree.root
LandingPageFreshness: 2 DAYS
LandingPageFreshness: 2
levelb:
Title: Level B
Parent: =>BlogTree.root
@ -27,7 +27,7 @@ BlogHolder:
levelaa_blog1:
Title: Level AA Blog 1
Parent: =>BlogTree.levelaa
LandingPageFreshness: 1 DAY
LandingPageFreshness: 1
levelaa_blog2:
Title: Level AA Blog 2
Parent: =>BlogTree.levelaa