require 'digest/sha1'
require 'logger' 
require 'ftools'
require 'cgi'

#--######################################################################
# Copyright (c) 2006 Logica
# 
# All rights reserved. This program and the accompanying materials
# are made available under the terms of the Eclipse Public License v1.0
# which accompanies this distribution, and is available at
# http://www.eclipse.org/legal/epl-v10.html
#
# Contributors:
# 
# Onno van der Straaten:: initial implementation
#++######################################################################
# {Copyright (c) 2006 Logica}[link:files/COPYRIGHT.html]

EPFWIKI_CSDIFF_PATH = "\"" + File.expand_path(RAILS_ROOT) + "/script/other/CSDiff/CSDiff.exe\""
FLASH_RECORD_UPDATED = "Record updated!"
FLASH_RECORD_CREATED = "Record created!"
FLASH_RECORD_DELETED = "Record deleted!"
FLASH_USE_POST_NOT_GET = 'The action does not allow a GET request, a POST request should be used'
FLASH_NOT_OWNER = "This record was created by someone else, it can only be modified by the user that created it."

MSG_EMAIL_SERVER_GENERATED = "**This message was generated by a server. Don't reply to this address.**"

REMOVE_PATTERN1 = /<script([^\<])*(ContentPageResource|ContentPageSection|ContentPageToolbar|contentPage\.preload|contentPage\.js|ContentPageSubSection|steps\.js|backPath =)([^\<])*<\/script>/mi

def create_cookie(theUser)
  cookies[:epfwiki_id] = {:value => theUser.id.to_s, :expires => Time.now+31536000}
  cookies[:epfwiki_token] = {:value => hash_pw(theUser.hashed_password),:expires => Time.now+31536000}
end

def expire_cookie
  cookies.delete :epfwiki_id
  cookies.delete :epfwiki_token
end

def notify_cadmin
  Notifier::deliver_env_to(User.find_central_admin, session.instance_variable_get("@data"), params, request.env, nil)
end

def job_monthly_report
  Notifier::deliver_summary(:type => 'M', :host => ENV['EPFWIKI_HOST'])
end

def job_weekly_report
  Notifier::deliver_summary(:type => 'W', :host => ENV['EPFWIKI_HOST'])
end

def job_daily_report
  Notifier::deliver_summary(:type => 'D', :host => ENV['EPFWIKI_HOST'])
end

