<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
 def filter_communities(cls, p, so, with_deleted=False):
 """Search for communities. Helper function which takes from database only those communities which match search criteria. Uses parameter 'so' to set communities in the correct order. Parameter 'page' is introduced to restrict results and return only slice of them for the current page. If page == 0 function will return all communities that match the pattern. """

        query = cls.query if with_deleted else \
            cls.query.filter(cls.deleted_at.is_(None))

        if p:
            p = p.replace(' ', '%')
            query = query.filter(db.or_(
                cls.id.ilike('%' + p + '%'),
                cls.title.ilike('%' + p + '%'),
                cls.description.ilike('%' + p + '%'),
            ))

        if so in current_app.config['COMMUNITIES_SORTING_OPTIONS']:
            order = so == 'title' and db.asc or db.desc
            query = query.order_by(order(getattr(cls, so)))
        else:
            query = query.order_by(db.desc(cls.ranking))
        return query