demo-teachme /app/helpers/contents_helper.rb

Language Ruby Lines 404
MD5 Hash ae3f7121b107e7e57af76b97e7740a7a Estimated Cost $5,563 (why?)
Repository https://bitbucket.org/kapilnakhwa/demo-teachme.git View Raw File
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
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};)/', '&amp;$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};)/', '&amp;$1', $chunk);
    #oregexp = Oniguruma::ORegexp.new('&([^#])(?![A-Za-z0-9]{0,7};)')
    text.gsub(/&([^#])(?![A-Za-z0-9]{0,7};)/, "&amp;\\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
Back to Top