def wrap_text(txt, col = 80)
  txt.gsub(/(.{1,#{col}})( +|$\n?)|(.{1,#{col}})/,
    "\\1\\3\n") 
end

def buildid(time)
  return time.strftime("%Y%m%d_%H%M")
end

def valid_filename(filename)
  filename.downcase.delete("&+-.\"/\[]:;=,\\").tr(' ','_')
end

def email_addresses_4_report(users)
  if  users.class.to_s == "User"
    return users.email
  else
    recipients = Array.new
    for user in users
      recipients = user.email if !recipients
      recipients << user.email
    end
    return recipients
  end
end

def mine?(theRecord)
  return (theRecord.id == session['user'].id) if (theRecord.class.to_s == "User")
  return (theRecord.user_id == session['user'].id)
end

def admin?
  return session['user'].admin? if session['user']
  return false
end

def user?
  return !session['user'].nil?
end

def cadmin?
  return (session['user'].admin == "C") if session['user']
  return false
end

# HTML Tidy Configuration Options see http://tidy.sourceforge.net/docs/quickref.html
# Ruby Interface on SuSE linux does not seem to work. Causes a segmentation fault.
# If this is fixed we can start using it again instead of the current #tidy_file. 
# To be able to use this we should add the EPFWIKI_TIDY_PATH environment variable.
# Examples:
# ENV['EPFWIKI_TIDY_PATH'] = '/usr/lib/libtidy.so'
# ENV['EPFWIKI_TIDY_PATH'] = ENV['EPFWIKI_ROOT_DIR'] + "vendor/tidy/bin/tidy.dll"
def tidy_file_segfaults_on_SuSE_Linux(path)
  require 'tidy'
  Tidy.path = ENV['EPFWIKI_TIDY_PATH'] 
  html = IO.readlines(path).join
  xml = Tidy.open(:show_warnings=>true) do |tidy|
    tidy.options.indent = 'auto' # auto won't indent title, li elements
    tidy.options.quote_ampersand = false # TODO is Tidy ignoring this option
    tidy.options.output_encoding = 'utf8'
    tidy.options.input_encoding = 'utf8'
    tidy.options.char_encoding = 'utf8'
    tidy.options.output_xhtml = true 
    tidy.options.vertical_space = 0
    tidy.options.wrap = 0
    tidy.options.quote_nbsp = 1
    tidy.options.tidy_mark = 0
    tidy.options.doctype = 'omit' # Prevent Tidy from adding some old doctype 
    
    # tidy.options.sort_attributes = 'alpha' #
    # the current version supports sort_attributes but unfortunatly there is no dll distribution, only an exe
    # TODO integrate new tidy dll when it is available. Note: this will improve generated diffs with xhtmldiff
    
    xml = tidy.clean(html)
    xml
    outFile = File.new(path, "w")
    outFile.puts(xml)
    outFile.close
    #puts tidy.errors
    #puts tidy.diagnostics       
  end
end

# HTML Tidy Configuration Options see http://tidy.sourceforge.net/docs/quickref.html
# TODO tidy causes message in console "caution:  both -n and -o specified; ignoring -o"
# TODO suppres tidy output in console. Is this possible?
def tidy_file(path)
    cmdline = "tidy -m -config \"#{File.expand_path(RAILS_ROOT)}/config/tidy.cfg\" \"#{path}\""
    RAILS_DEFAULT_LOGGER.info("HTML Tidy file with command #{cmdline}")
    cmd = IO.popen(cmdline, "w+") 
    cmd.close_write
    RAILS_DEFAULT_LOGGER.debug("HTML Tidy output: #{cmd.readlines.join}")
end

def db_script_version(path2migratefolder)
  files = Dir.entries(path2migratefolder)  - [".", ".."]
  version = 0
  files.each { |file| version = file.split("_")[0].to_i if file.split("_")[0].to_i > version } 
  return version
end

def write_log(logfilename, content)
  aOutputFile = File.new("#{ENV['EPFWIKI_ROOT_DIR']}log/#{logfilename}", "w")
  aOutputFile.puts(content)
  aOutputFile.close       
end

def hash_pw(pw)
  return Digest::SHA1.hexdigest(pw || '') 
end

# Schedule a job to run #job_daily. Schedule this job to run at night if 
# your sites are large (pages in the thousands). Under Windows this could be
# Scheduled Task to run from the app root the following command:
# ruby script/runner -e production 'job_daily'
# NOTE: ENV['EPFWIKI_HOST'] env variable is needed, because in a job we don't know the host
def job_daily

  @cadmin = User.find_central_admin
  
  BaselineProcess.find_2scan.each do |bp|
    bp.scan4content
  end
  
  expired_by_update = false
  Update.find_todo.each do |update|
    update.do_update
    expired_by_update = true
  end
  
  expire_all_pages unless expired_by_update
  
rescue => e
  Notifier::deliver_email(User.find_central_admin, 'Error running job_daily', [], e.message + "\n" + e.backtrace.join("\n"))
end

def expire_all_pages
  # expire cached pages
  FileUtils.rm_rf File.expand_path("public/index.html", RAILS_ROOT)
  FileUtils.rm_rf File.expand_path("public/portal/home.html", RAILS_ROOT)
  FileUtils.rm_rf File.expand_path("public/portal/about.html", RAILS_ROOT)
  #FileUtils.rm_rf File.expand_path("public/portal/search.html", RAILS_ROOT)
  FileUtils.rm_rf File.expand_path("public/portal/wikis.html", RAILS_ROOT)
  FileUtils.rm_rf File.expand_path("public/portal/users.html", RAILS_ROOT)  
  FileUtils.rm_rf File.expand_path("public/portal/privacypolicy.html", RAILS_ROOT)  
  FileUtils.rm_rf File.expand_path("public/portal/termsofuse.html", RAILS_ROOT)  
  
  # remove cache folders 
  ['public/archives', 'public/pages/view', 'public/rss'].each do |f|
    p = File.expand_path(f, RAILS_ROOT)
    FileUtils.rm_r(p) if File.exists?(p)
  end
  
end