'''  syntax:  python untextile.py [WP-CONFIG]

Replace Textile-formatted Wordpress posts with the plain HTML equivalent.
The optional argument is the name of Wordpress' wp-config.php file.
[Copyright (c) Alex Tingle, 2008. Released under GPL v2+]
'''

import MySQLdb, textile, re, sys, os.path

_more_literal     = '<!--more-->'
_more_placeholder = '.abc123MORE321cba.'


def untextile(db,table_prefix='wp_'):
  '''Replace Textile-formatted Wordpress posts with the plain HTML equivalent.
       db - a database object (made with MySQLdb.connect() )
       table_prefix - the Wordpress table prefix [DEFAULT: wp_]'''
  cin  = db.cursor()
  cout = db.cursor()
  wp_posts = table_prefix + 'posts'
  cin.execute('SELECT ID,post_content FROM '+wp_posts)
  while True:
    row = cin.fetchone()
    if not row:
      break
    print 'Converting post:',row[0]
    # Note WP's 'more' tag gets corrupted by textile.
    text = row[1].replace(_more_literal,_more_placeholder)
    text = textile.textile(text)
    text = text.replace(_more_placeholder,_more_literal)
    cout.execute(
        "UPDATE %s SET post_content='%s' WHERE ID=%i" % \
        ( wp_posts, db.escape_string(text), row[0] )
      )
  cin.close()
  cout.close()


class WpConfig(object):
  def __init__(self,filename='wp-config.php'):
      self.filename=filename
      self.db_params = {}
      self.table_prefix = 'wp_'

  def read(self):
      '''Extract the table_prefix from Wordpress' wp-config.php file, and
         place then in a dictionary, ready to be passed to MySQLdb.connect().'''
      mapping = {
          'DB_NAME'    :'db',
          'DB_USER'    :'user',
          'DB_PASSWORD':'passwd',
          'DB_HOST'    :'host',
        }
      xDbDefine = re.compile(
        r"^\s*define\s*\(\s*'(?P<key>DB_[A-Z]+)'\s*,\s*'(?P<val>\w+)'\s*\)\s*;")
      xTablePrefix = re.compile(
        r"^\s*\$table_prefix\s*=\s*'(\w+)'\s*;")
      f = file(self.filename)
      while(True):
        line = f.readline()
        if not line:
          break
        match = xDbDefine.match(line)
        if match:
          key = match.group('key')
          if key in mapping:
            self.db_params[ mapping[key] ] = match.group('val')
        match = xTablePrefix.match(line)
        if match:
          self.table_prefix = match.group(1)


if __name__=='__main__':
  if len(sys.argv)>1:
    wpconfig = WpConfig( sys.argv[1] )
  else:
    wpconfig = WpConfig()
  if not os.path.exists(wpconfig.filename):
    print "Can't find file " + wpconfig.filename
    sys.exit(1)
  wpconfig.read()
  db=MySQLdb.connect(**wpconfig.db_params)
  untextile(db,wpconfig.table_prefix)
