/app/helpers/contents_helper.rb
Ruby | 403 lines | 222 code | 34 blank | 147 comment | 32 complexity | ae3f7121b107e7e57af76b97e7740a7a MD5 | raw file
- module ContentsHelper
- # Drupal Filters
- #function do_flv($text){
- # $pattern = '/\[flvplayer\s+src="([A-Za-z0-9-_\.]+)"\s+width="(\d+)"\s+height="(\d+)"([^\]]*)\]/mi';
- # $replacement = '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" type="application/x-shockwave-flash" width="${2}" height="${3}" wmode="transparent" ' .
- # 'data="/tmcontent/flvplayer.swf?file=videos/${1}&autoStart=false">' .
- # '<param name="movie" value="/tmcontent/flvplayer.swf?file=videos/${1}&autoStart=false" />' .
- # '<param name="wmode" value="transparent" />' .
- # '<embed src="/tmcontent/flvplayer.swf?file=videos/${1}&autoStart=false" ' .
- # 'type="application/x-shockwave-flash" width="${2}" height="${3}"></embed></object>';
- # return preg_replace($pattern, $replacement, $text);
- #}
- def do_flv(text)
- output = '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" type="application/x-shockwave-flash" width="\2" height="\3" wmode="transparent" data="/tmcontent/flvplayer.swf?file=videos/\1&autoStart=false">' +
- '<param name="movie" value="/tmcontent/flvplayer.swf?file=videos/\1&autoStart=false" />' +
- '<param name="wmode" value="transparent" />' +
- '<embed src="/tmcontent/flvplayer.swf?file=videos/\1&autoStart=false" type="application/x-shockwave-flash" width="\2" height="\3"></embed>' +
- '</object>'
- text.gsub(/\[flvplayer\s+src="([A-Za-z0-9\-_\.]+)"\s+width="(\d+)"\s+height="(\d+)"([^\]]*)\]/, output)
- end
- #function do_tmreplace($text){
- # $KEYWORDS_PRIMARY = '/\[keywords_primary:([^\]]*)\]/mi';
- # $KEYWORDS_SECONDARY = '/\[keywords_secondary:([^\]]*)\]/mi';
- # $replace = '';
- # $new_text = preg_replace($KEYWORDS_PRIMARY, $replace, $text);
- # $new_text = preg_replace($KEYWORDS_SECONDARY, $replace, $new_text);
- # // insert sound link
- # $SOUND_LINK = '/\[sound(_|-)link:([^\]]*)\]/mi';
- # $replace = '<a href="${2}" onclick="play(this.href); return false;">' .
- # '<img alt="Sound" border="0" src="/cms_images/hear.gif" /></a>';
- # $new_text = preg_replace($SOUND_LINK, $replace, $new_text);
- # /// reference static server for images
- # $CMS_LINK = '%src="(http://(www.)?123teachme.com)?/cms_images%mi';
- # $replace = 'src="http://static.123teachme.com/cms_images';
- # $new_text = preg_replace($CMS_LINK, $replace, $new_text);
- # $IMG_LINK = '%src="(http://(www.)?123teachme.com)?/images/%mi';
- # $replace = 'src="http://static.123teachme.com/images/';
- # $new_text = preg_replace($IMG_LINK, $replace, $new_text);
- # return $new_text;
- #}
- def do_tmreplace(text)
- output = do_tmreplace_keywords_primary(text)
- output = do_tmreplace_keywords_secondary(output)
- output = do_tmreplace_sound_link(output)
- output = do_tmreplace_long_sound_link(output)
- output = do_tmreplace_static_link(output)
- end
- def do_tmreplace_keywords_primary(text)
- text.gsub(/(\[keywords_primary:)([^\]]*)(\])/mi, '')
- end
- def do_tmreplace_keywords_secondary(text)
- text.gsub(/(\[keywords_secondary:)([^\]]*)(\])/mi, '')
- end
- def do_tmreplace_sound_link(text)
- sound_link = Regexp.new('\[sound[-_]link:([^\]]*)\]', (Regexp::IGNORECASE || Regexp::MULTILINE))
- while match = text.match(sound_link) do
- link = match[1]
- replacement = %{<a href="#{link}" onclick="play(this.href); return false;"><img border="0" src="/cms_images/hear.gif" /></a>}
- text.gsub!(match[0], replacement)
- end
- text
- end
- def do_tmreplace_long_sound_link(text)
- #replaces long_sound_link:title:url or long_sound_link:url
- long_sound_link = Regexp.new('\[long[-_]sound[-_]link:([^:]+:)?([^\]]*)\]', (Regexp::IGNORECASE || Regexp::MULTILINE))
- while match = text.match(long_sound_link) do
- label = match[1]
- link = match[2]
- if (!label.blank?) then label=label.chop end
- if (label.blank?) then label="Audio Link" end
- label=CGI::escapeHTML(label)
- replacement = %{<a href="#{link}" class="long-sound-link" onclick="playLongSound(this.href,this); return false;">#{label}</a>}
- text.gsub!(match[0], replacement)
- end
- text
- end
- def do_tmreplace_static_link(text)
- # dev note: to parallelize downloads, multiple static hosts are used
- # but same path should ALWAYS map to same host to allow better caching
- # algorithm: get ascii value of 7th char from end of path. return 1 for even 2 for odd
- text.gsub(%r{(src="(http://(www.)?123teachme.com)?/)(cms_){0,1}(images)([^"]*)}mi) do |match|
- num = 3
- path = $6 || ''
- num = path[-7].ord%2 + 1 if path && path.length > 7
- %Q{src="http://static#{num}.123teachme.com/#{$4}images#{$6}}
- end
- #rand_int = rand(2) + 1 # 1 or 2
- #replacement = %Q{src="http://static#{rand_int}.123teachme.com/\\4images}
- #text.gsub(%r{(src="(http://(www.)?123teachme.com)?/)(cms_){0,1}(images)}mi, replacement)
- end
- # THE FOLLOWING FUNCTION IS DUPLICATED WITHIN THE DO_TMREPLACE FUNCTION.
- #function do_static($text){
- # //$CMS_LINK = '%src="http://(www\.)?123teachme.com/cms_images%i'; // using % instead of /
- # $CMS_LINK = '/src="http:\/\/www.123teachme.com\/cms_images/i';
- # $replace = 'src="http://static.123teachme.com/cms_images';
- # $new_text = preg_replace($CMS_LINK, $replace, $text);
- # return $new_text;
- #}
- #/**
- # * Convert line breaks into <p> and <br> in an intelligent fashion.
- # * Based on: http://photomatt.net/scripts/autop
- # */
- #function _filter_autop($text) {
- # // All block level tags
- # $block = '(?:table|thead|tfoot|caption|colgroup|tbody|tr|td|th|div|dl|dd|dt|ul|ol|li|pre|select|form|blockquote|address|p|h[1-6])';
- #
- # // Split at <pre>, <script>, <style> and </pre>, </script>, </style> tags.
- # // We don't apply any processing to the contents of these tags to avoid messing
- # // up code. We look for matched pairs and allow basic nesting. For example:
- # // "processed <pre> ignored <script> ignored </script> ignored </pre> processed"
- # $chunks = preg_split('@(</?(?:pre|script|style)[^>]*>)@i', $text, -1, PREG_SPLIT_DELIM_CAPTURE);
- # // Note: PHP ensures the array consists of alternating delimiters and literals
- # // and begins and ends with a literal (inserting NULL as required).
- # $ignore = false;
- # $ignoretag = '';
- # $output = '';
- # foreach ($chunks as $i => $chunk) {
- # if ($i % 2) {
- # // Opening or closing tag?
- # $open = ($chunk{1} != '/');
- # list($tag) = split('[ >]', substr($chunk, 2 - $open), 2);
- # if (!$ignore) {
- # if ($open) {
- # $ignore = true;
- # $ignoretag = $tag;
- # }
- # }
- # // Only allow a matching tag to close it.
- # else if (!$open && $ignoretag == $tag) {
- # $ignore = false;
- # $ignoretag = '';
- # }
- # }
- # else if (!$ignore) {
- # $chunk = preg_replace('|\n*$|', '', $chunk) ."\n\n"; // just to make things a little easier, pad the end
- # $chunk = preg_replace('|<br />\s*<br />|', "\n\n", $chunk);
- # $chunk = preg_replace('!(<'. $block .'[^>]*>)!', "\n$1", $chunk); // Space things out a little
- # $chunk = preg_replace('!(</'. $block .'>)!', "$1\n\n", $chunk); // Space things out a little
- # $chunk = preg_replace("/\n\n+/", "\n\n", $chunk); // take care of duplicates
- # $chunk = preg_replace('/\n?(.+?)(?:\n\s*\n|\z)/s', "<p>$1</p>\n", $chunk); // make paragraphs, including one at the end
- # $chunk = preg_replace('|<p>\s*?</p>|', '', $chunk); // under certain strange conditions it could create a P of entirely whitespace
- # $chunk = preg_replace("|<p>(<li.+?)</p>|", "$1", $chunk); // problem with nested lists
- # $chunk = preg_replace('|<p><blockquote([^>]*)>|i', "<blockquote$1><p>", $chunk);
- # $chunk = str_replace('</blockquote></p>', '</p></blockquote>', $chunk);
- # $chunk = preg_replace('!<p>\s*(</?'. $block .'[^>]*>)!', "$1", $chunk);
- # $chunk = preg_replace('!(</?'. $block .'[^>]*>)\s*</p>!', "$1", $chunk);
- # $chunk = preg_replace('|(?<!<br />)\s*\n|', "<br />\n", $chunk); // make line breaks
- # $chunk = preg_replace('!(</?'. $block .'[^>]*>)\s*<br />!', "$1", $chunk);
- # $chunk = preg_replace('!<br />(\s*</?(?:p|li|div|th|pre|td|ul|ol)>)!', '$1', $chunk);
- # $chunk = preg_replace('/&([^#])(?![A-Za-z0-9]{0,7};)/', '&$1', $chunk);
- # }
- # $output .= $chunk;
- # }
- # return $output;
- #}
- def filter_autop_pad_with_newlines(text)
- # $chunk = preg_replace('|\n*$|', '', $chunk) ."\n\n"; // just to make things a little easier, pad the end
- (text.gsub(/\\\n*$/, '') + "\n\n")
- end
- def filter_autop_replace_break_pairs_with_newline_pairs(text)
- # $chunk = preg_replace('|<br />\s*<br />|', "\n\n", $chunk);
- text.gsub(/<br \/>\s*<br \/>/, "\n\n")
- end
- def filter_autop_newline_before_opening_tags(text)
- # $chunk = preg_replace('!(<'. $block .'[^>]*>)!', "\n$1", $chunk); // Space things out a little
- text.gsub(/(<#{filter_autop_block}[^>]*>)/, "\n\\1")
- end
- def filter_autop_two_newlines_after_closing_tags(text)
- # $chunk = preg_replace('!(</'. $block .'>)!', "$1\n\n", $chunk); // Space things out a little
- text.gsub(%r{(</#{filter_autop_block}>)}, "\\1\n\n")
- end
- def filter_autop_remove_extraneous_newlines(text)
- # $chunk = preg_replace("/\n\n+/", "\n\n", $chunk); // take care of duplicates
- text.gsub(/\n\n+/, "\n\n")
- end
- def filter_autop_add_paragraph_tags(text)
- # $chunk = preg_replace('/\n?(.+?)(?:\n\s*\n|\z)/s', "<p>$1</p>\n", $chunk); // make paragraphs, including one at the end
- #oregexp = Oniguruma::ORegexp.new(/\n?(.+?)(?:\n\s*\n|\z)/, :options => Oniguruma::OPTION_MULTILINE)
- text.gsub(/\n?(.+?)(?:\n\s*\n|\z)/m, "<p>\\1</p>\n")
- end
- def filter_autop_remove_empty_paragraphs(text)
- # $chunk = preg_replace('|<p>\s*?</p>|', '', $chunk); // under certain strange conditions it could create a P of entirely whitespace
- text.gsub(/<p>\s*?<\/p>/, '')
- end
- def filter_autop_remove_paragraph_tags_from_around_list_items(text)
- # $chunk = preg_replace("|<p>(<li.+?)</p>|", "$1", $chunk); // problem with nested lists
- text.gsub(/<p>(<li.+?)<\/p>/, "\\1")
- end
- def filter_autop_swap_adjacent_blockquote_and_paragraph_tags(text)
- # $chunk = preg_replace('|<p><blockquote([^>]*)>|i', "<blockquote$1><p>", $chunk);
- text.gsub(/<p><blockquote([^>]*)>/i, "<blockquote\\1><p>")
- end
- def filter_autop_swap_adjacent_blockquote_and_paragraph_end_tags(text)
- # $chunk = str_replace('</blockquote></p>', '</p></blockquote>', $chunk);
- text.gsub(/<\/blockquote><\/p>/i, '</p></blockquote>')
- end
- def filter_autop_remove_paragraph_open_tags_followed_by_whitespace_preceding_closing_block_tags(text)
- # $chunk = preg_replace('!<p>\s*(</?'. $block .'[^>]*>)!', "$1", $chunk);
- text.gsub(%r{<p>\s*(</?#{filter_autop_block}[^>]*>)}m, "\\1")
- end
- def filter_autop_remove_paragraph_closing_tags_preceded_by_whitespace_which_is_preceded_by_closing_block_tags(text)
- # $chunk = preg_replace('!(</?'. $block .'[^>]*>)\s*</p>!', "$1", $chunk);
- text.gsub(%r{(</?#{filter_autop_block}[^>]*>)\s*</p>}m, "\\1")
- end
- def filter_autop_match_any_sequence_of_whitespace_characters_followed_by_a_newline_not_preceded_by_a_break(text)
- # $chunk = preg_replace('|(?<!<br />)\s*\n|', "<br />\n", $chunk); // make line breaks
- # Because Ruby 1.8 Regexp does not support zero-width negative look-behind assertions! Duh!!!
- #oregexp = Oniguruma::ORegexp.new('(?<!<br />)\s*\n')
- text.gsub(/(?<!<br \/>)\s*\n/, "<br \/>\n")
- end
- def filter_autop_strip_whitespace_and_line_breaks_after_closing_tags(text)
- # $chunk = preg_replace('!(</?'. $block .'[^>]*>)\s*<br />!', "$1", $chunk);
- text.gsub(%r{(</?#{filter_autop_block}[^>]*>)\s*<br />}m, "\\1")
- end
- def filter_autop_remove_line_breaks_preceding_certain_closing_tags(text)
- # $chunk = preg_replace('!<br />(\s*</?(?:p|li|div|th|pre|td|ul|ol)>)!', '$1', $chunk);
- #oregexp = Oniguruma::ORegexp.new('<br />(\s*</?(?:p|li|div|th|pre|td|ul|ol)>)')
- text.gsub(/<br \/>(\s*<\/?(?:p|li|div|th|pre|td|ul|ol)>)/, "\\1")
- end
- def filter_autop_should_convert_ampersands_except_entity_references(text)
- # $chunk = preg_replace('/&([^#])(?![A-Za-z0-9]{0,7};)/', '&$1', $chunk);
- #oregexp = Oniguruma::ORegexp.new('&([^#])(?![A-Za-z0-9]{0,7};)')
- text.gsub(/&([^#])(?![A-Za-z0-9]{0,7};)/, "&\\1")
- end
- def filter_autop_block
- '(?:table|thead|tfoot|caption|colgroup|tbody|tr|td|th|div|dl|dd|dt|ul|ol|li|pre|select|form|blockquote|address|p|h[1-6])'
- end
- def filter_autop(text)
- chunks = text.gsub("\015\012","\n").split(/(<\/?(?:pre|script|style)[^>]*>)/i)
- ignore = false
- output = ''
- index = 1
- chunks.each do |chunk|
- if (index % 2 == 0)
- open = (chunk.index('/') != 1)
- if (!ignore && open)
- chunk.match(/<(.*)>/)
- ignore = true
- elsif !open
- ignore = false
- end
- elsif (!ignore)
- chunk = filter_autop_pad_with_newlines(chunk)
- chunk = filter_autop_replace_break_pairs_with_newline_pairs(chunk)
- chunk = filter_autop_newline_before_opening_tags(chunk)
- chunk = filter_autop_two_newlines_after_closing_tags(chunk)
- chunk = filter_autop_remove_extraneous_newlines(chunk)
- chunk = filter_autop_add_paragraph_tags(chunk)
- chunk = filter_autop_remove_empty_paragraphs(chunk)
- chunk = filter_autop_remove_paragraph_tags_from_around_list_items(chunk)
- chunk = filter_autop_swap_adjacent_blockquote_and_paragraph_tags(chunk)
- chunk = filter_autop_swap_adjacent_blockquote_and_paragraph_end_tags(chunk)
- chunk = filter_autop_remove_paragraph_open_tags_followed_by_whitespace_preceding_closing_block_tags(chunk)
- chunk = filter_autop_remove_paragraph_closing_tags_preceded_by_whitespace_which_is_preceded_by_closing_block_tags(chunk)
- chunk = filter_autop_match_any_sequence_of_whitespace_characters_followed_by_a_newline_not_preceded_by_a_break(chunk)
- chunk = filter_autop_strip_whitespace_and_line_breaks_after_closing_tags(chunk)
- chunk = filter_autop_remove_line_breaks_preceding_certain_closing_tags(chunk)
- chunk = filter_autop_should_convert_ampersands_except_entity_references(chunk)
- end
- output = output + chunk
- index = index + 1
- end
- output
- end
- # == filter_icons
- # Convert format of [icon: class="star-icon-blue" href="someplace" title="Multiple Choice Quiz"] to
- # <a href="someplace" title="Multiple Choice Quiz"><img alt="Multiple Choice Quiz" class="star-icon-blue" src="http://static.123teachme.com/images/spacer.gif"></a>
- # Overlays can be created as well using the "overlay" attribute and specifying the id of the overlay div.
- # This depends on jQuery TOOLS - http://flowplayer.org/tools/overlay/index.html
- def filter_icons(text)
- # inner function allowing attribute name/value pairs to be easily generated
- def attr_str(params, key, name=nil)
- name = key if !name
- return '' if !params[key] || params[key]==''
- return %Q{#{name}="#{params[key]}" }
- end
- # extract icon codes and replace with HTML
- text = text.gsub(/\[\s*icon\s*:\s*(.*?)\]/) do |match|
- p = {}
- $1.scan(/\s*(\w+)=(?:"|')(.*?)(?:"|')\s*/) do |m_array|
- attr = m_array[0]
- val = m_array[1]
- p[attr.strip]=val.strip
- #print "_#{attr}__#{val}_\n"
- end
- title=p['title']
- overlay=p['overlay']
- #%Q{<a href="#{p['href']}" title="#{title}"><img alt="#{title}" class="#{p['class']}" src="http://static.123teachme.com/images/spacer.gif"></a>}
- %Q{<a #{attr_str(p,'href')} #{attr_str(p,'title')}><img #{attr_str(p,'title', 'alt')} #{attr_str(p,'class')} #{attr_str(p, 'overlay', 'rel')} src="http://static.123teachme.com/images/spacer.gif"></a>}
- end
- text
- end
- # == insert_info_tip(text)
- # Inserts an info icon capable of triggering a tooltip.
- # Code in /app/views/contents/show.html.erb contains the actual tooltip HTML and javascript
- def insert_info_tip(text)
- regex = /(class="spanish-lesson".*?class="bottom">)/m
- # return un-altered if insertion point does not exist OR no icons are embedded on the page
- return text if !regex.match(text) || text !~ /class="#?[a-z]+-icon/i
- text.sub!(regex) do |match|
- insertion_text = %Q{<div style="float:right;"><img class="info-icon icon-tip-trigger" src="http://static.123teachme.com/images/spacer.gif"></div>}
- "#{match}#{insertion_text}"
- end
- text
- end
- # == general_function_filter(text)
- # Allows functions from ContentsHelper to be called directly from within CMS page.
- # Function must take a parameter hash, and return any output (or none at all).
- # Here is an example code that would be replaced with the return value of the
- # mythical function 'hello_world' in the ContentsHelper module:
- # [function:hello_world input="hello" key2="world"]
- # This creates a hash {'input'=>'hello', 'key2'=>'world'} and passes that as the sole parameter to the hello_world function.
- def general_function_filter(text)
- regex = %r{\[\s*function\s*:\s*(\w+)(?:\s+(.*?))?\]}iu
- return text if !text || !regex.match(text)
- text.gsub(regex) do |match|
- params = {}
- func = $1
- if $2
- $2.scan(/\s*(\w+)=(?:"|')(.*?)(?:"|')\s*/) do |m_array|
- attr = m_array[0]
- val = m_array[1]
- params[attr.strip]=val.strip
- #print "_#{attr}__#{val}_\n"
- end
- end
- output = ''
- begin
- output = self.send(func, params) || ''
- rescue => e
- ::Rails.logger.warn(e.to_s)
- end
- output.to_s
- end
- end
- ####################################################### custom functions for general_function_filter
- # Just an example for testing -- prints out the number of key/value pairs
- def my_func(params)
- params.length
- end
- def previous_and_next_links(content)
- return '' if !content.previous_page && !content.next_page
- prev_url = clean_prev_next_url(content.previous_page)
- next_url = clean_prev_next_url(content.next_page)
- html = %Q{<div class="previous-and-next bigger-previous-and-next" >}
- if prev_url && prev_url.length > 1
- html += %Q{
- <div style="float:left"><a href="#{prev_url}"><img src="http://static.123teachme.com/images/icons/silk_icons/resultset_previous.png" /></a>
- <a href="#{prev_url}">Previous</a></div>
- }
- end
- if next_url && next_url.length > 1
- html += %Q{
- <div style="float:right"><a href="#{next_url}">Next</a>
- <a href="#{next_url}"><img src="http://static.123teachme.com/images/icons/silk_icons/resultset_next.png" /></a></div>
- }
- end
- html += "</div>"
- html
- end
- def clean_prev_next_url(page)
- return nil if !page
- if page =~ /^\w/
- return "/learn_spanish/" + page
- else
- return page
- end
- end
- end