def lookup_contact(context, contact): """Lookup existing contact from soup by given contact or add to soup if inexistent. """ soup = get_contacts_soup(context) query = ( Eq("firstname", contact["personal_data.firstname"].lower()) & Eq("lastname", contact["personal_data.lastname"].lower()) & Eq("zip", contact["billing_address.zip"].lower()) & Eq("street", contact["billing_address.street"].lower()) ) res = soup.query(query) record = None for rec in res: record = rec break if not record: record = Record() record.attrs["uid"] = uuid.uuid4() record.attrs["cid"] = next_contact_id(soup) record.attrs.update(contact.items()) soup.add(record) else: record.attrs.update(contact.items()) soup.reindex([record]) return record
def test_fetch_one_too_many(self): from collective.bookmarks.storage import Bookmarks from repoze.catalog.query import Eq from souper.soup import Record import uuid bookmarks = Bookmarks() data = {"owner": "kim stanley", "uid": uuid.uuid4(), "group": ""} record1 = Record() record1.attrs["owner"] = data["owner"] record1.attrs["uid"] = data["uid"] record1.attrs["group"] = data["group"] record2 = Record() record2.attrs["owner"] = data["owner"] record2.attrs["uid"] = data["uid"] record2.attrs["group"] = data["group"] bookmarks._soup.add(record1) bookmarks._soup.add(record2) with self.assertRaises(ValueError): bookmarks._fetch_one( Eq("owner", data["owner"]) & Eq("uid", data["uid"]) & Eq("group", data["group"]))
def render(self): portal = getSite() current_user = api.user.get_current() userid = current_user.id search_items_string = self.request.form['items'] search_items = search_items_string.split(',') soup_searches = get_soup('user_news_searches', portal) exist = [r for r in soup_searches.query(Eq('id', userid))] if not exist: record = Record() record.attrs['id'] = userid record.attrs['searches'] = [search_items] record_id = soup_searches.add(record) acl_record = soup_searches.get(record_id) else: acl_record = exist[0] in_list = False total_searches = acl_record.attrs['searches'] if acl_record.attrs['searches']: for search in acl_record.attrs['searches']: for i, item in enumerate(search_items): if item not in search: break if i == len(search_items) - 1: if len(search_items) < len(search): break else: in_list = True if not in_list: total_searches.append(search_items) acl_record.attrs['searches'] = total_searches else: acl_record.attrs['searches'] = total_searches soup_searches.reindex(records=[acl_record])
def render(self): portal = getSite() current_user = api.user.get_current() userid = current_user.id tag = self.request.form['tag'] soup_tags = get_soup('user_subscribed_tags', portal) exist = [r for r in soup_tags.query(Eq('id', userid))] if not exist: record = Record() record.attrs['id'] = userid record.attrs['tags'] = [tag] soup_tags.add(record) else: subscribed = [ True for utag in exist[0].attrs['tags'] if utag == tag ] if subscribed: exist[0].attrs['tags'].remove(tag) else: exist[0].attrs['tags'].append(tag) soup_tags.reindex() if IPloneSiteRoot.providedBy(self.context): self.request.response.redirect(self.context.absolute_url() + '/alltags') else: self.request.response.redirect(self.context.absolute_url())
def test_endpoint_returns_data(self): url = "{}/@subscriptions".format(self.portal_url) response = self.api_session.get(url) res = response.json() self.assertEqual(res["items_total"], 0) now = datetime.now() soup = get_soup("subscriptions_soup", self.portal) transaction.commit() record = Record() record.attrs["name"] = "John" record.attrs["email"] = "*****@*****.**" record.attrs["date"] = now intid = soup.add(record) transaction.commit() url = "{}/@subscriptions".format(self.portal_url) response = self.api_session.get(url) res = response.json() self.assertEqual(res["items_total"], 1) self.assertEqual( res["items"], [ { "id": intid, "email": "*****@*****.**", "name": "John", "date": json_compatible(now), } ], )
def render(self): portal = getSite() current_user = api.user.get_current() userid = current_user.id tag = self.request.form['tag'] soup_tags = get_soup('user_subscribed_tags', portal) exist = [r for r in soup_tags.query(Eq('id', userid))] if not exist: record = Record() record.attrs['id'] = userid record.attrs['tags'] = [tag] soup_tags.add(record) else: subscribed = [True for utag in exist[0].attrs['tags'] if utag == tag] if subscribed: exist[0].attrs['tags'].remove(tag) else: exist[0].attrs['tags'].append(tag) soup_tags.reindex() if IPloneSiteRoot.providedBy(self.context): self.request.response.redirect(self.context.absolute_url() + '/alltags') else: self.request.response.redirect(self.context.absolute_url())
def render(self): conn = ldap.initialize(ALT_LDAP_URI) conn.simple_bind_s(ALT_LDAP_DN, ALT_LDAP_PASSWORD) try: results = conn.search_s(BASEDN, ldap.SCOPE_SUBTREE, '(objectClass=groupOfNames)', ['cn']) except: # Just in case the user raise a "SIZE_LIMIT_EXCEEDED" api.portal.send_email( recipient="*****@*****.**", sender="*****@*****.**", subject="[uLearn] Exception raised: SIZE_LIMIT_EXCEEDED", body="The sync view on the uLearn instance has reached the SIZE_LIMIT_EXCEEDED and the groups has not been updated", ) if results: portal = api.portal.get() soup = get_soup('ldap_groups', portal) to_print = [] for dn, attrs in results: group_id = attrs['cn'][0] exist = [r for r in soup.query(Eq('id', group_id))] if exist: to_print.append('* Already existing record for group: {}'.format(group_id)) else: record = Record() record.attrs['id'] = group_id record.attrs['searchable_id'] = group_id soup.add(record) to_print.append('Added record for group: {}'.format(group_id)) return '\n'.join(to_print) else: return 'No results'
def render(self): portal = api.portal.get() soup = get_soup('uuid_preserver', portal) pc = api.portal.get_tool('portal_catalog') results = pc.searchResults() for result in results: record = Record() record.attrs['uuid'] = result.UID record.attrs['path'] = result.getPath() soup.add(record) logger.warning('Preserving {}: {}'.format(result.getPath(), result.UID))
def add(self, data): record = Record() for k, v in data.items(): if k not in self.fields: logger.warning("[ADD {}] SKIP unkwnown field: {}".format( self.soup_type, k)) else: if six.PY2: if isinstance(v, str): v = v.decode("utf-8") record.attrs[k] = v record.attrs["date"] = datetime.now() return self.soup.add(record)
def add(self, owner: str, uid: uuid.UUID, group: str, queryparams: str, payload: dict) -> typing.Union[int, None]: """add new entry. uniqueness is given by triple of owner, uid, group and queryparams. returns None if such a triple already exists returns record_id if successful added """ # check existing if (self._fetch_one( Eq("owner", owner) & Eq("uid", uid) & Eq("group", group) & Eq("queryparams", queryparams)) is not None): return None record = Record() record.attrs["owner"] = owner record.attrs["uid"] = uid record.attrs["group"] = group record.attrs["queryparams"] = queryparams record.attrs["payload"] = payload record.attrs["created"] = json_compatible(datetime.utcnow()) if self._soup.add(record): return self._dictify(record)
def UpdateUserCommunityAccess(content, event): """ Update data access to the user community when you add content to the community """ portal = getSite() community = findContainerCommunity(content) current_user = api.user.get_current() user_community = current_user.id + '_' + community.id soup_access = get_soup('user_community_access', portal) exist = [r for r in soup_access.query(Eq('user_community', user_community))] if not exist: record = Record() record.attrs['user_community'] = user_community record.attrs['data_access'] = DateTime() soup_access.add(record) else: exist[0].attrs['data_access'] = DateTime() soup_access.reindex()
def add(self, data): form_fields = self.get_form_fields() if not form_fields: logger.error( 'Block with id {} and type "form" not found in context: {}.'. format(self.block_id, self.context.absolute_url())) return None fields = { x["field_id"]: x.get("label", x["field_id"]) for x in form_fields } record = Record() fields_labels = {} fields_order = [] for field_data in data: field_id = field_data.get("field_id", "") value = field_data.get("value", "") if field_id in fields: record.attrs[field_id] = value fields_labels[field_id] = fields[field_id] fields_order.append(field_id) record.attrs["fields_labels"] = fields_labels record.attrs["fields_order"] = fields_order record.attrs["date"] = datetime.now() record.attrs["block_id"] = self.block_id return self.soup.add(record)
def test_dictify(self): from collective.bookmarks.storage import Bookmarks from souper.soup import Record import math import time import uuid bookmarks = Bookmarks() data = { "owner": "kim stanley", "uid": uuid.uuid4(), "group": "", "payload": {}, "created": math.floor(time.time()), } record = Record() record.attrs["owner"] = data["owner"] record.attrs["uid"] = data["uid"] record.attrs["group"] = data["group"] record.attrs["payload"] = data["payload"] record.attrs["created"] = data["created"] dictified = bookmarks._dictify(record) self.assertEqual(data, dictified)
def test_fetch_one_existing(self): from collective.bookmarks.storage import Bookmarks from repoze.catalog.query import Eq from souper.soup import Record import uuid bookmarks = Bookmarks() data = {"owner": "kim stanley", "uid": uuid.uuid4(), "group": ""} record = Record() record.attrs["owner"] = data["owner"] record.attrs["uid"] = data["uid"] record.attrs["group"] = data["group"] bookmarks._soup.add(record) result = bookmarks._fetch_one( Eq("owner", data["owner"]) & Eq("uid", data["uid"]) & Eq("group", data["group"])) self.assertIs(result, record)
def fix_data(blocks, context): fixed = False for block in blocks.values(): if block.get("@type", "") != "form": continue if not block.get("store", False): continue store = getMultiAdapter((context, getRequest()), IFormDataStore) fixed = True data = store.search() for record in data: labels = {} new_record = Record() for k, v in record.attrs.items(): new_id = get_field_info_from_block(block=block, field_id=k) new_record.attrs[new_id["id"]] = v labels.update({new_id["id"]: new_id["label"]}) new_record.attrs["fields_labels"] = labels # create new entry store.soup.add(new_record) # remove old one store.delete(record.intid) return fixed
def menu_enlaces(self): """ Devuelve el menu de enlaces segun el idioma que tenga definido el usuario en su perfil. Si no tiene nada, no lo devuleve """ portal = api.portal.get() current = api.user.get_current() user_language = current.getProperty('language') soup_menu = get_soup('menu_soup', portal) if not user_language or not isinstance(current.getProperty('language'), basestring): lt = getToolByName(self.portal(), 'portal_languages') language = lt.getPreferredLanguage() current.setMemberProperties(mapping={'language': language}) else: exist = [r for r in soup_menu.query(Eq('id_menusoup', user_language))] if not exist: dades = self.genera_menu_enlaces(user_language) record = Record() record.attrs['id_menusoup'] = user_language record.attrs['dades'] = dades.values() soup_menu.add(record) soup_menu.reindex() return dades.values() else: return exist[0].attrs['dades']
def lookup_contact(context, contact): """Lookup existing contact from soup by given contact or add to soup if inexistent. """ soup = get_contacts_soup(context) query = Eq('firstname', contact['personal_data.firstname'].lower()) & \ Eq('lastname', contact['personal_data.lastname'].lower()) & \ Eq('zip', contact['billing_address.zip'].lower()) & \ Eq('street', contact['billing_address.street'].lower()) res = soup.query(query) record = None for rec in res: record = rec break if not record: record = Record() record.attrs['uid'] = uuid.uuid4() record.attrs['cid'] = next_contact_id(soup) record.attrs.update(contact.items()) soup.add(record) else: record.attrs.update(contact.items()) soup.reindex([record]) return record
def insert(self, data): """ Inserts a row to the soup table. :param data: row dictionary :return: intid of created record """ if self._already_exists(data): logger.debug("Trying to insert existing record... {}".format(data)) return False record = Record() record.attrs[REMOTE_UID] = data[REMOTE_UID] record.attrs[LOCAL_UID] = data.get(LOCAL_UID, "") record.attrs[REMOTE_PATH] = data[REMOTE_PATH] record.attrs[LOCAL_PATH] = data.get(LOCAL_PATH, "") record.attrs[PORTAL_TYPE] = data[PORTAL_TYPE] record.attrs[UPDATED] = data.get(UPDATED, "0") r_id = self.soup.add(record) logger.info("Record {} inserted: {}".format(r_id, data)) return r_id
def add_portrait_user(user): """ Esta función le pide al max la foto de perfil del usuario la añade al portrait de plone y guarda en un soup si es la de por defecto o no """ id = user.id maxclient, settings = getUtility(IMAXClient)() foto = maxclient.people[id].avatar imageUrl = foto.uri + '/large' portrait = urllib.urlretrieve(imageUrl) scaled, mimetype = convertSquareImage(portrait[0]) portrait = Image(id=id, file=scaled, title=id) portal = api.portal.get() membertool = api.portal.get_tool(name='portal_memberdata') membertool._setPortrait(portrait, str(id)) import transaction transaction.commit() member_info = get_safe_member_by_id(id) if member_info.get('fullname', False) \ and member_info.get('fullname', False) != id \ and isinstance(portrait, Image) and portrait.size != 3566 and portrait.size != 6186: portrait_user = True # 3566 is the size of defaultUser.png I don't know how get image # title. This behavior is reproduced in profile portlet. Ahora tambien 6186 else: portrait_user = False soup_users_portrait = get_soup('users_portrait', portal) exist = [r for r in soup_users_portrait.query(Eq('id_username', id))] if exist: user_record = exist[0] user_record.attrs['id_username'] = id user_record.attrs['portrait'] = portrait_user else: record = Record() record_id = soup_users_portrait.add(record) user_record = soup_users_portrait.get(record_id) user_record.attrs['id_username'] = id user_record.attrs['portrait'] = portrait_user soup_users_portrait.reindex(records=[user_record])
def add_rule(self, context, index, kind, block, value, threshold, valid_from, valid_to, user='', group=''): rule = Record() rule.attrs['index'] = index assert (isinstance(self.category, str)) rule.attrs['category'] = self.category rule.attrs['context_uid'] = uuid.UUID(IUUID(context)) rule.attrs['creator'] = plone.api.user.get_current().getId() rule.attrs['created'] = datetime.now() assert (isinstance(kind, str)) rule.attrs['kind'] = kind assert (isinstance(block, bool)) rule.attrs['block'] = block assert (isinstance(value, float)) rule.attrs['value'] = value if threshold: assert (isinstance(threshold, float)) rule.attrs['threshold'] = threshold if valid_from: assert (isinstance(valid_from, datetime)) else: valid_from = FLOOR_DATETIME rule.attrs['valid_from'] = valid_from if valid_to: assert (isinstance(valid_to, datetime)) else: valid_to = CEILING_DATETIME rule.attrs['valid_to'] = valid_to assert (isinstance(user, str)) rule.attrs['user'] = user assert (isinstance(group, str)) rule.attrs['group'] = group self.rules_soup.add(rule)
def add_user_to_catalog(user, properties={}, notlegit=False, overwrite=False): """ Adds a user to the user catalog As this method can be called from multiple places, user parameter can be a MemberData wrapped user, a PloneUser object or a plain (string) username. If the properties parameter is ommitted, only a basic record identifying the user will be created, with no extra properties. The 'notlegit' argument is used when you can add the user for its use in the ACL user search facility. If so, the user would not have 'searchable_text' and therefore not searchable. It would have an extra 'notlegit' index. The overwrite argument controls whether an existing attribute value on a user record will be overwritten or not by the incoming value. This is in order to protect user-provided values via the profile page. """ portal = api.portal.get() soup = get_soup('user_properties', portal) if isinstance(user, MemberData): username = user.getUserName() elif isinstance(user, PloneUser): username = user.getUserName() else: username = user # add lower to take correct user_soup username = username.lower() exist = [r for r in soup.query(Eq('id', username))] user_properties_utility = getUtility(ICatalogFactory, name='user_properties') if exist: user_record = exist[0] # Just in case that a user became a legit one and previous was a nonlegit user_record.attrs['notlegit'] = False else: record = Record() record_id = soup.add(record) user_record = soup.get(record_id) # If the user do not exist, and the notlegit is set (created by other # means, e.g. a test or ACL) then set notlegit to True This is because # in non legit mode, maybe existing legit users got unaffected by it if notlegit: user_record.attrs['notlegit'] = True if isinstance(username, str): user_record.attrs['username'] = username.decode('utf-8') user_record.attrs['id'] = username.decode('utf-8') else: user_record.attrs['username'] = username user_record.attrs['id'] = username property_different_value = False if properties: for attr in user_properties_utility.properties + METADATA_USER_ATTRS: has_property_definition = attr in properties property_empty_or_not_set = user_record.attrs.get(attr, u'') == u'' if has_property_definition: property_different_value = user_record.attrs.get( attr, u'') != properties[attr] if has_property_definition and (property_empty_or_not_set or overwrite or property_different_value): if isinstance(properties[attr], str): user_record.attrs[attr] = properties[attr].decode('utf-8') else: user_record.attrs[attr] = properties[attr] # If notlegit mode, then reindex without setting the 'searchable_text' This # is because in non legit mode, maybe existing legit users got unaffected by # it if notlegit: soup.reindex(records=[user_record]) return # Build the searchable_text field for wildcard searchs user_record.attrs['searchable_text'] = ' '.join([ unicodedata.normalize('NFKD', user_record.attrs[key]).encode('ascii', errors='ignore') for key in user_properties_utility.properties if user_record.attrs.get(key, False) ]) soup.reindex(records=[user_record]) # If uLearn is present, then lookup for a customized set of fields and its # related soup. The soup has the form 'user_properties_<client_name>'. This # feature is currently restricted to uLearn but could be easily backported # to Genweb. The setting that makes the extension available lives in: # 'genweb.controlpanel.core.IGenwebCoreControlPanelSettings.user_properties_extender' if IAMULEARN: extender_name = api.portal.get_registry_record( 'genweb.controlpanel.core.IGenwebCoreControlPanelSettings.user_properties_extender' ) # Make sure that, in fact we have such a extender in place if extender_name in [a[0] for a in getUtilitiesFor(ICatalogFactory)]: extended_soup = get_soup(extender_name, portal) exist = [] exist = [r for r in extended_soup.query(Eq('id', username))] extended_user_properties_utility = getUtility(ICatalogFactory, name=extender_name) if exist: extended_user_record = exist[0] else: record = Record() record_id = extended_soup.add(record) extended_user_record = extended_soup.get(record_id) if isinstance(username, str): extended_user_record.attrs['username'] = username.decode( 'utf-8') extended_user_record.attrs['id'] = username.decode('utf-8') else: extended_user_record.attrs['username'] = username extended_user_record.attrs['id'] = username if properties: for attr in extended_user_properties_utility.properties: has_property_definition = attr in properties property_empty_or_not_set = extended_user_record.attrs.get( attr, u'') == u'' # Only update it if user has already not property set or it's empty if has_property_definition and (property_empty_or_not_set or overwrite): if isinstance(properties[attr], str): extended_user_record.attrs[attr] = properties[ attr].decode('utf-8') else: extended_user_record.attrs[attr] = properties[attr] # Update the searchable_text of the standard user record field with # the ones in the extended catalog user_record.attrs['searchable_text'] = user_record.attrs[ 'searchable_text'] + ' ' + ' '.join([ unicodedata.normalize( 'NFKD', extended_user_record.attrs[key]).encode( 'ascii', errors='ignore') for key in extended_user_properties_utility.properties if extended_user_record.attrs.get(key, False) ]) # Save for free the extended properties in the main user_properties soup # for easy access with one query if properties: for attr in extended_user_properties_utility.properties: has_property_definition = attr in properties property_empty_or_not_set = user_record.attrs.get( attr, u'') == u'' # Only update it if user has already not property set or it's empty if has_property_definition and (property_empty_or_not_set or overwrite): if isinstance(properties[attr], str): user_record.attrs[attr] = properties[attr].decode( 'utf-8') else: user_record.attrs[attr] = properties[attr] soup.reindex(records=[user_record]) extended_soup.reindex(records=[extended_user_record])
def create_rule(uid, category, creator, index, kind, block, value, threshold, threshold_calculation, portal_type, valid_from, valid_to, user='', group=''): rule = Record() rule.attrs['index'] = index assert (isinstance(category, str)) rule.attrs['category'] = category rule.attrs['context_uid'] = uid rule.attrs['creator'] = creator rule.attrs['created'] = datetime.now() assert (isinstance(kind, str)) rule.attrs['kind'] = kind assert (isinstance(block, bool)) rule.attrs['block'] = block assert (isinstance(value, float)) rule.attrs['value'] = value if threshold: assert (isinstance(threshold, float)) rule.attrs['threshold'] = threshold rule.attrs['threshold_calculation'] = threshold_calculation rule.attrs['portal_type'] = portal_type if valid_from: assert (isinstance(valid_from, datetime)) else: valid_from = FLOOR_DATETIME rule.attrs['valid_from'] = valid_from if valid_to: assert (isinstance(valid_to, datetime)) else: valid_to = CEILING_DATETIME rule.attrs['valid_to'] = valid_to assert (isinstance(user, str)) rule.attrs['user'] = user assert (isinstance(group, str)) rule.attrs['group'] = group return rule
def order(self): return Record()
def create_rule( uid, category, creator, index, kind, block, value, threshold, threshold_calculation, portal_type, valid_from, valid_to, user="", group="", ): rule = Record() rule.attrs["index"] = index assert isinstance(category, str) rule.attrs["category"] = category rule.attrs["context_uid"] = uid rule.attrs["creator"] = creator rule.attrs["created"] = datetime.now() assert isinstance(kind, str) rule.attrs["kind"] = kind assert isinstance(block, bool) rule.attrs["block"] = block assert isinstance(value, float) rule.attrs["value"] = value if threshold: assert isinstance(threshold, float) rule.attrs["threshold"] = threshold rule.attrs["threshold_calculation"] = threshold_calculation rule.attrs["portal_type"] = portal_type if valid_from: assert isinstance(valid_from, datetime) else: valid_from = FLOOR_DATETIME rule.attrs["valid_from"] = valid_from if valid_to: assert isinstance(valid_to, datetime) else: valid_to = CEILING_DATETIME rule.attrs["valid_to"] = valid_to assert isinstance(user, str) rule.attrs["user"] = user assert isinstance(group, str) rule.attrs["group"] = group return rule
def render(self): results = [] try: results = search_ldap_groups() except ldap.SERVER_DOWN: api.portal.send_email( recipient='*****@*****.**', sender='*****@*****.**', subject='[uLearn] No LDAP SERVER found in ' + self.context.absolute_url(), body="Can't contact with ldap_server to syncldapgroups in " + self.context.absolute_url(), ) return "Can't connect LDAP_SERVER." except: # Just in case the user raise a "SIZE_LIMIT_EXCEEDED" api.portal.send_email( recipient='*****@*****.**', sender='*****@*****.**', subject='[uLearn] Exception raised: SIZE_LIMIT_EXCEEDED at ' + self.context.absolute_url(), body='The sync view on the uLearn instance ' + self.context.absolute_url() + ' has reached the SIZE_LIMIT_EXCEEDED and groups have not been updated.', ) return "Error searching groups." try: from plone.protect.interfaces import IDisableCSRFProtection alsoProvides(self.request, IDisableCSRFProtection) except: pass if results: portal = api.portal.get() soup = get_soup('ldap_groups', portal) soup.clear() to_print = [] for dn, attrs in results: if 'cn' in attrs: group_id = attrs['cn'][0] record = Record() record.attrs['id'] = group_id # Index entries MUST be unicode in order to search using special chars record.attrs['searchable_id'] = group_id.decode('utf-8') soup.add(record) to_print.append(group_id) logger.info('[SYNCLDAPGROUPS]: {}'.format(to_print)) api.portal.send_email( recipient='*****@*****.**', sender='*****@*****.**', subject='[uLearn] OK! Import LDAP groups: ' + self.context.absolute_url(), body='OK - Sync LDAP groups to communities. URL: ' + self.context.absolute_url(), ) return 'Ok, groups imported.' else: api.portal.send_email( recipient='*****@*****.**', sender='*****@*****.**', subject='[uLearn] FAIL! Import LDAP groups: ' + self.context.absolute_url(), body='KO - No groups found syncing LDAP groups to communities. URL: ' + self.context.absolute_url(), ) return 'KO, no groups found.'
def render(self): results = [] try: results = search_ldap_groups() except ldap.SERVER_DOWN: api.portal.send_email( recipient='*****@*****.**', sender='*****@*****.**', subject='[uLearn] No LDAP SERVER found in ' + self.context.absolute_url(), body="Can't contact with ldap_server to syncldapgroups in " + self.context.absolute_url(), ) return "Can't connect LDAP_SERVER." except: # Just in case the user raise a "SIZE_LIMIT_EXCEEDED" api.portal.send_email( recipient='*****@*****.**', sender='*****@*****.**', subject='[uLearn] Exception raised: SIZE_LIMIT_EXCEEDED at ' + self.context.absolute_url(), body='The sync view on the uLearn instance ' + self.context.absolute_url() + ' has reached the SIZE_LIMIT_EXCEEDED and the groups has not been updated', ) return "Error searching groups." try: from plone.protect.interfaces import IDisableCSRFProtection alsoProvides(self.request, IDisableCSRFProtection) except: pass if results: portal = api.portal.get() soup = get_soup('ldap_groups', portal) soup.clear() to_print = [] for dn, attrs in results: group_id = attrs['cn'][0] record = Record() record.attrs['id'] = group_id # Index entries MUST be unicode in order to search using special chars record.attrs['searchable_id'] = group_id.decode('utf-8') soup.add(record) to_print.append(group_id) logger.info('[SYNCLDAPGROUPS]: {}'.format(to_print)) api.portal.send_email( recipient='*****@*****.**', sender='*****@*****.**', subject='[uLearn] OK! Import LDAP groups: ' + self.context.absolute_url(), body='OK - Sync LDAP groups to communities. URL: ' + self.context.absolute_url(), ) return 'Ok, groups imported.' else: api.portal.send_email( recipient='*****@*****.**', sender='*****@*****.**', subject='[uLearn] FAIL! Import LDAP groups: ' + self.context.absolute_url(), body= 'KO - No groups found syncing LDAP groups to communities. URL: ' + self.context.absolute_url(), ) return 'KO, no groups found. Error'
def add_rule(self, context, index, kind, block, value, threshold, valid_from, valid_to, user='', group=''): rule = Record() rule.attrs['index'] = index assert(isinstance(self.category, str)) rule.attrs['category'] = self.category rule.attrs['context_uid'] = uuid.UUID(IUUID(context)) rule.attrs['creator'] = plone.api.user.get_current().getId() rule.attrs['created'] = datetime.now() assert(isinstance(kind, str)) rule.attrs['kind'] = kind assert(isinstance(block, bool)) rule.attrs['block'] = block assert(isinstance(value, float)) rule.attrs['value'] = value if threshold: assert(isinstance(threshold, float)) rule.attrs['threshold'] = threshold if valid_from: assert(isinstance(valid_from, datetime)) else: valid_from = FLOOR_DATETIME rule.attrs['valid_from'] = valid_from if valid_to: assert(isinstance(valid_to, datetime)) else: valid_to = CEILING_DATETIME rule.attrs['valid_to'] = valid_to assert(isinstance(user, str)) rule.attrs['user'] = user assert(isinstance(group, str)) rule.attrs['group'] = group self.rules_soup.add(rule)
def render(self): try: from plone.protect.interfaces import IDisableCSRFProtection alsoProvides(self.request, IDisableCSRFProtection) except: pass portal = api.portal.get() soup_users_portrait = get_soup('users_portrait', portal) plugins = portal.acl_users.plugins.listPlugins(IPropertiesPlugin) # We use the most preferent plugin # If the most preferent plugin is: # mutable_properties --> users who have entered into communities # ldap --> users in LDAP pplugin = plugins[0][1] all_user_properties = pplugin.enumerateUsers() for user in all_user_properties: user_obj = api.user.get(user['id']) if user_obj: id = user['id'] maxclient, settings = getUtility(IMAXClient)() foto = maxclient.people[id].avatar imageUrl = foto.uri + '/large' portrait = urllib.urlretrieve(imageUrl) scaled, mimetype = convertSquareImage(portrait[0]) portrait = Image(id=id, file=scaled, title=id) # membertool = api.portal.get_tool(name='portal_memberdata') # membertool._setPortrait(portrait, str(id)) # import transaction # transaction.commit() member_info = get_safe_member_by_id(id) if member_info.get('fullname', False) \ and member_info.get('fullname', False) != id \ and isinstance(portrait, Image) and portrait.size != 3566 and portrait.size != 6186: portrait_user = True # 3566 is the size of defaultUser.png I don't know how get image # title. This behavior is reproduced in profile portlet. Ahora tambien 6186 else: portrait_user = False exist = [ r for r in soup_users_portrait.query(Eq('id_username', id)) ] if exist: user_record = exist[0] # Just in case that a user became a legit one and previous was a nonlegit user_record.attrs['id_username'] = id user_record.attrs['portrait'] = portrait_user else: record = Record() record_id = soup_users_portrait.add(record) user_record = soup_users_portrait.get(record_id) user_record.attrs['id_username'] = id user_record.attrs['portrait'] = portrait_user soup_users_portrait.reindex(records=[user_record]) else: logger.info( 'No user found in user repository (LDAP) {}'.format( user['id'])) logger.info('Updated portrait user for {}'.format(user['id'])) logger.info('Finish rebuild_user_portrait portal {}'.format(portal)) return 'Done'