3 from django.utils.translation import ugettext as _
4 from django.utils.safestring import mark_safe
5 from time import gmtime, strftime, localtime, mktime, time
6 from django.core.files import File
7 from django.core.files.storage import default_storage
9 from urlparse import urlparse
12 from filebrowser.fb_settings import *
24 def _url_to_path(value):
27 Value has to be an URL relative to MEDIA URL or a full URL (including MEDIA_URL).
29 Returns a PATH relative to MEDIA_ROOT.
31 mediaurl_re = re.compile(r'^(%s)' % (MEDIA_URL))
32 value = mediaurl_re.sub('', value)
36 def _path_to_url(value):
39 Value has to be a PATH relative to MEDIA_ROOT.
41 Return an URL relative to MEDIA_ROOT.
43 mediaroot_re = re.compile(r'^(%s)' % (MEDIA_ROOT))
44 value = mediaroot_re.sub('', value)
45 return _url_join(MEDIA_URL, value)
48 def _dir_from_url(value):
50 Get the relative server directory from a URL.
51 URL has to be an absolute URL including MEDIA_URL or
52 an URL relative to MEDIA_URL.
55 mediaurl_re = re.compile(r'^(%s)' % (MEDIA_URL))
56 value = mediaurl_re.sub('', value)
57 directory_re = re.compile(r'^(%s)' % (DIRECTORY))
58 value = directory_re.sub('', value)
59 return os.path.split(value)[0]
62 def _get_version_path(value, version_prefix):
64 Construct the PATH to an Image version.
65 Value has to be server-path, relative to MEDIA_ROOT.
67 version_filename = filename + version_prefix + ext
68 Returns a path relative to MEDIA_ROOT.
70 if os.path.isfile(os.path.join(MEDIA_ROOT, value)):
71 path, filename = os.path.split(value)
72 filename, ext = os.path.splitext(filename)
73 version_filename = filename + "_" + version_prefix + ext
74 return os.path.join(VERSIONS_BASEDIR, path, version_filename)
80 if args[0].startswith("http://"):
85 arg = str(arg).replace("\\", "/")
86 arg_split = arg.split("/")
87 for elem in arg_split:
88 if elem != "" and elem != "http:":
89 url = url + elem + "/"
90 # remove trailing slash for filenames
91 if os.path.splitext(args[-1])[1]:
101 if os.path.isabs(path) or not os.path.isdir(os.path.join(MEDIA_ROOT, DIRECTORY, path)):
106 def _get_file(path, filename):
111 if not os.path.isfile(os.path.join(MEDIA_ROOT, DIRECTORY, path, filename)) and not os.path.isdir(os.path.join(MEDIA_ROOT, DIRECTORY, path, filename)):
116 def _get_breadcrumbs(query, path, title):
124 for item in path.split(os.sep):
125 dir_query = os.path.join(dir_query, item)
126 breadcrumbs.append([item, dir_query])
128 breadcrumbs.append([title, ''])
132 def _get_filterdate(filterDate, dateTime):
138 dateYear = strftime("%Y", gmtime(dateTime))
139 dateMonth = strftime("%m", gmtime(dateTime))
140 dateDay = strftime("%d", gmtime(dateTime))
141 if filterDate == 'today' and int(dateYear) == int(localtime()[0]) and int(dateMonth) == int(localtime()[1]) and int(dateDay) == int(localtime()[2]): returnvalue = 'true'
142 elif filterDate == 'thismonth' and dateTime >= time() - 2592000: returnvalue = 'true'
143 elif filterDate == 'thisyear' and int(dateYear) == int(localtime()[0]): returnvalue = 'true'
144 elif filterDate == 'past7days' and dateTime >= time() - 604800: returnvalue = 'true'
145 elif filterDate == '': returnvalue = 'true'
149 def _get_settings_var():
151 Get settings variables used for FileBrowser listing.
156 settings_var['DEBUG'] = DEBUG
157 settings_var['MEDIA_ROOT'] = MEDIA_ROOT
158 settings_var['MEDIA_URL'] = MEDIA_URL
159 settings_var['DIRECTORY'] = DIRECTORY
161 settings_var['URL_FILEBROWSER_MEDIA'] = URL_FILEBROWSER_MEDIA
162 settings_var['PATH_FILEBROWSER_MEDIA'] = PATH_FILEBROWSER_MEDIA
164 settings_var['URL_TINYMCE'] = URL_TINYMCE
165 settings_var['PATH_TINYMCE'] = PATH_TINYMCE
166 # Extensions/Formats (for FileBrowseField)
167 settings_var['EXTENSIONS'] = EXTENSIONS
168 settings_var['SELECT_FORMATS'] = SELECT_FORMATS
170 settings_var['VERSIONS_BASEDIR'] = VERSIONS_BASEDIR
171 settings_var['VERSIONS'] = VERSIONS
172 settings_var['ADMIN_VERSIONS'] = ADMIN_VERSIONS
173 settings_var['ADMIN_THUMBNAIL'] = ADMIN_THUMBNAIL
174 # FileBrowser Options
175 settings_var['MAX_UPLOAD_SIZE'] = MAX_UPLOAD_SIZE
177 settings_var['CONVERT_FILENAME'] = CONVERT_FILENAME
181 def _handle_file_upload(path, file):
186 file_path = os.path.join(path, file.name)
187 uploadedfile = default_storage.save(file_path, file)
191 def _get_file_type(filename):
193 Get file type as defined in EXTENSIONS.
196 file_extension = os.path.splitext(filename)[1].lower()
198 for k, v in EXTENSIONS.iteritems():
200 if file_extension == extension.lower():
205 def _is_selectable(filename, selecttype):
207 Get select type as defined in FORMATS.
210 file_extension = os.path.splitext(filename)[1].lower()
212 for k, v in SELECT_FORMATS.iteritems():
214 if file_extension == extension.lower():
215 select_types.append(k)
219 def _version_generator(value, version_prefix, force = None):
221 Generate Version for an Image.
222 value has to be a serverpath relative to MEDIA_ROOT.
225 # PIL's Error "Suspension not allowed here" work around:
226 # s. http://mail.python.org/pipermail/image-sig/1999-August/000816.html
228 from PIL import ImageFile
231 from PIL import ImageFile
234 ImageFile.MAXBLOCK = IMAGE_MAXBLOCK # default is 64k
237 im = Image.open(os.path.join(MEDIA_ROOT, value))
238 version_path = _get_version_path(value, version_prefix)
239 absolute_version_path = os.path.join(MEDIA_ROOT, version_path)
240 version_dir = os.path.split(absolute_version_path)[0]
241 if not os.path.isdir(version_dir):
242 os.makedirs(version_dir)
243 os.chmod(version_dir, 0775)
244 version = scale_and_crop(im, VERSIONS[version_prefix]['width'], VERSIONS[version_prefix]['height'], VERSIONS[version_prefix]['opts'])
246 version.save(absolute_version_path, quality = 90, optimize = 1)
248 version.save(absolute_version_path, quality = 90)
254 def scale_and_crop(im, width, height, opts):
255 x, y = [float(v) for v in im.size]
259 xr = float(x * height / y)
263 yr = float(y * width / x)
266 r = max(xr / x, yr / y)
268 r = min(xr / x, yr / y)
270 if r < 1.0 or (r > 1.0 and 'upscale' in opts):
271 im = im.resize((int(x * r), int(y * r)), resample = Image.ANTIALIAS)
274 x, y = [float(v) for v in im.size]
275 ex, ey = (x - min(x, xr)) / 2, (y - min(y, yr)) / 2
277 im = im.crop((int(ex), int(ey), int(x - ex), int(y - ey)))
279 scale_and_crop.valid_options = ('crop', 'upscale')
282 def _convert_filename(value):
284 return value.replace(" ", "_").lower()