PageRenderTime 51ms CodeModel.GetById 22ms RepoModel.GetById 0ms app.codeStats 1ms

/app/helpers/contents_helper.rb

https://bitbucket.org/kapilnakhwa/demo-teachme
Ruby | 403 lines | 222 code | 34 blank | 147 comment | 32 complexity | ae3f7121b107e7e57af76b97e7740a7a MD5 | raw file
  1. module ContentsHelper
  2. # Drupal Filters
  3. #function do_flv($text){
  4. # $pattern = '/\[flvplayer\s+src="([A-Za-z0-9-_\.]+)"\s+width="(\d+)"\s+height="(\d+)"([^\]]*)\]/mi';
  5. # $replacement = '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" type="application/x-shockwave-flash" width="${2}" height="${3}" wmode="transparent" ' .
  6. # 'data="/tmcontent/flvplayer.swf?file=videos/${1}&autoStart=false">' .
  7. # '<param name="movie" value="/tmcontent/flvplayer.swf?file=videos/${1}&autoStart=false" />' .
  8. # '<param name="wmode" value="transparent" />' .
  9. # '<embed src="/tmcontent/flvplayer.swf?file=videos/${1}&autoStart=false" ' .
  10. # 'type="application/x-shockwave-flash" width="${2}" height="${3}"></embed></object>';
  11. # return preg_replace($pattern, $replacement, $text);
  12. #}
  13. def do_flv(text)
  14. 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">' +
  15. '<param name="movie" value="/tmcontent/flvplayer.swf?file=videos/\1&autoStart=false" />' +
  16. '<param name="wmode" value="transparent" />' +
  17. '<embed src="/tmcontent/flvplayer.swf?file=videos/\1&autoStart=false" type="application/x-shockwave-flash" width="\2" height="\3"></embed>' +
  18. '</object>'
  19. text.gsub(/\[flvplayer\s+src="([A-Za-z0-9\-_\.]+)"\s+width="(\d+)"\s+height="(\d+)"([^\]]*)\]/, output)
  20. end
  21. #function do_tmreplace($text){
  22. # $KEYWORDS_PRIMARY = '/\[keywords_primary:([^\]]*)\]/mi';
  23. # $KEYWORDS_SECONDARY = '/\[keywords_secondary:([^\]]*)\]/mi';
  24. # $replace = '';
  25. # $new_text = preg_replace($KEYWORDS_PRIMARY, $replace, $text);
  26. # $new_text = preg_replace($KEYWORDS_SECONDARY, $replace, $new_text);
  27. # // insert sound link
  28. # $SOUND_LINK = '/\[sound(_|-)link:([^\]]*)\]/mi';
  29. # $replace = '<a href="${2}" onclick="play(this.href); return false;">' .
  30. # '<img alt="Sound" border="0" src="/cms_images/hear.gif" /></a>';
  31. # $new_text = preg_replace($SOUND_LINK, $replace, $new_text);
  32. # /// reference static server for images
  33. # $CMS_LINK = '%src="(http://(www.)?123teachme.com)?/cms_images%mi';
  34. # $replace = 'src="http://static.123teachme.com/cms_images';
  35. # $new_text = preg_replace($CMS_LINK, $replace, $new_text);
  36. # $IMG_LINK = '%src="(http://(www.)?123teachme.com)?/images/%mi';
  37. # $replace = 'src="http://static.123teachme.com/images/';
  38. # $new_text = preg_replace($IMG_LINK, $replace, $new_text);
  39. # return $new_text;
  40. #}
  41. def do_tmreplace(text)
  42. output = do_tmreplace_keywords_primary(text)
  43. output = do_tmreplace_keywords_secondary(output)
  44. output = do_tmreplace_sound_link(output)
  45. output = do_tmreplace_long_sound_link(output)
  46. output = do_tmreplace_static_link(output)
  47. end
  48. def do_tmreplace_keywords_primary(text)
  49. text.gsub(/(\[keywords_primary:)([^\]]*)(\])/mi, '')
  50. end
  51. def do_tmreplace_keywords_secondary(text)
  52. text.gsub(/(\[keywords_secondary:)([^\]]*)(\])/mi, '')
  53. end
  54. def do_tmreplace_sound_link(text)
  55. sound_link = Regexp.new('\[sound[-_]link:([^\]]*)\]', (Regexp::IGNORECASE || Regexp::MULTILINE))
  56. while match = text.match(sound_link) do
  57. link = match[1]
  58. replacement = %{<a href="#{link}" onclick="play(this.href); return false;"><img border="0" src="/cms_images/hear.gif" /></a>}
  59. text.gsub!(match[0], replacement)
  60. end
  61. text
  62. end
  63. def do_tmreplace_long_sound_link(text)
  64. #replaces long_sound_link:title:url or long_sound_link:url
  65. long_sound_link = Regexp.new('\[long[-_]sound[-_]link:([^:]+:)?([^\]]*)\]', (Regexp::IGNORECASE || Regexp::MULTILINE))
  66. while match = text.match(long_sound_link) do
  67. label = match[1]
  68. link = match[2]
  69. if (!label.blank?) then label=label.chop end
  70. if (label.blank?) then label="Audio Link" end
  71. label=CGI::escapeHTML(label)
  72. replacement = %{<a href="#{link}" class="long-sound-link" onclick="playLongSound(this.href,this); return false;">#{label}</a>}
  73. text.gsub!(match[0], replacement)
  74. end
  75. text
  76. end
  77. def do_tmreplace_static_link(text)
  78. # dev note: to parallelize downloads, multiple static hosts are used
  79. # but same path should ALWAYS map to same host to allow better caching
  80. # algorithm: get ascii value of 7th char from end of path. return 1 for even 2 for odd
  81. text.gsub(%r{(src="(http://(www.)?123teachme.com)?/)(cms_){0,1}(images)([^"]*)}mi) do |match|
  82. num = 3
  83. path = $6 || ''
  84. num = path[-7].ord%2 + 1 if path && path.length > 7
  85. %Q{src="http://static#{num}.123teachme.com/#{$4}images#{$6}}
  86. end
  87. #rand_int = rand(2) + 1 # 1 or 2
  88. #replacement = %Q{src="http://static#{rand_int}.123teachme.com/\\4images}
  89. #text.gsub(%r{(src="(http://(www.)?123teachme.com)?/)(cms_){0,1}(images)}mi, replacement)
  90. end
  91. # THE FOLLOWING FUNCTION IS DUPLICATED WITHIN THE DO_TMREPLACE FUNCTION.
  92. #function do_static($text){
  93. # //$CMS_LINK = '%src="http://(www\.)?123teachme.com/cms_images%i'; // using % instead of /
  94. # $CMS_LINK = '/src="http:\/\/www.123teachme.com\/cms_images/i';
  95. # $replace = 'src="http://static.123teachme.com/cms_images';
  96. # $new_text = preg_replace($CMS_LINK, $replace, $text);
  97. # return $new_text;
  98. #}
  99. #/**
  100. # * Convert line breaks into <p> and <br> in an intelligent fashion.
  101. # * Based on: http://photomatt.net/scripts/autop
  102. # */
  103. #function _filter_autop($text) {
  104. # // All block level tags
  105. # $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])';
  106. #
  107. # // Split at <pre>, <script>, <style> and </pre>, </script>, </style> tags.
  108. # // We don't apply any processing to the contents of these tags to avoid messing
  109. # // up code. We look for matched pairs and allow basic nesting. For example:
  110. # // "processed <pre> ignored <script> ignored </script> ignored </pre> processed"
  111. # $chunks = preg_split('@(</?(?:pre|script|style)[^>]*>)@i', $text, -1, PREG_SPLIT_DELIM_CAPTURE);
  112. # // Note: PHP ensures the array consists of alternating delimiters and literals
  113. # // and begins and ends with a literal (inserting NULL as required).
  114. # $ignore = false;
  115. # $ignoretag = '';
  116. # $output = '';
  117. # foreach ($chunks as $i => $chunk) {
  118. # if ($i % 2) {
  119. # // Opening or closing tag?
  120. # $open = ($chunk{1} != '/');
  121. # list($tag) = split('[ >]', substr($chunk, 2 - $open), 2);
  122. # if (!$ignore) {
  123. # if ($open) {
  124. # $ignore = true;
  125. # $ignoretag = $tag;
  126. # }
  127. # }
  128. # // Only allow a matching tag to close it.
  129. # else if (!$open && $ignoretag == $tag) {
  130. # $ignore = false;
  131. # $ignoretag = '';
  132. # }
  133. # }
  134. # else if (!$ignore) {
  135. # $chunk = preg_replace('|\n*$|', '', $chunk) ."\n\n"; // just to make things a little easier, pad the end
  136. # $chunk = preg_replace('|<br />\s*<br />|', "\n\n", $chunk);
  137. # $chunk = preg_replace('!(<'. $block .'[^>]*>)!', "\n$1", $chunk); // Space things out a little
  138. # $chunk = preg_replace('!(</'. $block .'>)!', "$1\n\n", $chunk); // Space things out a little
  139. # $chunk = preg_replace("/\n\n+/", "\n\n", $chunk); // take care of duplicates
  140. # $chunk = preg_replace('/\n?(.+?)(?:\n\s*\n|\z)/s', "<p>$1</p>\n", $chunk); // make paragraphs, including one at the end
  141. # $chunk = preg_replace('|<p>\s*?</p>|', '', $chunk); // under certain strange conditions it could create a P of entirely whitespace
  142. # $chunk = preg_replace("|<p>(<li.+?)</p>|", "$1", $chunk); // problem with nested lists
  143. # $chunk = preg_replace('|<p><blockquote([^>]*)>|i', "<blockquote$1><p>", $chunk);
  144. # $chunk = str_replace('</blockquote></p>', '</p></blockquote>', $chunk);
  145. # $chunk = preg_replace('!<p>\s*(</?'. $block .'[^>]*>)!', "$1", $chunk);
  146. # $chunk = preg_replace('!(</?'. $block .'[^>]*>)\s*</p>!', "$1", $chunk);
  147. # $chunk = preg_replace('|(?<!<br />)\s*\n|', "<br />\n", $chunk); // make line breaks
  148. # $chunk = preg_replace('!(</?'. $block .'[^>]*>)\s*<br />!', "$1", $chunk);
  149. # $chunk = preg_replace('!<br />(\s*</?(?:p|li|div|th|pre|td|ul|ol)>)!', '$1', $chunk);
  150. # $chunk = preg_replace('/&([^#])(?![A-Za-z0-9]{0,7};)/', '&amp;$1', $chunk);
  151. # }
  152. # $output .= $chunk;
  153. # }
  154. # return $output;
  155. #}
  156. def filter_autop_pad_with_newlines(text)
  157. # $chunk = preg_replace('|\n*$|', '', $chunk) ."\n\n"; // just to make things a little easier, pad the end
  158. (text.gsub(/\\\n*$/, '') + "\n\n")
  159. end
  160. def filter_autop_replace_break_pairs_with_newline_pairs(text)
  161. # $chunk = preg_replace('|<br />\s*<br />|', "\n\n", $chunk);
  162. text.gsub(/<br \/>\s*<br \/>/, "\n\n")
  163. end
  164. def filter_autop_newline_before_opening_tags(text)
  165. # $chunk = preg_replace('!(<'. $block .'[^>]*>)!', "\n$1", $chunk); // Space things out a little
  166. text.gsub(/(<#{filter_autop_block}[^>]*>)/, "\n\\1")
  167. end
  168. def filter_autop_two_newlines_after_closing_tags(text)
  169. # $chunk = preg_replace('!(</'. $block .'>)!', "$1\n\n", $chunk); // Space things out a little
  170. text.gsub(%r{(</#{filter_autop_block}>)}, "\\1\n\n")
  171. end
  172. def filter_autop_remove_extraneous_newlines(text)
  173. # $chunk = preg_replace("/\n\n+/", "\n\n", $chunk); // take care of duplicates
  174. text.gsub(/\n\n+/, "\n\n")
  175. end
  176. def filter_autop_add_paragraph_tags(text)
  177. # $chunk = preg_replace('/\n?(.+?)(?:\n\s*\n|\z)/s', "<p>$1</p>\n", $chunk); // make paragraphs, including one at the end
  178. #oregexp = Oniguruma::ORegexp.new(/\n?(.+?)(?:\n\s*\n|\z)/, :options => Oniguruma::OPTION_MULTILINE)
  179. text.gsub(/\n?(.+?)(?:\n\s*\n|\z)/m, "<p>\\1</p>\n")
  180. end
  181. def filter_autop_remove_empty_paragraphs(text)
  182. # $chunk = preg_replace('|<p>\s*?</p>|', '', $chunk); // under certain strange conditions it could create a P of entirely whitespace
  183. text.gsub(/<p>\s*?<\/p>/, '')
  184. end
  185. def filter_autop_remove_paragraph_tags_from_around_list_items(text)
  186. # $chunk = preg_replace("|<p>(<li.+?)</p>|", "$1", $chunk); // problem with nested lists
  187. text.gsub(/<p>(<li.+?)<\/p>/, "\\1")
  188. end
  189. def filter_autop_swap_adjacent_blockquote_and_paragraph_tags(text)
  190. # $chunk = preg_replace('|<p><blockquote([^>]*)>|i', "<blockquote$1><p>", $chunk);
  191. text.gsub(/<p><blockquote([^>]*)>/i, "<blockquote\\1><p>")
  192. end
  193. def filter_autop_swap_adjacent_blockquote_and_paragraph_end_tags(text)
  194. # $chunk = str_replace('</blockquote></p>', '</p></blockquote>', $chunk);
  195. text.gsub(/<\/blockquote><\/p>/i, '</p></blockquote>')
  196. end
  197. def filter_autop_remove_paragraph_open_tags_followed_by_whitespace_preceding_closing_block_tags(text)
  198. # $chunk = preg_replace('!<p>\s*(</?'. $block .'[^>]*>)!', "$1", $chunk);
  199. text.gsub(%r{<p>\s*(</?#{filter_autop_block}[^>]*>)}m, "\\1")
  200. end
  201. def filter_autop_remove_paragraph_closing_tags_preceded_by_whitespace_which_is_preceded_by_closing_block_tags(text)
  202. # $chunk = preg_replace('!(</?'. $block .'[^>]*>)\s*</p>!', "$1", $chunk);
  203. text.gsub(%r{(</?#{filter_autop_block}[^>]*>)\s*</p>}m, "\\1")
  204. end
  205. def filter_autop_match_any_sequence_of_whitespace_characters_followed_by_a_newline_not_preceded_by_a_break(text)
  206. # $chunk = preg_replace('|(?<!<br />)\s*\n|', "<br />\n", $chunk); // make line breaks
  207. # Because Ruby 1.8 Regexp does not support zero-width negative look-behind assertions! Duh!!!
  208. #oregexp = Oniguruma::ORegexp.new('(?<!<br />)\s*\n')
  209. text.gsub(/(?<!<br \/>)\s*\n/, "<br \/>\n")
  210. end
  211. def filter_autop_strip_whitespace_and_line_breaks_after_closing_tags(text)
  212. # $chunk = preg_replace('!(</?'. $block .'[^>]*>)\s*<br />!', "$1", $chunk);
  213. text.gsub(%r{(</?#{filter_autop_block}[^>]*>)\s*<br />}m, "\\1")
  214. end
  215. def filter_autop_remove_line_breaks_preceding_certain_closing_tags(text)
  216. # $chunk = preg_replace('!<br />(\s*</?(?:p|li|div|th|pre|td|ul|ol)>)!', '$1', $chunk);
  217. #oregexp = Oniguruma::ORegexp.new('<br />(\s*</?(?:p|li|div|th|pre|td|ul|ol)>)')
  218. text.gsub(/<br \/>(\s*<\/?(?:p|li|div|th|pre|td|ul|ol)>)/, "\\1")
  219. end
  220. def filter_autop_should_convert_ampersands_except_entity_references(text)
  221. # $chunk = preg_replace('/&([^#])(?![A-Za-z0-9]{0,7};)/', '&amp;$1', $chunk);
  222. #oregexp = Oniguruma::ORegexp.new('&([^#])(?![A-Za-z0-9]{0,7};)')
  223. text.gsub(/&([^#])(?![A-Za-z0-9]{0,7};)/, "&amp;\\1")
  224. end
  225. def filter_autop_block
  226. '(?: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])'
  227. end
  228. def filter_autop(text)
  229. chunks = text.gsub("\015\012","\n").split(/(<\/?(?:pre|script|style)[^>]*>)/i)
  230. ignore = false
  231. output = ''
  232. index = 1
  233. chunks.each do |chunk|
  234. if (index % 2 == 0)
  235. open = (chunk.index('/') != 1)
  236. if (!ignore && open)
  237. chunk.match(/<(.*)>/)
  238. ignore = true
  239. elsif !open
  240. ignore = false
  241. end
  242. elsif (!ignore)
  243. chunk = filter_autop_pad_with_newlines(chunk)
  244. chunk = filter_autop_replace_break_pairs_with_newline_pairs(chunk)
  245. chunk = filter_autop_newline_before_opening_tags(chunk)
  246. chunk = filter_autop_two_newlines_after_closing_tags(chunk)
  247. chunk = filter_autop_remove_extraneous_newlines(chunk)
  248. chunk = filter_autop_add_paragraph_tags(chunk)
  249. chunk = filter_autop_remove_empty_paragraphs(chunk)
  250. chunk = filter_autop_remove_paragraph_tags_from_around_list_items(chunk)
  251. chunk = filter_autop_swap_adjacent_blockquote_and_paragraph_tags(chunk)
  252. chunk = filter_autop_swap_adjacent_blockquote_and_paragraph_end_tags(chunk)
  253. chunk = filter_autop_remove_paragraph_open_tags_followed_by_whitespace_preceding_closing_block_tags(chunk)
  254. chunk = filter_autop_remove_paragraph_closing_tags_preceded_by_whitespace_which_is_preceded_by_closing_block_tags(chunk)
  255. chunk = filter_autop_match_any_sequence_of_whitespace_characters_followed_by_a_newline_not_preceded_by_a_break(chunk)
  256. chunk = filter_autop_strip_whitespace_and_line_breaks_after_closing_tags(chunk)
  257. chunk = filter_autop_remove_line_breaks_preceding_certain_closing_tags(chunk)
  258. chunk = filter_autop_should_convert_ampersands_except_entity_references(chunk)
  259. end
  260. output = output + chunk
  261. index = index + 1
  262. end
  263. output
  264. end
  265. # == filter_icons
  266. # Convert format of [icon: class="star-icon-blue" href="someplace" title="Multiple Choice Quiz"] to
  267. # <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>
  268. # Overlays can be created as well using the "overlay" attribute and specifying the id of the overlay div.
  269. # This depends on jQuery TOOLS - http://flowplayer.org/tools/overlay/index.html
  270. def filter_icons(text)
  271. # inner function allowing attribute name/value pairs to be easily generated
  272. def attr_str(params, key, name=nil)
  273. name = key if !name
  274. return '' if !params[key] || params[key]==''
  275. return %Q{#{name}="#{params[key]}" }
  276. end
  277. # extract icon codes and replace with HTML
  278. text = text.gsub(/\[\s*icon\s*:\s*(.*?)\]/) do |match|
  279. p = {}
  280. $1.scan(/\s*(\w+)=(?:"|')(.*?)(?:"|')\s*/) do |m_array|
  281. attr = m_array[0]
  282. val = m_array[1]
  283. p[attr.strip]=val.strip
  284. #print "_#{attr}__#{val}_\n"
  285. end
  286. title=p['title']
  287. overlay=p['overlay']
  288. #%Q{<a href="#{p['href']}" title="#{title}"><img alt="#{title}" class="#{p['class']}" src="http://static.123teachme.com/images/spacer.gif"></a>}
  289. %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>}
  290. end
  291. text
  292. end
  293. # == insert_info_tip(text)
  294. # Inserts an info icon capable of triggering a tooltip.
  295. # Code in /app/views/contents/show.html.erb contains the actual tooltip HTML and javascript
  296. def insert_info_tip(text)
  297. regex = /(class="spanish-lesson".*?class="bottom">)/m
  298. # return un-altered if insertion point does not exist OR no icons are embedded on the page
  299. return text if !regex.match(text) || text !~ /class="#?[a-z]+-icon/i
  300. text.sub!(regex) do |match|
  301. insertion_text = %Q{<div style="float:right;"><img class="info-icon icon-tip-trigger" src="http://static.123teachme.com/images/spacer.gif"></div>}
  302. "#{match}#{insertion_text}"
  303. end
  304. text
  305. end
  306. # == general_function_filter(text)
  307. # Allows functions from ContentsHelper to be called directly from within CMS page.
  308. # Function must take a parameter hash, and return any output (or none at all).
  309. # Here is an example code that would be replaced with the return value of the
  310. # mythical function 'hello_world' in the ContentsHelper module:
  311. # [function:hello_world input="hello" key2="world"]
  312. # This creates a hash {'input'=>'hello', 'key2'=>'world'} and passes that as the sole parameter to the hello_world function.
  313. def general_function_filter(text)
  314. regex = %r{\[\s*function\s*:\s*(\w+)(?:\s+(.*?))?\]}iu
  315. return text if !text || !regex.match(text)
  316. text.gsub(regex) do |match|
  317. params = {}
  318. func = $1
  319. if $2
  320. $2.scan(/\s*(\w+)=(?:"|')(.*?)(?:"|')\s*/) do |m_array|
  321. attr = m_array[0]
  322. val = m_array[1]
  323. params[attr.strip]=val.strip
  324. #print "_#{attr}__#{val}_\n"
  325. end
  326. end
  327. output = ''
  328. begin
  329. output = self.send(func, params) || ''
  330. rescue => e
  331. ::Rails.logger.warn(e.to_s)
  332. end
  333. output.to_s
  334. end
  335. end
  336. ####################################################### custom functions for general_function_filter
  337. # Just an example for testing -- prints out the number of key/value pairs
  338. def my_func(params)
  339. params.length
  340. end
  341. def previous_and_next_links(content)
  342. return '' if !content.previous_page && !content.next_page
  343. prev_url = clean_prev_next_url(content.previous_page)
  344. next_url = clean_prev_next_url(content.next_page)
  345. html = %Q{<div class="previous-and-next bigger-previous-and-next" >}
  346. if prev_url && prev_url.length > 1
  347. html += %Q{
  348. <div style="float:left"><a href="#{prev_url}"><img src="http://static.123teachme.com/images/icons/silk_icons/resultset_previous.png" /></a>
  349. <a href="#{prev_url}">Previous</a></div>
  350. }
  351. end
  352. if next_url && next_url.length > 1
  353. html += %Q{
  354. <div style="float:right"><a href="#{next_url}">Next</a>
  355. <a href="#{next_url}"><img src="http://static.123teachme.com/images/icons/silk_icons/resultset_next.png" /></a></div>
  356. }
  357. end
  358. html += "</div>"
  359. html
  360. end
  361. def clean_prev_next_url(page)
  362. return nil if !page
  363. if page =~ /^\w/
  364. return "/learn_spanish/" + page
  365. else
  366. return page
  367. end
  368. end
  369. end