nsresult nsIDNService::stringPrepAndACE(const nsAString& in, nsACString& out)
{
  nsresult rv = NS_OK;

  out.Truncate();

  if (in.Length() > kMaxDNSNodeLen) {
    NS_ERROR("IDN node too large");
    return NS_ERROR_FAILURE;
  }

  if (IsASCII(in))
    LossyCopyUTF16toASCII(in, out);
  else {
    nsAutoString strPrep;
    rv = stringPrep(in, strPrep);
    if (NS_SUCCEEDED(rv)) {
      if (IsASCII(strPrep))
        LossyCopyUTF16toASCII(strPrep, out);
      else
        rv = encodeToACE(strPrep, out);
    }
  }

  if (out.Length() > kMaxDNSNodeLen) {
    NS_ERROR("IDN node too large");
    return NS_ERROR_FAILURE;
  }

  return rv;
}
void CBrowserView::OnCopyLinkLocation()
{
    if(! mCtxMenuLinkUrl.Length())
        return;

    if (! OpenClipboard())
        return;

    HGLOBAL hClipData = ::GlobalAlloc(GMEM_MOVEABLE | GMEM_DDESHARE, mCtxMenuLinkUrl.Length() + 1);
    if(! hClipData)
        return;

    char *pszClipData = (char*)::GlobalLock(hClipData);
    if(!pszClipData)
        return;

    nsFixedCString clipDataStr(pszClipData, mCtxMenuLinkUrl.Length() + 1);
    LossyCopyUTF16toASCII(mCtxMenuLinkUrl, clipDataStr);
    NS_ASSERTION(clipDataStr.get() == pszClipData, "buffer too small");

    GlobalUnlock(hClipData);

    EmptyClipboard();
    SetClipboardData(CF_TEXT, hClipData);
    CloseClipboard();
}
Esempio n. 3
0
BOOL CMapiApi::GetStringFromProp( LPSPropValue pVal, nsCString& val, BOOL delVal)
{
  BOOL bResult = TRUE;
  if ( pVal && (PROP_TYPE( pVal->ulPropTag) == PT_STRING8))
    val = pVal->Value.lpszA;
  else if ( pVal && (PROP_TYPE( pVal->ulPropTag) == PT_UNICODE))
    LossyCopyUTF16toASCII((PRUnichar *) pVal->Value.lpszW, val);
  else if (pVal && (PROP_TYPE( pVal->ulPropTag) == PT_NULL))
    val.Truncate();
  else if (pVal && (PROP_TYPE( pVal->ulPropTag) == PT_ERROR)) {
    val.Truncate();
    bResult = FALSE;
  }
  else {
    if (pVal) {
      MAPI_TRACE1( "GetStringFromProp: invalid value, expecting string - %d\n", (int) PROP_TYPE( pVal->ulPropTag));
    }
    else {
      MAPI_TRACE0( "GetStringFromProp: invalid value, expecting string, got null pointer\n");
    }
    val.Truncate();
    bResult = FALSE;
  }
  if (pVal && delVal)
    MAPIFreeBuffer( pVal);

  return( bResult);
}
Esempio n. 4
0
void txMozillaXMLOutput::processHTTPEquiv(nsIAtom* aHeader, const nsString& aValue)
{
    // For now we only handle "refresh". There's a longer list in
    // HTMLContentSink::ProcessHeaderData
    if (aHeader == txHTMLAtoms::refresh)
        LossyCopyUTF16toASCII(aValue, mRefreshString);
}
Esempio n. 5
0
/* According to the cups.development forum, only plain ASCII may be
 * reliably used for CUPS print job titles. See
 * <http://www.cups.org/newsgroups.php?s523+gcups.development+v530+T0>.
 */
