#  ATContentTypes http://sf.net/projects/collective/
#  Archetypes reimplementation of the CMF core types
#  Copyright (c) 2003-2005 AT Content Types development team
#
#  This program is free software; you can redistribute it and/or modify
#  it under the terms of the GNU General Public License as published by
#  the Free Software Foundation; either version 2 of the License, or
#  (at your option) any later version.
#
#  This program is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#
#  You should have received a copy of the GNU General Public License
#  along with this program; if not, write to the Free Software
#  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA 
#
"""Find staled objects

find all objects which are:
 * visible
 * last modified more than a week ago
 * have an empty Title and empty Description
 * aren't modified after creation
 * have an autogenerated id


""" 

__author__  = 'Christian Heimes <tiran@cheimes.de>'
__docformat__ = 'restructuredtext'

from DateTime import DateTime
from Acquisition import aq_parent
from cStringIO import StringIO

portal_types = ('Document', 'Event', 'Favorite', 'File', 'Folder', 'Image',
                'Link', 'News Item', )

def findStaledObjects(self, remove=False, portal_types=portal_types):
    out      = StringIO()
    wftool   = self.portal_workflow
    catalog  = self.portal_catalog

    aweek    = DateTime() - 7
    twoweeks = DateTime() - 14
    amonth   = DateTime() - 30
    
    brains = [brain
              for brain in catalog(portal_type_operator='or',
                                   portal_type=portal_types,
                                   review_state='visible',
                                   modified={'query': aweek, 'range': 'max'},
                                  )
              if brain.Description.strip() == '' \
                 and brain.Title.strip() == '' \
                 and brain.modified == brain.created
           ]
    
    print >>out, "Found %s matching objects in the catalog" % len(brains)
    removed = 0
    
    for brain in brains:
        ob = brain.getObject()
        if not ob: continue
        id = ob.getId()
        parent = aq_parent(ob)
        if not parent.isIDAutoGenerated(id): continue
        
        removed+=1
        print >>out, "%s (%s)" % (ob.absolute_url(1), ob.portal_type)
        if remove:
            parent.manage_delObjects((id,))
    
    print >>out, "Removed: %s" % removed
    
    if not remove:
        print >>out, "NO OBJECTS REMOVED, set remove to True!"
    
    return out.getvalue()
