def __call__(self): factories_menu = getUtility(IBrowserMenu, name='plone_contentmenu_factory', context=self.context).getMenuItems( self.context, self.request) factories_menu = [ m for m in factories_menu if m.get('title') != 'folder_add_settings' ] context = aq_inner(self.context) crumbs = [] while not INavigationRoot.providedBy(context): crumbs.append({ 'id': context.getId(), 'title': utils.pretty_title_or_id(context, context) }) context = utils.parent(context) catalog = getToolByName(self.context, 'portal_catalog') try: brains = catalog(UID=IUUID(self.context)) except TypeError: brains = [] item = None if len(brains) > 0: obj = brains[0] # context here should be site root base_path = '/'.join(context.getPhysicalPath()) item = {} for attr in self.attributes: key = attr if key == 'path': attr = 'getPath' val = getattr(obj, attr, None) if callable(val): if attr in _safe_callable_metadata: val = val() else: continue if key == 'path': val = val[len(base_path):] item[key] = val return json_dumps({ 'addButtons': factories_menu, 'defaultPage': self.context.getDefaultPage(), 'breadcrumbs': [c for c in reversed(crumbs)], 'object': item })
def __call__(self): factories_menu = getUtility( IBrowserMenu, name='plone_contentmenu_factory', context=self.context).getMenuItems(self.context, self.request) factories_menu = [m for m in factories_menu if m.get('title') != 'folder_add_settings'] context = aq_inner(self.context) crumbs = [] while not INavigationRoot.providedBy(context): crumbs.append({ 'id': context.getId(), 'title': utils.pretty_title_or_id(context, context) }) context = utils.parent(context) catalog = getToolByName(self.context, 'portal_catalog') try: brains = catalog(UID=IUUID(self.context)) except TypeError: brains = [] item = None if len(brains) > 0: obj = brains[0] # context here should be site root base_path = '/'.join(context.getPhysicalPath()) item = {} for attr in self.attributes: key = attr if key == 'path': attr = 'getPath' val = getattr(obj, attr, None) if callable(val): if attr in _safe_callable_metadata: val = val() else: continue if key == 'path': val = val[len(base_path):] item[key] = val return json_dumps({ 'addButtons': factories_menu, 'defaultPage': self.context.getDefaultPage(), 'breadcrumbs': [c for c in reversed(crumbs)], 'object': item })
def __call__(self): req = self.request tusrequest = False if TUS_ENABLED: adapter = Zope2RequestAdapter(req) tus = Tus(adapter, **tus_settings) if tus.valid: tusrequest = True tus.handle() if not tus.upload_finished: return else: filename = req.getHeader('FILENAME') if tus.send_file: filedata = req._file filedata.filename = filename else: filepath = req._file.read() filedata = open(filepath) if not tusrequest: if req.REQUEST_METHOD != 'POST': return filedata = self.request.form.get("file", None) if filedata is None: return filename = filedata.filename content_type = mimetypes.guess_type(filename)[0] or "" if not filedata: return # Determine if the default file/image types are DX or AT based ctr = getToolByName(self.context, 'content_type_registry') type_ = ctr.findTypeName(filename.lower(), '', '') or 'File' DX_BASED = False if HAS_DEXTERITY: pt = getToolByName(self.context, 'portal_types') if IDexterityFTI.providedBy(getattr(pt, type_)): factory = IDXFileFactory(self.context) DX_BASED = True else: factory = IATCTFileFactory(self.context) else: factory = IATCTFileFactory(self.context) obj = factory(filename, content_type, filedata) if DX_BASED: if 'File' in obj.portal_type: size = obj.file.getSize() content_type = obj.file.contentType elif 'Image' in obj.portal_type: size = obj.image.getSize() content_type = obj.image.contentType result = {"type": content_type, "size": size} else: try: size = obj.getSize() except AttributeError: size = obj.getObjSize() result = {"type": obj.getContentType(), "size": size} if tusrequest: tus.cleanup_file() result.update({ 'url': obj.absolute_url(), 'name': obj.getId(), 'UID': IUUID(obj), 'filename': filename }) return json_dumps(result)
def __call__(self): """ Accepts GET parameters of: name: Name of the vocabulary query: string or json object of criteria and options. json value consists of a structure: { criteria: object, sort_on: index, sort_order: (asc|reversed) } attributes: comma seperated, or json object list batch: { page: 1-based page of results, size: size of paged results } """ self.request.response.setHeader("Content-type", "application/json") factory_name = self.request.get('name', None) if not factory_name: return json_dumps({'error': 'No factory provided.'}) if factory_name not in _permissions: return json_dumps({'error': 'Vocabulary lookup not allowed'}) sm = getSecurityManager() if not sm.checkPermission(_permissions[factory_name], self.context): raise Unauthorized('You do not have permission to use this ' 'vocabulary') factory = queryUtility(IVocabularyFactory, factory_name) if not factory: return json_dumps( {'error': 'No factory with name "%s" exists.' % factory_name}) # check if factory accepts query argument query = _parseJSON(self.request.get('query', '')) batch = _parseJSON(self.request.get('batch', '')) if type(factory) is FunctionType: factory_spec = inspect.getargspec(factory) else: factory_spec = inspect.getargspec(factory.__call__) try: supports_query = False supports_batch = False if query and len(factory_spec.args) >= 3 and \ factory_spec.args[2] == 'query': supports_query = True if len(factory_spec.args) >= 4 and \ factory_spec.args[3] == 'batch': supports_batch = True if (not supports_query and query): raise KeyError( "The vocabulary factory %s does not support " "query arguments", factory) if batch and supports_batch: vocabulary = factory(self.context, query, batch) elif query: vocabulary = factory(self.context, query) else: vocabulary = factory(self.context) except (TypeError, ParseError): raise return self.error() try: total = len(vocabulary) except TypeError: # do not error if object does not support __len__ we'll check again # later if we can figure some size out total = 0 if batch and ('size' not in batch or 'page' not in batch): batch = None # batching not providing correct options logger.error("A vocabulary request contained bad batch " "information. The batch information is ignored.") if batch and not supports_batch and \ ISlicableVocabulary.providedBy(vocabulary): # must be slicable for batching support page = int(batch['page']) # page is being passed in is 1-based start = (max(page - 1, 0)) * int(batch['size']) end = start + int(batch['size']) vocabulary = vocabulary[start:end] items = [] attributes = _parseJSON(self.request.get('attributes', '')) if isinstance(attributes, basestring) and attributes: attributes = attributes.split(',') if attributes: base_path = '/'.join(self.context.getPhysicalPath()) for vocab_item in vocabulary: item = {} for attr in attributes: key = attr if ':' in attr: key, attr = attr.split(':', 1) if attr in _unsafe_metadata: continue if key == 'path': attr = 'getPath' vocab_value = vocab_item.value val = getattr(vocab_value, attr, None) if callable(val): if attr in _safe_callable_metadata: val = val() else: continue if key == 'path': val = val[len(base_path):] item[key] = val items.append(item) else: for item in vocabulary: items.append({'id': item.token, 'text': item.title}) if total == 0: total = len(items) return json_dumps({'results': items, 'total': total})
def error(self): return json_dumps({'results': [], 'total': 0, 'error': True})
def __call__(self): registry = getUtility(IRegistry) config = IQuerystringRegistryReader(registry)() self.request.response.setHeader("Content-Type", "application/json") return json_dumps(config)
def json(self, data): self.request.response.setHeader("Content-Type", "application/json") return json_dumps(data)
def __call__(self): site = getSite() base_url = site.absolute_url() base_vocabulary = '%s/@@wcVocabulary?name=' % base_url site_path = site.getPhysicalPath() context_path = self.context.getPhysicalPath() options = { 'vocabularyUrl': '%swildcard.foldercontents.vocabularies.Catalog' % (base_vocabulary), 'tagsVocabularyUrl': '%splone.app.vocabularies.Keywords' % (base_vocabulary), 'usersVocabularyUrl': '%splone.app.vocabularies.Users' % (base_vocabulary), 'moveUrl': '%s{path}/fc-itemOrder' % base_url, 'indexOptionsUrl': '%s/@@qsOptions' % base_url, 'contextInfoUrl': '%s{path}/@@fc-contextInfo' % base_url, 'setDefaultPageUrl': '%s{path}/@@fc-setDefaultPage' % base_url, 'buttonGroups': { 'primary': [{ 'title': 'Cut', }, { 'title': 'Copy', }, { 'title': 'Paste', 'url': base_url + '{path}/@@fc-paste' }, { 'title': 'Delete', 'url': base_url + '/@@fc-delete', 'context': 'danger', 'icon': 'trash' }], 'secondary': [{ 'title': 'Workflow', 'url': base_url + '/@@fc-workflow' }, { 'title': 'Tags', 'url': base_url + '/@@fc-tags' }, { 'title': 'Properties', 'url': base_url + '/@@fc-properties' }, { 'title': 'Rename', 'url': base_url + '/@@fc-rename' }] }, 'rearrange': { 'properties': { 'id': 'ID', 'sortable_title': 'Title', 'modified': 'Last Modified', 'created': 'Created on', 'effective': 'Publication Date', 'Type': 'Type' }, 'url': '%s{path}/@@fc-sort' % base_url }, 'basePath': '/' + '/'.join(context_path[len(site_path):]), 'upload': { 'relativePath': 'wcFileUpload', 'baseUrl': base_url, 'initialFolder': IUUID(self.context, None), 'useTus': TUS_ENABLED } } self.options = json_dumps(options) return super(FolderContentsView, self).__call__()
def __call__(self): req = self.request tusrequest = False if TUS_ENABLED: adapter = Zope2RequestAdapter(req) tus = Tus(adapter, **tus_settings) if tus.valid: tusrequest = True tus.handle() if not tus.upload_finished: return else: filename = req.getHeader('FILENAME') if tus.send_file: filedata = req._file filedata.filename = filename else: filepath = req._file.read() filedata = open(filepath) if not tusrequest: if req.REQUEST_METHOD != 'POST': return filedata = self.request.form.get("file", None) if filedata is None: return filename = filedata.filename content_type = mimetypes.guess_type(filename)[0] or "" if not filedata: return # Determine if the default file/image types are DX or AT based ctr = getToolByName(self.context, 'content_type_registry') type_ = ctr.findTypeName(filename.lower(), '', '') or 'File' DX_BASED = False if HAS_DEXTERITY: pt = getToolByName(self.context, 'portal_types') if IDexterityFTI.providedBy(getattr(pt, type_)): factory = IDXFileFactory(self.context) DX_BASED = True else: factory = IATCTFileFactory(self.context) else: factory = IATCTFileFactory(self.context) obj = factory(filename, content_type, filedata) if DX_BASED: if 'File' in obj.portal_type: size = obj.file.getSize() content_type = obj.file.contentType elif 'Image' in obj.portal_type: size = obj.image.getSize() content_type = obj.image.contentType result = { "type": content_type, "size": size } else: try: size = obj.getSize() except AttributeError: size = obj.getObjSize() result = { "type": obj.getContentType(), "size": size } if tusrequest: tus.cleanup_file() result.update({ 'url': obj.absolute_url(), 'name': obj.getId(), 'UID': IUUID(obj), 'filename': filename }) return json_dumps(result)
def __call__(self): """ Accepts GET parameters of: name: Name of the vocabulary query: string or json object of criteria and options. json value consists of a structure: { criteria: object, sort_on: index, sort_order: (asc|reversed) } attributes: comma seperated, or json object list batch: { page: 1-based page of results, size: size of paged results } """ self.request.response.setHeader("Content-type", "application/json") factory_name = self.request.get('name', None) if not factory_name: return json_dumps({'error': 'No factory provided.'}) if factory_name not in _permissions: return json_dumps({'error': 'Vocabulary lookup not allowed'}) sm = getSecurityManager() if not sm.checkPermission(_permissions[factory_name], self.context): raise Unauthorized('You do not have permission to use this ' 'vocabulary') factory = queryUtility(IVocabularyFactory, factory_name) if not factory: return json_dumps({ 'error': 'No factory with name "%s" exists.' % factory_name}) # check if factory accepts query argument query = _parseJSON(self.request.get('query', '')) batch = _parseJSON(self.request.get('batch', '')) if type(factory) is FunctionType: factory_spec = inspect.getargspec(factory) else: factory_spec = inspect.getargspec(factory.__call__) try: supports_query = False supports_batch = False if query and len(factory_spec.args) >= 3 and \ factory_spec.args[2] == 'query': supports_query = True if len(factory_spec.args) >= 4 and \ factory_spec.args[3] == 'batch': supports_batch = True if (not supports_query and query): raise KeyError("The vocabulary factory %s does not support " "query arguments", factory) if batch and supports_batch: vocabulary = factory(self.context, query, batch) elif query: vocabulary = factory(self.context, query) else: vocabulary = factory(self.context) except (TypeError, ParseError): raise return self.error() try: total = len(vocabulary) except TypeError: # do not error if object does not support __len__ we'll check again # later if we can figure some size out total = 0 if batch and ('size' not in batch or 'page' not in batch): batch = None # batching not providing correct options logger.error("A vocabulary request contained bad batch " "information. The batch information is ignored.") if batch and not supports_batch and \ ISlicableVocabulary.providedBy(vocabulary): # must be slicable for batching support page = int(batch['page']) # page is being passed in is 1-based start = (max(page - 1, 0)) * int(batch['size']) end = start + int(batch['size']) vocabulary = vocabulary[start:end] items = [] attributes = _parseJSON(self.request.get('attributes', '')) if isinstance(attributes, basestring) and attributes: attributes = attributes.split(',') if attributes: base_path = '/'.join(self.context.getPhysicalPath()) for vocab_item in vocabulary: item = {} for attr in attributes: key = attr if ':' in attr: key, attr = attr.split(':', 1) if attr in _unsafe_metadata: continue if key == 'path': attr = 'getPath' vocab_value = vocab_item.value val = getattr(vocab_value, attr, None) if callable(val): if attr in _safe_callable_metadata: val = val() else: continue if key == 'path': val = val[len(base_path):] item[key] = val items.append(item) else: for item in vocabulary: items.append({'id': item.token, 'text': item.title}) if total == 0: total = len(items) return json_dumps({ 'results': items, 'total': total })
def error(self): return json_dumps({ 'results': [], 'total': 0, 'error': True })
def __call__(self): site = getSite() base_url = site.absolute_url() base_vocabulary = '%s/@@wcVocabulary?name=' % base_url site_path = site.getPhysicalPath() context_path = self.context.getPhysicalPath() options = { 'vocabularyUrl': '%swildcard.foldercontents.vocabularies.Catalog' % ( base_vocabulary), 'tagsVocabularyUrl': '%splone.app.vocabularies.Keywords' % ( base_vocabulary), 'usersVocabularyUrl': '%splone.app.vocabularies.Users' % ( base_vocabulary), 'moveUrl': '%s{path}/fc-itemOrder' % base_url, 'indexOptionsUrl': '%s/@@qsOptions' % base_url, 'contextInfoUrl': '%s{path}/@@fc-contextInfo' % base_url, 'setDefaultPageUrl': '%s{path}/@@fc-setDefaultPage' % base_url, 'buttonGroups': { 'primary': [{ 'title': 'Cut', }, { 'title': 'Copy', }, { 'title': 'Paste', 'url': base_url + '{path}/@@fc-paste' }, { 'title': 'Delete', 'url': base_url + '/@@fc-delete', 'context': 'danger', 'icon': 'trash' }], 'secondary': [{ 'title': 'Workflow', 'url': base_url + '/@@fc-workflow' }, { 'title': 'Tags', 'url': base_url + '/@@fc-tags' }, { 'title': 'Properties', 'url': base_url + '/@@fc-properties' }, { 'title': 'Rename', 'url': base_url + '/@@fc-rename' }] }, 'rearrange': { 'properties': { 'id': 'ID', 'sortable_title': 'Title', 'modified': 'Last Modified', 'created': 'Created on', 'effective': 'Publication Date', 'Type': 'Type' }, 'url': '%s{path}/@@fc-sort' % base_url }, 'basePath': '/' + '/'.join(context_path[len(site_path):]), 'upload': { 'relativePath': 'wcFileUpload', 'baseUrl': base_url, 'initialFolder': IUUID(self.context, None), 'useTus': TUS_ENABLED } } self.options = json_dumps(options) return super(FolderContentsView, self).__call__()