PHP code files for PubKitBlog
This is the main logic section of PubKitBlog, which is included towards the end of the snippet code. Below the main listing are listings of the functions and classes that it uses. (Not all the functions are not used in pkBlog.)
pubKitBlog.inc.php
<?php
#::::::::::::::::::::::::::::::::::::::::
# Snippet Name: PubKitBlog 1.4.1
# include file for pkBlog
# see pubKitBlog.snippet.txt for parameters
# and required function/class files
#::::::::::::::::::::::::::::::::::::::::
#;;;;;;;;;; updates ;;;;;;;;;;;;;;;;;;;;;;;
# 18 Sep 09: v1.4.1
# - must use "||" to split tags in edit command
# - abolish dependence on PHx
# - add +intro+ placeholder
#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
// list parameters and REQUEST variables if debug is enabled
if ($debug == 1) {
$dbg .= '<pre>' . print_r($params, true) . '</pre>';
$dbg .= '<pre>' . print_r($_REQUEST, true) . '</pre>';
} else {
$dbg= NULL;
}
// define location of file defining input form
$chunk_place = $modx->config['base_path'] . 'assets/snippets/pubKit/chunks/';
// define location of main MODx content table
$contentTable = $modx->getFullTableName('site_content');
define('ONE_DAY',86400); //seconds in a day (for unpub dates)
// copy input variables to array so they can be updated
$fields = $_REQUEST;
// If docID is set, you are editing existing item
$docId = isset($fields['docId']) ? $fields['docId'] : '';
// operation required - create, delete, edit etc.
$cmd = $fields['command'];
// test if input has come back from form (check for hidden field)
$isPostBack = (isset($fields['pkForm'])) ? true:false;
// 2-stage deletion - first prompt, delete if confirmed
// maybe this needs some security checks???
$isDeletion = isset($fields['confirmDeletion']) ? true:false;
// retrieve or set up tags array for template variable
// class definition in optionsbuilder.class.php
$options = new OptionButtons($tagTv,'tags');
if (empty($fields['tags'])) {
$tags = array();
$tags[] = $options->definition['value'];
} else {
if (is_array($fields['tags'])) {
$tags = $fields['tags'];
} else {
$tags = explode($delimiter,$fields['tags']);
}
}
if (!isset($fields['displayDate'])) {
$fields['displayDate'] = strftime('%d %b %y');
}
// populate template variables as array
// name the fields that may need to be extracted from $doc object
$tvs = array('pkDate'=>"",'pkDateTo'=>"");
$tvs[$tagTv] = $tags;
$tvs['pkPreviewFlag'] = (isset($fields['preview'])) ? 1:0;
// blank out error messages
$message = NULL;
// get form template. No default - always use a chunk or file
// $formtpl will be final output of the snippet
if (isset($formtpl)) {
if (substr($formtpl,0,5) != '@FILE') {
$formtpl = $modx->getChunk($formtpl);
} else {
$formFile = $chunk_place . 'chunk.' . trim(substr($formtpl,6)) . '.html';
$formtpl = file_get_contents($formFile);
}
} else {
$formtpl = 'You must define the form template in a chunk or a file';
}
// if form input, check mandatory fields, build error message
// this is probably where language variations could come in???
if ($isPostBack) {
// retrieve showInMenu setting
$showinmenu = (isset($fields['show'])) ? 1 : 0;
if(empty($fields['pagetitle'])) {
$message .= "You must enter a title; <br />\n";
}
if(empty($fields['longtitle'])) {
$message .= "You must enter a full headline; <br />\n";
}
if(empty($fields[$rtcontent])) {
$message .= "Content is missing; <br />\n";
}
// Require at least one tag
if (empty($tags[0])) {
$message .= "Please choose at least one tag <br />\n";
}
// check dates readable by strtotime() (PHP 5.1+ only)
// "false" parameter disallows blank
// see pubKit.functions.php
$message .= DateValid($fields['displayDate'], 'Date', false);
$message .= DateValid($fields['displayFrom'],'Display from date');
$message .= DateValid($fields['displayTo'],'Display to date');
// If error messages exist, skip create/update and redisplay form (populated)
// newsBody is default content of the rich-text TV
if (!empty($message)) {
$modx->setPlaceholder('newsBody', $fields[$rtcontent]);
$message = '<div id="inputErrors">' . $message . '</div>';
$modx->setPlaceholder('errors', $message);
} else {
// sanitize content. $allowedTags set in snippet (not a parameter)
$content = $modx->stripTags($fields[$rtcontent], $allowedTags);
$title = $modx->stripTags($fields['pagetitle']);
$longtitle = $modx->stripTags($fields['longtitle']);
$introtext = $modx->stripTags($fields[$rtsummary], $allowedTags);
// substitute =intro+ in content with text from introtext field
if (!isset($fields['preview'])) {
$content = str_replace('+intro+', $introtext, $content);
}
// calculate next menu index; NB double quotes for string make sense here!
$mnuidx = $modx->db->getValue("
SELECT MAX(menuindex) + 1 as 'mnuidx'
FROM $contentTable
WHERE parent = '$folder' ");
if($mnuidx<1) {
$mnuidx = 0;
}
// menu-hiding set by parameter or form field
$hidemenu = ($showinmenu == 1) ? 0 : 1;
// validate and format dates, set published or unpublished (using function)
// NB unpub_date = displayTo + 1 day
$startDate = strtotime($fields['displayDate']);
$pubDate = (!empty($fields['displayFrom'])) ? strtotime($fields['displayFrom']) : 0;
$endDate = (!empty($fields['displayTo'])) ? strtotime($fields['displayTo']) : 0;
$publishable = pubUnpub($startDate,$pubDate,$endDate);
$published = $publishable['published'];
$unpubDate = $publishable['unpub'];
$tvs['pkDate'] = strftime('%Y-%m-%d',$startDate);
$tvs['pkDateTo'] = ($endDate > 0) ? strftime('%Y-%m-%d',$endDate) : '';
// make previews unpublished
if (isset($fields['preview'])) {
$published = 0;
}
// set user for author fields
$user = $modx->getLoginUserName();
$userid = $modx->getLoginUserID();
if(!$user && $allowAnyPost) {
$user = 'anon';
}
// *********** CREATE || UPDATE DOCUMENT **************
// Use DocManager to create/update document, including TV values
// TO DO: Introtext & Content entities if TEXTAREA, not if rich text input
$doc = new Document($docId);
$doc->Set('pagetitle', $modx->db->escape(htmlspecialchars($title)));
$doc->Set('longtitle', $modx->db->escape(htmlspecialchars($longtitle)));
$doc->Set('introtext', $modx->db->escape(htmlspecialchars($introtext)));
$doc->Set('content', $modx->db->escape($content));
$doc->Set('menuindex', $mnuidx);
$doc->Set('hidemenu', $hidemenu);
$doc->Set('editedon', time());
// next line inherited from NewsPublisher - adjusts user ID database index for web/manager user
$doc->Set('editedby', ($userid > 0 ? $userid * -1 : 0));
$doc->SetTemplate($template);
$doc->Set('pub_date', $pubDate);
$doc->Set('published', $published);
$doc->Set('unpub_date', $unpubDate);
// rewrite TV values; DocManager needs "tv" prefix to identify them
foreach ($tvs as $tv=>$value) {
$value = (is_array($value)) ? implode('||', $value) : $value;
$doc->Set('tv' . $tv, $modx->db->escape(htmlspecialchars($value)));
}
// Prserve previous values for these fields if updating document
if (empty($docId)) {
$doc->Set('parent', $folder);
$doc->Set('createdon', time());
$doc->Set('createdby', ($userid>0 ? $userid * -1 : 0));
$doc->Set('deleted', '0');
// resource's cacheability set in &cacheItem parameter, default = 1.
$doc->Set('cacheable', $cacheable);
if ($permalinks == 1) {
$doc->Save();
// now doc has its own ID, create alias using it for unique permalink
$safalias = preg_replace('#[^a-zA-Z0-9\s\-]#',"",$title);
$safalias = trim(strtolower($safalias));
$safalias = preg_replace('#\s+#','-',$safalias);
$safalias = '-' . substr($safalias,0,$permaLength);
} else {
$safalias = "";
}
$safalias = $doc->Get('id') . $safalias;
$doc->Set('alias', $safalias);
}
$doc->Save();
// tidy menuindex after deletions or manual ordering (rank)
// (see pubKit.functions.php)
resetRank($table, $folder, 1);
$redirect = TRUE;
}
}
/******************** Form display operations *******************
* New item, re-edit, request/do deletion,
* or redisplay with error messages and entered data
****************************************************************/
if (!empty($docId) && empty($redirect)) {
$doc = new Document($docId);
// complete deletion (after confiration)
if ($isDeletion) {
if($fields['delete'] == 'Yes') {
$doc->Delete();
}
$postid = $fields['returnId'];
$redirect = TRUE;;
}
// request deletion. (returnId from management or preview screen)
elseif ($cmd == 'delete') {
$formtpl = $modx->getChunk('confirmDeletion');
$modx->setPlaceholder('docId', $doc->Get('id'));
$modx->setPlaceholder('returnId', $fields['returnId']);
$modx->setPlaceholder('title', $doc->Get('pagetitle'));
$modx->setPlaceholder('headline', $doc->Get('longtitle'));
}
// update item
elseif ($cmd == 'edit') {
$modx->setPlaceholder('docId', $doc->Get('id'));
$modx->setPlaceholder('pagetitle', $doc->Get('pagetitle'));
$modx->setPlaceholder('longtitle', $doc->Get('longtitle'));
$modx->setPlaceholder('introtext', $doc->Get('introtext'));
$modx->setPlaceholder('newsBody', $doc->Get('content'));
$modx->setPlaceholder('menuindex', $doc->Get('menuindex'));
$hidemenu = $doc->Get('hidemenu');
$showinmenu = 1 - $hidemenu;
// retrieve TV values. $fields array will be made into placeholders further on.
foreach($tvs as $tvName=>$tvValue) {
$tv = $doc->Get('tv' . $tvName);
$fields[$tvName] = $tv;
}
// TVs retrieved in raw format, no widget processing
$tags = explode('||',$fields[$tagTv]);
$fields['displayDate'] = strftime('%d %b %y', strtotime($fields['pkDate']));
$fields['displayTo'] = ($fields['pkDateTo'] > 0) ? strftime('%d %b %y', strtotime($fields['pkDateTo'])) : "";
$fields['displayFrom'] = ($doc->Get('pub_date') > 0) ? strftime('%d %b %y', $doc->Get('pub_date')) : "";
// set up status placeholders
if ($doc->Get('published') == 0) {
$modx->setPlaceholder('itemStatus', '<b style="color:#800;">Unpublished</b>');
} else {
$modx->setPlaceholder('itemStatus', '<b>Published</b>');
}
if ($doc->Get('tvpkPreviewFlag') == 1) {
$modx->setPlaceholder('previewStatus', '<b style="color:#800;">Draft</b>');
} else {
$modx->setPlaceholder('previewStatus', '');
}
// hidden form field for redirect after submission
$modx->setPlaceholder('postid', $postid);
}
// publish (from button in Preview screen)
// create new doc object - don't want to rewrite every field
// replace +intro+ in content with introtext
elseif ($cmd == 'publish') {
$doc = new Document($docId, 'published,pub_date,introtext,content');
// may not be due for publication yet
$publishable = pubUnpub(
$doc->Get('tvpkDate'),
$doc->Get('pub_date'),
$doc->Get('tvpkDateTo'));
$introtext = $doc->Get('introtext');
$content = $doc->Get('content');
$content = str_replace('+intro+', $introtext, $content);
$doc->Set('introtext', $modx->db->escape($introtext));
$doc->Set('content', $modx->db->escape($content));
$doc->Set('published', $publishable['published']);
// see pubKit.functions.php
setTemplateVar(0, $docId, 'pkPreviewFlag');
$doc->Save();
$redirect = TRUE;
}
} else {
$modx->setPlaceholder('itemStatus','New Item');
}
// redirect after item creation/update/publication
if ($redirect) {
// clear site cache (see pubKit.functions.php)
if($clearcache==1){
emptyCache();
}
// redirect to post id (with anchor #+$prefix+docId if reediting)
// postId may be array for radio button tags corresponding to different pages
if (is_array($postid)) {
$landing = $modx->makeUrl($postid[$fields['tags'] ]);
} elseif (isset($postid)) {
$landing = $modx->makeUrl($postid);
} else {
$landing = $modx->makeUrl($doc->Get('id'));
}
if (isset($fields['preview'])) {
$landing .= '?template=preview&id=' . $doc->Get('id');
} else {
$landing .= (!empty($docId)) ? '#' . $prefix . $docId: '';
}
$modx->sendRedirect($landing);
}
/***************** Prepare form for display *****************/
// Create radio-button or checkbox code (optionsbuilder.class.php)
$modx->setPlaceholder('tagSet', $options->BuildSet($tags, $tagFormat));
// Initialize show in menu checkbox
if ($showinmenu == 1) {
$modx->setPlaceholder('showInMenu', ' checked="checked"');
}
// check user rights
if(!$allowAnyPost && !$modx->isMemberOfWebGroup($postgrp)) {
$formtpl = 'You do not have permission to post items here - please contact Administrator';
} else {
// populate form fields placeholders with any existing data
// convert quotes etc. so text fields are not mangled
// NB applied to all fields (only relevant to text and textarea)
// assuming XHTML, single quotes are left alone
foreach($fields as $n=>$v) {
$v = htmlspecialchars($v);
$modx->setPlaceholder($n, $v);
}
}
// return form to snippet call, preceded by debug info
$pubKit = $dbg . $formtpl;
?>
#::::::::::::::::::::::::::::::::::::::::
# Snippet Name: PubKitBlog 1.4.1
# include file for pkBlog
# see pubKitBlog.snippet.txt for parameters
# and required function/class files
#::::::::::::::::::::::::::::::::::::::::
#;;;;;;;;;; updates ;;;;;;;;;;;;;;;;;;;;;;;
# 18 Sep 09: v1.4.1
# - must use "||" to split tags in edit command
# - abolish dependence on PHx
# - add +intro+ placeholder
#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
// list parameters and REQUEST variables if debug is enabled
if ($debug == 1) {
$dbg .= '<pre>' . print_r($params, true) . '</pre>';
$dbg .= '<pre>' . print_r($_REQUEST, true) . '</pre>';
} else {
$dbg= NULL;
}
// define location of file defining input form
$chunk_place = $modx->config['base_path'] . 'assets/snippets/pubKit/chunks/';
// define location of main MODx content table
$contentTable = $modx->getFullTableName('site_content');
define('ONE_DAY',86400); //seconds in a day (for unpub dates)
// copy input variables to array so they can be updated
$fields = $_REQUEST;
// If docID is set, you are editing existing item
$docId = isset($fields['docId']) ? $fields['docId'] : '';
// operation required - create, delete, edit etc.
$cmd = $fields['command'];
// test if input has come back from form (check for hidden field)
$isPostBack = (isset($fields['pkForm'])) ? true:false;
// 2-stage deletion - first prompt, delete if confirmed
// maybe this needs some security checks???
$isDeletion = isset($fields['confirmDeletion']) ? true:false;
// retrieve or set up tags array for template variable
// class definition in optionsbuilder.class.php
$options = new OptionButtons($tagTv,'tags');
if (empty($fields['tags'])) {
$tags = array();
$tags[] = $options->definition['value'];
} else {
if (is_array($fields['tags'])) {
$tags = $fields['tags'];
} else {
$tags = explode($delimiter,$fields['tags']);
}
}
if (!isset($fields['displayDate'])) {
$fields['displayDate'] = strftime('%d %b %y');
}
// populate template variables as array
// name the fields that may need to be extracted from $doc object
$tvs = array('pkDate'=>"",'pkDateTo'=>"");
$tvs[$tagTv] = $tags;
$tvs['pkPreviewFlag'] = (isset($fields['preview'])) ? 1:0;
// blank out error messages
$message = NULL;
// get form template. No default - always use a chunk or file
// $formtpl will be final output of the snippet
if (isset($formtpl)) {
if (substr($formtpl,0,5) != '@FILE') {
$formtpl = $modx->getChunk($formtpl);
} else {
$formFile = $chunk_place . 'chunk.' . trim(substr($formtpl,6)) . '.html';
$formtpl = file_get_contents($formFile);
}
} else {
$formtpl = 'You must define the form template in a chunk or a file';
}
// if form input, check mandatory fields, build error message
// this is probably where language variations could come in???
if ($isPostBack) {
// retrieve showInMenu setting
$showinmenu = (isset($fields['show'])) ? 1 : 0;
if(empty($fields['pagetitle'])) {
$message .= "You must enter a title; <br />\n";
}
if(empty($fields['longtitle'])) {
$message .= "You must enter a full headline; <br />\n";
}
if(empty($fields[$rtcontent])) {
$message .= "Content is missing; <br />\n";
}
// Require at least one tag
if (empty($tags[0])) {
$message .= "Please choose at least one tag <br />\n";
}
// check dates readable by strtotime() (PHP 5.1+ only)
// "false" parameter disallows blank
// see pubKit.functions.php
$message .= DateValid($fields['displayDate'], 'Date', false);
$message .= DateValid($fields['displayFrom'],'Display from date');
$message .= DateValid($fields['displayTo'],'Display to date');
// If error messages exist, skip create/update and redisplay form (populated)
// newsBody is default content of the rich-text TV
if (!empty($message)) {
$modx->setPlaceholder('newsBody', $fields[$rtcontent]);
$message = '<div id="inputErrors">' . $message . '</div>';
$modx->setPlaceholder('errors', $message);
} else {
// sanitize content. $allowedTags set in snippet (not a parameter)
$content = $modx->stripTags($fields[$rtcontent], $allowedTags);
$title = $modx->stripTags($fields['pagetitle']);
$longtitle = $modx->stripTags($fields['longtitle']);
$introtext = $modx->stripTags($fields[$rtsummary], $allowedTags);
// substitute =intro+ in content with text from introtext field
if (!isset($fields['preview'])) {
$content = str_replace('+intro+', $introtext, $content);
}
// calculate next menu index; NB double quotes for string make sense here!
$mnuidx = $modx->db->getValue("
SELECT MAX(menuindex) + 1 as 'mnuidx'
FROM $contentTable
WHERE parent = '$folder' ");
if($mnuidx<1) {
$mnuidx = 0;
}
// menu-hiding set by parameter or form field
$hidemenu = ($showinmenu == 1) ? 0 : 1;
// validate and format dates, set published or unpublished (using function)
// NB unpub_date = displayTo + 1 day
$startDate = strtotime($fields['displayDate']);
$pubDate = (!empty($fields['displayFrom'])) ? strtotime($fields['displayFrom']) : 0;
$endDate = (!empty($fields['displayTo'])) ? strtotime($fields['displayTo']) : 0;
$publishable = pubUnpub($startDate,$pubDate,$endDate);
$published = $publishable['published'];
$unpubDate = $publishable['unpub'];
$tvs['pkDate'] = strftime('%Y-%m-%d',$startDate);
$tvs['pkDateTo'] = ($endDate > 0) ? strftime('%Y-%m-%d',$endDate) : '';
// make previews unpublished
if (isset($fields['preview'])) {
$published = 0;
}
// set user for author fields
$user = $modx->getLoginUserName();
$userid = $modx->getLoginUserID();
if(!$user && $allowAnyPost) {
$user = 'anon';
}
// *********** CREATE || UPDATE DOCUMENT **************
// Use DocManager to create/update document, including TV values
// TO DO: Introtext & Content entities if TEXTAREA, not if rich text input
$doc = new Document($docId);
$doc->Set('pagetitle', $modx->db->escape(htmlspecialchars($title)));
$doc->Set('longtitle', $modx->db->escape(htmlspecialchars($longtitle)));
$doc->Set('introtext', $modx->db->escape(htmlspecialchars($introtext)));
$doc->Set('content', $modx->db->escape($content));
$doc->Set('menuindex', $mnuidx);
$doc->Set('hidemenu', $hidemenu);
$doc->Set('editedon', time());
// next line inherited from NewsPublisher - adjusts user ID database index for web/manager user
$doc->Set('editedby', ($userid > 0 ? $userid * -1 : 0));
$doc->SetTemplate($template);
$doc->Set('pub_date', $pubDate);
$doc->Set('published', $published);
$doc->Set('unpub_date', $unpubDate);
// rewrite TV values; DocManager needs "tv" prefix to identify them
foreach ($tvs as $tv=>$value) {
$value = (is_array($value)) ? implode('||', $value) : $value;
$doc->Set('tv' . $tv, $modx->db->escape(htmlspecialchars($value)));
}
// Prserve previous values for these fields if updating document
if (empty($docId)) {
$doc->Set('parent', $folder);
$doc->Set('createdon', time());
$doc->Set('createdby', ($userid>0 ? $userid * -1 : 0));
$doc->Set('deleted', '0');
// resource's cacheability set in &cacheItem parameter, default = 1.
$doc->Set('cacheable', $cacheable);
if ($permalinks == 1) {
$doc->Save();
// now doc has its own ID, create alias using it for unique permalink
$safalias = preg_replace('#[^a-zA-Z0-9\s\-]#',"",$title);
$safalias = trim(strtolower($safalias));
$safalias = preg_replace('#\s+#','-',$safalias);
$safalias = '-' . substr($safalias,0,$permaLength);
} else {
$safalias = "";
}
$safalias = $doc->Get('id') . $safalias;
$doc->Set('alias', $safalias);
}
$doc->Save();
// tidy menuindex after deletions or manual ordering (rank)
// (see pubKit.functions.php)
resetRank($table, $folder, 1);
$redirect = TRUE;
}
}
/******************** Form display operations *******************
* New item, re-edit, request/do deletion,
* or redisplay with error messages and entered data
****************************************************************/
if (!empty($docId) && empty($redirect)) {
$doc = new Document($docId);
// complete deletion (after confiration)
if ($isDeletion) {
if($fields['delete'] == 'Yes') {
$doc->Delete();
}
$postid = $fields['returnId'];
$redirect = TRUE;;
}
// request deletion. (returnId from management or preview screen)
elseif ($cmd == 'delete') {
$formtpl = $modx->getChunk('confirmDeletion');
$modx->setPlaceholder('docId', $doc->Get('id'));
$modx->setPlaceholder('returnId', $fields['returnId']);
$modx->setPlaceholder('title', $doc->Get('pagetitle'));
$modx->setPlaceholder('headline', $doc->Get('longtitle'));
}
// update item
elseif ($cmd == 'edit') {
$modx->setPlaceholder('docId', $doc->Get('id'));
$modx->setPlaceholder('pagetitle', $doc->Get('pagetitle'));
$modx->setPlaceholder('longtitle', $doc->Get('longtitle'));
$modx->setPlaceholder('introtext', $doc->Get('introtext'));
$modx->setPlaceholder('newsBody', $doc->Get('content'));
$modx->setPlaceholder('menuindex', $doc->Get('menuindex'));
$hidemenu = $doc->Get('hidemenu');
$showinmenu = 1 - $hidemenu;
// retrieve TV values. $fields array will be made into placeholders further on.
foreach($tvs as $tvName=>$tvValue) {
$tv = $doc->Get('tv' . $tvName);
$fields[$tvName] = $tv;
}
// TVs retrieved in raw format, no widget processing
$tags = explode('||',$fields[$tagTv]);
$fields['displayDate'] = strftime('%d %b %y', strtotime($fields['pkDate']));
$fields['displayTo'] = ($fields['pkDateTo'] > 0) ? strftime('%d %b %y', strtotime($fields['pkDateTo'])) : "";
$fields['displayFrom'] = ($doc->Get('pub_date') > 0) ? strftime('%d %b %y', $doc->Get('pub_date')) : "";
// set up status placeholders
if ($doc->Get('published') == 0) {
$modx->setPlaceholder('itemStatus', '<b style="color:#800;">Unpublished</b>');
} else {
$modx->setPlaceholder('itemStatus', '<b>Published</b>');
}
if ($doc->Get('tvpkPreviewFlag') == 1) {
$modx->setPlaceholder('previewStatus', '<b style="color:#800;">Draft</b>');
} else {
$modx->setPlaceholder('previewStatus', '');
}
// hidden form field for redirect after submission
$modx->setPlaceholder('postid', $postid);
}
// publish (from button in Preview screen)
// create new doc object - don't want to rewrite every field
// replace +intro+ in content with introtext
elseif ($cmd == 'publish') {
$doc = new Document($docId, 'published,pub_date,introtext,content');
// may not be due for publication yet
$publishable = pubUnpub(
$doc->Get('tvpkDate'),
$doc->Get('pub_date'),
$doc->Get('tvpkDateTo'));
$introtext = $doc->Get('introtext');
$content = $doc->Get('content');
$content = str_replace('+intro+', $introtext, $content);
$doc->Set('introtext', $modx->db->escape($introtext));
$doc->Set('content', $modx->db->escape($content));
$doc->Set('published', $publishable['published']);
// see pubKit.functions.php
setTemplateVar(0, $docId, 'pkPreviewFlag');
$doc->Save();
$redirect = TRUE;
}
} else {
$modx->setPlaceholder('itemStatus','New Item');
}
// redirect after item creation/update/publication
if ($redirect) {
// clear site cache (see pubKit.functions.php)
if($clearcache==1){
emptyCache();
}
// redirect to post id (with anchor #+$prefix+docId if reediting)
// postId may be array for radio button tags corresponding to different pages
if (is_array($postid)) {
$landing = $modx->makeUrl($postid[$fields['tags'] ]);
} elseif (isset($postid)) {
$landing = $modx->makeUrl($postid);
} else {
$landing = $modx->makeUrl($doc->Get('id'));
}
if (isset($fields['preview'])) {
$landing .= '?template=preview&id=' . $doc->Get('id');
} else {
$landing .= (!empty($docId)) ? '#' . $prefix . $docId: '';
}
$modx->sendRedirect($landing);
}
/***************** Prepare form for display *****************/
// Create radio-button or checkbox code (optionsbuilder.class.php)
$modx->setPlaceholder('tagSet', $options->BuildSet($tags, $tagFormat));
// Initialize show in menu checkbox
if ($showinmenu == 1) {
$modx->setPlaceholder('showInMenu', ' checked="checked"');
}
// check user rights
if(!$allowAnyPost && !$modx->isMemberOfWebGroup($postgrp)) {
$formtpl = 'You do not have permission to post items here - please contact Administrator';
} else {
// populate form fields placeholders with any existing data
// convert quotes etc. so text fields are not mangled
// NB applied to all fields (only relevant to text and textarea)
// assuming XHTML, single quotes are left alone
foreach($fields as $n=>$v) {
$v = htmlspecialchars($v);
$modx->setPlaceholder($n, $v);
}
}
// return form to snippet call, preceded by debug info
$pubKit = $dbg . $formtpl;
?>
optionsbuilder.class.php
<?php
class OptionButtons
{
var $options;
var $setName;
var $definition;
function __construct($tv, $setName) {
global $modx;
$this->definition = $modx->getTemplateVar($tv,'type,elements,default_text');
$this->type = $this->definition['type'];
$this->setName = $setName;
$this->options = array();
$unpack = explode("||",$this->definition['elements']);
for ($j=0;$j<count($unpack);$j++) {
$elements = explode("==",$unpack[$j]);
$this->options[$elements[0] ]= (isset($elements[1])) ? $elements[1] : $elements[0];
}
}
function buildSet($selected=NULL, $className="") {
$output = "\n";
if ($this->type == 'option') {
$selected = $selected[0];
foreach ($this->options as $optName =>$option) {
$output .= (empty($className)) ? "" : '<span class="' . $className . '"> ';
$output .= '<label> <input ';
$output .= 'type="radio" name="' . $this->setName . '" ';
$output .= 'value="'.$option.'"';
if (!empty($selected) && $selected == $option) {
$output .= ' checked="checked"';
}
$output .= ' />' . $optName . "</label>\n";
$output .= (empty($className)) ? "" : "</span>\n";
}
}
elseif ($this->type == 'checkbox') {
foreach ($this->options as $optName =>$option) {
$output .= (empty($className)) ? "" : '<span class="' . $className.'"> ';
$output .= '<label> <input ';
$output .= 'type="checkbox" name="' . $this->setName . '[]" ';
$output .= 'value="' . $option.'"';
if (!empty($selected) && in_array($option,$selected)) {
$output .= ' checked="checked"';
}
$output .= ' />'.$optName."</label>\n";
$output .= (empty($className)) ? "" : "</span>\n";
}
}
return $output;
}
}
?>
class OptionButtons
{
var $options;
var $setName;
var $definition;
function __construct($tv, $setName) {
global $modx;
$this->definition = $modx->getTemplateVar($tv,'type,elements,default_text');
$this->type = $this->definition['type'];
$this->setName = $setName;
$this->options = array();
$unpack = explode("||",$this->definition['elements']);
for ($j=0;$j<count($unpack);$j++) {
$elements = explode("==",$unpack[$j]);
$this->options[$elements[0] ]= (isset($elements[1])) ? $elements[1] : $elements[0];
}
}
function buildSet($selected=NULL, $className="") {
$output = "\n";
if ($this->type == 'option') {
$selected = $selected[0];
foreach ($this->options as $optName =>$option) {
$output .= (empty($className)) ? "" : '<span class="' . $className . '"> ';
$output .= '<label> <input ';
$output .= 'type="radio" name="' . $this->setName . '" ';
$output .= 'value="'.$option.'"';
if (!empty($selected) && $selected == $option) {
$output .= ' checked="checked"';
}
$output .= ' />' . $optName . "</label>\n";
$output .= (empty($className)) ? "" : "</span>\n";
}
}
elseif ($this->type == 'checkbox') {
foreach ($this->options as $optName =>$option) {
$output .= (empty($className)) ? "" : '<span class="' . $className.'"> ';
$output .= '<label> <input ';
$output .= 'type="checkbox" name="' . $this->setName . '[]" ';
$output .= 'value="' . $option.'"';
if (!empty($selected) && in_array($option,$selected)) {
$output .= ' checked="checked"';
}
$output .= ' />'.$optName."</label>\n";
$output .= (empty($className)) ? "" : "</span>\n";
}
}
return $output;
}
}
?>
pubKit.functions.php
<?php
function emptyCache() {
global $modx;
include_once $modx->config['base_path']."manager/processors/cache_sync.class.processor.php";
$sync = new synccache();
$sync->setCachepath("assets/cache/");
$sync->setReport(false);
$sync->emptyCache();
}
function DateValid ($subject,$msgId,$blankAllowed=true) {
$msg = "";
if (empty($subject)) {
if ($blankAllowed) {
return;
} else {
$msg .= 'Date may not be blank.';
}
}
elseif (! $unixTime = strtotime($subject)) {
$msg.= ' Date is not valid; use format "6 Apr 09"';
}
if (!empty($msg)) {
return $msgId.': '.$msg." \n";
}
}
function timeValid(&$t) {
//Test for blank or HHMM, HH:MM, HH.MM, return HHMM
$t=trim($t);
if ($t=="") {
$output = TRUE;
}
elseif (substr($t,0,1) == 2 && substr($t,1,1) > 3) {
$output = FALSE;
}
elseif (strlen($t) > 5) {
$output = FALSE;
}
elseif (preg_match('|^[012][0-9][0-5][0-9]$|',$t)) {
$output = TRUE;
}
elseif (preg_match('|^[012][0-9][\.:][0-5][0-9]$|',$t)) {
$t=substr($t,0,2).substr($t,3,2);
$output = TRUE;
}
else {
$output = FALSE;
}
return $output;
}
function pubUnpub($itemDate, $pubDate=0, $endDate=0, $oneDayEvent=false) {
// calculate Published flag for current time vs publication date range
// Auto unpub date of day after event start if $oneDayEvent is true (for events calendar)
if ($pubDate == "") {
$pubDate = "0";
$published = 1;
} else {
$published = ($pubDate <= time()) ? 1 : 0;
}
if ($endDate > 0) {
$endDate += ONE_DAY;
}
elseif ($oneDayEvent) {
$endDate = $itemDate + ONE_DAY;
}
if ($endDate > 0 && $endDate < time()) {
$published = 0;
}
return array('published'=>$published, 'unpub'=>$endDate, 'oneD'=>$oneDayEvent);
}
function setRank($table, $index, $docId, $parent, $inc=1, $offset) {
global $modx;
resetRank($table, $parent,$inc);
$ins = 2*$index + $offset;
return $ins;
}
function resetRank($table, $parent, $inc) {
// rewrite RANK field in unbroken sequence
global $modx;
$rank = 0;
$res = $modx->db->select('*', $modx->getFullTableName('site_content'), 'parent=' . $parent, 'menuindex');
while($row = $modx->db->getRow($res)) {
$rank += $inc;
$modx->db->update('menuindex = ' . $rank, $table, 'id=' . $row['id']);
}
}
// user function lifted from CSS Star Rating snippet
// http://modxcms.com/extras/package/?package=81
if (!function_exists('setTemplateVar')) {
function setTemplateVar($value, $docID, $tplVarName) {
global $modx;
// get tmplvar id
$tplName = $modx->getFullTableName('site_tmplvars');
$tplRS = $modx->db->select('id', $tplName, 'name="' . $tplVarName . '"');
$tplRow = $modx->db->getRow($tplRS);
$tblName = $modx->getFullTableName('site_tmplvar_contentvalues');
$selectQuery = $modx->db->select('*', $tblName, 'contentid=' . $docID . ' AND tmplvarid=' . $tplRow['id']);
$updFields = array (
'value' => $value
);
$insFields = array (
'tmplvarid' => $tplRow['id'],
'contentid' => $docID,
'value' => $value
);
if ($modx->db->getRecordCount($selectQuery) < 1) {
$modx->db->insert($insFields, $tblName);
} else {
$modx->db->update($updFields, $tblName, 'contentid=' . $docID . ' AND tmplvarid=' . $tplRow['id']);
}
}
}
?>
function emptyCache() {
global $modx;
include_once $modx->config['base_path']."manager/processors/cache_sync.class.processor.php";
$sync = new synccache();
$sync->setCachepath("assets/cache/");
$sync->setReport(false);
$sync->emptyCache();
}
function DateValid ($subject,$msgId,$blankAllowed=true) {
$msg = "";
if (empty($subject)) {
if ($blankAllowed) {
return;
} else {
$msg .= 'Date may not be blank.';
}
}
elseif (! $unixTime = strtotime($subject)) {
$msg.= ' Date is not valid; use format "6 Apr 09"';
}
if (!empty($msg)) {
return $msgId.': '.$msg." \n";
}
}
function timeValid(&$t) {
//Test for blank or HHMM, HH:MM, HH.MM, return HHMM
$t=trim($t);
if ($t=="") {
$output = TRUE;
}
elseif (substr($t,0,1) == 2 && substr($t,1,1) > 3) {
$output = FALSE;
}
elseif (strlen($t) > 5) {
$output = FALSE;
}
elseif (preg_match('|^[012][0-9][0-5][0-9]$|',$t)) {
$output = TRUE;
}
elseif (preg_match('|^[012][0-9][\.:][0-5][0-9]$|',$t)) {
$t=substr($t,0,2).substr($t,3,2);
$output = TRUE;
}
else {
$output = FALSE;
}
return $output;
}
function pubUnpub($itemDate, $pubDate=0, $endDate=0, $oneDayEvent=false) {
// calculate Published flag for current time vs publication date range
// Auto unpub date of day after event start if $oneDayEvent is true (for events calendar)
if ($pubDate == "") {
$pubDate = "0";
$published = 1;
} else {
$published = ($pubDate <= time()) ? 1 : 0;
}
if ($endDate > 0) {
$endDate += ONE_DAY;
}
elseif ($oneDayEvent) {
$endDate = $itemDate + ONE_DAY;
}
if ($endDate > 0 && $endDate < time()) {
$published = 0;
}
return array('published'=>$published, 'unpub'=>$endDate, 'oneD'=>$oneDayEvent);
}
function setRank($table, $index, $docId, $parent, $inc=1, $offset) {
global $modx;
resetRank($table, $parent,$inc);
$ins = 2*$index + $offset;
return $ins;
}
function resetRank($table, $parent, $inc) {
// rewrite RANK field in unbroken sequence
global $modx;
$rank = 0;
$res = $modx->db->select('*', $modx->getFullTableName('site_content'), 'parent=' . $parent, 'menuindex');
while($row = $modx->db->getRow($res)) {
$rank += $inc;
$modx->db->update('menuindex = ' . $rank, $table, 'id=' . $row['id']);
}
}
// user function lifted from CSS Star Rating snippet
// http://modxcms.com/extras/package/?package=81
if (!function_exists('setTemplateVar')) {
function setTemplateVar($value, $docID, $tplVarName) {
global $modx;
// get tmplvar id
$tplName = $modx->getFullTableName('site_tmplvars');
$tplRS = $modx->db->select('id', $tplName, 'name="' . $tplVarName . '"');
$tplRow = $modx->db->getRow($tplRS);
$tblName = $modx->getFullTableName('site_tmplvar_contentvalues');
$selectQuery = $modx->db->select('*', $tblName, 'contentid=' . $docID . ' AND tmplvarid=' . $tplRow['id']);
$updFields = array (
'value' => $value
);
$insFields = array (
'tmplvarid' => $tplRow['id'],
'contentid' => $docID,
'value' => $value
);
if ($modx->db->getRecordCount($selectQuery) < 1) {
$modx->db->insert($insFields, $tblName);
} else {
$modx->db->update($updFields, $tblName, 'contentid=' . $docID . ' AND tmplvarid=' . $tplRow['id']);
}
}
}
?>