Sep 18

NextGen Gallery SQL script (to scan folders and add them as galleries)

Tags: , , , , , , , , Ignace Mouzannar (ghantoos) @ 5:51 pm

This time I needed this time to provision the NextGen SQL database with all the folders I’ve put on my server.

Again, i did a little python script. I scans your NextGen gallery folder, and enters all new folders as “galleries” in the SQL DB, and creates the thumbs for the pictures.

This was usefull for me. : )

You can download the script here.

#!/usr/bin/env python
#
# Dependencies:
#         - ImageMagick (for Ubuntu user, sudo apt-get install imagemagick :) )
#        - MySQL module for python (MySQLdb)
#        - getpass module for python

import MySQLdb
import os
import stat
from getpass import getpass
from sys import exit, argv

def usage():
    if len(argv) != 2:
        print "Usage: ./ngall_sql.py /path/to/ng/gallery/folder"
        exit(0)

##########
## main ##
##########

if __name__ == '__main__' :
	try:
		usage()

		password = getpass("Please enter password :")
		source = argv[1]

		try:
			conn = MySQLdb.connect (host = "localhost",
			user = "WORDPRESS_SQL_USER",
			passwd = password,
			db = "WORDPRESS_SQL_USER_PASSWORD")
		except MySQLdb.Error, e:
			print "Error %d: %s" % (e.args[0], e.args[1])
			exit (1)

		cursor = conn.cursor ()

		# put folder & pictures in an array
		folders = os.listdir(source)
		content = []

		for folder in folders:
			folder_test = os.lstat(source + folder)
			if stat.S_ISDIR(folder_test.st_mode):
				pictures = os.listdir(source + folder)
				files = []
				for picture in pictures:
				    picture_test = os.lstat(source + folder + '/' + picture)
				    if not stat.S_ISDIR(picture_test.st_mode):
				        files.append(picture)
				content.append([folder, files])

		# get existing galleries
		cursor.execute ("SELECT path from wp_ngg_gallery")
		rows = cursor.fetchall()
		existing_galleries = []
		for row in rows:
			existing_galleries.append(row[0].split('/').pop())

		# fetch the maximum pictureID (pid) and GalleryID(gid) to add above them
		# the try/except part is just in case script is launched on empty DB
		try:
			cursor.execute ("select MAX(pid) from wp_ngg_pictures;")
			pid = cursor.fetchall()[0][0] + 1
		except: pid = 1

		try:
			cursor.execute ("select MAX(gid) from wp_ngg_gallery;")
			gid = cursor.fetchall()[0][0] + 1
		except: gid = 1

		# Start processing folders & pictures
		for array in content:
			folder = array[0]

			if not folder in existing_galleries:
				print "## ADDING", folder
				if os.path.isdir(source + folder + '/thumbs') == False:
				    print "# adding thumb folder for:", folder
				    os.makedirs(source + folder + '/thumbs')
				    os.chmod(source + folder + '/thumbs', 0777)
				cursor.execute ("INSERT INTO wp_ngg_gallery (gid,name,path,title,galdesc,pageid,previewpic) \
					VALUES (%i,'%s', '%s', '%s','',0,%i);" %(gid,folder,"wp-content/gallery/" + folder,folder.replace('_',' '),pid))

				array[1].sort()
				for picture in array[1]:
				    print "    processing", picture
				    cursor.execute ("INSERT INTO wp_ngg_pictures (pid,galleryid,filename,description,alttext,exclude) \
					VALUES (%i,%i, '%s',NULL,'%s',0);" %(pid,gid,picture,picture))
				    os.popen('convert -resize "150x112" -quality 60 %s %s'
				        % (source + folder + '/' + picture, source + folder + '/thumbs/thumbs_' + picture))
				    pid += 1
				gid += 1

		cursor.close ()
		conn.commit ()
		conn.close ()
		print "done!"
	except KeyboardInterrupt:
		print 'Exiting on user request'

4 Responses to “NextGen Gallery SQL script (to scan folders and add them as galleries)”

  1. Vanessa says:

    Nice Site! Thanks!

  2. Jacob Stoops says:

    Great tutorial. This really helps as I had previously had to create my folders in my server and set them to writeable before I added them in the nextgen admin panel. Otherwise, it just created ghost folders that I could use.

    Also, I’ve figured out how to implement the gallery into the header, which wasn’t fully explained on alex.rabe’s site…here is a short tutorial on implementing the NEXTGEN Gallery into your blog’s header

  3. Henrik says:

    Hi!

    How would I go about using your scrip? I really have no clue even where to start. Do I need to upload this and run it on my server?

    Greatful for any help!

    Best, Henrik

  4. Ignace Mouzannar (-ghantoos-) says:

    Hey Henrik,
    As you said, you should upload it on your server then run it:

    bosta:~/tmp$ ./ngall_sql.py
    Usage: ./ngall_sql.py /path/to/ng/gallery/folder
    

    Hope this will be helpful,
    Regards,
    Ignace M -ghantoos-

Leave a Reply