void
nsPrintJobCUPS::SetJobTitle(const PRUnichar *aTitle)
{
    if (aTitle) {
        LossyCopyUTF16toASCII(aTitle, mJobTitle);
    }
}
Esempio n. 6
0
nsMsgCompFields::nsMsgCompFields()
{
  PRInt16 i;
  for (i = 0; i < MSG_MAX_HEADERS; i ++)
    m_headers[i] = nsnull;

  m_body.Truncate();

  m_attachVCard = false;
  m_forcePlainText = false;
  m_useMultipartAlternative = false;
  m_returnReceipt = false;
  m_receiptHeaderType = nsIMsgMdnGenerator::eDntType;
  m_DSN = false;
  m_bodyIsAsciiOnly = false;
  m_forceMsgEncoding = false;
  m_needToCheckCharset = true;

  // Get the default charset from pref, use this as a mail charset.
  nsString charset;
  NS_GetLocalizedUnicharPreferenceWithDefault(nsnull, "mailnews.send_default_charset", 
                                              NS_LITERAL_STRING("ISO-8859-1"), charset);

  LossyCopyUTF16toASCII(charset, m_DefaultCharacterSet); // Charsets better be ASCII
  SetCharacterSet(m_DefaultCharacterSet.get());
}
nsresult
nsDirIndexParser::Init() {
  mLineStart = 0;
  mHasDescription = PR_FALSE;
  mFormat = nsnull;

  // get default charset to be used for directory listings (fallback to
  // ISO-8859-1 if pref is unavailable).
  NS_NAMED_LITERAL_CSTRING(kFallbackEncoding, "ISO-8859-1");
  nsXPIDLString defCharset;
  nsCOMPtr<nsIPrefBranch> prefs(do_GetService(NS_PREFSERVICE_CONTRACTID));
  if (prefs) {
    nsCOMPtr<nsIPrefLocalizedString> prefVal;
    prefs->GetComplexValue("intl.charset.default",
                           NS_GET_IID(nsIPrefLocalizedString),
                           getter_AddRefs(prefVal));
    if (prefVal)
      prefVal->ToString(getter_Copies(defCharset));
  }
  if (!defCharset.IsEmpty())
    LossyCopyUTF16toASCII(defCharset, mEncoding); // charset labels are always ASCII
  else
    mEncoding.Assign(kFallbackEncoding);
 
  nsresult rv;
  // XXX not threadsafe
  if (gRefCntParser++ == 0)
    rv = CallGetService(NS_ITEXTTOSUBURI_CONTRACTID, &gTextToSubURI);
  else
    rv = NS_OK;

  return rv;
}
Esempio n. 8
0
void ExtractMetaCharset(const wchar_t* body, int bodySz, /*out*/nsCString& charset)
{
  charset.Truncate();
  const wchar_t* body_end = body+bodySz;
  const wchar_t str_eohd[] = L"/head";
  const wchar_t *str_eohd_end = str_eohd+sizeof(str_eohd)/sizeof(str_eohd[0])-1;
  const wchar_t* eohd_pos = std::search(body, body_end, str_eohd, str_eohd_end,
                                        CaseInsensitiveComp);
  if (eohd_pos == body_end) // No header!
    return;
  const wchar_t str_chset[] = L"charset=";
  const wchar_t *str_chset_end =
    str_chset + sizeof(str_chset)/sizeof(str_chset[0])-1;
  const wchar_t* chset_pos = std::search(body, eohd_pos, str_chset,
                                         str_chset_end, CaseInsensitiveComp);
  if (chset_pos == eohd_pos) // No charset!
    return;
  chset_pos += 8;

  // remove everything from the string after the next ; or " or space,
  // whichever comes first.
  // The inital sting looks something like
  // <META content="text/html; charset=utf-8" http-equiv=Content-Type>
  // <META content="text/html; charset=utf-8;" http-equiv=Content-Type>
  // <META content="text/html; charset=utf-8 ;" http-equiv=Content-Type>
  // <META content="text/html; charset=utf-8 " http-equiv=Content-Type>
  const wchar_t term[] = L";\" ", *term_end= term+sizeof(term)/sizeof(term[0])-1;
  const wchar_t* chset_end = std::find_first_of(chset_pos, eohd_pos, term,
                                                term_end);
  if (chset_end != eohd_pos)
    LossyCopyUTF16toASCII(Substring(chset_pos, chset_end), charset);
}
Esempio n. 9
0
nsresult nsAutoConfig::PromptForEMailAddress(nsACString &emailAddress)
{
    nsresult rv;
    nsCOMPtr<nsIPromptService> promptService = do_GetService("@mozilla.org/embedcomp/prompt-service;1", &rv);
    NS_ENSURE_SUCCESS(rv, rv);
    nsCOMPtr<nsIStringBundleService> bundleService = do_GetService(NS_STRINGBUNDLE_CONTRACTID, &rv);
    NS_ENSURE_SUCCESS(rv, rv);

    nsCOMPtr<nsIStringBundle> bundle;
    rv = bundleService->CreateBundle("chrome://autoconfig/locale/autoconfig.properties",
                                getter_AddRefs(bundle));
    NS_ENSURE_SUCCESS(rv, rv);

    nsXPIDLString title;
    rv = bundle->GetStringFromName(NS_LITERAL_STRING("emailPromptTitle").get(), getter_Copies(title));
    NS_ENSURE_SUCCESS(rv, rv);

    nsXPIDLString err;
    rv = bundle->GetStringFromName(NS_LITERAL_STRING("emailPromptMsg").get(), getter_Copies(err));
    NS_ENSURE_SUCCESS(rv, rv);
    bool check = false;
    nsXPIDLString emailResult;
    bool success;
    rv = promptService->Prompt(nsnull, title.get(), err.get(), getter_Copies(emailResult), nsnull, &check, &success);
    if (!success)
      return NS_ERROR_FAILURE;
    NS_ENSURE_SUCCESS(rv, rv);
    LossyCopyUTF16toASCII(emailResult, emailAddress);
    return NS_OK;
}
Esempio n. 10
0
nsresult
nsPlatformCharset::MapToCharset(nsAString& inANSICodePage, nsACString& outCharset)
{
  //delay loading os2charset.properties bundle if possible
  if (inANSICodePage.EqualsLiteral("os2.850")) {
    outCharset.AssignLiteral("IBM850");
    return NS_OK;
  } 

  if (inANSICodePage.EqualsLiteral("os2.932")) {
    outCharset.AssignLiteral("Shift_JIS");
    return NS_OK;
  } 

  // ensure the .property file is loaded
  nsresult rv = InitInfo();
  if (NS_FAILED(rv)) {
    outCharset.AssignLiteral("IBM850");
    return rv;
  }

  nsAutoString charset;
  rv = gInfo->Get(inANSICodePage, charset);
  if (NS_FAILED(rv)) {
    outCharset.AssignLiteral("IBM850");
    return rv;
  }

  LossyCopyUTF16toASCII(charset, outCharset);
  return NS_OK;
}
Esempio n. 11
0
void
HttpServer::GetCertKey(nsACString& aKey)
{
  nsAutoString tmp;
  if (mCert) {
    mCert->GetSha256Fingerprint(tmp);
  }
  LossyCopyUTF16toASCII(tmp, aKey);
}
Esempio n. 12
0
nsresult
nsPlatformCharset::ConvertLocaleToCharsetUsingDeprecatedConfig(nsAString& locale, nsACString& oResult)
{

  // locked for thread safety 
  {
    nsAutoLock guard(gLock);
    if (!gInfo_deprecated) {
      nsGREResProperties *info =
          new nsGREResProperties(NS_LITERAL_CSTRING("unixcharset.properties"));
      NS_ASSERTION(info, "cannot create nsGREResProperties");
      gInfo_deprecated = info;
    }
  }

  if (gInfo_deprecated && !(locale.IsEmpty())) {
    nsAutoString platformLocaleKey;
    // note: NS_LITERAL_STRING("locale." OSTYPE ".") does not compile on AIX
    platformLocaleKey.AssignLiteral("locale.");
    platformLocaleKey.AppendWithConversion(OSTYPE);
    platformLocaleKey.AppendLiteral(".");
    platformLocaleKey.Append(locale);

    nsAutoString charset;
    nsresult res = gInfo_deprecated->Get(platformLocaleKey, charset);
    if (NS_SUCCEEDED(res))  {
      LossyCopyUTF16toASCII(charset, oResult);
      return NS_OK;
    }
    nsAutoString localeKey;
    localeKey.AssignLiteral("locale.all.");
    localeKey.Append(locale);
    res = gInfo_deprecated->Get(localeKey, charset);
    if (NS_SUCCEEDED(res))  {
      LossyCopyUTF16toASCII(charset, oResult);
      return NS_OK;
    }
   }
   NS_ERROR("unable to convert locale to charset using deprecated config");
   mCharset.AssignLiteral("ISO-8859-1");
   oResult.AssignLiteral("ISO-8859-1");
   return NS_SUCCESS_USING_FALLBACK_LOCALE;
}
Esempio n. 13
0
nsresult nsPlatformCharset::MapToCharset(short script, short region, nsACString& outCharset)
{
  switch (region) {
    case verUS:
    case verFrance:
    case verGermany:
      outCharset.AssignLiteral("x-mac-roman");
      return NS_OK;
    case verJapan:
      outCharset.AssignLiteral("Shift_JIS");
      return NS_OK;
  }

  // ensure the .property file is loaded
  nsresult rv = InitInfo();
  NS_ENSURE_SUCCESS(rv, rv);

  // try mapping from region then from script
  nsAutoString key(NS_LITERAL_STRING("region."));
  key.AppendInt(region, 10);

  nsAutoString uCharset;
  rv = gInfo->Get(key, uCharset);
  if (NS_SUCCEEDED(rv))
    LossyCopyUTF16toASCII(uCharset, outCharset);
  else {
    key.AssignLiteral("script.");
    key.AppendInt(script, 10);
    rv = gInfo->Get(key, uCharset);
    // not found in the .property file, assign x-mac-roman
    if (NS_SUCCEEDED(rv))
      LossyCopyUTF16toASCII(uCharset, outCharset);
    else {
      outCharset.AssignLiteral("x-mac-roman");
    }
  }
  
  return NS_OK;
}
Esempio n. 14
0
const char *nsStringToCString(const nsAString &str) {
  const char *cStr;
  nsCString tmpStr;

#ifdef _WIN32
  LossyCopyUTF16toASCII(str, tmpStr);
#else
  CopyUTF16toUTF8(str, tmpStr);
#endif

  NS_CStringGetData(tmpStr, &cStr);
  return strdup(cStr);
}
// C++ file contents
NeckoParent::NeckoParent()
{
  // Init HTTP protocol handler now since we need atomTable up and running very
  // early (IPDL argument handling for PHttpChannel constructor needs it) so
  // normal init (during 1st Http channel request) isn't early enough.
  nsCOMPtr<nsIProtocolHandler> proto =
    do_GetService("@mozilla.org/network/protocol;1?name=http");

  if (UsingNeckoIPCSecurity()) {
    // cache values for core/packaged apps basepaths
    nsAutoString corePath, webPath;
    nsCOMPtr<nsIAppsService> appsService = do_GetService(APPS_SERVICE_CONTRACTID);
    if (appsService) {
      appsService->GetCoreAppsBasePath(corePath);
      appsService->GetWebAppsBasePath(webPath);
    }
    // corePath may be empty: we don't use it for all build types
    MOZ_ASSERT(!webPath.IsEmpty());

    LossyCopyUTF16toASCII(corePath, mCoreAppsBasePath);
    LossyCopyUTF16toASCII(webPath, mWebAppsBasePath);
  }
}
mozilla::ipc::IPCResult
GamepadTestChannelParent::RecvGamepadTestEvent(const uint32_t& aID,
                                               const GamepadChangeEvent& aEvent)
{
  mozilla::ipc::AssertIsOnBackgroundThread();
  RefPtr<GamepadPlatformService>  service =
    GamepadPlatformService::GetParentService();
  MOZ_ASSERT(service);
  if (aEvent.type() == GamepadChangeEvent::TGamepadAdded) {
    const GamepadAdded& a = aEvent.get_GamepadAdded();
    nsCString gamepadID;
    LossyCopyUTF16toASCII(a.id(), gamepadID);
    uint32_t index = service->AddGamepad(gamepadID.get(),
                                         static_cast<GamepadMappingType>(a.mapping()),
                                         a.hand(),
                                         a.num_buttons(),
                                         a.num_axes(),
                                         a.num_haptics());
    if (!mShuttingdown) {
      Unused << SendReplyGamepadIndex(aID, index);
    }
    return IPC_OK();
  }
  if (aEvent.type() == GamepadChangeEvent::TGamepadRemoved) {
    const GamepadRemoved& a = aEvent.get_GamepadRemoved();
    service->RemoveGamepad(a.index());
    return IPC_OK();
  }
  if (aEvent.type() == GamepadChangeEvent::TGamepadButtonInformation) {
    const GamepadButtonInformation& a = aEvent.get_GamepadButtonInformation();
    service->NewButtonEvent(a.index(), a.button(), a.pressed(), a.touched(),
                            a.value());
    return IPC_OK();
  }
  if (aEvent.type() == GamepadChangeEvent::TGamepadAxisInformation) {
    const GamepadAxisInformation& a = aEvent.get_GamepadAxisInformation();
    service->NewAxisMoveEvent(a.index(), a.axis(), a.value());
    return IPC_OK();
  }
  if (aEvent.type() == GamepadChangeEvent::TGamepadPoseInformation) {
    const GamepadPoseInformation& a = aEvent.get_GamepadPoseInformation();
    service->NewPoseEvent(a.index(), a.pose_state());
    return IPC_OK();
  }

  NS_WARNING("Unknown event type.");
  return IPC_FAIL_NO_REASON(this);
}
nsresult
nsSmtpServer::GetPasswordWithoutUI()
{
  nsresult rv;
  nsCOMPtr<nsILoginManager> loginMgr(do_GetService(NS_LOGINMANAGER_CONTRACTID,
                                                   &rv));
  NS_ENSURE_SUCCESS(rv, rv);

  NS_ConvertASCIItoUTF16 serverUri(GetServerURIInternal(false));

  uint32_t numLogins = 0;
  nsILoginInfo** logins = nullptr;
  rv = loginMgr->FindLogins(&numLogins, serverUri, EmptyString(),
                            serverUri, &logins);
  // Login manager can produce valid fails, e.g. NS_ERROR_ABORT when a user
  // cancels the master password dialog. Therefore handle that here, but don't
  // warn about it.
  if (NS_FAILED(rv))
    return rv;

  // Don't abort here, if we didn't find any or failed, then we'll just have
  // to prompt.
  if (numLogins > 0)
  {
    nsCString serverCUsername;
    rv = GetUsername(serverCUsername);
    NS_ConvertASCIItoUTF16 serverUsername(serverCUsername);

    nsString username;
    for (uint32_t i = 0; i < numLogins; ++i)
    {
      rv = logins[i]->GetUsername(username);
      NS_ENSURE_SUCCESS(rv, rv);

      if (username.Equals(serverUsername))
      {
        nsString password;
        rv = logins[i]->GetPassword(password);
        NS_ENSURE_SUCCESS(rv, rv);

        LossyCopyUTF16toASCII(password, m_password);
        break;
      }
    }
  }
  NS_FREE_XPCOM_ISUPPORTS_POINTER_ARRAY(numLogins, logins);
  return NS_OK;
}
Esempio n. 18
0
nsresult
nsMsgPrintEngine::FireThatLoadOperation(const nsString& uri)
{
  nsresult rv;
  
  nsCString uriCStr;
  LossyCopyUTF16toASCII(uri, uriCStr);

  nsCOMPtr <nsIMsgMessageService> messageService;
  // if this is a data: url, skip it, because 
  // we've already got something we can print
  // and we know it is not a message.
  //
  // if this an about:blank url, skip it, because
  // ...
  //
  // if this is an addbook: url, skip it, because
  // we know that isn't a message.
  //
  // if this is a message part (or .eml file on disk)
  // skip it, because we don't want to print the parent message
  // we want to print the part.
  // example:  imap://sspitzer@nsmail-1:143/fetch%3EUID%3E/INBOX%3E180958?part=1.1.2&type=application/x-message-display&filename=test"
  if (!StringBeginsWith(uriCStr, NS_LITERAL_CSTRING(DATA_URL_PREFIX)) &&
      !StringBeginsWith(uriCStr, NS_LITERAL_CSTRING(ADDBOOK_URL_PREFIX)) &&
      !uriCStr.EqualsLiteral("about:blank") && 
      uriCStr.Find(NS_LITERAL_CSTRING("type=application/x-message-display")) == -1) {
    rv = GetMessageServiceFromURI(uriCStr, getter_AddRefs(messageService));
  }

  if (NS_SUCCEEDED(rv) && messageService)
    rv = messageService->DisplayMessageForPrinting(uriCStr.get(), mDocShell, nsnull, nsnull, nsnull);
  //If it's not something we know about, then just load try loading it directly.
  else
  {
    nsCOMPtr<nsIWebNavigation> webNav(do_QueryInterface(mDocShell));
    if (webNav)
      rv = webNav->LoadURI(uri.get(),                        // URI string
                           nsIWebNavigation::LOAD_FLAGS_NONE, // Load flags
                           nsnull,                            // Referring URI
                           nsnull,                            // Post data
                           nsnull);                           // Extra headers
  }
  return rv;
}
Esempio n. 19
0
NS_UTF16ToCString(const nsAString& aSrc,
                  nsCStringEncoding aDestEncoding,
                  nsACString& aDest)
{
  switch (aDestEncoding) {
    case NS_CSTRING_ENCODING_ASCII:
      LossyCopyUTF16toASCII(aSrc, aDest);
      break;
    case NS_CSTRING_ENCODING_UTF8:
      CopyUTF16toUTF8(aSrc, aDest);
      break;
    case NS_CSTRING_ENCODING_NATIVE_FILESYSTEM:
      NS_CopyUnicodeToNative(aSrc, aDest);
      break;
    default:
      return NS_ERROR_NOT_IMPLEMENTED;
  }

  return NS_OK; // XXX report errors
}
NS_IMETHODIMP
nsHttpBasicAuth::GenerateCredentials(nsIHttpAuthenticableChannel *authChannel,
                                     const char *challenge,
                                     bool isProxyAuth,
                                     const PRUnichar *domain,
                                     const PRUnichar *user,
                                     const PRUnichar *password,
                                     nsISupports **sessionState,
                                     nsISupports **continuationState,
                                     uint32_t *aFlags,
                                     char **creds)

