Personal tools
Share your tags here
From CMSMS
Table of Contents
- Main page
- For All Users
- For Designers
- For Developers
- For Editors of this wiki
This page in: English - Deutsch - Español - Français - Italiano - Lietuvių - Nederlands - Norsk - Polski - Русский - Svenska - Tiếng việt - عربي - 日本語 简体中文
Share your User Defined tags here
Important Information - READ IT FIRST!
UDT names cannot have a dash (-) in the name!
Wrong: {my-tag}
Correct: {my_tag}
Source: http://smarty.php.net/manual/en/plugins.naming.conventions.php
PHP Style Sheet Switcher
page_class
You can use this little tag to get yourself a class name for the current page. This is very useful when you want to apply particular CSS style only to a certain page, or a subset of pages.
global $gCms;
$classes = array();
$manager =& $gCms->GetHierarchyManager();
$thisPage = $gCms->variables['content_id'];
$currentNode = &$manager->sureGetNodeById($thisPage);
while( isset($currentNode) && $currentNode->getLevel() >= 0 )
{
$currentContent =& $currentNode->getContent();
array_unshift($classes, $currentContent->Alias());
$currentNode =& $currentNode->getParentNode();
}
echo implode($classes, ' ') . ' ' . implode($classes, '-') . ' ' . 'page-' . $thisPage;
Usage:
Let's say you are on the page with the following URL: /en/some/page
In your template:
<body class="{page_class}">
Result:
<body class="en some page en-some-page page-23">
In your CSS:
// to affect "en" page and all it's children
body.en {
// style declarations
}
// to affect only that specific page
// this is not 100% proof, and might break in cases where you have similar URLs:
// /en/some/page/ and /en/some-page/ will result in the same class name
// for these cases you can use the ID of the page
body.en-some-page {
// style declarations
}
// uses ID of the page
body.page-23 {
// style declarations
}
get_template_vars
When working with smarty templates in your modules , it's useful to know what variables are available and their values. Fortunately, this is now possible.
// get a list of all of the smarty assigned variables // user defined tag named "get_template_vars" global $gCms; $tpl_vars = $gCms->smarty->get_template_vars(); print_r( $tpl_vars );
author calguy1000
A Redirect UDT
Below you will find the code for a UDT to do redirecting. Create a new UDT under Extensions >> Tags, and call it 'redirect'. Then paste this code in there.
if( isset( $params['to'] ) )
{
global $gCms;
$manager =& $gCms->GetHierarchyManager();
$node =& $manager->sureGetNodeByAlias($params['to']);
$content =& $node->GetContent();
if (isset($content) && is_object($content))
{
if ($content->GetURL() != '')
{
redirect($content->GetURL());
}
}
else return '<!-- redirect udt - page not found: '.$params['to'].' -->';
}
How do I use it: add {redirect to='page_alias'} into one of your pages, or somewhere intelligently placed in your template (you should have an if statement around this, or you'll get some nasty redirection loops).
author calguy1000
else_if
what it does is take the "name" of a page and determines what HTML gets writen in order to control images, nav on states, etc. once you have the name of the page, the if, elseif and else statement can control enything in the template.
global $gCms; $thispage = ; $thispage = $gCms->variables['page_name']; if ($thispage == "pagename") echo "this is for pagename"; elseif ($thispage == "othername") echo "this is for othername"; elseif ($thispage == "npage") echo "you can have as many elseif clauses you want"; else echo "default text";
author dan?
recently_updated
Outputs a list of the 10 most recently updated pages.
$output = '<div class="nav"><div class="heading">Most Recently Updated</div>';
$output .= '<ul class="links">';
global $gCms;
$hm =& $gCms->GetHierarchyManager();
$db = &$gCms->db;
// Get list of 10 most recently updated pages excluding the home page
$q = "SELECT * FROM ".cms_db_prefix()."content WHERE (type='content' OR type='link')
AND default_content != 1 AND active = 1 AND show_in_menu = 1
ORDER BY modified_date DESC LIMIT 10";
$dbresult = $db->Execute( $q );
if( !$dbresult )
{
echo 'DB error: '. $db->ErrorMsg()."<br/>";
}
while ($dbresult && $updated_page = $dbresult->FetchRow())
{
$curnode =& $hm->getNodeById($updated_page['content_id']);
$curcontent =& $curnode->GetContent();
$output .= '<li class="updated">';
$output .= '<a href="'.$curcontent->GetURL().'">'.$updated_page['content_name'].'</a>';
$output .= '<br />';
$output .= $updated_page['titleattribute'];
$output .= '<br />';
$output .= 'Modified: ' .$updated_page['modified_date'];
$output .= '</li>';
}
$output .= '</ul></div>';
echo $output;
author Elijah Lofgren
table_of_contents
Genrates a table of contents for your pages based on the heading tags. It requires, depending on how you want to use it, some IDs or some anchors like:
<a name="packages">Packages</a> or <h2 id="packages">Packages</h2>
Put this in a user-defined tag named table_of_contents:
/**
* Generates a table of contents based on parameters you want
* @example: <h2 id="packages">Packages</h2> use: tag="h2" type="id"
* @example: <a name="packages">Packages</a> use: tag="a" type="name"
*/
function get_table_of_contents($page_contents, $tag, $type)
{
// Generate table of contents
preg_match_all("/<$tag $type=\"([a-z-0-9]+)\">(.*)<\/$tag>/i", $page_contents, $match);
if (false == empty($match[0])) {
$contents = "<h2>Contents</h2>\n";
$contents .= "<ul>\n";
foreach ($match[1] as $key => $value) {
if ($type == $match[1][$key]) {
$contents .= '';
} else {
$contents .= ' ';
}
$contents .= '<li><a href="'.$_SERVER['REQUEST_URI'].'#'.$match[1][$key].'">'.$match[2][$key].'</a>';
// Start a new sub-list if this item has children otherwise just end the list item
if (false == empty($match[1][$key + 1]) && $match[1][$key + 1] == $match[1][$key] + 1) {
$contents .= "\n <ul>\n";
$unclosed_list = TRUE;
} else {
$contents .= "</li>\n";
}
// If the next item is higher level then close this list item (I.E. current item is h3 and next is h2
if (false == empty($match[1][$key + 1]) && $match[1][$key + 1] == $match[1][$key] - 1) {
$contents .= " </ul>\n</li>\n";
$unclosed_list = FALSE;
}
}
if (false == empty($unclosed_list)) {
$contents .= " </ul>\n</li>\n";
}
$contents .= "</ul>\n";
} else {
$contents = '';
}
return $contents;
}
echo get_table_of_contents($params['thepagecontent'], $params['tag'], $params['type']);
Then in your template put this:
{content assign=pagecontent}
{table_of_contents thepagecontent="$pagecontent" tag="a" type="name"}
author Elijah Lofgren, modified by Simon Schaufelberger
Original:
/**
* Generates a table of contents based on heading tags that have ids
* @example: <h2 id="packages">Packages</h2>
*/
function get_table_of_contents($page_contents)
{
// Generate table of contents
preg_match_all("/<h([[:digit:]])[[:space:]]id=\"([a-z-0-9]+)\">(.*)<\/h[0-9]>/i", $page_contents, $match);
if (FALSE == empty($match[0])) {
$contents = "<h2>Contents</h2>\n";
$contents .= "<ul>\n";
foreach ($match[0] as $key => $value) {
if (2 == $match[1][$key]) {
$contents .= '';
} else {
$contents .= ' ';
}
$contents .= '<li><a href="'.$_SERVER['REQUEST_URI'].'#'.$match[2][$key].'">'.$match[3][$key].'</a>';
// Start a new sub-list if this item has children otherwise just end the list item
if (FALSE == empty($match[1][$key + 1]) && $match[1][$key + 1] == $match[1][$key] + 1) {
$contents .= "\n <ul>\n";
$unclosed_list = TRUE;
} else {
$contents .= "</li>\n";
}
// If the next item is higher level then close this list item (I.E. current item is h3 and next is h2
if (FALSE == empty($match[1][$key + 1]) && $match[1][$key + 1] == $match[1][$key] - 1) {
$contents .= " </ul>\n</li>\n";
$unclosed_list = FALSE;
}
}
if (FALSE == empty($unclosed_list)) {
$contents .= " </ul>\n</li>\n";
}
$contents .= "</ul>\n";
} else {
$contents = '';
}
return $contents;
}
echo get_table_of_contents($params['thepagecontent']);
embed existing smarty app
I need to show existing data from an app that was written with smarty and had existing templates this seems to work for me at least
made a function in plugins
<?php
function smarty_cms_function_myapp($params, &$smarty){
$smarty->assign('comments','big comment');
//both these methods work
$smarty->display('myapp.tpl');
or
return $smarty->fetch('myapp.tpl');
// just chose one method I think
//fetch would be best
}
?>
the tpl file had existing smarty stuff and was placed in tmp/templates eg myapp.tpl
{$smarty.now|date_format}smarty now
<br />
it works
<br />
{$comments}
and in your page {myapp} I also found like {$comments} also works
author cdstg
change copyright date based on server
make a user defined tag eg custom_copyright
//set start to date your site was published
$startCopyRight='2005';
if(date('Y')== $startCopyRight){
echo $startCopyRight;
}else{
echo $startCopyRight.' - '. date('Y');
}
in the Global Content Blocks place {custom_copyright} in the footer now next year it will say 2005 - 2007
author cdstg
listpictures
global $gCms;
$dir = $gCms->config['root_path'] . DIRECTORY_SEPARATOR .'uploads/images/africa/';
$url = './uploads/images/africa/';
echo '<ul>';
// Open a known directory, and proceed to read its contents
if (is_dir($dir)) {
if ($dh = opendir($dir)) {
while (($file = readdir($dh)) !== false) {
if ('file' == filetype($dir . $file)) {
echo "<li><a href=".$url.$file.'" rel="lightbox"><img src="'.$url.'thumb_'.$file.'" /></a>'."</li>\n";
}
}
closedir($dh);
}
}
echo '</ul>';
Author: Elijah Lofgren
count_news_items
Create a new User Defined Tag named 'count_news_items' with the following content:
global $gCms;
$items = $gCms->smarty->get_template_vars('items');
$gCms->smarty->assign('itemcount', count($items));
Then put something like this in your news summary template:
<!-- Start News Display Template -->
{count_news_items}
{if $itemcount != 0}
{foreach from=$items item=entry}
...
{/foreach}
{else}
No items
{/if}
<!-- End News Display Template -->
Author: Elijah Lofgren
Simple, accessible Wikipedia-style external links
This article on Max Design was the inspiration for this tag, which appends the text " (external link)" to the link text of your link. When viewed in a CSS-enabled browser this phrase is hidden from view and replaced with a graphical icon indicating an external link.
Note: Internet Explorer does not display the icon correctly when link text spans multiple lines so non-breaking spaces are inserted between words to overcome this problem.
Using CSS this icon will change color to reflect the following link states:
- :link
- :visited
- :hover
Create a new user-defined tag named 'extlink' with the following content:
$linktext = $params['linktext'];
$words = explode(" ", $linktext);
if ($words != $linktext) {
$linktext = $words[0];
foreach ($words as $key => $value) {
if ($key >0) {
$linktext .= ' '.$value;
}
}
}
echo '<a class="external" href="'.$params['href'].'"';
if(!empty($params['title']))
echo ' title="'.$params['title'].'"';
echo '>'.$linktext.'<span> (external link)</span></a>';
This tag accepts three parameters:
- href—contains the href for the external link (required).
- linktext—contains the linktext to be inserted into the link (required).
- title—contains the title attribute text to be inserted into the link (;optional).
Example:
{extlink href="http://external.site.com" title="A site about widgets" linktext="Cool Widgets"}
will generate the following HTML:
<a class="external" href="http://external.site.com" title="A site about widgets">Cool Widgets<span> (external link)</span></a>
Right click on the image above and save it to your computer as "External.gif", then upload it to the location on your web site where you store your images.
The following stylesheet rules will need to be added to your CSS to implement this functionality
a.external span {
position: absolute;
left: -5000px;
width: 4000px;
}
a.external {
padding: 0 12px 0 0
}
a.external:link {
background: url(/images/External.gif) no-repeat 100% 0;
}
a.external:visited {
color: #609;
background: url(/images/External.gif) no-repeat 100% -100px;
}
a.external:hover {
color: #f00;
background: url(/images/External.gif) no-repeat 100% -200px;
}
If your web site image folder is not "/images/" you will need to modify the rules above to point to the correct location for the image file "External.gif".
Author: Tygger2512
acronym_replacer
Automatically replaces acronyms in your content with an <acronym title="description">TLA</acronym> tag, unless you surround the acronym with $ signs--e.g. DVD will be replaced with <acronym title="Digital Versatile Disc">DVD</acronym> but $DVD$ will be replaced with DVD.
This is a modified version of the Acronym Replacer 2.0 WordPress Plugin.
Put this in a user-defined tag named acronym_replacer:
/*
Acronym Replacer is modified from the Acronym Replacer 2.0
WordPress Plugin at: http://www.huddledmasses.org/wp-content/plugins/source.php?file=acronyms.php
----------------------------------------------------------
replace the following line in your template:
{content}
with:
{content assign=pagecontent}
{acronym_replacer thepagecontent="$pagecontent"}
*/
$text = $params['thepagecontent'];
global $acronym_acronym;
// First, define all the things to replace, without using parenthesis or pipes (|).
// Each definition is in the form: // "acronym" => "definition",
// ESPECIALLY note that they all end with commas EXCEPT the last one.
if( empty($acronym_acronym) ) {
$acronym_acronym = array(
"AOL" => "America Online",
"API" => "Application Programming Interface",
"BTW" => "By The Way",
"BPL" => "Broadband over Power Lines",
"CD" => "Compact Disc",
"CGI" => "Common Gateway Interface",
"CLI" => "Common Language Interpreter",
"CMS" => "Content Management System",
"CSS" => "Cascading Style Sheet",
"CVS" => "Concurrent Versions System",
"DNS" => "Domain Name System",
"DOM" => "Document Object Model",
"DSL" => "Digital Subscriber Line (broadband over phone lines)",
"DTD" => "Document Type Definition",
"DVD" => "Digital Versatile Disc",
"EFT" => "Emotional Freedom Technique",
"FAQ" => "Frequently Asked Questions",
"FCC" => "Federal Communications Commission",
"FOAF" => "Friend Of A Friend is a RDF dialect for describing relationships",
"FSF" => "Free Software Foundation",
"FTP" => "File Transfer Protocol",
"FTTH" => "Fiber to the Home",
"GB" => "Gigabyte",
"GFDL" => "GNU Free Documentation License",
"GPG" => "Gnu PG (Open source public key encryption)",
"GPL" => "GNU General Public License",
"GTK" => "GUI ToolKit - The GIMP Tool Kit for dcreating user-interfaces",
"GUI" => "Graphical User Interface",
"HDTV" => "High Definition TeleVision",
"HTML" => "HyperText Markup Language",
"HTTP" => "HyperText Transfer Protocol",
"IE" => "Internet Explorer",
"ICANN" => "Internet Corporation for Assigned Names and Numbers",
"IHOP" => "International House of Pancakes",
"IIRC" => "if I remember correctly",
"IIS" => "Internet Infomation Server",
"IM" => "Instant Message",
"IMAP" => "Internet Message Access Protocol",
"IP" => "Internet Protocol",
"IRC" => "Internet Relay Chat - like Instant Messaging for groups",
"JSP" => "Java Server Pages",
"KB" => "Kilobyte",
"KDE" => "K Desktop Environment",
"KVM" => "Keyboard, Video, Mouse switch for controlling multiple computers",
"LDAP" => "Lightweight Directory Access Protocol",
"LGPL" => "GNU Lesser General Public License",
"MAPI" => "Mail Application Programming Interface",
"MB" => "Megabyte",
"MP3" => "MPEG Layer 3 - a common audio codec for music files",
"MS" => "Microsoft",
"MSDN" => "Microsoft Developer Network",
"MSIE" => "Microsoft Internet Explorer",
"MSN" => "Microsoft Network",
"NNTP" => "Network News Transfer Protocol - the protocol used for NewsGroups",
"NYC" => "New York City",
"OPML" => "Outline Processor Markup Language",
"P2P" => "Peer To Peer",
"PBS" => "Public Broadcasting System",
"PDF" => "Portable Document Format",
"PGP" => "Pretty Good Privacy (public key encryption)",
"PHP" => "Hypertext PreProcessing",
"PNG" => "Portable Network Graphics",
"POP" => "Short for POP3, the Post Office Protocol for email",
"POP3" => "Post Office Protocol 3 (for email)",
"RAID" => "Redundant Array of Independent Disks",
"RDF" => "Resource Description Framework",
"RPC" => "Remote Procedure Call",
"RSS" => "Really Simple Syndication",
"SIG" => "Special Interest Group",
"SOAP" => "Simple Object Access Protocol",
"SQL" => "Structured Query Language (a database standard)",
"SSH" => "Secure SHell (encrypted protocol replaces telnet and FTP)",
"SSN" => "Social Security Number",
"SSL" => "Secure Sockets Layer (a security protocol)",
"SVG" => "Scalable Vector Graphics",
"TCP" => "Transmission Control Protocol",
"UDP" => "User Datagram Protocol",
"URI" => "Uniform Resource Identifier",
"URL" => "Uniform Resource Locator",
"USB" => "Universal Serial Bus",
"VB" => "Visual Basic",
"VBS" => "Visual Basic Script",
"VM" => "Virtual Machine",
"VNC" => "Virtual Network Computing",
"W3C" => "World Wide Web Consortium",
"WCAG" => "Web Content Accessibility Guidelines",
"WYSIWYG" => "what you see is what you get",
"XHTML" => "eXtensible HyperText Markup Language - HTML reformulated as XML",
"XML" => "eXtensible Markup Language",
"XSL" => "eXtensible Stylesheet Language",
"XSLT" => "eXtensible Stylesheet Language Transformation"
);
}
foreach($acronym_acronym as $acronym => $description) {
$text = preg_replace("|(?!<[^<>]*?)(?<![?./&])\b$acronym\b(?!:)(?![^<>]*?>)|imsU","<acronym title=\"$description\">$acronym</acronym>" , $text);
// Acronyms wrapped in dollar signs will just be unwrapped:
// So: $AOL$ will become AOL, without the <acronym title="America Online">AOL</acronym>
$text = preg_replace("|[$]<acronym title=\"$description\">$acronym</acronym>[$]|imsU" , "$acronym" , $text);
}
return trim( $text );
Then in your template put this:
{content assign=pagecontent}
{acronym_replacer thepagecontent="$pagecontent"}
Author: Tygger2512
style_switcher
Note: Images used are the ones used here: http://test.thinkofdesign.com/Default.aspx?alias=test.thinkofdesign.com/beyondcss
Create new UDT named 'style_switcher' with this content:
if ('css_head' == $params['action']) {
if (FALSE != isset($_COOKIE['Style_Layout']) && 'small' != $_COOKIE['Style_Layout']) {
echo '<link rel="stylesheet" type="text/css" href="stylesheet.php?name='.$params['template'].'_layout_'.$_COOKIE['Style_Layout'].'" />';
}
if (FALSE != isset($_COOKIE['Style_Text']) && 'small' != $_COOKIE['Style_Text']) {
echo '<link rel="stylesheet" type="text/css" href="stylesheet.php?name='.$params['template'].'_text_'.$_COOKIE['Style_Text'].'" />';
}
}
if ('show_switcher' == $params['action']) {
echo <<<EOF
<script type="text/javascript">function setLayout(size){ document.cookie = 'Style_Layout=' + escape(size) + ';expires=' + new Date('December 31, 2020 23:59:59').toGMTString() + ';path=/';location.reload();}</script>
<span style="margin-right: 1em;">
EOF;
if (FALSE != isset($_COOKIE['Style_Layout']) && 'small' != $_COOKIE['Style_Layout']) {
echo '<a href="javascript:setLayout(\'small\')">';
}
echo '<img alt="Narrow width layout" src="uploads/images/style_switcher/icon-layout-small';
if (FALSE == isset($_COOKIE['Style_Layout']) || 'small' == $_COOKIE['Style_Layout']) {
echo '-on';
}
echo '.gif" style="height:17px;width:16px;" />';
if (FALSE != isset($_COOKIE['Style_Layout']) && 'small' != $_COOKIE['Style_Layout']) {
echo '</a>';
}
if ('medium' != $_COOKIE['Style_Layout']) {
echo '<a href="javascript:setLayout(\'medium\')">';
}
echo '<img alt="Medium width layout" src="uploads/images/style_switcher/icon-layout-medium';
if (FALSE != isset($_COOKIE['Style_Layout']) && 'medium' == $_COOKIE['Style_Layout']) {
echo '-on';
}
echo '.gif" style="height:17px;width:16px;" />';
if ('medium' != $_COOKIE['Style_Layout']) {
echo '</a>';
}
if ('large' != $_COOKIE['Style_Layout']) {
echo '<a href="javascript:setLayout(\'large\')">';
}
echo '<img alt="Large width layout" src="uploads/images/style_switcher/icon-layout-large';
if (FALSE != isset($_COOKIE['Style_Layout']) && 'large' == $_COOKIE['Style_Layout']) {
echo '-on';
}
echo '.gif" style="height:17px;width:16px;" />';
if ('large' != $_COOKIE['Style_Layout']) {
echo '</a>';
}
echo '</span>';
echo "<script type=\"text/javascript\">function setText(size){ document.cookie = 'Style_Text=' + escape(size) + ';expires=' + new Date('December 31, 2020 23:59:59').toGMTString() + ';path=/';location.reload();}</script>";
if (FALSE != isset($_COOKIE['Style_Text']) && 'small' != $_COOKIE['Style_Text']) {
echo '<a href="javascript:setText(\'small\')">';
}
echo '<img alt="Small text" src="uploads/images/style_switcher/icon-text-small';
if (FALSE == isset($_COOKIE['Style_Text']) || 'small' == $_COOKIE['Style_Text']) {
echo '-on';
}
echo '.gif" style="height:17px;width:17px;" />';
if (FALSE != isset($_COOKIE['Style_Text']) && 'small' != $_COOKIE['Style_Text']) {
echo '</a>';
}
if ('medium' != $_COOKIE['Style_Text']) {
echo '<a href="javascript:setText(\'medium\')">';
}
echo '<img alt="Medium text" src="uploads/images/style_switcher/icon-text-medium';
if (FALSE != isset($_COOKIE['Style_Text']) && 'medium' == $_COOKIE['Style_Text']) {
echo '-on';
}
echo '.gif" style="height:17px;width:17px;" />';
if ('medium' != $_COOKIE['Style_Text']) {
echo '</a>';
}
if ('large' != $_COOKIE['Style_Text']) {
echo '<a href="javascript:setText(\'large\')">';
}
echo '<img alt="Large text" src="uploads/images/style_switcher/icon-text-large';
if (FALSE != isset($_COOKIE['Style_Text']) && 'large' == $_COOKIE['Style_Text']) {
echo '-on';
}
echo '.gif" style="height:17px;width:17px;" />';
if ('large' != $_COOKIE['Style_Text']) {
echo '</a>';
}
}
Then in betwen your 'head' tags in your template put something like this:
{style_switcher action="css_head" template="business_design"}
Next, where you want the switcher to appear put this:
Style: {style_switcher action="show_switcher"}
Now, create stylesheets with names like these:
- business_design_layout_large
- business_design_layout_medium
- business_design_text_large
- business_design_text_medium
Author: Elijah Lofgren
favicon
This tag generates XHTML code to display a favicon in the browser. To generate a icon you can use this http://www.html-kit.com/favicon/.
Create a new User Defined Tag named 'favicon' with the following content:
if(isset($params['static'])) echo '<link rel="shortcut icon" href="'.$params['static'].'" type="image/x-icon" />'."\n"; if(isset($params['animated'])) echo '<link rel="icon" href="'.$params['animated'].'" type="image/gif" />'."\n";
Then put something like this in the header of your template:
<!--Favicon-->
{favicon static="../images/favicon.ico" animated="../images/animated_favicon.gif"}
The two attributes are optional, but if you leave them both there isn't happening nothing.
Author: Christophe Lambrechts (EhpotsirhC)
Google adsense
get your adsense code from google.
copy paste it as is into user defined tag (in extension -> user defined tags -> add user defined tag) as this code has javascript { and } we need to wrap it inside {literal} and {/literal} otherwise smarty will miss interperet those extra { } as its own. so add {literal} at the top and {/literal} at the bottom.
edit your template in which you want the ads to be shown. check where you want your ads (you might want to wrap em in<div id="ads"> </div>) and add call to your user defined tag with {name_of_your_udt}. save
refresh your page, and thats it.
Author: tsw
Get a page's root parent's alias
Gets the alias of a pages very top parent.
global $gCms;
global $smarty;
$manager =& $gCms->GetHierarchyManager();
$var = 'root_page_alias';
if( isset($params['assign']) && $params['assign'] != '' )
{
$var = $params['assign'];
}
$result = "NO RESULT";
$thisPage = $gCms->variables['content_id'];
$currentNode = &$manager->sureGetNodeById($thisPage);
while( isset($currentNode) && $currentNode->getLevel() >= 0 )
{
$currentContent =& $currentNode->getContent();
$result = $currentContent->Alias();
$currentNode =& $currentNode->getParentNode();
}
$smarty->assign($var,$result);
Create a new user-defined tag called get_root_page_alias and copy in the above code.
The tag can be called using...
{get_root_page_alias assign="varname"}
An example use would be...
{get_root_page_alias assign="root_page_alias"} The root parent of this page is:{$root_page_alias}
Author: calguy1000 (posted by binarybee on the forum).
Get a page's root parent's hierarchy-position
Gets the hierarchy-position of a pages very top parent.
global $gCms;
global $smarty;
$manager =& $gCms->GetHierarchyManager();
$var = 'root_page_id';
if( isset($params['assign']) && $params['assign'] != '' )
{
$var = $params['assign'];
}
$result = "NO RESULT";
$thisPage = $gCms->variables['content_id'];
$currentNode = &$manager->sureGetNodeById($thisPage);
while( isset($currentNode) && $currentNode->getLevel() >= 0 )
{
$currentContent =& $currentNode->getContent();
$result = $currentContent->Hierarchy();
$currentNode =& $currentNode->getParentNode();
}
$smarty->assign($var,$result);
Create a new user-defined tag called get_root_page_hierarchy and copy in the above code.
The tag can be called using...
{get_root_page_hierarchy assign="varname"}
An example use would be...
{get_root_page_hierarchy assign="root_page_hierarchy"} The root parent hierarchy of this page is: {$root_page_hierarchy}
Author: calguy1000 (modified by nils73 and posted on the forum).
File link
Description: Use this tag for linking files within your page. The link is furthermore also provided with the filesize of the file you are linking.
The tag is represented similar to
Description of the file (2.56MB)
How to use it: Add the following code as a new User Defined Tag. Name it e.g. 'filelink'.
// ----
// filelink - user defined tag for cms made simple
// Author: Kutschera Ralph
// Email: news2006@ecuapac.dyn.priv.at
// Last Update: 09/26/2006
// No warranty.
// ----
// get file
$localprefix='/var/www/pathtocms/uploads/File/'; // server sided root directory of the files you are linking
$webprefix='uploads/File/'; // the same directory but where your webserver will find it
$localpathtofile=$localprefix.$params['file'];
$webpathtofile=$webprefix.$params['file'];
// get link name
$linkname='';
if(isset($params['name'])) {
$linkname = $params['name'];
}
else {
// you can leave away the tag attribute 'name'
// if so, the name of the file is shown as the link
$linkname = basename($localpathtofile);
}
// check if file exists
if(file_exists($localpathtofile)) {
$filesize = filesize($localpathtofile);
// beautify filesize
$suffix = "B"; // for Bytes
if($filesize > 1024) {
$filesize = $filesize / 1024;
$suffix = "KB";
if($filesize > 1024) {
$filesize = $filesize / 1024;
$suffix = "MB";
if($filesize > 1024) {
$filesize = $filesize / 1024;
$suffix = "GB";
}
}
}
$filesize = sprintf("%.2f", $filesize);
// edit the following line, if you want a different representation of your link
echo '<a href="'.$webpathtofile.'"><b>'.$linkname.'</b> ('.$filesize.$suffix.')</a>';
}
else {
// this is shown if the file you try to link to cannot be find
echo $linkname.' (sorry, broken)';
}
Now if you want to provide a link to a file of your page, simply add
{filelink file='path/to/file' name='Name shown as the link or description of file'}
and you get a link as shown in the description. In the example above the file is saved at /var/www/pathtocms/uploads/File/path/to/file on your server. As you will use another server environment than I do, you'll have to edit the variables $localprefix and $webprefix in the above code. I think, the code should be self explanatory. You can omit the tag attribute 'name' if you want the name of the file as the link text. The code also checks whether the file does exist and gives a '(sorry, broken)' otherwise.
Obfuscate mailto: Email Address Links
This user-defined tag inserts a clickable "mailto:fred@example.com" link that is difficult for spambots to parse, unless they understand Javascript.
Usage:
{emailaddress mailbox="fred" domain="example.com" name="Fred Bloggs"}
Tag name: emailaddress
Tag code:
echo '
<script type="text/javascript">
<!--
document.write("<a ", "href=\"", "mail", "to", ":",
"'.$params['mailbox'].'", "@",
"'.$params['domain'].'", "\">",
"'.$params['name'].'", "</", "a>");
//-->
</script>';
Date of the latest modification on the site
This can be useful if you want to add a line like "Latest update: 01/02/2008" automatically on your website. In this example, the date is formated d/M/Y but you can change it as you like (see PHP Date format). You can see how easy it is to format a MySQL date to any format.
global $gCms;
$hm =& $gCms->GetHierarchyManager();
$db = &$gCms->db;
// Get the most recently updated page excluding the home page
$q = "SELECT modified_date FROM ".cms_db_prefix()."content WHERE (type='content' OR type='link')
AND default_content != 1 AND active = 1 AND show_in_menu = 1
ORDER BY modified_date DESC LIMIT 1";
$dbresult = $db->Execute( $q );
if( !$dbresult )
{
echo 'DB error: '. $db->ErrorMsg()."<br/>";
}
while ($dbresult && $updated_page = $dbresult->FetchRow())
{
$output = date("d/m/Y",strtotime ($updated_page['modified_date']));
}
echo $output;
This is based on the tag recently_updated Author: Jean-Sebastien Monzani / jsmonzani.com
List the children of the current page
This simple tag makes a UL list of the children of this page (no recursion, just direct children) It also shows you how you can access Menu information from a tag. It can be useful to populate an empty page which has numerous subpages.
global $gCms;
$manager =& $gCms->GetHierarchyManager();
$thisPage = $gCms->variables['page_name'];
$currentNode = &$manager->sureGetNodeByAlias($thisPage);
$nodes = $currentNode->getChildren();
if ($currentNode->hasChildren()) {
echo '<ul class="sectionlinks">';
foreach ($nodes as $node) {
$content= $node->getContent();
$url = $content->GetURL();
if ($url == "#") { /* section header has no link by default */
$url = "index.php?page=".$content->Alias();
}
echo "<li><a href=\"".$url."\">".$content->MenuText()."</a> </li>";
}
echo "</ul>";
}
Author: Jean-Sebastien Monzani / jsmonzani.com
Is this page recent? (count days)
A client asked me to put a "New" label in the menu, next to the most recent pages. My idea was to use a CSS style, that would be set to "new" or "old", depending on the page. It would produce something like
<span class="new">This page is recent</span>.
This tag addresses this problem, feel free to modify it to suit your needs. In this example, a page is new if its latest update was no more than 31 days before today.
Use it like this: {is_this_page_recent pageid="INSERT-YOUR-PAGE-ID-HERE"} Now you can use {isnew} that will get "new" or "old" depending on the result.
/* param: pageid, assigns {isnew} to new or old*/
global $gCms;
$manager =& $gCms->GetHierarchyManager();
$thisPage = intval($params['pageid']);
$currentNode = &$manager->sureGetNodeById($thisPage);
$currentContent =& $currentNode->getContent();
$nbdays = (time()-strtotime($currentContent->GetModifiedDate())) / 86400;
if ($nbdays <= 31) { /* Update in the last month? */
$gCms->smarty->assign('isnew', "new");
} else {
$gCms->smarty->assign('isnew', "old");
}
Author: Jean-Sebastien Monzani / jsmonzani.com
Geshi hilight
download geshi and unzip it in your plugins folder (refer to geshi documentation on geshis cabapilities geshi doc)
Create new file in the lib/smarty/plugins dircctory named "block.cms_geshi.php" with this content
<?php
include_once(dirname(__FILE__) . DIRECTORY_SEPARATOR. 'geshi' . DIRECTORY_SEPARATOR. 'geshi.php');
/***
* GeSHi highlighting
* -------------------------------------------------------------
* File: block.highlight.php
* Type: block
* Name: highlight
* Purpose: highlight a block of text using GeSHi
* Author: tsw
* -------------------------------------------------------------
*/
function smarty_block_cms_geshi($params, $content, &$smarty)
{
if (isset($content) && isset($params['lang'])) {
return geshi_highlight($content, $params['lang'], "", true);
}
}
?>
Now you can have hilighted code by calling this block from your page with:
{cms_geshi lang="php"}
{literal}
<?php if ($test == true) { echo 1; } ?>
{/literal}
{/cms_geshi}
note that you need {literal}{/literal} tags around your code when braces are used inside
pageAliasMatch
UDT to ensure that the current page alias matches the defined prefix rules which are similar to the Menu Manager module's prefix rules.
This is useful if you want to prevent non-registered users from seeing private pages.
///
/// UDT to ensure that the current page alias matches the defined prefix rules
/// which are similar to the Menu Manager module's prefix rules.
///
/// @param "includeprefix"
/// The current page alias must start with the given prefix, or the
/// user will be redirected.
///
/// @param "excludeprefix"
/// The current page alias must NOT start with the given prefix, or
/// the user will be redirected
///
/// @param "redirectTo"
/// The page to redirect to, can be an ID number or an alias.
///
/// @example
/// The following example uses customcontent to see if the user is
/// logged in. If s/he is, then the user must not be at a "public-"
/// page. If s/he is not logged in, then the user must be at a
/// "public-" page.
///
/// {if $customcontent_loggedin > 0}
/// {quarantine excludeprefix="public" defaultPage="private-account"}
/// {else}
/// {quarantine includeprefix="public" defaultPage="public-home"}
/// {/if}
///
///
//
// Grab CMS object
//
global $gCms;
if((empty($params["excludeprefix"]) &&
empty($params["includeprefix"])) ||
empty($params["redirectTo"]))
{
//
// No exclude or include passed
//
return;
}
//
// Convert parameters into prefixes
//
$excludePrefix = empty($params["excludeprefix"]) ? "" : $params["excludeprefix"]."-";
$includePrefix = empty($params["includeprefix"]) ? "" : $params["includeprefix"]."-";
//
// Get current page, and destination page
//
$current = $gCms->variables['page_name'];
$newAlias = $params['redirectTo'];
if(is_numeric($newAlias))
{
$manager =& $gCms->GetHierarchyManager();
$node = &$manager->sureGetNodeById($params['redirectToID']);
if($node)
{
$content =& $node->GetContent();
$newAlias = $content->Alias();
}
else
{
die("Invalid page id passed as quarantine 'redirectTo'");
}
}
//
// Check if current page is outside quarantine
//
if((substr($current, 0, max(1, strlen($excludePrefix))) == $excludePrefix) ||
(substr($current, 0, strlen($includePrefix)) != $includePrefix))
{
//
// Check for cyclical quarantine
//
if((substr($newAlias, 0, max(1, strlen($excludePrefix))) == $excludePrefix) ||
(substr($newAlias, 0, strlen($includePrefix)) != $includePrefix))
{
die("Illegal redirect: $newAlias does NOT start with [$includePrefix] or DOES start with [$excludePrefix]");
}
//
// Push to quarantine default page
//
redirect_to_alias($newAlias);
}
IP Block and XSS Attack notifier
I don't really know if this is usefull but i will post it:
I called it block_xss but you can give it any name. Works only if you are using NO ModRewrite
Exactly this UDT is 3 UDTs, you can use whatever you need/want
/*Here you can lookup where your visitor comes from. Will be sent in the email*/
$lookup = "http://www.maxmind.com/app/lookup_city?ips=";
if(substr($_GET['page'], 0, 4) == "http"){
$time = time();
$ip = $_SERVER["REMOTE_ADDR"];
// Convert IP Address into hostname
$hostname = gethostbyaddr($_SERVER['REMOTE_ADDR']);
if (false != isset($_SERVER["HTTP_REFERER"])) {
$referrer = $_SERVER["HTTP_REFERER"];
} else {
$referrer = 'none';
}
//Modify!
$header = 'From: youremail@domain.com' . "\n";
$timestamp = time()+date("Z");
$entry = "Date: ".gmdate("d.m.Y H:i:s", $timestamp)."\n".
"Host: $hostname \n".
"IP: $lookup$ip \n".
"URL: ".$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI']."\n".
"Referer: $referrer \n".
"Browser: ".$_SERVER['HTTP_USER_AGENT'];
//Modify!
mail('youremail@domain.com', 'XSS Attack on yourdomain.org', $entry, $header);
?>
<!--Here you can enter HTML if you want.-->
<?php
exit;
}
//Modify: here you list the ips to block; to test it, use 127.0.0.1
$block_ips = Array('0.0.0.0');
if (in_array($_SERVER['REMOTE_ADDR'], $block_ips)) {
$time = time();
$ip = $_SERVER["REMOTE_ADDR"];
// Convert IP Address into hostname
$hostname = gethostbyaddr($_SERVER['REMOTE_ADDR']);
if (false != isset($_SERVER["HTTP_REFERER"])) {
$referrer = $_SERVER["HTTP_REFERER"];
} else {
$referrer = 'none';
}
//Modify
$header = 'From: email@domain.com' . "\n";
$timestamp = time()+date("Z");
$entry = "Date: ".gmdate("d.m.Y H:i:s", $timestamp)."\n".
"Host: $hostname \n".
"IP: $lookup$ip \n".
"URL: ".$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI']."\n".
"Referer: $referrer \n".
"Browser: ".$_SERVER['HTTP_USER_AGENT'];
//Modify
mail('email@domain.com', 'Homepage visit from blocked IP on domain.com', $entry, $header);
?>
<!--Here you can enter HTML if you want.-->
<?php
exit;
}
$disallow = array("script");
for($i=0; $i < count($disallow); $i++){
$pos = strpos($_SERVER['REQUEST_URI'], $disallow[$i]);
if ($pos === false) {
/* That's ok.*/
} else {
$time = time();
$ip = $_SERVER["REMOTE_ADDR"];
// Convert IP Address into hostname
$hostname = gethostbyaddr($_SERVER['REMOTE_ADDR']);
if (false != isset($_SERVER["HTTP_REFERER"])) {
$referrer = $_SERVER["HTTP_REFERER"];
} else {
$referrer = 'none';
}
//Modify
$header = 'From: email@domain.com' . "\n";
$timestamp = time()+date("Z");
$entry = "Date: ".gmdate("d.m.Y H:i:s", $timestamp)."\n".
"Host: $hostname \n".
"IP: $lookup$ip \n".
"URL: ".$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI']."\n".
"Referer: $referrer \n".
"Browser: ".$_SERVER['HTTP_USER_AGENT'];
//Modify
mail('email@domain.com', 'XSS Attack on domain.org', $entry, $header);
?>
<!--Here you can enter HTML if you want.-->
<?php
exit;
}
}
Author: simonschaufi http://forum.cmsmadesimple.org/index.php?action=profile;u=6497
Send Email Notification on Page Change
This is a UDT/Event combination that sends an email when a page is changed. This example uses the CMSMailer module (recommended).
First, create the following UDT named send_email_notification (or whatever name you want). Be sure to change the email address.
global $gCms;
$content =& $params['content'];
$editedby = $gCms->variables['username'];
$bodytext = '
A page on the web site has been changed.
Page Name: '.$content->Name().'
Page Alias: '.$content->Alias().'
Page Type: '.$content->Type().'
Page Created: '.$content->GetCreationDate().'
Modified on: '.$content->GetModifiedDate().'
Modified by: '.$editedby.'
Page URL: '.$content->GetURL();
$cmsmailer =& $gCms->modules['CMSMailer']['object'];
$cmsmailer->AddAddress('your@email.com');
$cmsmailer->SetBody($bodytext);
$cmsmailer->IsHTML(false);
$cmsmailer->SetSubject('Page change notification--' .$content->Name());
$cmsmailer->Send();
Next, go to Extensions->Events, click the edit button for ContentEditPost, find your new UDT in the dropdown list, and ADD it.
That's it, good luck!
Sending a new user his information after adding him via the Admin Console
You don't need to inform new users about the username and password any more via email! You can inform them via the new UDT automatically!
I added the validate_email function for at least a little checking if the email address seams to be ok becaue the Admin Console does not yet check it. If no email is set, no email will be sent!
function validate_email($email){
$exp = "^[a-z0-9]+([._-][a-z0-9]+)*@([a-z0-9]+([._-][a-z0-9]+))+$";
if(eregi($exp,$email)){
if(checkdnsrr(array_pop(explode("@",$email)),"MX")){
return true;
}else{
return false;
}
}else{
return false;
}
}
global $gCms;
$sitename = get_site_preference('sitename', 'My Homepage'); /* If sitename is not set (usually it is), use My Homepage */
$newuser =& $params['user'];
$bodytext = 'This is your new user account information:
First Name: '.$newuser->firstname.'
Last Name: '.$newuser->lastname.'
Username: '.$newuser->username.'
Password: '.$_POST["password"].'
Email: '.$newuser->email.'
Login here: '.$gCms->config["root_url"].DIRECTORY_SEPARATOR.$gCms->config["admin_dir"].'
After login please change your password here: My Preferences -> My Account!';
if($newuser->email != "" && validate_email($newuser->email)){
$cmsmailer =& $gCms->modules['CMSMailer']['object'];
$cmsmailer->AddAddress($newuser->email);
$cmsmailer->SetBody($bodytext);
$cmsmailer->IsHTML(false);
$cmsmailer->SetSubject($sitename.' User Account Information');
$cmsmailer->Send();
}
Author: simonschaufi http://forum.cmsmadesimple.org/index.php?action=profile;u=6497
UDT to count time in admin area
This UDT will count the time you are in the admin area. This might be good to know how much time you need for a homepage to finish it.
Add this UDT in the Event manager to "LogoutPost" but install it first!
/*
* Use in a page or template like this: {time_account show=true}
* Install with {time_account install=true} BE CAREFULL!!! Execute only once!
* Uninstall with {time_account uninstall=true}
* Written by Simon Schaufelberger 2007
*/
global $gCms;
$db = &$gCms->db;
$userid = get_userid(false);
/*
* Calculates the seconds, minutes and hours from a given timestamp
* returns an array of it
*/
function mod_time($timestamp){
$tmp = array();
$tmp['seconds'] = $timestamp % 60;
$tmp['minutes'] = ($timestamp / 60) % 60;
$tmp['hours'] = ($timestamp / pow(60, 2)) % 60;
return $tmp;
}
/* Display the time in a page or template if parameter show="true" */
if($params['install'] == true){
$sql_install = 'CREATE TABLE '.cms_db_prefix().'time_account ('
. ' user_id int(11) NOT NULL,'
. ' time int(11) NOT NULL,'
. ' PRIMARY KEY (user_id) )';
$dbresult = $db->Execute($sql_install);
if( !$dbresult ){
echo 'DB error: '. $db->ErrorMsg();
exit;
}
echo "<p>UDT installed!</p>";
}
elseif($params['uninstall'] == true){
$sql_uninstall = 'DROP TABLE '.cms_db_prefix().'time_account';
$dbresult = $db->Execute($sql_uninstall);
if( !$dbresult ){
echo 'DB error: '. $db->ErrorMsg();
exit;
}
echo "<p>UDT uninstalled! Please remove it from the page or template!</p>";
}
if($userid && $params['show']== true){
/* Select the last login time from adminlog */
$sql = 'SELECT MAX(timestamp) AS login_time '
. ' FROM '.cms_db_prefix().'adminlog '
. ' WHERE (action = "User Login") '
. ' AND user_id = ?';
$dbresult = $db->Execute($sql, array($userid));
if(!$dbresult){
echo 'DB error: '. $db->ErrorMsg();
exit;
}
if($last_login = $dbresult->FetchRow()){
$logout_time = time();
$login_time = $last_login['login_time'];
$time_div = $logout_time - $login_time;
$sql = 'SELECT time '
. ' FROM '.cms_db_prefix().'time_account '
. ' WHERE ( user_id = ? ) ';
$dbresult = $db->Execute($sql, array($userid));
if( !$dbresult ){
echo 'DB error: '. $db->ErrorMsg();
exit;
}
if($dbresult && $new_time = $dbresult->FetchRow()){
$date = mod_time($new_time['time'] + $time_div);
echo "<p>My time account: ";
echo $date['hours'] . ":";
echo $date['minutes'] . ":";
echo $date['seconds'] . " (h:min:sec)</p>";
}
}
}
elseif($userid){
/* Select the last login time from adminlog */
$sql = 'SELECT MAX(timestamp) AS login_time '
. ' FROM '.cms_db_prefix().'adminlog '
. ' WHERE (action = "User Login") '
. ' AND user_id = ?';
$dbresult = $db->Execute($sql, array($userid));
if(!$dbresult){
echo 'DB error: '. $db->ErrorMsg();
exit;
}
//Is the user already in the time_account table?
$sql = 'SELECT time '
. ' FROM '.cms_db_prefix().'time_account '
. ' WHERE user_id = ?';
$dbresult2 = $db->Execute($sql, array($userid));
if(!$dbresult2){
echo 'DB error: '. $db->ErrorMsg();
exit;
}
/* Add a new user to the table */
if($dbresult2->RecordCount() == 0 && $last_login = $dbresult->FetchRow()){
$logout_time = time();
$login_time = $last_login['login_time'];
$time_div = $logout_time - $login_time;
$sql = 'INSERT INTO '.cms_db_prefix().'time_account (user_id, time) VALUES (?, ?)';
$dbresult = $db->Execute($sql, array($userid, $time_div));
if( !$dbresult ){
echo 'DB error: '. $db->ErrorMsg();
exit;
}
} /* Update his existing time account */
elseif($last_login = $dbresult->FetchRow()){
$logout_time = time();
$login_time = $last_login['login_time'];
$time_div = $logout_time - $login_time;
$sql = 'UPDATE '.cms_db_prefix().'time_account SET time = time + ? WHERE user_id = ?';
$dbresult = $db->Execute($sql, array($time_div, $userid));
if( !$dbresult ){
echo 'DB error: '. $db->ErrorMsg();
exit;
}
}
}
else{
echo "<p>Not logged in. Please login to see your time account!</p>";
}
Author: simonschaufi http://forum.cmsmadesimple.org/index.php?action=profile;u=6497
Call Global Content Block from User Defined Tag
http://forum.cmsmadesimple.org/index.php/topic,15381.0.html
Fix for anchors when using /index.php?page= URL format
If you make a link to an anchor named "bookmark" in your WYSIWYG editor on page with id number 12, your users get sent to /#bookmark instead of /index.php?page=12#bookmark. You can fix this fairly easy.
Open modules/TinyMCE/tinymce/jscripts/tiny_mce/plugins/advlink/jscripts/functions.js
On (or around) line 411, you'll see the following line of code:
html += '<option value="#' + name + '">' + name + '</option>';
Replace that with the following line of code and save it
html += '<option value="index.php?page={get_idnumber}#' + name + '">' + name + '</option>';
Create a new User Defined Tag called get_idnumber with the following code:
global $gCms; $thisPage = $gCms->variables['page_name']; echo $thisPage;
That's it.
Author: Jules Bressers (edited by Simon Schaufelberger to variables['page_name'] which makes more sense - you might want to change the name of the UDT, if so please remember to update it in .../functions.js)
Embed a YouTube video with valid XHTML
The default HTML provided by YouTube is not valid XHTML. I wrote a very simple tag called youtube_video to embed YouTube videos with valid XHTML (I googled cmsmadesimple.org, and it seems there's nothing about this yet):
/* Embed a YouTube video with valid XHTML Parameter: url Reference: http://www.bernzilla.com/item.php?id=681 */ echo '<object class="youtube" type="application/x-shockwave-flash" width="425" height="350"'; echo ' data="'.$params['url'].'">'; echo '<param name="movie" value="'.$params['url'].'" />'; echo '<param name="wmode" value="transparent" />'; echo '</object>';
Here is the original code to embed a video:
<object width="425" height="355"> <param name="movie" value="http://www.youtube.com/v/UiszfEazOaI"></param> <param name="wmode" value="transparent"></param> <embed src="http://www.youtube.com/v/UiszfEazOaI" type="application/x-shockwave-flash" wmode="transparent" width="425" height="355"> </embed> </object>
An here it is how to use the tag:
{youtube_video url="http://www.youtube.com/v/UiszfEazOaI"}
In the forum there's a thread with an example how to add more parameters to the video object.
Author: Marcos Cruz (CMSMS forum profile, alinome.net)
Date: 2008-02-28 Last update: 2008-10-01
YALIM – Yet Another Login Info Mailer
A simple mailing script to send the newly added user’s login info to his e-mail which is based on the existing mailer you got when you installed the CMS.
Steps to set up:
- Create new user defined tag (“Extensions > User Defined Tags”)
- Paste the following code into the textarea:
global $config; $site = $config['root_url']; $link = $config['root_url'] . "/". $config['admin_dir']; if (isset($_POST["email"])) { $to = $_POST["email"]; $subject = 'CMS Account Information'; $message = <<<EOF You have been added as new user to the CMS at $site. This is your new account information: username: {$_POST["user"]} password: {$_POST["password"]} Log into the site admin here: $link EOF; echo "<p>E-mailing user account information…"; echo ( @mail($to, $subject, $message) ? '[done]' : '<strong>[failed]</strong>' ); echo '</p>'; } - Save the tag and go to the Events section (“Extensions > Events”)
- Click the event “AddUserPost”
- Select your newly created tag from the dropdown box at the end of the page and click “Add”
Now everytime a new user is added through the Admin Console, she gets the login info sent (of course only if you also add his/her e-mail address in the user data). You can change the message subject to your liking.
— added by User:10010110 09:48, 12 March 2008 (CDT)
Set Default Group for New Users
Create a UDT that is run from the AddUserPost Event, that puts them in a particular group. The group_id depends on which group you want to use as the default:
- Admin - 1
- Editor - 2
- Designer - 3
Of course, if you add groups with different permissions, you will have to look up the id for the one you want to use.
In this example, the new user will be automatically added to the Editor group.
Create a UDT called set_user_group, with this code:
global $gCms;
$db = &$gCms->db;
$group_id = 2;
$query = "SELECT * FROM ".cms_db_prefix()."users_seq";
$dbresult = $db->Execute($query);
if ($dbresult && $dbresult->RecordCount() > 0)
{
$row = $dbresult->FetchRow();
$user_id = $row['id'];
}
$query = "INSERT INTO ".cms_db_prefix()."user_groups (group_id, user_id, create_date, modified_date)
VALUES ($group_id, $user_id, ".$db->DBTimeStamp(time()).", ".$db->DBTimeStamp(time()).")";
$result = $db->Execute($query);
In the Admin Console, go to Extensions/Events and select the AddUserPost event. Select the set_user_group UDT from the drop down menu and click on the Add button.
Now, whenever you add a new user, they will be assigned to that group.
Author: Nullig
popup
Script to popup a window.
echo "<a href='javascript:popUp(\"index.php?page=" . $params["pagealias"] .'","' . $params["width"] .'","' . $params["height"]. "\")'>" . $params['linkname'] . "</a>";
This is useful if you just want to {popup} a cms page for reference e.g. tooltip, reference text. The {cmslink} function takes the operator to that page necessitating a return, with {popup} the operator stays on the same page.
To create a popup from a page just add the following tag:
{popup pagealias="P" linkname="L" width="W" height="H"}
where:
P is the pagealias mention on the Options tab of the page you want to popup
L is the text for the link
W is the width of the popup, I recommend 800 as this prevents scrollbars
H is the height of the popup. This will depend on the material being
displayed.
Author: goallblacks (this is not right way to create popups, because if guest have javascript turned off he won't be able to open the link, the javascript call should be placed in onclick event instead)
popup (with javascript code)
The popup UDT above is missing the javascript code to actually open a window. Here's an UDT complete with javascript and further options for window sizing.
Put this in a user-defined tag named popup:
// Verifiy UDT parameters.
global $gCms;
if (! isset($params['url']))
{
return;
}
else
{
$url = $params['url'];
}
if (isset($params['width']))
{
$width= $params['width'];
}
else
{
$width = 0;
}
if (isset($params['height']))
{
$height= $params['height'];
}
else
{
$height = 0;
}
if (isset($params['text']))
{
$text = $params['text'];
}
else
{
$text = "Click here";
}
// Insert script into output stream.
echo '
<script type="text/javascript">
<!--
function popup(url, w, h)
{
var xMin = 50;
var yMin = 50;
var xMax = screen.availWidth * 0.7;
var yMax = screen.availHeight * 0.7;
if (w < xMin || w > xMax)
{
w = xMax;
}
if (h < yMin || h > yMax)
{
h = yMax;
}
// Center on screen.
var x = screen.availWidth / 2 - w / 2;
var y = screen.availHeight / 2 - h / 2;
var options = "";
options += "toolbar=no, location=no, directories=no, status=yes, ";
options += "menubar=no, scrollbars=yes, resizable=yes, copyhistory=no, ";
options += "dependent=yes, ";
options += "width=" + w + ", height=" + h + ", left=" + x + ", top=" + y;
var popupWindow = window.open(url, "PopUp", options);
}
// -->
</script>';
// Insert anchor tag into output stream.
echo "<a href='javascript:popup(\"$url\", $width, $height)'>$text</a>";
Then in your content put this:
{popup url='page_url' width=n, height=n, text='xxx'}
url - The URL of the page to be shown in the new window. If not given the UDT call is ignored.
width - The width of the new window in pixels. If not given 70% of screen width is used.
height - The height of the new window in pixels. If not given 70% of screen heightis used.
text - Text to show for the link. If not given "Click here" is used.
The new window gets displayed centered on screen. If given widht/height for the window are too small the defaults are used.
Alternatively this UDT could be rewritten/expanded to use a CMSMS page alias instead of a URL.
author ernst
Using a Push Button for a Hyperlink
Displaying a standard push button that links to a page within the CMS.
Put this in a user-defined tag named link_button:
global $gCms;
if (! isset($params['page']))
{
return;
}
if (isset($params['caption']))
{
$caption= $params['caption'];
}
else
{
$caption= "?";
}
$page = $params['page'];
$manager =& $gCms->GetHierarchyManager();
$node =& $manager->sureGetNodeByAlias($page);
if (! isset($node))
{
return;
}
$content =& $node->GetContent();
if ($content == FALSE)
{
return;
}
$url = $content->GetUrl();
/* Output form with submit button */
echo '<form method="POST" action="'.$url.'">';
echo '<p><input type="submit" value="'.$caption.'" name="LinkButton"></p>';
echo '</form>';
Then in your content put this:
{link_button page='my_page_alias' caption='click me!'}
page - Is the page alias for the page that is shown when the button is pressed.
caption - The caption of the push button.
Expanding this UDT should be easy, for example to support CSS styling or enhanced error handling.
author ernst
Display Flash, Windows Media, and Quicktime XHTML Compliant
The Object Tag is a wrapper for XHTML Compliant use of <object> tag
Examples using Flash Object
{object src='uploads/movie.swf' height='300' width='300' class='flashplayer'}
{object src='uploads/movie.swf' height='300' width='300'
param='quality::low||bgcolor::#ffffff' alt='Download Flash Player'}
Example with Quicktime Object
{object type='qt' src='uploads/GatesBlueScreen.mov' height='500' width='300'
param='controller::true||autoplay::false' alt='Bill Gates crashing Windows 98'}
Example with Windows Media Object
{object type='wmv' src='uploads/cmsMadeSimple.wvm' height='700' width='500'
param='controller::false||autoplay::true' alt='CMSMS Tutorial Video part 1'}
You can download it here
author viebig
Simple random quote system
I was looking for a very simple script that shows at random a quote. There is a project that helps out, but the maintenance of the quotes is not that easy (to my opinion). I prepared a txt file with each line containing a quote. I uploaded this, using the file manager, to the uploads directory. Next I prepared the following tag:
$delim = "\n"; // $quotefile points to the file that holds the actual quotes $quotefile = "uploads/quotes.txt"; $fp = fopen($quotefile, "r"); $contents = fread($fp, filesize($quotefile)); $quote_arr = explode($delim,$contents); fclose($fp); srand((double)microtime()*1000000); $quote_index = (rand(1, sizeof($quote_arr)) - 1); $herequote = $quote_arr[$quote_index]; echo $herequote;
author: Duketown (the coding from Jeff Richards)
Simple random quote system (remote file version)
I modified Duketown's concept above slightly to allow for a remote txt file to be used rather than a local one. This is especially useful for those who manage multiple websites and would like to have the same quotes on every site while keeping the quote data stored in one central file for edits/changes.
$delim = "\n"; // $quotefile points to the remote file that holds the actual quotes (1 per line) $quotefile = "http://www.yoursite.com/quotes.txt"; $fp = fopen($quotefile, "r"); $contents = stream_get_contents($fp); $quote_arr = explode($delim,$contents); fclose($fp); srand((double)microtime()*1000000); $quote_index = (rand(1, sizeof($quote_arr)) - 1); $herequote = $quote_arr[$quote_index]; echo $herequote;
author: Franklin (original concept from Duketown and orignal coding from Jeff Richards)
Display user properties of Frontend Users module
This UDT allows you to get the value of any user property you have defined in the Frontend Users (FEU) module. The value can be displayed or assigned to a Smarty variable for later use.
Create a UDT called get_feu_properties and paste the code below:
global $gCms;
$error = "";
$result = "";
$feusers = $gCms->modules['FrontEndUsers']['object'];
if ($feusers) {
$username = $params['username'];
if ($username == "") {
$error = " [UDT get_feu_properties Error; Missing or empty parameter: username] ";
}
else {
$uid = $feusers->GetUserID($username);
if ($uid == "") {
$property = "uid";
}
else {
$property = $params['property'];
if ($property == "") {
$property = "uid";
$result = $uid;
}
else {
$properties = $feusers->GetUserProperties($uid);
foreach($properties as $key=>$value) {
if ($value["title"] == $property) {
$result = $value["data"];
}
}
}
}
}
}
else {
$error = " [UDT get_feu_properties Error; Can not communicate with FrontEndUsers module] ";
}
if ($error == "") {
if ($params['method'] == "assign") {
$gCms->smarty->assign($property, $result);
}
else {
return $result;
}
}
else {
return $error;
}
Parameters:
username (required): the Frontend Users username.
property (optional): the name of the property value to return as the result; When not specified, the result will be the Frontend Users uid.
method (optional): when not specified, the result is simply displayed; When method="assign", the value is returned in a Smarty variable with the same name as the property.
Usage:
To display the user id (uid) of a FEU user named "Frank" use:
{get_feu_properties username="Frank"}
To display the value of the property "phone_number" of the user "Jane" use:
{get_feu_properties username="Jane" property="phone_number"}
To assign the value of the property "email_addr" of the currently logged in FEU user use:
{get_feu_properties username=$username property="email_addr" method="assign"}
In this case nothing is displayed but instead the variable "$email_addr" now contains this users' email address.
This UDT can be used in page content or, for example, in a Newletter Made Simple message to personalize mailings.
Author: Ron Wardenier
get_content_props [1]
This UDT gets all properties of a content:
global $gCms;
$db =& $gCms->GetDb();
$content_id = $gCms->variables['pageinfo']->content_id;
$fields = array();
$separator = '<br />';
$result = array();
if( isset($params['content_id']) ) {
$content_id = trim($params['content_id']);
}
if( isset($params['fields']) ) {
$fields = explode(',',trim($params['fields']));
}
if( isset($params['separator']) ) {
$separator= $params['separator'];
}
$i=0;
$query = "SELECT prop_name,content FROM ".cms_db_prefix()."content_props WHERE content_id=".$content_id;
if(!empty($fields)) {
$query .= " AND (";
foreach($fields as $f)
{
$i++;
$query .= "prop_name='".$f."'";
if($i<count($fields))
$query .= " OR ";
}
$query .= ")";
}
$dbresult = $db->Execute($query);
while($dbresult && $row = $dbresult->FetchRow()) {
$result[$row['prop_name']]['fieldname'] = $row['prop_name'];
$result[$row['prop_name']]['data'] = $row['content'];
}
// assign vars to smarty
if( isset($params['assign']) ) {
$smarty->assign(trim($params['assign']), $result);
}
// or just print out the result
else {
$i=0;
foreach($result as $res) {
$i++;
echo $res['data'];
if($i<count($result))
echo $separator;
}
}
How to use:
Store that code as an UDT named e.g. get_content_props. In your template/content call {get_content_props}. Using no params will print out all fields of the database table 'content_props'.
Available params:
fields="fieldname1,fieldname2,..." (optional) a list of fields that will be printed out separated by a separator. it must contain a list of the prop_names as they where stored in the database. if not set all properties will be printed out.
content_id="15" (optional) the id of the content that properties will be printed out. If not set the current contents id will be used.
separator="<br />" (optional)
a character or HTML-Tag that separates the fields from each other if multiple fields are displayed.
If not set a line break (
) will be used.
assign=content_props (optional) if set the field(s) will not be displayed instantly but smarty vars will be assigned to your template instead. That means you will have an array called {$content_props} that can be accessed in a {foreach}-loop in your template.
Examples:
This will print out all content properties of the current page separated by a linebreak:
{get_content_props}
This will print out all content properties of the page with the content_id "15" separated by a linebreak:
{get_content_props content_id="15"}
This will print out all content properties of the page with the content_id "15" separated by a comma:
{get_content_props content_id="15" separator=","}
This will only print out the properties named "extra1" and "extra2" of the current page separated by a linebreak:
{get_content_props fields="extra1,extra2"}
This will provide smarty variables that you can access after calling the UDT:
{get_content_props assign="content_props"}
{$content_props.content_en.data}
{$content_props.target.data}
{$content_props.extra1.data}
or this one:
{get_content_props assign=content_props}
{foreach from=$content_props item=prop}
{$prop.fieldname}:{$prop.data}
{/foreach}
author: NaN
Show links to pages at the same menu level
This UDT Shows links to pages at the same menu level in a " 1 2 3 < > " format, where 2 is the current page.
Task example:
-To create a menu entry: "items" to display many "item" pages and navigate through the item pages with links in "1 2 3 4 < >" fashion.
Solution:
-Create a "items" internal-link page linking to the first "item" page. (i.e. "item-1")
-Create pages "item-1","item-2",etc.. all hidden from menu, and with menu parent "items".
-Add the {list_siblings} UDT in each "item" page.
{list_siblings}
global $gCms;
// get current page
$manager =& $gCms->GetHierarchyManager();
$thisPage = $gCms->variables['page_name'];
//get current page parent
$currentNode = & $manager->sureGetNodeByAlias($thisPage);
$parentNode = $currentNode->getParent();
if ($parentNode->hasChildren())
{
$sibblings = $parentNode->getChildren();
$numPages = count($sibblings);
$bFirst = false;
$bLast = false;
$prevURL ="";
$nextURL ="";
$url = "#";
for ($i=0; $i<$numPages; $i++)
{
$page = $sibblings[$i];
$content = $page->getContent();
$alias = $content->Alias();
$lastURL = $url;
$url = $content->GetURL();
if ($thisPage == $alias)
{
if ($i==0) $bFirst = true;
if ($i== $numPages-1) $bLast = true;
echo "<strong>".($i+1)."</strong> ";
$prevURL = $lastURL;
}
else
{
echo "<a href=\"".$url."\">".($i+1)."</a> ";
if ($prevURL != "" && $nextURL=="") $nextURL = $url;
}
}
}
if (!$bFirst)
echo "<a href=\"".$prevURL ."\"> < </a>";
else
echo " ";
if (!$bLast)
echo "<a href=\"".$nextURL ."\"> > </a>";
author: David Picón
User Defined Tags for New Module (for older versions)
- NOTE: Pagination is available by default in version 1.1. This information is for those still using the older versions.
This UDT allows you to add "Older/Newer News" type links at the bottom of pages containing News, as well as the page-number-links. Note that this does not work for 'news' type pages. You will need to set your page type to 'Content' and add the appropriate {news} or {cms_module} tags.
1. Create a User Defined Tag "newsindex" as follows:
global $gCms, $number;
$start = ($_REQUEST['start']) ? $_REQUEST['start'] : $params['start'];
$number = ($_REQUEST['number']) ? $_REQUEST['number'] : $params['number'];
$older = $params['older'] ? $params['older'] : 'Older Stories';
$newer = $params['newer'] ? $params['newer'] : 'Newer Stories';
/*Get URL for 1st page*/
$hm =& $gCms->GetHierarchyManager();
$firstpage = $gCms->variables['content_id'];
$curnode = &$hm->getNodeById($firstpage);
$curcontent =& $curnode->getContent();
/* Count the number of articles we have in total */
$db = &$gCms->db;
$tables=cms_db_prefix().'module_news';
$cond='';
if (isset($params['count_expired'])) {
switch ($params['count_expired']) {
case 'true':
$cmpr='<';
break;
case 'false':
$cmpr='>';
break;
default:
return 'Wrong argument in "count_expired"';
}
$cond='(end_time '.$cmpr.' NOW() OR end_time IS NULL )';
}
if (isset($params['category'])) {
$tables.=', '.cms_db_prefix().'module_news_categories';
if ($cond!='') $cond.=" AND ";
$cond.="(news_category_name LIKE '".$params['category']."') AND (".cms_db_prefix()."module_news_categories.news_category_id = ".cms_db_prefix()."module_news.news_category_id)";
}
if($cond!='') $cond='WHERE ('.$cond.')';
$query = 'SELECT COUNT(news_id) FROM '.$tables.' '.$cond;
$newscount = &$db->GetOne($query);
/* utility to make a URL */
function join_uri($middle) {
global $gCms, $number;
return 'index.php?page=' . $gCms->variables['page_name'] . '&start=' . $middle . '&number=' . $number;
}
/* Create the Next and Previous URLS */
$older_uri = join_uri($start + $number);
$newer_uri = (($_REQUEST['start'] - $params['number']) == $params['start'])
? $curcontent->GetURL()
: join_uri($start - $number);
/* Make the page links */
$newscrumbs='';
$page = 0;
for( $i=0; $i <= $newscount; $i += $number ) {
$page++;
if( $i != $start ) {
$newscrumbs .= ($i == $params['start'])
? '<a href="'.$curcontent->GetURL().'">'.$page.'</a>'
: '<a href="'.join_uri($i).'">'.$page.'</a>';
} else {
$newscrumbs .= $page;
}
if( $i <= $newscount && isset($params['delimiter'] ) ) {
$newscrumbs.=$params['delimiter'];
}
}
$smarty->assign('news_start', $start);
$smarty->assign('news_number', $number);
$smarty->assign('news_count',$newscount);
$smarty->assign('news_newer_link', ($start > 0)
? "<a href=\"$newer_uri\">$newer</a>"
: ''
);
$smarty->assign('news_older_link', ($start + $number < $newscount)
? "<a href=\"$older_uri\">$older</a>"
: ''
);
$smarty->assign('news_crumbs',$newscrumbs);
This tag sets six smarty-variables (variables you can access in your page).
2. Create a page for your news. It should have a Content Type of 'Content' rather than 'News'
3. Execute your User Defined Tag by adding the following to the page's Content:
{newsindex number='5' start='0' category='General' count_expired='true' delimiter='|' older='Older Stories' newer='Newer Stories'}
Parameters:
-
startThe story number to default to at the top of this page -
numberThe number of stories to show on each page -
categorySpecifies the category of the displayed news; if not specified, every category is included -
count_expiredShow expired news in the pagination (takes 'true' or 'false') -
delimiterSpecify the delimiter of the page-number-links, like ' | ' in1 | 2 | 3 -
older: The text to use for the link to the previous page -
newer: The text to use for the link to the next page
That will set the six smarty variables:
-
$news_start: The story number that starts the current page -
$news_number: The number of stories on the current page -
$news_newer_link: A link to the next page (if there is a next page, empty string otherwise) -
$news_older_link: A link to the previous page (if there is a previous page, empty string otherwise) -
$news_count: The total number of stories available to show -
$news_crumbs: A list of pages (linked) separated by the delimiter provided
4. Add (or change) the {cms_module} or just {news} tag to insert your news, using the two variables:
{cms_module module='news' number=$news_number start=$news_start category='General' showarchive='true'}
Note that this must come after the previous tag.
5. Finally, create the next/prev links and the page-number-links ({$newscrumbs})
{$news_newer_link} {$news_crumbs} {$news_older_link}
In summary, add the following to your content:
{newsindex number='5' start='0' category='General' count_expired='true' delimiter='|' older='Older Stories' newer='Newer Stories'}
{cms_module module='news' number=$news_number start=$news_start category='General' showarchive='true'}
{$news_newer_link} {$news_crumbs} {$news_older_link}
This shows an archive of the now archived news with the proper pagination.
Check for (expire) dates
Call this UDT e.g. "datum"
/**
* DATUM checks whether the submitted date is older ($expired=true) or newer ($expired=false)
* in comparison to the current date. It provides the numbers of days from today to the
* submitted date if the date is in the future.
*
* The variables are available via Smarty as {$expired}, {$num_days}, etc.
*
* @param day day of the month, 1 or 2 digits (e.g. 1)
* @param month numeric representation of a month, 1 or 2 digits (e.g. 7)
* @param year a full numeric representation of a year, 4 digits (e.g. 2008)
* @return expired true or false, see description above
* @return num_days numbers of days from today to the submitted date if the date is in the future
*
*/
global $gCms;
$smarty = &$gCms->GetSmarty();
$err = 'DATUM UDT error: No day, month or year submitted, correct form: e.g. {datum day="1" month="7" year="2008"}';
if (isset($params['day']) AND isset($params['month']) AND isset($params['year'])){
$datum = mktime(0, 0, 0, $params[month], $params[day], $params[year]);
$heute = mktime();
if ($datum < $heute){
$expired = true; // date expired
} else {
$expired = false; // date NOT expired
$num_days = date(j, ($datum - $heute)); // numbers of days from today to the submitted date
}
$smarty->assign('expired', $expired); // make variable "expired" visible for CMSms
$smarty->assign('num_days', $num_days); // make variable "num_days" visible for CMSms
}else{
echo '<p style="color:red; font-weight:bold;">'. $err . '</p>';
}
Usage in page or template (example):
{datum day="25" month="12" year="2008"} {* Invoke the UDT "datum" *}
{if !$expired} {* date is not expired *}
Only {$num_days}
{if $num_days == 1}
day
{else}
days
{/if}
left until Christmas.
{else} {* date is expired *}
Christmas is over for this year.
{/if}
author: hibr
get_template_vars
Very often when put image in the content I had to do small image and then bigger image. I have created tag which is triggered before content is send which creates thumbnails on the fly for big images depending on the image size defined by the content editdor.
1. Create user defined tag
function replaceContentImageWithThumbs($txt, $thumb_prefix){
global $gCms;
$config =& $gCms->GetConfig();
$rootPath = $gCms->config["root_path"] ;
$imgs = findAllImg($txt) ;
for ($i=0 ; $i < count($imgs); $i++){
$filename = basename($imgs[$i]["src"]);
//already a thumb?
if (substr($filename, 0 ,strlen($filename)) != $thumb_prefix ){
$imgInfo = getimagesize($rootPath."/".$imgs[$i]["src"]) ;
//condition to generate thumb
if ($imgInfo[0] > $imgs[$i]["width"] || $imgInfo[1] > $imgs[$i]["height"]){
$thumbSrc = generateImgThumb($imgs[$i]["src"], $imgs[$i]["width"], $imgs[$i]["height"], $thumb_prefix);
//let's replace the content
$pattern = "<[iI][mM][gG][^>]*src=\"".$imgs[$i]["src"]."\"[^>]*>" ;
$a_pattern = "<[Aa][^>]*><[iI][mM][gG][^>]*src=\"".$imgs[$i]["src"]."\"[^>]*>\s*</a>" ;
$pattern = "/".str_replace("/", "\/", $pattern)."/" ;
$a_pattern = "/".str_replace("/", "\/", $a_pattern)."/" ;
if (preg_match($a_pattern, $txt)){
$txt = preg_replace($pattern, $imgs[$i]["beforSrc"]."src=\"".$thumbSrc."\"".$imgs[$i]["afterSrc"], $txt) ;
}else{
$txt = preg_replace($pattern, "<a target=\"_blank\" rel=\"lightbox\" href=\"".$imgs[$i]["src"]."\">".$imgs[$i]["beforSrc"]."src=\"".$thumbSrc."\"".$imgs[$i]["afterSrc"]."</a>", $txt) ;
}
}
}
}
return $txt ;
}
function findAllImg($txt){
preg_match_all("/<[iI][mM][gG][^>]*>/", $txt, $out, PREG_PATTERN_ORDER);
$k=0 ;
for ($i = 0 ; $i < count($out[0]) ; $i++)
{
$imgTxt = $out[0][$i] ;
preg_match("/width=\"([^\"]*)\"/", $imgTxt, $imgWidth);
preg_match("/height=\"([^\"]*)\"/", $imgTxt, $imgHeight);
preg_match("/(.*)src=\"([^\"]*)\"(.*)/", $imgTxt, $imgSrc);
if (!empty($imgWidth[1]) && !empty($imgHeight[1]) && !empty($imgSrc[2]) ){
$img[$k]["width"] = $imgWidth[1] ;
$img[$k]["height"] = $imgHeight[1] ;
$img[$k]["src"] = $imgSrc[2] ;
$img[$k]["beforSrc"] = $imgSrc[1] ;
$img[$k]["afterSrc"] = $imgSrc[3] ;
$k++;
}
}
return $img ;
}
//returns new path to thumb
function generateImgThumb($src, $width, $height, $thumb_prefix){
global $gCms;
$config =& $gCms->GetConfig();
$rootPath = $gCms->config["root_path"] ;
$imageManagerRelPath = "lib/filemanager/ImageManager/" ;
require_once($rootPath."/".$imageManagerRelPath."Classes/ImageManager.php");
require_once($rootPath."/".$imageManagerRelPath."config.inc.php");
$thumbName = getThumbPath($rootPath."/".$src, $thumb_prefix, $width, $height) ;
//generujemy miniaturke
if(!is_file($thumbName)){
$imgInfo = getimagesize($rootPath."/".$src);
if(!is_array($imgInfo))
return $src;
require_once($rootPath."/".$imageManagerRelPath.'Classes/Thumbnail.php');
// if image smaller than config size for thumbs
if ($imgInfo[0] <= $width && $imgInfo[1] <= $height)
{
$thumbnailer = new Thumbnail($imgInfo[0],$imgInfo[1]);
$thumbnailer->createThumbnail($rootPath."/".$src, $thumbName);
}
// if image bigger than config size for thumbs
else {
$thumbnailer = new Thumbnail($width, $height);
$thumbnailer->createThumbnail($rootPath."/".$src, $thumbName);
}
if(is_file($thumbName))
{
return getThumbPath($src,$thumb_prefix,$width,$height) ;
}
}
return getThumbPath($src,$thumb_prefix,$width,$height) ;
}
function getThumbPath($fullpathfile, $thumb_prefix, $width, $height)
{
$path_parts = pathinfo($fullpathfile);
return $path_parts['dirname']."/".$thumb_prefix.$width."_".$height."_".$path_parts['basename'];
}
$propertyHolder = $params['content']->mProperties;
$values = $params['content']->mProperties->mPropertyValues ;
$thumb_prefix = "thumb_" ;
foreach($values as $key=>$value)
{
if (substr($key, 0 ,7) == "content" ){
$propertyHolder->SetValue($key, replaceContentImageWithThumbs($value, $thumb_prefix) ) ;
}
}
2. Create event ContentEditPre which use this tag
author: shipmen => gmail.com
Inserting an anchor in generated HTML
If you like to see your anchors with their names in the contents window of the editor then use this little UDT.
Put this in a user-defined tag named insert_anchor:
echo '<a name="' . $params['name'] . '"></a>';
Then in your content put this:
{insert_anchor name='anchorname'}
name - Is the name for the anchor.
In the generated HTML you will get this:
<a name="anchorname">
With the {anchor} or {cms_selflink} tags (part of the CMSMS installation) the anchor can be addressed with an internal page link.
author christiaans
documented by ernst
Calculate distance between to Geo-Coordinates
This UDT can be used to calculate the distance between two places (straight line on a globe). It returns the distance in a selectable metric and detail. The default metric is "imperial miles" and only full miles (rounded)
Safe the code as {gps_distance} and use the following parameters:
- ²round: takes a full number (integer) as value and is used to determine the detail of the result (e.g: round=5)
- convert: pick a shortcut from the code to convert result into this metric (e.g. convert="km")
- gps_lat_1: Latitude of first GPS point (e.g. gps_lat_1=53.12456).
- gps_long_1: Longitude of first GPS point
- gps_lat_2: Latitude of second GPS point
- gps_long_2: Longitude of second GPS point
- ²assign: assign output to variable
²=optional
//
// Check for parameters, if not set or empty, set default
//
// This parameter is used to select the scaling of the result returned
if (isset($params['round']) AND ($params['round'] != '')) {
$roundt = (integer)$params['round'];
} else {$roundt = 0;}
// This parameter is used to select the scaling of the result returned
if (isset($params['convert']) AND ($params['convert'] != '')) {
$convert = strtolower($params['convert']);
} else {$convert = 'mi';}
// This is the latitude of the first point
if (isset($params['gps_lat_1']) AND ($params['gps_lat_1'] != '')) {
$gps_lat_1 = (float)$params['gps_lat_1'];
} else {$gps_lat_1 = -10;}
// This is the latitude of the first point
if (isset($params['gps_lat_2']) AND ($params['gps_lat_2'] != '')) {
$gps_lat_2 = (float)$params['gps_lat_2'];
} else {$gps_lat_2 = 11;}
// This is the longitude of the second point
if (isset($params['gps_long_1']) AND ($params['gps_long_1'] != '')) {
$gps_long_1 = (float)$params['gps_long_1'];
} else {$gps_long_1 = 10;}
// This is the longitude of the second point
if (isset($params['gps_long_2']) AND ($params['gps_long_2'] != '')) {
$gps_long_2 = (float)$params['gps_long_2'];
} else {$gps_long_2 = 11;}
//
// Do the distance calculation
//
$result = sin(deg2rad($gps_lat_1)) * sin(deg2rad($gps_lat_2)) + cos(deg2rad($gps_lat_1)) * cos(deg2rad($gps_lat_2)) * cos(deg2rad($gps_long_1 - $gps_long_2));
$result = rad2deg(acos($result)) * 69.09;
//
// If a converting is required do this
// --> You may delete those lines containing metrics you think you wont use at no harm.
//
// metric
if ($convert== 'km' ) {$result = $result * 1.609344;}
if ($convert== 'meter' ) {$result = $result * 1609.344;}
if ($convert== 'cm' ) {$result = $result * 160934.4;}
// imperial
if ($convert== 'league' ) {$result = $result * 0.333333;}
if ($convert== 'yard' ) {$result = $result * 1760;}
if ($convert== 'foot' ) {$result = $result * 5280;}
if ($convert== 'inch' ) {$result = $result * 63360;}
// nautic
if ($convert== 'sealeague' ) {$result = $result * 0.289659;}
if ($convert== 'seamile' ) {$result = $result * 0.868976;}
if ($convert== 'cable' ) {$result = $result * 7.33333;}
if ($convert== 'shortcable' ) {$result = $result * 8.68976;}
if ($convert== 'fathom' ) {$result = $result * 880;}
// japanese
if ($convert== 'ri' ) {$result = $result * 0.409784;}
if ($convert== 'kairi' ) {$result = $result * 0.868976;}
if ($convert== 'cho' ) {$result = $result * 14.7522;}
if ($convert== 'iyo' ) {$result = $result * 531.08;}
if ($convert== 'ken' ) {$result = $result * 885.133;}
if ($convert== 'shyaku' ) {$result = $result * 5310.8;}
// chinese imperial
if ($convert== 'li' ) {$result = $result * 3.21869;}
if ($convert== 'yin' ) {$result = $result * 48.2803;}
if ($convert== 'zhang' ) {$result = $result * 482.803;}
if ($convert== 'bu' ) {$result = $result * 965.606;}
if ($convert== 'chi' ) {$result = $result * 4828.03;}
if ($convert== 'cun' ) {$result = $result * 48280.3;}
// German geographical
if ($convert== 'geomile' ) {$result = $result * 0.216893;}
// typographic - ATA system
if ($convert== 'pica' ) {$result = $result * 381597;}
if ($convert== 'point' ) {$result = $result * 4579160;}
if ($convert== 'pixel' ) {$result = $result * 6105550;}
// astronomic
if ($convert== 'redshift' ) {$result = $result * 1.23532e-23;}
if ($convert== 'parsec' ) {$result = $result * 5.21553e-14;}
if ($convert== 'astronomicalunit' ) {$result = $result * 1.70111e-13;}
if ($convert== 'lightyear' ) {$result = $result * 1.07578e-8;}
if ($convert== 'lightminute' ) {$result = $result * 8.94699e-8;}
if ($convert== 'lightsecond' ) {$result = $result * 0.00000536819;}
// ancient roman
if ($convert== 'millarium' ) {$result = $result * 1.00735;}
if ($convert== 'akt' ) {$result = $result * 41.973;}
if ($convert== 'decimpeda' ) {$result = $result * 503.676;}
if ($convert== 'pace' ) {$result = $result * 1007.35;}
if ($convert== 'cubit' ) {$result = $result * 3357.84;}
if ($convert== 'ped' ) {$result = $result * 5036.76;} // ordinary ped
if ($convert== 'ounce' ) {$result = $result * 60441.1;} // ounce (inch)
if ($convert== 'digit' ) {$result = $result * 80588.1;}
//
// Return integer value for distance in selected scaling
//
$value = round($result,$roundt);
if( isset($params['assign']) )
{
$smarty->assign(trim($params['assign']),$value);
return;
}
return $value;
Author: Nils Haack (nhaack)
setCookies
I wrote this User Defined Tag (UDT) to set multiple cookies. I saved it as "setCookies" in the site's UDT section.
Use it like this in the page:
{setCookies days='numDays' cookie1="value1" cookie2="value2"}
Required Parameters:
days='5' this sets the expiration date of the cookie.
This will work with versions of CMSMS that process the body before the head of the document. (Cookies must be sent before the <html>. So if you have it set up that CMSMS processes the head before the body, where your {setCookies} tag is, then it will not work.)
You can have as many cookie="value" pairs as you want, with any name you want, as long as each cookie name is unique.
if (isset($params)) {
if (isset($params['days'])) {
$expire=time() + ($params['days']*86400);
foreach ($params as $name => $value) {
if ($name!='days') {
setcookie($name,$value,$expire);
unset($value);
}
}
return;
}
else {
print('Error: setCookies parameter "days" is required');
}
}
else {
print('Error: setCookies requires parameters.');
return;
}
Author: Ken Griffith (kendo451)
This page in: English - Deutsch - Español - Français - Italiano - Lietuvių - Nederlands - Norsk - Polski - Русский - Svenska - Tiếng Việt - عربي
Note: CMSMS cant take responsibility for these codes. Please read through the code before using. All tags shared under GPL license
This page in: English - Deutsch - Español - Français - Italiano - Lietuvių - Nederlands - Norsk - Polski - Русский - Svenska - Tiếng Việt - عربي
