public Order createOrderFromAssets(WebPageRequest inReq) {
    String catalogId = inReq.findValue("catalogid");
    MediaArchive archive = getMediaArchive(catalogId);
    String[] assetids = inReq.getRequestParameters("assetid");
    Order order =
        getOrderManager()
            .createNewOrder(inReq.findValue("applicationid"), catalogId, inReq.getUserName());

    for (int i = 0; i < assetids.length; i++) {
      String id = assetids[i];
      if (id.startsWith("multiedit:hits")) {
        HitTracker hits = (HitTracker) inReq.getSessionValue(id.substring("multiedit:".length()));
        if (hits != null) {
          for (Iterator iterator = hits.iterator(); iterator.hasNext(); ) {
            Data data = (Data) iterator.next();
            Asset asset = archive.getAssetBySourcePath(data.getSourcePath());
            getOrderManager().addItemToOrder(catalogId, order, asset, null);
          }
        }
      } else {
        Asset asset = archive.getAsset(id);
        getOrderManager().addItemToOrder(catalogId, order, asset, null);
      }
    }

    getOrderManager().saveOrder(catalogId, inReq.getUser(), order);
    inReq.putPageValue("order", order);

    return order;
  }
 public void clearOrderItems(WebPageRequest inReq) {
   MediaArchive archive = getMediaArchive(inReq);
   HitTracker items = findOrderItems(inReq);
   Searcher searcher = getSearcherManager().getSearcher(archive.getCatalogId(), "orderitem");
   for (Iterator iterator = items.iterator(); iterator.hasNext(); ) {
     Data item = (Data) iterator.next();
     searcher.delete(item, inReq.getUser());
   }
 }
  public void toggleItemInOrderBasket(WebPageRequest inReq) {
    MediaArchive archive = getMediaArchive(inReq);
    Order basket = loadOrderBasket(inReq);
    String assetid = inReq.getRequestParameter("assetid");

    Asset asset = archive.getAsset(assetid, inReq);

    getOrderManager().toggleItemInOrder(archive, basket, asset);
  }
  /**
   * Is this needed?
   *
   * @deprecated
   * @param inReq
   */
  public void createQuickOrder(WebPageRequest inReq) {

    MediaArchive archive = getMediaArchive(inReq);

    OrderManager manager = getOrderManager();
    String catalogid = inReq.findValue("catalogid");
    Searcher searcher = getSearcherManager().getSearcher(catalogid, "order");
    Searcher itemsearcher = getSearcherManager().getSearcher(catalogid, "orderitem");

    Order order = (Order) searcher.createNewData();
    order.setProperty("userid", inReq.getUserName());
    String quickpublishid = inReq.getRequestParameter("quickid");
    Data publishtemplate = archive.getData("quickpublish", quickpublishid);

    order.setProperty(
        "publishdestination",
        publishtemplate.get(
            "publishdestination")); // assume 0 for most orders, 0 can be told to use Aspera
    searcher.saveData(order, inReq.getUser());

    String hitssessionid = inReq.getRequestParameter("hitssessionid");
    HitTracker hits = (HitTracker) inReq.getSessionValue(hitssessionid);
    for (Iterator iterator = hits.getSelectedHitracker().iterator(); iterator.hasNext(); ) {
      Data hit = (Data) iterator.next();
      Data item = itemsearcher.createNewData();
      item.setProperty("presetid", publishtemplate.get("convertpreset"));
      item.setProperty("assetid", hit.getId());
      item.setProperty("orderid", order.getId());

      item.setId(itemsearcher.nextId());
      itemsearcher.saveData(item, inReq.getUser());
    }

    List assetids =
        manager.addConversionAndPublishRequest(
            inReq, order, archive, new HashMap(), inReq.getUser());
    // OrderHistory history =
    // getOrderManager().createNewHistory(archive.getCatalogId(), order,
    // inReq.getUser(), "pending");
    // history.setAssetIds(assetids);
    // manager.saveOrderWithHistory(archive.getCatalogId(), inReq.getUser(),
    // order, history);
    //		if (assetids.size() > 0)
    //		{
    //			order.setProperty("orderstatus", "ordered");
    //		}
    //		manager.saveOrder(archive.getCatalogId(), inReq.getUser(), order);
    inReq.putPageValue("order", order);
    inReq.putPageValue("data", order);

    log.info("Added conversion and publish requests for order id:" + order.getId());
  }
  public void removeSelectionFromOrderBasket(WebPageRequest inReq) {
    MediaArchive archive = getMediaArchive(inReq);
    Order basket = loadOrderBasket(inReq);
    String hitssessionid = inReq.getRequestParameter("hitssessionid");
    HitTracker assets = (HitTracker) inReq.getSessionValue(hitssessionid);

    for (Iterator iterator = assets.getSelectedHitracker().iterator(); iterator.hasNext(); ) {

      Data hit = (Data) iterator.next();
      Asset asset = getMediaArchive(archive.getCatalogId()).getAsset(hit.getId());
      getOrderManager().removeItemFromOrder(archive.getCatalogId(), basket, asset);
    }
    inReq.removeSessionValue(hitssessionid);
    loadAssets(inReq);
  }
  protected void processDeleteLog(File inLog, MediaArchive inArchive, ConvertStatus inStatus)
      throws FileNotFoundException, IOException, Exception {
    BufferedReader reader = new BufferedReader(new FileReader(inLog));
    try {
      String line = reader.readLine();
      int count = 0;
      while (line != null) {
        String[] tabs = line.split("\t");
        if (tabs.length > 3) {
          if ("Record deleted".equals(tabs[3])) {
            String catName = inLog.getName();
            if (catName.indexOf('-') != -1) {
              catName = catName.substring(0, catName.indexOf('-'));
            } else if (catName.indexOf('.') != -1) {
              catName = catName.substring(0, catName.lastIndexOf('.'));
            }
            String recordId = tabs[4];
            String cumulusid = catName + "_" + recordId; // /createCumulusID(catName, recordId);

            // catName = extractId(catName);
            // Category root =
            // inArchive.getStore().getCatalogArchive().getRootCatalog().getChildByName(catName);
            SearchQuery query = inArchive.getAssetSearcher().createSearchQuery();
            query.addExact("cumulusid", cumulusid);
            HitTracker hits = inArchive.getAssetSearcher().search(query);
            if (hits.getTotal() > 0) {
              count++;
              String id = hits.get(0).get("id");
              deleteAsset(inArchive, id);
            } else {
              log.debug("No record found " + catName + "dash" + recordId);
            }
          }
        }
        line = reader.readLine();
      }
      if (count > 0) {
        inArchive.getAssetSearcher().flush();
        logMessage(inStatus, "Removed " + count + " records");
      }
    } finally {
      FileUtils.safeClose(reader);
    }
  }
  public List removeExpiredAssets(MediaArchive archive, String sourcepath, User inUser) {
    AssetSearcher searcher = archive.getAssetSearcher();
    SearchQuery q = searcher.createSearchQuery();
    HitTracker assets = null;
    if (sourcepath == null) {
      assets = searcher.getAllHits();
    } else {
      q.addStartsWith("sourcepath", sourcepath);
      assets = searcher.search(q);
    }
    List<String> removed = new ArrayList<String>();
    List<String> sourcepaths = new ArrayList<String>();

    for (Object obj : assets) {
      Data hit = (Data) obj;
      sourcepaths.add(hit.get("sourcepath")); // TODO: Move to using page of hits
      if (sourcepaths.size() > 250000) {
        log.error("Should not load up so many paths");
        break;
      }
    }
    for (String path : sourcepaths) {
      Asset asset = archive.getAssetBySourcePath(path);
      if (asset == null) {
        continue;
      }
      String assetsource = asset.getSourcePath();
      String pathToOriginal =
          "/WEB-INF/data" + archive.getCatalogHome() + "/originals/" + assetsource;
      if (asset.isFolder() && asset.getPrimaryFile() != null) {
        pathToOriginal = pathToOriginal + "/" + asset.getPrimaryFile();
      }
      Page page = getPageManager().getPage(pathToOriginal);
      if (!page.exists()) {
        removed.add(asset.getSourcePath());
        archive.removeGeneratedImages(asset);
        archive.getAssetSearcher().delete(asset, inUser);
      }
    }
    return removed;
  }
  protected Asset createAssetFromPage(MediaArchive inArchive, User inUser, Page inAssetPage) {
    Asset asset =
        getAssetUtilities().createAssetIfNeeded(inAssetPage.getContentItem(), inArchive, inUser);
    boolean existing = true;
    if (asset == null) {
      // Should never call this
      String originals = "/WEB-INF/data" + inArchive.getCatalogHome() + "/originals/";
      String sourcepath = inAssetPage.getPath().substring(originals.length());
      asset = inArchive.getAssetBySourcePath(sourcepath);
      return asset;
    }
    if (asset.get("recordmodificationdate") == null) {
      existing = false;
    }
    inArchive.saveAsset(asset, inUser);
    if (existing) {
      inArchive.fireMediaEvent("asset/originalmodified", inUser, asset);
    } else {
      inArchive.fireMediaEvent("asset/assetcreated", inUser, asset);
    }

    inArchive.fireMediaEvent("importing/assetsimported", inUser, asset);

    return asset;
  }
  public Order loadOrderBasket(WebPageRequest inReq) {
    Order basket = null;
    try {
      MediaArchive archive = getMediaArchive(inReq);
      basket = (Order) inReq.getPageValue("orderbasket");

      if (basket == null) {
        String id = inReq.getUserName() + "_orderbasket";
        String appid = inReq.findValue("applicationid");
        Searcher searcher = getSearcherManager().getSearcher(archive.getCatalogId(), "order");
        basket = (Order) searcher.searchById(id);
        if (basket == null) {
          basket =
              getOrderManager().createNewOrder(appid, archive.getCatalogId(), inReq.getUserName());
          basket.setId(id);
          basket.setProperty("ordertype", "basket");
          getOrderManager().saveOrder(archive.getCatalogId(), inReq.getUser(), basket);
        }
        basket.setProperty("basket", "true");
        basket.setProperty("ordertype", "basket");

        inReq.putSessionValue("orderbasket", basket);
      }
      inReq.putPageValue("order", basket);

      HitTracker items =
          loadOrderManager(inReq).findOrderItems(inReq, archive.getCatalogId(), basket);
      inReq.putPageValue("orderitems", items);

      String check = inReq.findValue("clearmissing");
      if (Boolean.parseBoolean(check)) {
        // Make sure these have the same number of assets found
        getOrderManager().removeMissingAssets(inReq, archive, basket, items);
      }
    } catch (Throwable ex) {
      log.error(ex);
    }

    return basket;
  }
  public Data addItemToOrderBasket(WebPageRequest inReq) {
    MediaArchive archive = getMediaArchive(inReq);
    Order basket = loadOrderBasket(inReq);
    String[] assetids = inReq.getRequestParameters("assetid");
    String[] fields = inReq.getRequestParameters("field");
    Map props = new HashMap();
    if (fields != null) {
      for (int i = 0; i < fields.length; i++) {
        String key = fields[i];
        String value = inReq.getRequestParameter(key + ".value");
        props.put(key, value);
      }
    }

    for (int i = 0; i < assetids.length; i++) {
      String assetid = assetids[i];
      Asset asset = archive.getAsset(assetid);
      getOrderManager().addItemToOrder(archive.getCatalogId(), basket, asset, props);
    }

    return basket;
  }
  public boolean checkItemApproval(WebPageRequest inReq) throws Exception {

    if (inReq.getUser() == null) {
      return false;
    }
    MediaArchive archive = getMediaArchive(inReq);

    // Searcher ordersearcher =
    // archive.getSearcherManager().getSearcher(archive.getCatalogId(),
    // "order");
    // SearchQuery search = ordersearcinKeyher.createSearchQuery();
    // search.addExact("userid", inReq.getUser().getId());
    // search.addExact("orderstatus", "processed");
    // search.addSortBy("date");
    // HitTracker hits = ordersearcher.search(search);
    // look for the most recent order for an approved asset
    Asset asset = (Asset) inReq.getPageValue("asset");
    String sourcepath = null;
    if (asset != null) {
      sourcepath = asset.getSourcePath();
    } else {
      sourcepath = archive.getSourcePathForPage(inReq);
    }
    if (sourcepath == null) {
      return false;
    }
    Searcher itemsearcher =
        archive.getSearcherManager().getSearcher(archive.getCatalogId(), "orderitem");
    SearchQuery search = itemsearcher.createSearchQuery();
    search.addExact("userid", inReq.getUser().getId());
    search.addExact("assetsourcepath", sourcepath);
    search.addMatches("status", "approved");
    HitTracker results = itemsearcher.search(search);
    if (results.size() > 0) {
      return true;
    }
    return false;
  }
  public Data createAssetFromExistingFile(
      MediaArchive inArchive, User inUser, boolean unzip, String inSourcepath) {
    String catalogid = inArchive.getCatalogId();

    String originalspath = "/WEB-INF/data/" + catalogid + "/originals/";
    Page page = getPageManager().getPage(originalspath + inSourcepath);
    if (!page.exists()) {
      return null;
    }

    String ext = PathUtilities.extractPageType(page.getName());
    if (unzip && "zip".equalsIgnoreCase(ext)) {
      // unzip and create
      List assets = new ArrayList();
      // the folder we are in
      Page parentfolder = getPageManager().getPage(page.getParentPath());
      File dest = new File(parentfolder.getContentItem().getAbsolutePath());
      String destpath = dest.getAbsolutePath();
      ZipUtil zip = new ZipUtil();
      zip.setPageManager(getPageManager());
      try {
        List files = zip.unzip(page.getContentItem().getInputStream(), dest);
        for (Object o : files) {
          File f = (File) o;
          String path = f.getAbsolutePath().substring(destpath.length());
          path = path.replace('\\', '/');
          path = parentfolder.getPath() + path; // fix slashes
          Page p = getPageManager().getPage(path);
          Asset asset = createAssetFromPage(inArchive, inUser, p);
          if (asset != null) {
            assets.add(asset);
          }
        }

        getPageManager().removePage(page);
        CompositeAsset results = new CompositeAsset(inArchive, new ListHitTracker(assets));

        return results;
      } catch (Exception e) {
        throw new OpenEditException(e);
      }
    } else {
      return createAssetFromPage(inArchive, inUser, page);
    }
  }
  /**
   * @param inArchive
   * @param inAssetID
   * @throws StoreException
   */
  protected void deleteAsset(MediaArchive inArchive, String inAssetID) {
    // String id = findAssetId(tabs[5],tabs[4],catName);

    Asset product = inArchive.getAsset(inAssetID);
    if (product == null) {
      inArchive.getAssetSearcher().deleteFromIndex(inAssetID); // Just in case index is out of date
    } else {
      String sourcePath = product.getSourcePath();
      Page thumb = inArchive.getCreatorManager().getThumbImageFile(sourcePath);
      Page medium = inArchive.getCreatorManager().getMediumImageFile(sourcePath);
      getPageManager().removePage(thumb);
      getPageManager().removePage(medium);

      inArchive.getAssetSearcher().deleteFromIndex(inAssetID);
      inArchive.getAssetArchive().deleteAsset(product);
      inArchive.getAssetArchive().clearAsset(product);
    }
  }