{
    LOG(("nsHttpBasicAuth::GenerateCredentials [challenge=%s]\n", challenge));

    NS_ENSURE_ARG_POINTER(creds);

    *aFlags = 0;

    // we only know how to deal with Basic auth for http.
    bool isBasicAuth = !PL_strncasecmp(challenge, "basic", 5);
    NS_ENSURE_TRUE(isBasicAuth, NS_ERROR_UNEXPECTED);

    // we work with ASCII around here
    nsAutoCString userpass;
    LossyCopyUTF16toASCII(user, userpass);
    userpass.Append(':'); // always send a ':' (see bug 129565)
    if (password)
        LossyAppendUTF16toASCII(password, userpass);

    // plbase64.h provides this worst-case output buffer size calculation.
    // use calloc, since PL_Base64Encode does not null terminate.
    *creds = (char *) calloc(6 + ((userpass.Length() + 2)/3)*4 + 1, 1);
    if (!*creds)
        return NS_ERROR_OUT_OF_MEMORY;

    memcpy(*creds, "Basic ", 6);
    PL_Base64Encode(userpass.get(), userpass.Length(), *creds + 6);
    return NS_OK;
}
Esempio n. 21
0
// Headers - fetch will get PR_TRANSPORT_MESSAGE_HEADERS
// or if they do not exist will build a header from
//  PR_DISPLAY_TO, _CC, _BCC
//  PR_SUBJECT
//  PR_MESSAGE_RECIPIENTS
// and PR_CREATION_TIME if needed?
bool CMapiMessage::FetchHeaders(void)
{
  ULONG tag = PR_TRANSPORT_MESSAGE_HEADERS_A;
  LPSPropValue pVal = CMapiApi::GetMapiProperty(m_lpMsg, tag);
  if (!pVal)
    pVal = CMapiApi::GetMapiProperty(m_lpMsg, tag = PR_TRANSPORT_MESSAGE_HEADERS_W);
  if (pVal) {
    if (CMapiApi::IsLargeProperty(pVal)) {
      nsCString headers;
      CMapiApi::GetLargeStringProperty(m_lpMsg, tag, headers);
      m_headers.Assign(headers.get());
    }
    else if ((PROP_TYPE(pVal->ulPropTag) == PT_STRING8) &&
             (pVal->Value.lpszA) && (*(pVal->Value.lpszA)))
      m_headers.Assign(pVal->Value.lpszA);
    else if ((PROP_TYPE(pVal->ulPropTag) == PT_UNICODE) &&
             (pVal->Value.lpszW) && (*(pVal->Value.lpszW))) {
      nsCString headers;
      LossyCopyUTF16toASCII(nsDependentString(pVal->Value.lpszW), headers);
      m_headers.Assign(headers.get());
    }

    CMapiApi::MAPIFreeBuffer(pVal);
  }

  EnsureDate();
  if (!EnsureHeader(CMapiMessageHeaders::hdrFrom, PR_SENDER_NAME_W))
    EnsureHeader(CMapiMessageHeaders::hdrFrom, PR_SENDER_EMAIL_ADDRESS_W);
  EnsureHeader(CMapiMessageHeaders::hdrSubject, PR_SUBJECT_W);
  EnsureHeader(CMapiMessageHeaders::hdrTo, PR_DISPLAY_TO_W);
  EnsureHeader(CMapiMessageHeaders::hdrCc, PR_DISPLAY_CC_W);
  EnsureHeader(CMapiMessageHeaders::hdrBcc, PR_DISPLAY_BCC_W);

  ProcessContentType();

  return !m_headers.IsEmpty();
}
Esempio n. 22
0
void
gfxPlatform::AppendCJKPrefLangs(eFontPrefLang aPrefLangs[], PRUint32 &aLen, eFontPrefLang aCharLang, eFontPrefLang aPageLang)
{
    nsCOMPtr<nsIPrefBranch> prefs(do_GetService(NS_PREFSERVICE_CONTRACTID));

    // prefer the lang specified by the page *if* CJK
    if (IsLangCJK(aPageLang)) {
        AppendPrefLang(aPrefLangs, aLen, aPageLang);
    }
    
    // if not set up, set up the default CJK order, based on accept lang settings and locale
    if (mCJKPrefLangs.Length() == 0) {
    
        // temp array
        eFontPrefLang tempPrefLangs[kMaxLenPrefLangList];
        PRUint32 tempLen = 0;
        
        // Add the CJK pref fonts from accept languages, the order should be same order
        nsCAutoString list;
        if (prefs) {
            nsCOMPtr<nsIPrefLocalizedString> prefString;
            nsresult rv =
                prefs->GetComplexValue("intl.accept_languages",
                                       NS_GET_IID(nsIPrefLocalizedString),
                                       getter_AddRefs(prefString));
            if (NS_SUCCEEDED(rv) && prefString) {
                nsAutoString temp;
                prefString->ToString(getter_Copies(temp));
                LossyCopyUTF16toASCII(temp, list);
            }
        }
        
        if (!list.IsEmpty()) {
            const char kComma = ',';
            const char *p, *p_end;
            list.BeginReading(p);
            list.EndReading(p_end);
            while (p < p_end) {
                while (nsCRT::IsAsciiSpace(*p)) {
                    if (++p == p_end)
                        break;
                }
                if (p == p_end)
                    break;
                const char *start = p;
                while (++p != p_end && *p != kComma)
                    /* nothing */ ;
                nsCAutoString lang(Substring(start, p));
                lang.CompressWhitespace(PR_FALSE, PR_TRUE);
                eFontPrefLang fpl = gfxPlatform::GetFontPrefLangFor(lang.get());
                switch (fpl) {
                    case eFontPrefLang_Japanese:
                    case eFontPrefLang_Korean:
                    case eFontPrefLang_ChineseCN:
                    case eFontPrefLang_ChineseHK:
                    case eFontPrefLang_ChineseTW:
                        AppendPrefLang(tempPrefLangs, tempLen, fpl);
                        break;
                    default:
                        break;
                }
                p++;
            }
        }

        do { // to allow 'break' to abort this block if a call fails
            nsresult rv;
            nsCOMPtr<nsILocaleService> ls =
                do_GetService(NS_LOCALESERVICE_CONTRACTID, &rv);
            if (NS_FAILED(rv))
                break;

            nsCOMPtr<nsILocale> appLocale;
            rv = ls->GetApplicationLocale(getter_AddRefs(appLocale));
            if (NS_FAILED(rv))
                break;

            nsString localeStr;
            rv = appLocale->
                GetCategory(NS_LITERAL_STRING(NSILOCALE_MESSAGE), localeStr);
            if (NS_FAILED(rv))
                break;

            const nsAString& lang = Substring(localeStr, 0, 2);
            if (lang.EqualsLiteral("ja")) {
                AppendPrefLang(tempPrefLangs, tempLen, eFontPrefLang_Japanese);
            } else if (lang.EqualsLiteral("zh")) {
                const nsAString& region = Substring(localeStr, 3, 2);
                if (region.EqualsLiteral("CN")) {
                    AppendPrefLang(tempPrefLangs, tempLen, eFontPrefLang_ChineseCN);
                } else if (region.EqualsLiteral("TW")) {
                    AppendPrefLang(tempPrefLangs, tempLen, eFontPrefLang_ChineseTW);
                } else if (region.EqualsLiteral("HK")) {
                    AppendPrefLang(tempPrefLangs, tempLen, eFontPrefLang_ChineseHK);
                }
            } else if (lang.EqualsLiteral("ko")) {
                AppendPrefLang(tempPrefLangs, tempLen, eFontPrefLang_Korean);
            }
        } while (0);

        // last resort... (the order is same as old gfx.)
        AppendPrefLang(tempPrefLangs, tempLen, eFontPrefLang_Japanese);
        AppendPrefLang(tempPrefLangs, tempLen, eFontPrefLang_Korean);
        AppendPrefLang(tempPrefLangs, tempLen, eFontPrefLang_ChineseCN);
        AppendPrefLang(tempPrefLangs, tempLen, eFontPrefLang_ChineseHK);
        AppendPrefLang(tempPrefLangs, tempLen, eFontPrefLang_ChineseTW);
        
        // copy into the cached array
        PRUint32 j;
        for (j = 0; j < tempLen; j++) {
            mCJKPrefLangs.AppendElement(tempPrefLangs[j]);
        }
    }
    
    // append in cached CJK langs
    PRUint32  i, numCJKlangs = mCJKPrefLangs.Length();
    
    for (i = 0; i < numCJKlangs; i++) {
        AppendPrefLang(aPrefLangs, aLen, (eFontPrefLang) (mCJKPrefLangs[i]));
    }
        
}
nsresult
nsMsgAttachmentHandler::UrlExit(nsresult status, const PRUnichar* aMsg)
{
  NS_ASSERTION(m_mime_delivery_state != nsnull, "not-null m_mime_delivery_state");

  // Close the file, but don't delete the disk file (or the file spec.)
  if (mOutFile)
  {
    mOutFile->Close();
    mOutFile = nsnull;
  }
  // this silliness is because Windows nsILocalFile caches its file size
  // so if an output stream writes to it, it will still return the original
  // cached size.
  if (mTmpFile)
  {
    nsCOMPtr <nsIFile> tmpFile;
    mTmpFile->Clone(getter_AddRefs(tmpFile));
    mTmpFile = do_QueryInterface(tmpFile);
  }
  mRequest = nsnull;

  // First things first, we are now going to see if this is an HTML
  // Doc and if it is, we need to see if we can determine the charset
  // for this part by sniffing the HTML file.
  // This is needed only when the charset is not set already.
  // (e.g. a charset may be specified in HTTP header)
  //
  if (!m_type.IsEmpty() && m_charset.IsEmpty() &&
      m_type.LowerCaseEqualsLiteral(TEXT_HTML))
    m_charset = nsMsgI18NParseMetaCharset(mTmpFile);

  nsresult mimeDeliveryStatus;
  m_mime_delivery_state->GetStatus(&mimeDeliveryStatus);

  if (mimeDeliveryStatus == NS_ERROR_ABORT)
    status = NS_ERROR_ABORT;

  if (NS_FAILED(status) && status != NS_ERROR_ABORT && NS_SUCCEEDED(mimeDeliveryStatus))
  {
    // At this point, we should probably ask a question to the user
    // if we should continue without this attachment.
    //
    bool              keepOnGoing = true;
    nsCString    turl;
    nsString     msg;
    PRUnichar         *printfString = nsnull;
    nsresult rv;
    nsCOMPtr<nsIStringBundleService> bundleService(do_GetService("@mozilla.org/intl/stringbundle;1", &rv));
    NS_ENSURE_SUCCESS(rv, rv);
    nsCOMPtr<nsIStringBundle> bundle;
    rv = bundleService->CreateBundle("chrome://messenger/locale/messengercompose/composeMsgs.properties", getter_AddRefs(bundle));
    NS_ENSURE_SUCCESS(rv, rv);
    nsMsgDeliverMode mode = nsIMsgSend::nsMsgDeliverNow;
    m_mime_delivery_state->GetDeliveryMode(&mode);
    if (mode == nsIMsgSend::nsMsgSaveAsDraft || mode == nsIMsgSend::nsMsgSaveAsTemplate)
      bundle->GetStringFromID(NS_MSG_FAILURE_ON_OBJ_EMBED_WHILE_SAVING, getter_Copies(msg));
    else
      bundle->GetStringFromID(NS_MSG_FAILURE_ON_OBJ_EMBED_WHILE_SENDING, getter_Copies(msg));
    if (!m_realName.IsEmpty())
      printfString = nsTextFormatter::smprintf(msg.get(), m_realName.get());
    else if (NS_SUCCEEDED(mURL->GetSpec(turl)) && !turl.IsEmpty())
    {
      nsCAutoString unescapedUrl;
      MsgUnescapeString(turl, 0, unescapedUrl);
      if (unescapedUrl.IsEmpty())
        printfString = nsTextFormatter::smprintf(msg.get(), turl.get());
      else
        printfString = nsTextFormatter::smprintf(msg.get(), unescapedUrl.get());
    }
    else
      printfString = nsTextFormatter::smprintf(msg.get(), "?");

    nsCOMPtr<nsIPrompt> aPrompt;
    if (m_mime_delivery_state)
      m_mime_delivery_state->GetDefaultPrompt(getter_AddRefs(aPrompt));
    nsMsgAskBooleanQuestionByString(aPrompt, printfString, &keepOnGoing);
    PR_FREEIF(printfString);

    if (keepOnGoing)
    {
      status = 0;
      m_bogus_attachment = true; //That will cause this attachment to be ignored.
    }
    else
    {
      status = NS_ERROR_ABORT;
      m_mime_delivery_state->SetStatus(status);
      nsresult ignoreMe;
      m_mime_delivery_state->Fail(status, nsnull, &ignoreMe);
      m_mime_delivery_state->NotifyListenerOnStopSending(nsnull, status, 0, nsnull);
      SetMimeDeliveryState(nsnull);
      return status;
    }
  }

  m_done = true;

  //
  // Ok, now that we have the file here on disk, we need to see if there was
  // a need to do conversion to plain text...if so, the magic happens here,
  // otherwise, just move on to other attachments...
  //
  if (NS_SUCCEEDED(status) && !m_type.LowerCaseEqualsLiteral(TEXT_PLAIN) &&
      m_desiredType.LowerCaseEqualsLiteral(TEXT_PLAIN))
  {
    //
    // Conversion to plain text desired.
    //
    PRInt32       width = 72;
    nsCOMPtr<nsIPrefBranch> pPrefBranch(do_GetService(NS_PREFSERVICE_CONTRACTID));
    if (pPrefBranch)
      pPrefBranch->GetIntPref("mailnews.wraplength", &width);
    // Let sanity reign!
    if (width == 0)
      width = 72;
    else if (width < 10)
      width = 10;
    else if (width > 30000)
      width = 30000;

    //
    // Now use the converter service here to do the right
    // thing and convert this data to plain text for us!
    //
    nsAutoString      conData;

    if (NS_SUCCEEDED(LoadDataFromFile(mTmpFile, conData, true)))
    {
      if (NS_SUCCEEDED(ConvertBufToPlainText(conData, UseFormatFlowed(m_charset.get()))))
      {
        if (mDeleteFile)
          mTmpFile->Remove(false);

        nsCOMPtr<nsIOutputStream> outputStream;
        nsresult rv = NS_NewLocalFileOutputStream(getter_AddRefs(outputStream), mTmpFile,  PR_WRONLY | PR_CREATE_FILE, 00600);

        if (NS_SUCCEEDED(rv))
        {
          nsCAutoString tData;
          if (NS_FAILED(ConvertFromUnicode(m_charset.get(), conData, tData)))
            LossyCopyUTF16toASCII(conData, tData);
          if (!tData.IsEmpty())
          {
            PRUint32 bytesWritten;
            (void) outputStream->Write(tData.get(), tData.Length(), &bytesWritten);
          }
          outputStream->Close();
          // this silliness is because Windows nsILocalFile caches its file size
          // so if an output stream writes to it, it will still return the original
          // cached size.
          if (mTmpFile)
          {
            nsCOMPtr <nsIFile> tmpFile;
            mTmpFile->Clone(getter_AddRefs(tmpFile));
            mTmpFile = do_QueryInterface(tmpFile);
          }

        }
      }
    }

    m_type = m_desiredType;
    m_desiredType.Truncate();
    m_encoding.Truncate();
  }

  PRUint32 pendingAttachmentCount = 0;
  m_mime_delivery_state->GetPendingAttachmentCount(&pendingAttachmentCount);
  NS_ASSERTION (pendingAttachmentCount > 0, "no more pending attachment");

  m_mime_delivery_state->SetPendingAttachmentCount(pendingAttachmentCount - 1);

  bool processAttachmentsSynchronously = false;
  m_mime_delivery_state->GetProcessAttachmentsSynchronously(&processAttachmentsSynchronously);
  if (NS_SUCCEEDED(status) && processAttachmentsSynchronously)
  {
    /* Find the next attachment which has not yet been loaded,
     if any, and start it going.
     */
    PRUint32 i;
    nsMsgAttachmentHandler *next = 0;
    nsMsgAttachmentHandler *attachments = nsnull;
    PRUint32 attachmentCount = 0;

    m_mime_delivery_state->GetAttachmentCount(&attachmentCount);
    if (attachmentCount)
      m_mime_delivery_state->GetAttachmentHandlers(&attachments);

    for (i = 0; i < attachmentCount; i++)
    {
      if (!attachments[i].m_done)
      {
        next = &attachments[i];
        //
        // rhp: We need to get a little more understanding to failed URL
        // requests. So, at this point if most of next is NULL, then we
        // should just mark it fetched and move on! We probably ignored
        // this earlier on in the send process.
        //
        if ( (!next->mURL) && (next->m_uri.IsEmpty()) )
        {
          attachments[i].m_done = true;
          m_mime_delivery_state->GetPendingAttachmentCount(&pendingAttachmentCount);
          m_mime_delivery_state->SetPendingAttachmentCount(pendingAttachmentCount - 1);
          next->mPartUserOmissionOverride = true;
          next = nsnull;
          continue;
        }

        break;
      }
    }

    if (next)
    {
      int status = next->SnarfAttachment(mCompFields);
      if (NS_FAILED(status))
      {
        nsresult ignoreMe;
        m_mime_delivery_state->Fail(status, nsnull, &ignoreMe);
        m_mime_delivery_state->NotifyListenerOnStopSending(nsnull, status, 0, nsnull);
        SetMimeDeliveryState(nsnull);
        return NS_ERROR_UNEXPECTED;
      }
    }
  }

  m_mime_delivery_state->GetPendingAttachmentCount(&pendingAttachmentCount);
  if (pendingAttachmentCount == 0)
  {
    // If this is the last attachment, then either complete the
    // delivery (if successful) or report the error by calling
    // the exit routine and terminating the delivery.
    if (NS_FAILED(status))
    {
      nsresult ignoreMe;
      m_mime_delivery_state->Fail(status, aMsg, &ignoreMe);
      m_mime_delivery_state->NotifyListenerOnStopSending(nsnull, status, aMsg, nsnull);
      SetMimeDeliveryState(nsnull);
      return NS_ERROR_UNEXPECTED;
    }
    else
    {
      status = m_mime_delivery_state->GatherMimeAttachments ();
      if (NS_FAILED(status))
      {
        nsresult ignoreMe;
        m_mime_delivery_state->Fail(status, aMsg, &ignoreMe);
        m_mime_delivery_state->NotifyListenerOnStopSending(nsnull, status, aMsg, nsnull);
        SetMimeDeliveryState(nsnull);
        return NS_ERROR_UNEXPECTED;
      }
    }
  }
  else
  {
    // If this is not the last attachment, but it got an error,
    // then report that error and continue
    if (NS_FAILED(status))
    {
      nsresult ignoreMe;
      m_mime_delivery_state->Fail(status, aMsg, &ignoreMe);
    }
  }

  SetMimeDeliveryState(nsnull);
  return NS_OK;
}
Esempio n. 24
0
//-------------------------------------------------------------------------
//
// Show - Display the file dialog
//
//-------------------------------------------------------------------------
NS_IMETHODIMP nsFilePicker::Show(PRInt16 *retval)
{
  NS_ENSURE_ARG_POINTER(retval);

  PRBool result = PR_FALSE;
  nsCAutoString fileBuffer;
  char *converted = ConvertToFileSystemCharset(mDefault);
  if (nsnull == converted) {
    LossyCopyUTF16toASCII(mDefault, fileBuffer);
  }
  else {
    fileBuffer.Assign(converted);
    nsMemory::Free( converted );
  }

  char *title = ConvertToFileSystemCharset(mTitle);
  if (nsnull == title)
    title = ToNewCString(mTitle);
  nsCAutoString initialDir;
  if (mDisplayDirectory)
    mDisplayDirectory->GetNativePath(initialDir);
  // If no display directory, re-use the last one.
  if(initialDir.IsEmpty())
    initialDir = mLastUsedDirectory;

  mFile.Truncate();

  FILEDLG filedlg;
  memset(&filedlg, 0, sizeof(FILEDLG));
  filedlg.cbSize = sizeof(FILEDLG);
  filedlg.pszTitle = title;

  if (mMode == modeGetFolder) {
    PL_strncat(filedlg.szFullFile, initialDir.get(), MAX_PATH);
    PL_strncat(filedlg.szFullFile, "\\", 1);
    PL_strncat(filedlg.szFullFile, "^", 1);
    filedlg.fl = FDS_OPEN_DIALOG | FDS_CENTER;
    filedlg.pfnDlgProc = DirDialogProc;
    DosError(FERR_DISABLEHARDERR);
    WinFileDlg(HWND_DESKTOP, mWnd, &filedlg);
    DosError(FERR_ENABLEHARDERR);
    char* tempptr = strstr(filedlg.szFullFile, "^");
    if (tempptr)
      *tempptr = '\0';
    if (filedlg.lReturn == DID_OK) {
      result = PR_TRUE;
      if (!mDisplayDirectory)
        mDisplayDirectory = do_CreateInstance("@mozilla.org/file/local;1");
      if (mDisplayDirectory)
        mDisplayDirectory->InitWithNativePath(nsDependentCString(filedlg.szFullFile));
      mFile.Assign(filedlg.szFullFile);
    }
  }
  else {
    PL_strncpy(filedlg.szFullFile, initialDir.get(), MAX_PATH);
    PL_strncat(filedlg.szFullFile, "\\", 1);
    PL_strncat(filedlg.szFullFile, fileBuffer.get(), MAX_PATH);
    filedlg.fl = FDS_CENTER;
    if (mMode == modeSave) {
       filedlg.fl |= FDS_SAVEAS_DIALOG | FDS_ENABLEFILELB;
    } else if (mMode == modeOpenMultiple) {
       filedlg.fl |= FDS_MULTIPLESEL | FDS_OPEN_DIALOG;
    } else {
       filedlg.fl |= FDS_OPEN_DIALOG;
    }
    PMYDATA pmydata;
    pmydata = (PMYDATA)calloc(1, sizeof(MYDATA));
    filedlg.ulUser = (ULONG)pmydata;
    filedlg.pfnDlgProc = FileDialogProc;

    PRUint32 i;

    PSZ *apszTypeList;
    apszTypeList = (PSZ *)malloc(mTitles.Length()*sizeof(PSZ)+1);
    for (i = 0; i < mTitles.Length(); i++)
    {
      const nsString& typeWide = mTitles[i];
      nsAutoCharBuffer buffer;
      PRInt32 bufLength;
      WideCharToMultiByte(0, typeWide.get(), typeWide.Length(),
                          buffer, bufLength);
      apszTypeList[i] = ToNewCString(nsDependentCString(buffer.Elements()));
    }
    apszTypeList[i] = 0;
    filedlg.papszITypeList = (PAPSZ)apszTypeList;

    PSZ *apszFilterList;
    apszFilterList = (PSZ *)malloc(mFilters.Length()*sizeof(PSZ)+1);
    for (i = 0; i < mFilters.Length(); i++)
    {
      const nsString& filterWide = mFilters[i];
      apszFilterList[i] = ToNewCString(filterWide);
    }
    apszFilterList[i] = 0;
    pmydata->papszIFilterList = (PAPSZ)apszFilterList;

    pmydata->ulCurExt = mSelectedType;

    PRBool fileExists;
    do {
      DosError(FERR_DISABLEHARDERR);
      WinFileDlg(HWND_DESKTOP, mWnd, &filedlg);
      DosError(FERR_ENABLEHARDERR);
      if ((filedlg.lReturn == DID_OK) && (mMode == modeSave)) {
         PRFileInfo64 fileinfo64;
         PRStatus status = PR_GetFileInfo64(filedlg.szFullFile, &fileinfo64);
         if (status == PR_SUCCESS) {
            fileExists = PR_TRUE;
         } else {
            fileExists = PR_FALSE;
         }
         if (fileExists) {
            if (!gpszFDSaveCaption) {
              HMODULE hmod;
              char LoadError[CCHMAXPATH];
              char loadedString[256];
              int length;
              DosLoadModule(LoadError, CCHMAXPATH, "PMSDMRI", &hmod);
              length = WinLoadString((HAB)0, hmod, 1110, 256, loadedString);
              gpszFDSaveCaption = (char*)malloc(length+1);
              strcpy(gpszFDSaveCaption, loadedString);
              length = WinLoadString((HAB)0, hmod, 1135, 256, loadedString);
              gpszFDFileExists = (char*)malloc(length+1);
              strcpy(gpszFDFileExists, loadedString);
              length = WinLoadString((HAB)0, hmod, 1136, 256, loadedString);
              gpszFDFileReadOnly = (char*)malloc(length+1);
              strcpy(gpszFDFileReadOnly, loadedString);
              int i;
              for (i=0;i<256 && gpszFDFileExists[i];i++ ) {
                if (gpszFDFileExists[i] == '%') {
                  gpszFDFileExists[i+1] = 's';
                  break;
                }
              }
              for (i=0;i<256 && gpszFDFileReadOnly[i];i++ ) {
                if (gpszFDFileReadOnly[i] == '%') {
                  gpszFDFileReadOnly[i+1] = 's';
                  break;
                }
              }
              DosFreeModule(hmod);

            }
            char pszFullText[256+CCHMAXPATH];
            FILESTATUS3 fsts3;
            ULONG ulResponse;
            DosQueryPathInfo( filedlg.szFullFile, FIL_STANDARD, &fsts3, sizeof(FILESTATUS3));
            if (fsts3.attrFile & FILE_READONLY) {
              sprintf(pszFullText, gpszFDFileReadOnly, filedlg.szFullFile);
              ulResponse = WinMessageBox(HWND_DESKTOP, mWnd, pszFullText,
                                               gpszFDSaveCaption, 0,
                                               MB_OK | MB_MOVEABLE | MB_WARNING);
            } else {
              sprintf(pszFullText, gpszFDFileExists, filedlg.szFullFile);
              ulResponse = WinMessageBox(HWND_DESKTOP, mWnd, pszFullText,
                                               gpszFDSaveCaption, 0,
                                               MB_YESNO | MB_MOVEABLE | MB_WARNING);
            }

            if (ulResponse == MBID_YES) {
               fileExists = PR_FALSE;
            }
         }
      }
    } while (mMode == modeSave && fileExists && filedlg.lReturn == DID_OK);

    if (filedlg.lReturn == DID_OK) {
      result = PR_TRUE;
      if (mMode == modeOpenMultiple) {
        nsresult rv;

        if (filedlg.papszFQFilename) {
          for (ULONG i=0;i<filedlg.ulFQFCount;i++) {
            nsCOMPtr<nsILocalFile> file = do_CreateInstance("@mozilla.org/file/local;1", &rv);
            NS_ENSURE_SUCCESS(rv,rv);

            rv = file->InitWithNativePath(nsDependentCString(*(filedlg.papszFQFilename)[i]));
            NS_ENSURE_SUCCESS(rv,rv);

            rv = mFiles.AppendObject(file);
            NS_ENSURE_SUCCESS(rv,rv);
          }
          WinFreeFileDlgList(filedlg.papszFQFilename);
        } else {
          nsCOMPtr<nsILocalFile> file = do_CreateInstance("@mozilla.org/file/local;1", &rv);
          NS_ENSURE_SUCCESS(rv,rv);

          rv = file->InitWithNativePath(nsDependentCString(filedlg.szFullFile));
          NS_ENSURE_SUCCESS(rv,rv);

          rv = mFiles.AppendObject(file);
          NS_ENSURE_SUCCESS(rv,rv);
        }
      } else {
        mFile.Assign(filedlg.szFullFile);
      }
      mSelectedType = (PRInt16)pmydata->ulCurExt;
    }

    for (i = 0; i < mTitles.Length(); i++)
    {
      nsMemory::Free(*(filedlg.papszITypeList[i]));
    }
    free(filedlg.papszITypeList);

    for (i = 0; i < mFilters.Length(); i++)
    {
      nsMemory::Free(*(pmydata->papszIFilterList[i]));
    }
    free(pmydata->papszIFilterList);
    free(pmydata);
  }

  if (title)
    nsMemory::Free( title );

  if (result) {
    PRInt16 returnOKorReplace = returnOK;

    nsresult rv;
    // Remember last used directory.
    nsCOMPtr<nsILocalFile> file(do_CreateInstance("@mozilla.org/file/local;1", &rv));
    NS_ENSURE_SUCCESS(rv, rv);

    file->InitWithNativePath(mFile);
    nsCOMPtr<nsIFile> dir;
    if (NS_SUCCEEDED(file->GetParent(getter_AddRefs(dir)))) {
      nsCOMPtr<nsILocalFile> localDir(do_QueryInterface(dir));
      if (localDir) {
        nsCAutoString newDir;
        localDir->GetNativePath(newDir);
        if(!newDir.IsEmpty())
          PL_strncpyz(mLastUsedDirectory, newDir.get(), MAX_PATH+1);
        // Update mDisplayDirectory with this directory, also.
        // Some callers rely on this.
        if (!mDisplayDirectory)
           mDisplayDirectory = do_CreateInstance("@mozilla.org/file/local;1");
        if (mDisplayDirectory)
           mDisplayDirectory->InitWithNativePath( nsDependentCString(mLastUsedDirectory) );
      }
    }

    if (mMode == modeSave) {
      // Windows does not return resultReplace,
      //   we must check if file already exists
      PRBool exists = PR_FALSE;
      file->Exists(&exists);
      if (exists)
        returnOKorReplace = returnReplace;
    }
    *retval = returnOKorReplace;
  }
  else {
    *retval = returnCancel;
  }
  return NS_OK;
}
nsresult nsOutlookMail::CreateList(const PRUnichar * pName,
                                   nsIAddrDatabase *pDb,
                                   LPMAPIPROP pUserList,
                                   nsIImportFieldMap *pFieldMap)
{
  // If no name provided then we're done.
  if (!pName || !(*pName))
    return NS_OK;

  nsresult rv = NS_ERROR_FAILURE;
  // Make sure we have db to work with.
  if (!pDb)
    return rv;

  nsCOMPtr <nsIMdbRow> newListRow;
  rv = pDb->GetNewListRow(getter_AddRefs(newListRow));
  NS_ENSURE_SUCCESS(rv, rv);
  nsAutoCString column;
  LossyCopyUTF16toASCII(nsDependentString(pName), column);
  rv = pDb->AddListName(newListRow, column.get());
  NS_ENSURE_SUCCESS(rv, rv);

  HRESULT             hr;
  LPSPropValue value = NULL;
  ULONG valueCount = 0;

  LPSPropTagArray properties = NULL;
  m_mapi.MAPIAllocateBuffer(CbNewSPropTagArray(1),
    (void **)&properties);
  properties->cValues = 1;
  properties->aulPropTag [0] = m_mapi.GetEmailPropertyTag(pUserList, 0x8054);
  hr = pUserList->GetProps(properties, 0, &valueCount, &value);
  m_mapi.MAPIFreeBuffer(properties);
  if (HR_FAILED(hr))
    return NS_ERROR_FAILURE;
  if (!value)
    return NS_ERROR_NOT_AVAILABLE;
  // XXX from here out, value must be freed with MAPIFreeBuffer 

  SBinaryArray *sa=(SBinaryArray *)&value->Value.bin;
  if (!sa || !sa->lpbin) {
    m_mapi.MAPIFreeBuffer(value);
    return NS_ERROR_NULL_POINTER;
  }

  LPENTRYID    lpEid;
  ULONG        cbEid;
  int32_t        idx;
  LPMESSAGE        lpMsg;
  nsCString        type;
  LPSPropValue    pVal;
  nsString        subject;
  uint32_t total;

  total=sa->cValues;
  for (idx = 0; idx < sa->cValues; idx++)
  {
    lpEid= (LPENTRYID) sa->lpbin[idx].lpb;
    cbEid = sa->lpbin[idx].cb;

    if (!m_mapi.OpenEntry(cbEid, lpEid, (LPUNKNOWN *) &lpMsg))
    {

      IMPORT_LOG1("*** Error opening messages in mailbox: %S\n", pName);
      m_mapi.MAPIFreeBuffer(value);
      return NS_ERROR_FAILURE;
    }
    // This is a contact, add it to the address book!
    subject.Truncate();
    pVal = m_mapi.GetMapiProperty(lpMsg, PR_SUBJECT);
    if (pVal)
      m_mapi.GetStringFromProp(pVal, subject);

    nsCOMPtr <nsIMdbRow> newRow;
    nsCOMPtr <nsIMdbRow> oldRow;
    pDb->GetNewRow(getter_AddRefs(newRow));
    if (newRow) {
      if (BuildCard(subject.get(), pDb, newRow, lpMsg, pFieldMap))
      {
        nsCOMPtr <nsIAbCard> userCard;
        nsCOMPtr <nsIAbCard> newCard;
        userCard = do_CreateInstance(NS_ABMDBCARD_CONTRACTID, &rv);
        NS_ENSURE_SUCCESS(rv, rv);
        pDb->InitCardFromRow(userCard,newRow);

        //add card to db
        bool bl=false;
        pDb->FindRowByCard(userCard,getter_AddRefs(oldRow));
        if (oldRow)
          newRow = oldRow;
        else
          pDb->AddCardRowToDB(newRow);

        //add card list
        pDb->AddListCardColumnsToRow(userCard,
                                     newListRow,idx+1, getter_AddRefs(newCard),
                                     true, nullptr, nullptr);
      }
    }
  }
  m_mapi.MAPIFreeBuffer(value);

  rv = pDb->AddCardRowToDB(newListRow);
  NS_ENSURE_SUCCESS(rv, rv);

  rv = pDb->SetListAddressTotal(newListRow, total);
  rv = pDb->AddListDirNode(newListRow);
  return rv;
}
Esempio n. 26
0
/* static */ nsresult
nsScriptLoader::ConvertToUTF16(nsIChannel* aChannel, const PRUint8* aData,
                               PRUint32 aLength, const nsString& aHintCharset,
                               nsIDocument* aDocument, nsString& aString)
{
    if (!aLength) {
        aString.Truncate();
        return NS_OK;
    }

    nsCAutoString characterSet;

    nsresult rv = NS_OK;
    if (aChannel) {
        rv = aChannel->GetContentCharset(characterSet);
    }

    if (!aHintCharset.IsEmpty() && (NS_FAILED(rv) || characterSet.IsEmpty())) {
        // charset name is always ASCII.
        LossyCopyUTF16toASCII(aHintCharset, characterSet);
    }

    if (NS_FAILED(rv) || characterSet.IsEmpty()) {
        DetectByteOrderMark(aData, aLength, characterSet);
    }

    if (characterSet.IsEmpty()) {
        // charset from document default
        characterSet = aDocument->GetDocumentCharacterSet();
    }

    if (characterSet.IsEmpty()) {
        // fall back to ISO-8859-1, see bug 118404
        characterSet.AssignLiteral("ISO-8859-1");
    }

    nsCOMPtr<nsICharsetConverterManager> charsetConv =
        do_GetService(NS_CHARSETCONVERTERMANAGER_CONTRACTID, &rv);

    nsCOMPtr<nsIUnicodeDecoder> unicodeDecoder;

    if (NS_SUCCEEDED(rv) && charsetConv) {
        rv = charsetConv->GetUnicodeDecoder(characterSet.get(),
                                            getter_AddRefs(unicodeDecoder));
        if (NS_FAILED(rv)) {
            // fall back to ISO-8859-1 if charset is not supported. (bug 230104)
            rv = charsetConv->GetUnicodeDecoderRaw("ISO-8859-1",
                                                   getter_AddRefs(unicodeDecoder));
        }
    }

    // converts from the charset to unicode
    if (NS_SUCCEEDED(rv)) {
        PRInt32 unicodeLength = 0;

        rv = unicodeDecoder->GetMaxLength(reinterpret_cast<const char*>(aData),
                                          aLength, &unicodeLength);
        if (NS_SUCCEEDED(rv)) {
            if (!EnsureStringLength(aString, unicodeLength))
                return NS_ERROR_OUT_OF_MEMORY;

            PRUnichar *ustr = aString.BeginWriting();

            PRInt32 consumedLength = 0;
            PRInt32 originalLength = aLength;
            PRInt32 convertedLength = 0;
            PRInt32 bufferLength = unicodeLength;
            do {
                rv = unicodeDecoder->Convert(reinterpret_cast<const char*>(aData),
                                             (PRInt32 *) &aLength, ustr,
                                             &unicodeLength);
                if (NS_FAILED(rv)) {
                    // if we failed, we consume one byte, replace it with U+FFFD
                    // and try the conversion again.
                    ustr[unicodeLength++] = (PRUnichar)0xFFFD;
                    ustr += unicodeLength;

                    unicodeDecoder->Reset();
                }
                aData += ++aLength;
                consumedLength += aLength;
                aLength = originalLength - consumedLength;
                convertedLength += unicodeLength;
                unicodeLength = bufferLength - convertedLength;
            } while (NS_FAILED(rv) && (originalLength > consumedLength) && (bufferLength > convertedLength));
            aString.SetLength(convertedLength);
        }
    }
    return rv;
}
Esempio n. 27
0
void nsAbIPCCard::JoinAddress(PRBool isUnicode, LPTSTR *ptrAddress, nsString &address1, nsString &address2)
{
  // If the two address lines in a moz card are not empty
  // then join the lines into a single line separated by
  // '\x0A'. This is the format expected by Palm.
  *ptrAddress = NULL;
  PRUint32 strLength= address1.Length() + address2.Length();
  if(!strLength)
    return;

  // Allocate space for 'strLength' plus three for nulls and one for "\x0A".
  // These strings are defined as wide in the idl, so we need to add up to 3
  // bytes of 0 byte padding at the end (if the string is an odd number of 
  // bytes long, we need one null byte to pad out the last char to a wide char
  // and then  two more nulls as a wide null terminator.
  strLength += 4;
  if(isUnicode)
  { 
    PRUnichar * uniStr = (PRUnichar *) CoTaskMemAlloc(sizeof(PRUnichar) * (strLength));
    if(address1.Length())
    {
      wcsncpy(uniStr, address1.get(), strLength-1);
      uniStr[strLength-1] = '\0';
      if(address2.Length())
      {
        wcsncat(uniStr, (const wchar_t *)"\x0A", strLength-1);
        wcsncat(uniStr, address2.get(), strLength-1);
        uniStr[strLength-1] = '\0';
      }
    }
    else
    {
      wcsncpy(uniStr, address2.get(), strLength-1);
      uniStr[strLength-1] = '\0';
    }

    *ptrAddress = uniStr;
  } 
  else
  { 
    char * str = (char *) CoTaskMemAlloc(strLength);
    if(address1.Length())
    {
      NS_LossyConvertUTF16toASCII cStr(address1);
      strncpy(str, cStr.get(), strLength-1);
      str[strLength-1] = '\0';
      if(address2.Length())
      {
        LossyCopyUTF16toASCII(address2, cStr);
        strncat(str, "\x0A", strLength-1);
        strncat(str, cStr.get(), strLength-1);
        str[strLength-1] = '\0';
      }
    }
    else
    {
      NS_LossyConvertUTF16toASCII cStr(address2);
      strncpy(str, cStr.get(), strLength-1);
      str[strLength-1] = '\0';
    }
    *ptrAddress = (LPTSTR) str;
  } 
}
Esempio n. 28
0
nsresult nsMsgI18NConvertFromUnicode(const char* aCharset,
                                     const nsString& inString,
                                     nsACString& outString,
                                     bool aIsCharsetCanonical)
{
  if (inString.IsEmpty()) {
    outString.Truncate();
    return NS_OK;
  }
  // Note: this will hide a possible error when the unicode text may contain more than one charset.
  // (e.g. Latin1 + Japanese). Use nsMsgI18NSaveAsCharset instead to avoid that problem.
  else if (!*aCharset || !PL_strcasecmp(aCharset, "us-ascii") ||
           !PL_strcasecmp(aCharset, "ISO-8859-1")) {
    LossyCopyUTF16toASCII(inString, outString);
    return NS_OK;
  }
  else if (!PL_strcasecmp(aCharset, "UTF-8")) {
    CopyUTF16toUTF8(inString, outString);
    return NS_OK;
  }

  nsresult rv;
  nsCOMPtr <nsICharsetConverterManager> ccm = do_GetService(NS_CHARSETCONVERTERMANAGER_CONTRACTID, &rv);
  NS_ENSURE_SUCCESS(rv, rv);
  nsCOMPtr <nsIUnicodeEncoder> encoder;

  // get an unicode converter
  if (aIsCharsetCanonical)  // optimize for modified UTF-7 used by IMAP
    rv = ccm->GetUnicodeEncoderRaw(aCharset, getter_AddRefs(encoder));
  else
    rv = ccm->GetUnicodeEncoder(aCharset, getter_AddRefs(encoder));
  NS_ENSURE_SUCCESS(rv, rv);
  rv = encoder->SetOutputErrorBehavior(nsIUnicodeEncoder::kOnError_Replace, nullptr, '?');
  NS_ENSURE_SUCCESS(rv, rv);

  const char16_t *originalSrcPtr = inString.get();
  const char16_t *currentSrcPtr = originalSrcPtr;
  int32_t originalUnicharLength = inString.Length();
  int32_t srcLength;
  int32_t dstLength;
  char localbuf[512];
  int32_t consumedLen = 0;

  outString.Truncate();
  // convert
  while (consumedLen < originalUnicharLength) {
    srcLength = originalUnicharLength - consumedLen;  
    dstLength = 512;
    rv = encoder->Convert(currentSrcPtr, &srcLength, localbuf, &dstLength);
    if (NS_FAILED(rv) || dstLength == 0)
      break;
    outString.Append(localbuf, dstLength);

    currentSrcPtr += srcLength;
    consumedLen = currentSrcPtr - originalSrcPtr; // src length used so far
  }
  rv = encoder->Finish(localbuf, &dstLength);
  if (NS_SUCCEEDED(rv))
    outString.Append(localbuf, dstLength);
  return rv;
}
Esempio n. 29
0
// this is used for Send without UI
nsresult nsMapiHook::BlindSendMail (unsigned long aSession, nsIMsgCompFields * aCompFields)
{
  nsresult rv = NS_OK ;

  if (!IsBlindSendAllowed())
    return NS_ERROR_FAILURE;

  /** create nsIMsgComposeParams obj and other fields to populate it **/

  nsCOMPtr<nsIDOMWindowInternal>  hiddenWindow;
  // get parent window
  nsCOMPtr<nsIAppShellService> appService = do_GetService( "@mozilla.org/appshell/appShellService;1", &rv);
  if (NS_FAILED(rv)|| (!appService) ) return rv ;

  rv = appService->GetHiddenDOMWindow(getter_AddRefs(hiddenWindow));
  if ( NS_FAILED(rv) ) return rv ;
  // smtp password and Logged in used IdKey from MapiConfig (session obj)
  nsMAPIConfiguration * pMapiConfig = nsMAPIConfiguration::GetMAPIConfiguration() ;
  if (!pMapiConfig) return NS_ERROR_FAILURE ;  // get the singelton obj
  PRUnichar * password = pMapiConfig->GetPassword(aSession) ;
  // password
  nsCAutoString smtpPassword;
  LossyCopyUTF16toASCII(password, smtpPassword);

  // Id key
  nsCString MsgIdKey;
  pMapiConfig->GetIdKey(aSession, MsgIdKey);

  // get the MsgIdentity for the above key using AccountManager
  nsCOMPtr <nsIMsgAccountManager> accountManager = do_GetService (NS_MSGACCOUNTMANAGER_CONTRACTID) ;
  if (NS_FAILED(rv) || (!accountManager) ) return rv ;

  nsCOMPtr <nsIMsgIdentity> pMsgId ;
  rv = accountManager->GetIdentity (MsgIdKey, getter_AddRefs(pMsgId)) ;
  if (NS_FAILED(rv) ) return rv ;

  // create a send listener to get back the send status
  nsCOMPtr <nsIMsgSendListener> sendListener ;
  rv = nsMAPISendListener::CreateMAPISendListener(getter_AddRefs(sendListener)) ;
  if (NS_FAILED(rv) || (!sendListener) ) return rv;

  // create the compose params object
  nsCOMPtr<nsIMsgComposeParams> pMsgComposeParams (do_CreateInstance(NS_MSGCOMPOSEPARAMS_CONTRACTID, &rv));
  if (NS_FAILED(rv) || (!pMsgComposeParams) ) return rv ;

  // populate the compose params
  PRBool forcePlainText;
  aCompFields->GetForcePlainText(&forcePlainText);
  pMsgComposeParams->SetType(nsIMsgCompType::New);
  pMsgComposeParams->SetFormat(forcePlainText ? nsIMsgCompFormat::PlainText : nsIMsgCompFormat::HTML);
  pMsgComposeParams->SetIdentity(pMsgId);
  pMsgComposeParams->SetComposeFields(aCompFields);
  pMsgComposeParams->SetSendListener(sendListener) ;
  pMsgComposeParams->SetSmtpPassword(smtpPassword.get());

  // create the nsIMsgCompose object to send the object
  nsCOMPtr<nsIMsgCompose> pMsgCompose (do_CreateInstance(NS_MSGCOMPOSE_CONTRACTID, &rv));
  if (NS_FAILED(rv) || (!pMsgCompose) ) return rv ;

  /** initialize nsIMsgCompose, Send the message, wait for send completion response **/

  rv = pMsgCompose->Initialize(hiddenWindow, pMsgComposeParams) ;
  if (NS_FAILED(rv)) return rv ;

  return pMsgCompose->SendMsg(nsIMsgSend::nsMsgDeliverNow, pMsgId, nsnull, nsnull, nsnull) ;
  if (NS_FAILED(rv)) return rv ;

  // assign to interface pointer from nsCOMPtr to facilitate typecast below
  nsIMsgSendListener * pSendListener = sendListener ;

  // we need to wait here to make sure that we return only after send is completed
  // so we will have a event loop here which will process the events till the Send IsDone.
  nsIThread *thread = NS_GetCurrentThread();
  while ( !((nsMAPISendListener *) pSendListener)->IsDone() )
  {
    PR_CEnterMonitor(pSendListener);
    PR_CWait(pSendListener, PR_MicrosecondsToInterval(1000UL));
    PR_CExitMonitor(pSendListener);
    NS_ProcessPendingEvents(thread);
  }

  return rv ;
}
Esempio n. 30
0
void
nsCString::AssignWithConversion( const nsAString& aData )
  {
    LossyCopyUTF16toASCII(aData, *this);
  }