1   /**
2    * Copyright (c) 2000-2010 Liferay, Inc. All rights reserved.
3    *
4    * This library is free software; you can redistribute it and/or modify it under
5    * the terms of the GNU Lesser General Public License as published by the Free
6    * Software Foundation; either version 2.1 of the License, or (at your option)
7    * any later version.
8    *
9    * This library is distributed in the hope that it will be useful, but WITHOUT
10   * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
11   * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
12   * details.
13   */
14  
15  package com.liferay.portlet.wiki.importers.mediawiki;
16  
17  import com.liferay.documentlibrary.service.DLLocalServiceUtil;
18  import com.liferay.portal.NoSuchUserException;
19  import com.liferay.portal.kernel.exception.PortalException;
20  import com.liferay.portal.kernel.exception.SystemException;
21  import com.liferay.portal.kernel.io.unsync.UnsyncBufferedReader;
22  import com.liferay.portal.kernel.log.Log;
23  import com.liferay.portal.kernel.log.LogFactoryUtil;
24  import com.liferay.portal.kernel.util.ArrayUtil;
25  import com.liferay.portal.kernel.util.MapUtil;
26  import com.liferay.portal.kernel.util.ObjectValuePair;
27  import com.liferay.portal.kernel.util.ProgressTracker;
28  import com.liferay.portal.kernel.util.ProgressTrackerThreadLocal;
29  import com.liferay.portal.kernel.util.StringBundler;
30  import com.liferay.portal.kernel.util.StringPool;
31  import com.liferay.portal.kernel.util.StringUtil;
32  import com.liferay.portal.kernel.util.Validator;
33  import com.liferay.portal.kernel.xml.Document;
34  import com.liferay.portal.kernel.xml.DocumentException;
35  import com.liferay.portal.kernel.xml.Element;
36  import com.liferay.portal.kernel.xml.SAXReaderUtil;
37  import com.liferay.portal.kernel.zip.ZipReader;
38  import com.liferay.portal.kernel.zip.ZipReaderFactoryUtil;
39  import com.liferay.portal.model.User;
40  import com.liferay.portal.service.ServiceContext;
41  import com.liferay.portal.service.UserLocalServiceUtil;
42  import com.liferay.portal.util.PropsValues;
43  import com.liferay.portlet.asset.NoSuchTagException;
44  import com.liferay.portlet.asset.model.AssetTag;
45  import com.liferay.portlet.asset.service.AssetTagLocalServiceUtil;
46  import com.liferay.portlet.asset.service.AssetTagPropertyLocalServiceUtil;
47  import com.liferay.portlet.asset.util.AssetUtil;
48  import com.liferay.portlet.wiki.ImportFilesException;
49  import com.liferay.portlet.wiki.NoSuchPageException;
50  import com.liferay.portlet.wiki.importers.WikiImporter;
51  import com.liferay.portlet.wiki.importers.WikiImporterKeys;
52  import com.liferay.portlet.wiki.model.WikiNode;
53  import com.liferay.portlet.wiki.model.WikiPage;
54  import com.liferay.portlet.wiki.model.WikiPageConstants;
55  import com.liferay.portlet.wiki.service.WikiPageLocalServiceUtil;
56  import com.liferay.portlet.wiki.translators.MediaWikiToCreoleTranslator;
57  
58  import java.io.File;
59  import java.io.FileReader;
60  import java.io.IOException;
61  
62  import java.util.ArrayList;
63  import java.util.Collections;
64  import java.util.HashMap;
65  import java.util.Iterator;
66  import java.util.List;
67  import java.util.Map;
68  import java.util.regex.Matcher;
69  import java.util.regex.Pattern;
70  
71  /**
72   * <a href="MediaWikiImporter.java.html"><b><i>View Source</i></b></a>
73   *
74   * @author Alvaro del Castillo
75   * @author Jorge Ferrer
76   */
77  public class MediaWikiImporter implements WikiImporter {
78  
79      public static final String SHARED_IMAGES_CONTENT = "See attachments";
80  
81      public static final String SHARED_IMAGES_TITLE = "SharedImages";
82  
83      public void importPages(
84              long userId, WikiNode node, File[] files,
85              Map<String, String[]> options)
86          throws PortalException {
87  
88          if ((files.length < 1) || (files[0] == null) || (!files[0].exists())) {
89              throw new PortalException("The pages file is mandatory");
90          }
91  
92          File pagesFile = files[0];
93          File usersFile = files[1];
94          File imagesFile = files[2];
95  
96          try {
97              Document doc = SAXReaderUtil.read(pagesFile);
98  
99              Map<String, String> usersMap = readUsersFile(usersFile);
100 
101             Element root = doc.getRootElement();
102 
103             List<String> specialNamespaces = readSpecialNamespaces(root);
104 
105             processSpecialPages(userId, node, root, specialNamespaces);
106             processRegularPages(
107                 userId, node, root, specialNamespaces, usersMap, imagesFile,
108                 options);
109             processImages(userId, node, imagesFile);
110 
111             moveFrontPage(userId, node, options);
112         }
113         catch (DocumentException de) {
114             throw new ImportFilesException("Invalid XML file provided");
115         }
116         catch (IOException de) {
117             throw new ImportFilesException("Error reading the files provided");
118         }
119         catch (PortalException e) {
120             throw e;
121         }
122         catch (Exception e) {
123             throw new PortalException(e);
124         }
125     }
126 
127     protected long getUserId(
128             long userId, WikiNode node, String author,
129             Map<String, String> usersMap)
130         throws PortalException, SystemException {
131 
132         User user = null;
133 
134         String emailAddress = usersMap.get(author);
135 
136         try {
137             if (Validator.isNull(emailAddress)) {
138                 user = UserLocalServiceUtil.getUserByScreenName(
139                     node.getCompanyId(), author.toLowerCase());
140             }
141             else {
142                 user = UserLocalServiceUtil.getUserByEmailAddress(
143                     node.getCompanyId(), emailAddress);
144             }
145         }
146         catch (NoSuchUserException nsue) {
147             user = UserLocalServiceUtil.getUserById(userId);
148         }
149 
150         return user.getUserId();
151     }
152 
153     protected void importPage(
154             long userId, String author, WikiNode node, String title,
155             String content, String summary, Map<String, String> usersMap)
156         throws PortalException {
157 
158         try {
159             long authorUserId = getUserId(userId, node, author, usersMap);
160             String parentTitle = readParentTitle(content);
161             String redirectTitle = readRedirectTitle(content);
162 
163             ServiceContext serviceContext = new ServiceContext();
164 
165             serviceContext.setAddCommunityPermissions(true);
166             serviceContext.setAddGuestPermissions(true);
167             serviceContext.setAssetTagNames(
168                 readAssetTagNames(userId, node, content));
169 
170             if (Validator.isNull(redirectTitle)) {
171                 content = _translator.translate(content);
172             }
173             else {
174                 content =
175                     StringPool.DOUBLE_OPEN_BRACKET + redirectTitle +
176                         StringPool.DOUBLE_CLOSE_BRACKET;
177             }
178 
179             WikiPage page = null;
180 
181             try {
182                 page = WikiPageLocalServiceUtil.getPage(
183                     node.getNodeId(), title);
184             }
185             catch (NoSuchPageException nspe) {
186                 page = WikiPageLocalServiceUtil.addPage(
187                     authorUserId, node.getNodeId(), title,
188                     WikiPageConstants.NEW, null, true, serviceContext);
189             }
190 
191             WikiPageLocalServiceUtil.updatePage(
192                 authorUserId, node.getNodeId(), title, page.getVersion(),
193                 content, summary, true, "creole", parentTitle, redirectTitle,
194                 serviceContext);
195         }
196         catch (Exception e) {
197             throw new PortalException("Error importing page " + title, e);
198         }
199     }
200 
201     protected boolean isSpecialMediaWikiPage(
202         String title, List<String> specialNamespaces) {
203 
204         for (String namespace: specialNamespaces) {
205             if (title.startsWith(namespace + StringPool.COLON)) {
206                 return true;
207             }
208         }
209 
210         return false;
211     }
212 
213     protected boolean isValidImage(String[] paths, byte[] bytes) {
214         if (ArrayUtil.contains(_SPECIAL_MEDIA_WIKI_DIRS, paths[0])) {
215             return false;
216         }
217 
218         if ((paths.length > 1) &&
219             (ArrayUtil.contains(_SPECIAL_MEDIA_WIKI_DIRS, paths[1]))) {
220 
221             return false;
222         }
223 
224         String fileName = paths[paths.length - 1];
225 
226         try {
227             DLLocalServiceUtil.validate(fileName, true, bytes);
228         }
229         catch (PortalException pe) {
230             return false;
231         }
232         catch (SystemException se) {
233             return false;
234         }
235 
236         return true;
237     }
238 
239     protected void moveFrontPage(
240         long userId, WikiNode node, Map<String, String[]> options) {
241 
242         String frontPageTitle = MapUtil.getString(
243             options, WikiImporterKeys.OPTIONS_FRONT_PAGE);
244 
245         if (Validator.isNotNull(frontPageTitle)) {
246             frontPageTitle = normalizeTitle(frontPageTitle);
247 
248             try {
249                 if (WikiPageLocalServiceUtil.getPagesCount(
250                         node.getNodeId(), frontPageTitle, true) > 0) {
251 
252                     ServiceContext serviceContext = new ServiceContext();
253 
254                     serviceContext.setAddCommunityPermissions(true);
255                     serviceContext.setAddGuestPermissions(true);
256 
257                     WikiPageLocalServiceUtil.movePage(
258                         userId, node.getNodeId(), frontPageTitle,
259                         WikiPageConstants.FRONT_PAGE, false, serviceContext);
260 
261                 }
262             }
263             catch (Exception e) {
264                 if (_log.isWarnEnabled()) {
265                     StringBundler sb = new StringBundler(4);
266 
267                     sb.append("Could not move ");
268                     sb.append(WikiPageConstants.FRONT_PAGE);
269                     sb.append(" to the title provided: ");
270                     sb.append(frontPageTitle);
271 
272                     _log.warn(sb.toString(), e);
273                 }
274             }
275 
276         }
277 
278     }
279 
280     protected String normalize(String categoryName, int length) {
281         categoryName = AssetUtil.toWord(categoryName.trim());
282 
283         return StringUtil.shorten(categoryName, length);
284     }
285 
286     protected String normalizeDescription(String description) {
287         description = description.replaceAll(
288             _categoriesPattern.pattern(), StringPool.BLANK);
289 
290         return normalize(description, 300);
291     }
292 
293     protected String normalizeTitle(String title) {
294         title = title.replaceAll(
295             PropsValues.WIKI_PAGE_TITLES_REMOVE_REGEXP, StringPool.BLANK);
296 
297         return StringUtil.shorten(title, 75);
298     }
299 
300     protected void processImages(long userId, WikiNode node, File imagesFile)
301         throws Exception {
302 
303         if ((imagesFile == null) || (!imagesFile.exists())) {
304             return;
305         }
306 
307         ProgressTracker progressTracker =
308             ProgressTrackerThreadLocal.getProgressTracker();
309 
310         int count = 0;
311 
312         ZipReader zipReader = ZipReaderFactoryUtil.getZipReader(imagesFile);
313 
314         List<String> entries = zipReader.getEntries();
315 
316         int total = entries.size();
317 
318         if (total > 0) {
319             try {
320                 WikiPageLocalServiceUtil.getPage(
321                     node.getNodeId(), SHARED_IMAGES_TITLE);
322             }
323             catch (NoSuchPageException nspe) {
324                 ServiceContext serviceContext = new ServiceContext();
325 
326                 serviceContext.setAddCommunityPermissions(true);
327                 serviceContext.setAddGuestPermissions(true);
328 
329                 WikiPageLocalServiceUtil.addPage(
330                     userId, node.getNodeId(), SHARED_IMAGES_TITLE,
331                     SHARED_IMAGES_CONTENT, null, true, serviceContext);
332             }
333         }
334 
335         List<ObjectValuePair<String, byte[]>> attachments =
336             new ArrayList<ObjectValuePair<String, byte[]>>();
337 
338         int percentage = 50;
339 
340         for (int i = 0; i < entries.size(); i++) {
341             String entry = entries.get(i);
342 
343             String key = entry;
344             byte[] value = zipReader.getEntryAsByteArray(entry);
345 
346             String[] paths = StringUtil.split(key, StringPool.SLASH);
347 
348             if (!isValidImage(paths, value)) {
349                 if (_log.isInfoEnabled()) {
350                     _log.info("Ignoring " + key);
351                 }
352 
353                 continue;
354             }
355 
356             String fileName = paths[paths.length - 1].toLowerCase();
357 
358             attachments.add(
359                 new ObjectValuePair<String, byte[]>(fileName, value));
360 
361             count++;
362 
363             if ((i % 5) == 0) {
364                 WikiPageLocalServiceUtil.addPageAttachments(
365                     node.getNodeId(), SHARED_IMAGES_TITLE, attachments);
366 
367                 attachments.clear();
368 
369                 percentage = Math.min(50 + (i * 50) / total, 99);
370 
371                 progressTracker.updateProgress(percentage);
372             }
373         }
374 
375         if (!attachments.isEmpty()) {
376             WikiPageLocalServiceUtil.addPageAttachments(
377                 node.getNodeId(), SHARED_IMAGES_TITLE, attachments);
378         }
379 
380         zipReader.close();
381 
382         if (_log.isInfoEnabled()) {
383             _log.info("Imported " + count + " images into " + node.getName());
384         }
385     }
386 
387     protected void processRegularPages(
388         long userId, WikiNode node, Element root,
389         List<String> specialNamespaces, Map<String, String> usersMap,
390         File imagesFile, Map<String, String[]> options) {
391 
392         boolean importLatestVersion = MapUtil.getBoolean(
393             options, WikiImporterKeys.OPTIONS_IMPORT_LATEST_VERSION);
394 
395         ProgressTracker progressTracker =
396             ProgressTrackerThreadLocal.getProgressTracker();
397 
398         int count = 0;
399 
400         List<Element> pages = root.elements("page");
401 
402         int total = pages.size();
403 
404         Iterator<Element> itr = root.elements("page").iterator();
405 
406         int percentage = 10;
407         int maxPercentage = 50;
408 
409         if ((imagesFile == null) || (!imagesFile.exists())) {
410             maxPercentage = 99;
411         }
412 
413         int percentageRange = maxPercentage - percentage;
414 
415         for (int i = 0; itr.hasNext(); i++) {
416             Element pageEl = itr.next();
417 
418             String title = pageEl.elementText("title");
419 
420             title = normalizeTitle(title);
421 
422             percentage = Math.min(
423                 10 + (i * percentageRange) / total, maxPercentage);
424 
425             progressTracker.updateProgress(percentage);
426 
427             if (isSpecialMediaWikiPage(title, specialNamespaces)) {
428                 continue;
429             }
430 
431             List<Element> revisionEls = pageEl.elements("revision");
432 
433             if (importLatestVersion) {
434                 Element lastRevisionEl = revisionEls.get(
435                     revisionEls.size() - 1);
436 
437                 revisionEls = new ArrayList<Element>();
438 
439                 revisionEls.add(lastRevisionEl);
440             }
441 
442             for (Element curRevisionEl : revisionEls) {
443                 String author = curRevisionEl.element(
444                     "contributor").elementText("username");
445                 String content = curRevisionEl.elementText("text");
446                 String summary = curRevisionEl.elementText("comment");
447 
448                 try {
449                     importPage(
450                         userId, author, node, title, content, summary,
451                         usersMap);
452                 }
453                 catch (Exception e) {
454                     if (_log.isWarnEnabled()) {
455                         StringBundler sb = new StringBundler(3);
456 
457                         sb.append("Page with title ");
458                         sb.append(title);
459                         sb.append(" could not be imported");
460 
461                         _log.warn(sb.toString(), e);
462                     }
463                 }
464             }
465 
466             count++;
467         }
468 
469         if (_log.isInfoEnabled()) {
470             _log.info("Imported " + count + " pages into " + node.getName());
471         }
472     }
473 
474     protected void processSpecialPages(
475             long userId, WikiNode node, Element root,
476             List<String> specialNamespaces)
477         throws PortalException {
478 
479         ProgressTracker progressTracker =
480             ProgressTrackerThreadLocal.getProgressTracker();
481 
482         List<Element> pages = root.elements("page");
483 
484         int total = pages.size();
485 
486         Iterator<Element> itr = pages.iterator();
487 
488         for (int i = 0; itr.hasNext(); i++) {
489             Element page = itr.next();
490 
491             String title = page.elementText("title");
492 
493             if (!title.startsWith("Category:")) {
494                 if (isSpecialMediaWikiPage(title, specialNamespaces)) {
495                     root.remove(page);
496                 }
497 
498                 continue;
499             }
500 
501             String categoryName = title.substring("Category:".length());
502 
503             categoryName = normalize(categoryName, 75);
504 
505             String description = page.element("revision").elementText("text");
506 
507             description = normalizeDescription(description);
508 
509             try {
510                 AssetTag assetTag = null;
511 
512                 try {
513                     assetTag = AssetTagLocalServiceUtil.getTag(
514                         node.getCompanyId(), categoryName);
515                 }
516                 catch (NoSuchTagException nste) {
517                     ServiceContext serviceContext = new ServiceContext();
518 
519                     serviceContext.setAddCommunityPermissions(true);
520                     serviceContext.setAddGuestPermissions(true);
521                     serviceContext.setScopeGroupId(node.getGroupId());
522 
523                     assetTag = AssetTagLocalServiceUtil.addTag(
524                         userId, categoryName, null, serviceContext);
525                 }
526 
527                 if (Validator.isNotNull(description)) {
528                     AssetTagPropertyLocalServiceUtil.addTagProperty(
529                         userId, assetTag.getTagId(), "description",
530                         description);
531                 }
532             }
533             catch (SystemException se) {
534                  _log.error(se, se);
535             }
536 
537             if ((i % 5) == 0) {
538                 progressTracker.updateProgress((i * 10) / total);
539             }
540         }
541     }
542 
543     protected String[] readAssetTagNames(
544             long userId, WikiNode node, String content)
545         throws PortalException, SystemException {
546 
547         Matcher matcher = _categoriesPattern.matcher(content);
548 
549         List<String> assetTagNames = new ArrayList<String>();
550 
551         while (matcher.find()) {
552             String categoryName = matcher.group(1);
553 
554             categoryName = normalize(categoryName, 75);
555 
556             AssetTag assetTag = null;
557 
558             try {
559                 assetTag = AssetTagLocalServiceUtil.getTag(
560                     node.getCompanyId(), categoryName);
561             }
562             catch (NoSuchTagException nste) {
563                 ServiceContext serviceContext = new ServiceContext();
564 
565                 serviceContext.setAddCommunityPermissions(true);
566                 serviceContext.setAddGuestPermissions(true);
567                 serviceContext.setScopeGroupId(node.getGroupId());
568 
569                 assetTag = AssetTagLocalServiceUtil.addTag(
570                     userId, categoryName, null, serviceContext);
571             }
572 
573             assetTagNames.add(assetTag.getName());
574         }
575 
576         if (content.indexOf(_WORK_IN_PROGRESS) != -1) {
577             assetTagNames.add(_WORK_IN_PROGRESS_TAG);
578         }
579 
580         return assetTagNames.toArray(new String[assetTagNames.size()]);
581     }
582 
583     protected String readParentTitle(String content) {
584         Matcher matcher = _parentPattern.matcher(content);
585 
586         String redirectTitle = StringPool.BLANK;
587 
588         if (matcher.find()) {
589             redirectTitle = matcher.group(1);
590 
591             redirectTitle = normalizeTitle(redirectTitle);
592 
593             redirectTitle += " (disambiguation)";
594         }
595 
596         return redirectTitle;
597     }
598     protected String readRedirectTitle(String content) {
599         Matcher matcher = _redirectPattern.matcher(content);
600 
601         String redirectTitle = StringPool.BLANK;
602 
603         if (matcher.find()) {
604             redirectTitle = matcher.group(1);
605 
606             redirectTitle = normalizeTitle(redirectTitle);
607         }
608 
609         return redirectTitle;
610     }
611     protected List<String> readSpecialNamespaces(Element root)
612         throws ImportFilesException {
613 
614         List<String> namespaces = new ArrayList<String>();
615 
616         Element siteinfoEl = root.element("siteinfo");
617 
618         if (siteinfoEl == null) {
619             throw new ImportFilesException("Invalid pages XML file");
620         }
621 
622         Iterator<Element> itr = siteinfoEl.element(
623             "namespaces").elements("namespace").iterator();
624 
625         while (itr.hasNext()) {
626             Element namespace = itr.next();
627 
628             if (!namespace.attribute("key").getData().equals("0")) {
629                 namespaces.add(namespace.getText());
630             }
631         }
632 
633         return namespaces;
634     }
635 
636     protected Map<String, String> readUsersFile(File usersFile)
637         throws IOException {
638 
639         if ((usersFile == null) || (!usersFile.exists())) {
640             return Collections.EMPTY_MAP;
641         }
642 
643         Map<String, String> usersMap = new HashMap<String, String>();
644 
645         UnsyncBufferedReader unsyncBufferedReader =
646             new UnsyncBufferedReader(new FileReader(usersFile));
647 
648         String line = unsyncBufferedReader.readLine();
649 
650         while (line != null) {
651             String[] array = StringUtil.split(line);
652 
653             if ((array.length == 2) && (Validator.isNotNull(array[0])) &&
654                 (Validator.isNotNull(array[1]))) {
655 
656                 usersMap.put(array[0], array[1]);
657             }
658             else {
659                 if (_log.isInfoEnabled()) {
660                     _log.info(
661                         "Ignoring line " + line +
662                             " because it does not contain exactly 2 columns");
663                 }
664             }
665 
666             line = unsyncBufferedReader.readLine();
667         }
668 
669         return usersMap;
670     }
671 
672     private static final String[] _SPECIAL_MEDIA_WIKI_DIRS = {
673         "thumb", "temp", "archive"
674     };
675 
676     private static final String _WORK_IN_PROGRESS = "{{Work in progress}}";
677 
678     private static final String _WORK_IN_PROGRESS_TAG = "work in progress";
679 
680     private static Log _log = LogFactoryUtil.getLog(MediaWikiImporter.class);
681 
682     private static Pattern _categoriesPattern = Pattern.compile(
683         "\\[\\[[Cc]ategory:([^\\]]*)\\]\\][\\n]*");
684     private static Pattern _parentPattern = Pattern.compile(
685         "\\{{2}OtherTopics\\|([^\\}]*)\\}{2}");
686     private static Pattern _redirectPattern = Pattern.compile(
687         "#REDIRECT \\[\\[([^\\]]*)\\]\\]");
688 
689     private MediaWikiToCreoleTranslator _translator =
690         new MediaWikiToCreoleTranslator();
691 
692 }