392a9128e3d52256a21a22dfbaa713cfed66807f
[mir.git] / source / mircoders / abuse / FilterEngine.java
1 /*
2  * Copyright (C) 2001, 2002 The Mir-coders group
3  *
4  * This file is part of Mir.
5  *
6  * Mir is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation; either version 2 of the License, or
9  * (at your option) any later version.
10  *
11  * Mir is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with Mir; if not, write to the Free Software
18  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
19  *
20  * In addition, as a special exception, The Mir-coders gives permission to link
21  * the code of this program with  any library licensed under the Apache Software License,
22  * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
23  * (or with modified versions of the above that use the same license as the above),
24  * and distribute linked combinations including the two.  You must obey the
25  * GNU General Public License in all respects for all of the code used other than
26  * the above mentioned libraries.  If you modify this file, you may extend this
27  * exception to your version of the file, but you are not obligated to do so.
28  * If you do not wish to do so, delete this exception statement from your version.
29  */
30
31 package mircoders.abuse;
32
33 import mir.entity.Entity;
34 import mir.entity.adapter.EntityAdapter;
35 import mir.entity.adapter.EntityAdapterModel;
36 import mir.entity.adapter.EntityIteratorAdapter;
37 import mir.log.LoggerWrapper;
38 import mir.session.Request;
39 import mir.storage.DatabaseExc;
40 import mir.storage.DatabaseHelper;
41 import mircoders.global.MirGlobal;
42 import mircoders.storage.DatabaseFilter;
43 import mircoders.storage.DatabaseFilterGroup;
44
45 import java.util.ArrayList;
46 import java.util.Collections;
47 import java.util.Date;
48 import java.util.HashMap;
49 import java.util.Iterator;
50 import java.util.List;
51 import java.util.Map;
52 /** The FilterEngine manages a list of all filters and filter groups.
53  *  Use the testPosting() method to apply all filters on an 
54  *  Entity (for ex. an article or a comment)
55  */
56 public class FilterEngine {
57   private final Map filterTypes = new HashMap();
58   private final List filterTypeIds = new ArrayList();
59
60   private final List filterGroups = new ArrayList();
61   private final Map idToFilterGroup = new HashMap();
62   private final LoggerWrapper logger = new LoggerWrapper("Global.Abuse.FilterEngine");
63   private EntityAdapterModel model;
64
65   public FilterEngine(EntityAdapterModel aModel) {
66     try {
67       Iterator i = MirGlobal.localizer().openPostings().getAntiAbuseFilterTypes().iterator();
68       while (i.hasNext()) {
69         FilterType filterType = (FilterType) i.next();
70
71         filterTypes.put(filterType.getName(), filterType);
72         filterTypeIds.add(filterType.getName());
73       }
74     }
75     catch (Throwable t) {
76       throw new RuntimeException(t.getMessage());
77     }
78
79     model = aModel;
80
81     reload();
82   }
83
84   /** applies all filters from all filter groups to an Entity.
85    *  The entity may be, for example, an article, or a comment.
86    *  It returns a filter that matches if it finds one, null otherwise  
87    */
88   public synchronized Filter testPosting(Entity anEntity, Request aRequest) {
89     Iterator i = filterGroups.iterator();
90     while (i.hasNext()) {
91       FilterGroup group = (FilterGroup) i.next();
92
93       Iterator j = group.getFilters().iterator();
94       while (j.hasNext()) {
95         Filter filter = (Filter) j.next();
96         try {
97           if (filter.test(anEntity, aRequest)) {
98             return filter;
99           }
100         }
101         catch (Throwable t) {
102           logger.warn("Exception thrown while testing filter " + filter.getType() + " ( " + filter.getExpression() + ") " + t.toString());
103         }
104       }
105     }
106
107     return null;
108   }
109
110   public List getFilterTypes() {
111     try {
112       List result = new ArrayList();
113
114       Iterator i = filterTypeIds.iterator();
115       while (i.hasNext()) {
116         String id = (String) i.next();
117
118         Map action = new HashMap();
119         action.put("resource", id);
120         action.put("identifier", id);
121
122         result.add(action);
123       }
124
125       return result;
126     }
127     catch (Throwable t) {
128       throw new RuntimeException("can't get article actions: " + t.getMessage());
129     }
130   }
131   /** This class reflects a row of the filter_group 
132    * database table. Filters groups allow you to organize 
133    * your filters. For example: group1=spammer ,  
134    * group2=nazis etc.  
135    */
136   public class FilterGroup {
137     private List filters;
138     private Entity entity;
139     private Map idToFilter;
140
141     public FilterGroup(Entity anEntity) {
142       this (anEntity, Collections.EMPTY_LIST);
143     }
144
145     public FilterGroup(Entity anEntity, List aFilters) {
146       entity = anEntity;
147       filters = new ArrayList();
148       idToFilter = new HashMap();
149       Iterator i = aFilters.iterator();
150
151       while (i.hasNext()) {
152         Entity entity = (Entity) i.next();
153         try {
154           Filter filter = new Filter(entity);
155           introduceFilter(filter);
156         }
157         catch (AbuseExc e) {
158         }
159       }
160     }
161
162     public Entity getEntity() {
163       return entity;
164     }
165
166     public EntityAdapter getEntityAdapter() {
167       return model.makeEntityAdapter("filterGroup",  entity);
168     }
169
170     public List getFilterEntityAdapterList() {
171       List result = new ArrayList();
172
173       Iterator i = filters.iterator();
174       while (i.hasNext()) {
175         Filter filter = (Filter) i.next();
176         result.add(filter.getEntityAdapter());
177       }
178
179       return result;
180     }
181
182     public List getFilters() {
183       return filters;
184     }
185
186     public Filter getFilterForId(String anId) {
187       Filter result = (Filter) idToFilter.get(anId);
188       if (result==null) {
189         throw new NullPointerException("No such filter");
190       }
191
192       return result;
193     }
194
195     private void introduceFilter(Filter aFilter) {
196       filters.add(aFilter);
197       idToFilter.put(aFilter.getEntity().getId(), aFilter);
198     }
199
200     private void removeFilter(Filter aFilter) {
201       filters.remove(aFilter);
202       idToFilter.remove(aFilter.getEntity().getId());
203     }
204
205     private void deleteFilter(String anId) {
206       Filter filter = getFilterForId(anId);
207       removeFilter(filter);
208       DatabaseFilter.getInstance().delete(anId);
209     }
210
211     public void populateFilterEntity(Entity anEntity, String aType, String anExpression,
212                              String aComments, String aTag, String anArticleAction,
213                              String aCommentAction) {
214
215       anEntity.setFieldValue("type", aType);
216       anEntity.setFieldValue("expression", anExpression);
217       anEntity.setFieldValue("comment", aComments);
218       anEntity.setFieldValue("tag", aTag);
219       anEntity.setFieldValue("articleaction", anArticleAction);
220       anEntity.setFieldValue("commentaction", aCommentAction);
221     }
222
223     public String updateFilter(String anId, String aType, String anExpression,
224                              String aComments, String aTag, String anArticleAction,
225                              String aCommentAction) {
226
227       try {
228         getFilterTypeForId(aType).constructFilterInstance(anExpression);
229       }
230       catch (AbuseExc e) {
231         return e.getMessage();
232       }
233
234       Entity entity = getFilterForId(anId).getEntity();
235       populateFilterEntity(entity, aType, anExpression, aComments, aTag,
236           anArticleAction, aCommentAction);
237       entity.update();
238
239       return "";
240     }
241
242     public String createFilter(String aType, String anExpression,
243                              String aComments, String aTag, String anArticleAction,
244                              String aCommentAction) throws DatabaseExc {
245       FilterInstance instance;
246
247       try {
248         instance = getFilterTypeForId(aType).constructFilterInstance(anExpression);
249       }
250       catch (AbuseExc e) {
251         return e.getMessage();
252       }
253
254       Entity entity = DatabaseFilter.getInstance().createNewEntity();
255       populateFilterEntity(entity, aType, anExpression, aComments, aTag,
256           anArticleAction, aCommentAction);
257
258
259       String priority = "1";
260
261       if (filters.size() > 0) {
262         try {
263           String lastPriorityString = ((Filter) filters.get(filters.size()-1)).getEntity().getFieldValue("priority");
264           int lastPriority = Integer.parseInt(lastPriorityString);
265           priority = Integer.toString(lastPriority + 1);
266         }
267         catch (Exception e) {
268         }
269       }
270
271       entity.setFieldValue("priority", priority);
272       entity.setFieldValue("filter_group_id", getEntity().getId());
273       entity.insert();
274
275       Filter filter = new Filter(entity, instance);
276       introduceFilter(filter);
277
278       return "";
279     }
280
281     public String moveFilterUp(String anId) {
282       Filter filter = getFilterForId(anId);
283       String priority = filter.getEntity().getFieldValue("priority");
284       int index = filters.indexOf(filter);
285       if (index>=1) {
286         Filter filterBefore= (Filter) filters.remove(index-1);
287         filters.add(index, filterBefore);
288         filter.getEntity().setFieldValue("priority", filterBefore.getEntity().getFieldValue("priority"));
289         filterBefore.getEntity().setFieldValue("priority", priority);
290         filter.getEntity().update();
291         filterBefore.getEntity().update();
292       }
293
294       return "";
295     }
296
297     public String moveFilterToTop(String anId) {
298       Filter filter = getFilterForId(anId);
299       String priority = filter.getEntity().getFieldValue("priority");
300       int index = filters.indexOf(filter);
301       if (index>0) {
302         filters.remove(index);
303         Filter filterBefore= (Filter) filters.get(0);
304         filters.add(0, filter);
305         filter.getEntity().setFieldValue("priority", filterBefore.getEntity().getFieldValue("priority"));
306         filterBefore.getEntity().setFieldValue("priority", priority);
307         filter.getEntity().update();
308         filterBefore.getEntity().update();
309       }
310
311       return "";
312     }
313
314     public String moveFilterDown(String anId) {
315       Filter filter = getFilterForId(anId);
316       String priority = filter.getEntity().getFieldValue("priority");
317       int index = filters.indexOf(filter);
318       if (index<filters.size()-1) {
319         Filter filterAfter = (Filter) filters.remove(index+1);
320         filters.add(index, filterAfter);
321         filter.getEntity().setFieldValue("priority", filterAfter.getEntity().getFieldValue("priority"));
322         filterAfter.getEntity().setFieldValue("priority", priority);
323         filter.getEntity().update();
324         filterAfter.getEntity().update();
325       }
326
327       return "";
328     }
329
330     public String moveFilterToBottom(String anId) {
331       Filter filter = getFilterForId(anId);
332       String priority = filter.getEntity().getFieldValue("priority");
333       int index = filters.indexOf(filter);
334       if (index>=0 && index<filters.size()-1) {
335         filters.remove(index);
336         Filter filterBefore= (Filter) filters.get(filters.size()-1);
337         filters.add(filters.size(), filter);
338         filter.getEntity().setFieldValue("priority", filterBefore.getEntity().getFieldValue("priority"));
339         filterBefore.getEntity().setFieldValue("priority", priority);
340         filter.getEntity().update();
341         filterBefore.getEntity().update();
342       }
343
344       return "";
345     }
346
347
348     public String getName() {
349       return entity.getFieldValue("name");
350     }
351   }
352   
353   /** This class reflects a row of the filter database table. 
354    * To actually run a filter on data, use the test() method. 
355    * This class will automatically retreive and use the correct 
356    * filter type.
357    */
358   public class Filter {
359     private Entity entity;
360     private FilterInstance instance;
361
362     public Filter(Entity anEntity) throws AbuseExc {
363       this(anEntity, getFilterTypeForId(anEntity.getFieldValue("type")).constructFilterInstance(anEntity.getFieldValue("expression")));
364     }
365
366     public Filter(Entity anEntity, FilterInstance anInstance) {
367       entity = anEntity;
368       instance = anInstance;
369     }
370
371     public Entity getEntity() {
372       return entity;
373     }
374
375     public EntityAdapter getEntityAdapter() {
376       return model.makeEntityAdapter("filter", entity);
377     }
378
379     public void update(String aType, String anExpression, String aComments, String aTag,
380                        String anArticleAction, String aCommentAction) throws AbuseExc {
381
382       instance = getFilterTypeForId(aType).constructFilterInstance(anExpression);
383
384       entity.setFieldValue("type", aType);
385       entity.setFieldValue("expression", anExpression);
386       entity.setFieldValue("tag", aType);
387       entity.setFieldValue("comment", aComments);
388       entity.setFieldValue("articleaction", anArticleAction);
389       entity.setFieldValue("commentaction", aCommentAction);
390       entity.setFieldValue("last_hit", null);
391       entity.update();
392    }
393
394     public void updateLastHit(Date aDate) {
395       entity.setFieldValue("last_hit",
396           DatabaseHelper.convertDateToInternalRepresenation(
397               new Date(System.currentTimeMillis())));
398       entity.update();
399     }
400
401     public String getType() {
402       return entity.getFieldValue("type");
403     }
404
405     public String getExpression() {
406       return entity.getFieldValue("expression");
407     }
408
409     public String getTag() {
410       return entity.getFieldValue("tag");
411     }
412
413     public String getComment() {
414       return entity.getFieldValue("comment");
415     }
416
417     public String getArticleAction() {
418       return entity.getFieldValue("articleaction");
419     }
420
421     public String getCommentAction() {
422       return entity.getFieldValue("commentaction");
423     }
424
425     public FilterInstance getInstance() {
426       return instance;
427     }
428
429     public boolean test(Entity anEntity, Request aRequest) {
430       return instance.test(anEntity, aRequest);
431     }
432   }
433
434   public synchronized void reload() {
435     filterGroups.clear();
436     idToFilterGroup.clear();
437
438     try {
439       Iterator i = new EntityIteratorAdapter("", "priority asc", 100, model, "filterGroup");
440       while (i.hasNext()) {
441         EntityAdapter entityAdapter = (EntityAdapter) i.next();
442         List filters = new ArrayList();
443         Iterator j = (Iterator) entityAdapter.getIterator("to_filters");
444         while (j.hasNext()) {
445           filters.add(((EntityAdapter) j.next()).getEntity());
446         }
447
448         FilterGroup filterGroup = new FilterGroup(entityAdapter.getEntity(), filters);
449         introduceFilterGroup(filterGroup);
450       }
451     }
452     catch (Throwable e) {
453       logger.error("Can't load filters: " + e.getMessage());
454     }
455   }
456
457   public synchronized List getFilterGroups() {
458     List result = new ArrayList();
459     Iterator i = filterGroups.iterator();
460     while (i.hasNext()) {
461       result.add(((FilterGroup) i.next()).getEntityAdapter());
462     }
463
464     return result;
465   }
466
467   public synchronized void updateFilterGroup(String anId, String aName) {
468     FilterGroup filterGroup = getFilterGroupForId(anId);
469     filterGroup.getEntity().setFieldValue("name", aName);
470     filterGroup.getEntity().update();
471   }
472
473   public synchronized void addFilterGroup(String aName) throws DatabaseExc {
474     Entity entity = DatabaseFilterGroup.getInstance().createNewEntity();
475     entity.setFieldValue("name", aName);
476
477     String priority = "1";
478
479     if (filterGroups.size() > 0) {
480       try {
481         String lastPriorityString = ((FilterGroup) filterGroups.get(filterGroups.size()-1)).getEntity().getFieldValue("priority");
482         int lastPriority = Integer.parseInt(lastPriorityString);
483         priority = Integer.toString(lastPriority + 1);
484       }
485       catch (Exception e) {
486       }
487     }
488     entity.setFieldValue("priority", priority);
489     entity.insert();
490
491     FilterGroup filterGroup = new FilterGroup(entity);
492     introduceFilterGroup(filterGroup);
493   }
494
495   public synchronized void moveFilterGroupUp(String anId) {
496     FilterGroup group = (FilterGroup) idToFilterGroup.get(anId);
497     String priority = group.getEntity().getFieldValue("priority");
498     int index = filterGroups.indexOf(group);
499     if (index>=1) {
500       FilterGroup groupBefore = (FilterGroup) filterGroups.remove(index-1);
501       filterGroups.add(index, groupBefore);
502       group.getEntity().setFieldValue("priority", groupBefore.getEntity().getFieldValue("priority"));
503       groupBefore.getEntity().setFieldValue("priority", priority);
504       group.getEntity().update();
505       groupBefore.getEntity().update();
506     }
507   }
508
509   public synchronized void moveFilterGroupDown(String anId) {
510     FilterGroup group = (FilterGroup) idToFilterGroup.get(anId);
511     String priority = group.getEntity().getFieldValue("priority");
512     int index = filterGroups.indexOf(group);
513     if (index<filterGroups.size()-1) {
514       FilterGroup groupAfter = (FilterGroup) filterGroups.remove(index+1);
515       filterGroups.add(index, groupAfter);
516       group.getEntity().setFieldValue("priority", groupAfter.getEntity().getFieldValue("priority"));
517       groupAfter.getEntity().setFieldValue("priority", priority);
518       group.getEntity().update();
519       groupAfter.getEntity().update();
520     }
521   }
522
523   public synchronized void deleteFilterGroup(String anId) {
524
525     FilterGroup filterGroup = getFilterGroupForId(anId);
526     removeFilterGroup(filterGroup);
527     DatabaseFilter.getInstance().deleteByWhereClause("filter_group_id = " + anId);
528     DatabaseFilterGroup.getInstance().delete(anId);
529   }
530
531   public synchronized void deleteFilter(String aGroupId, String anId) {
532     getFilterGroupForId(aGroupId).deleteFilter(anId);
533   }
534
535
536   public synchronized String updateFilter(String aGroupId, String anId,
537                                         String aType, String anExpression,
538                                         String aComments,
539                                         String aTag,
540                                         String anArticleAction,
541                                         String aCommentAction) {
542     return getFilterGroupForId(aGroupId).updateFilter(anId, aType,
543         anExpression, aComments, aTag, anArticleAction, aCommentAction);
544   }
545
546   public synchronized String addFilter(String aGroupId,
547                                        String aType, String anExpression,
548                                        String aComments,
549                                        String aTag,
550                                        String anArticleAction,
551                                        String aCommentAction) throws DatabaseExc {
552     return getFilterGroupForId(aGroupId).createFilter(aType, anExpression,
553         aComments, aTag, anArticleAction, aCommentAction);
554   }
555
556   public synchronized String moveFilterUp(String aGroupId, String anId) {
557     return getFilterGroupForId(aGroupId).moveFilterUp(anId);
558   }
559
560   public synchronized String moveFilterDown(String aGroupId, String anId) {
561     return getFilterGroupForId(aGroupId).moveFilterDown(anId);
562   }
563
564   public synchronized String moveFilterToTop(String aGroupId, String anId) {
565     return getFilterGroupForId(aGroupId).moveFilterToTop(anId);
566   }
567
568   public synchronized String moveFilterToBottom(String aGroupId, String anId) {
569     return getFilterGroupForId(aGroupId).moveFilterToBottom(anId);
570   }
571
572
573
574   public FilterGroup getFilterGroupForId(String anId) {
575     FilterGroup result = (FilterGroup) idToFilterGroup.get(anId);
576     if (result == null) {
577       throw new NullPointerException("No such filter group");
578     }
579
580     return result;
581   }
582
583   public Filter getFilterForId(String aGroupId, String anId) {
584     return getFilterGroupForId(aGroupId).getFilterForId(anId);
585   }
586
587
588   public List getFilters(String aFilterGroupId) {
589     return getFilterGroupForId(aFilterGroupId).getFilterEntityAdapterList();
590   }
591
592   private synchronized void introduceFilterGroup(FilterGroup aFilterGroup) {
593     filterGroups.add(aFilterGroup);
594     idToFilterGroup.put(aFilterGroup.getEntity().getId(), aFilterGroup);
595   }
596
597   private synchronized void removeFilterGroup(FilterGroup aFilterGroup) {
598     filterGroups.remove(aFilterGroup);
599     idToFilterGroup.remove(aFilterGroup.getEntity().getId());
600   }
601
602   private FilterType getFilterTypeForId(String anId) {
603     return (FilterType) filterTypes.get(anId);
604   }
605 }