Ejemplo n.º 1
0
  /** @hide */
  public void getXmlString(StringBuilder builder, Context context) {
    builder.append("<profile ");
    if (mNameResId > 0) {
      builder.append("nameres=\"");
      builder.append(context.getResources().getResourceEntryName(mNameResId));
    } else {
      builder.append("name=\"");
      builder.append(TextUtils.htmlEncode(getName()));
    }
    builder.append("\" uuid=\"");
    builder.append(TextUtils.htmlEncode(getUuid().toString()));
    builder.append("\">\n");

    builder.append("<statusbar>");
    builder.append(getStatusBarIndicator() ? "yes" : "no");
    builder.append("</statusbar>\n");

    for (ProfileGroup pGroup : profileGroups.values()) {
      pGroup.getXmlString(builder, context);
    }
    for (StreamSettings sd : streams.values()) {
      sd.getXmlString(builder, context);
    }
    for (ConnectionSettings cs : connections.values()) {
      cs.getXmlString(builder, context);
    }
    builder.append("</profile>\n");
    mDirty = false;
  }
Ejemplo n.º 2
0
 public static String UrlEncodeUpper(String str) {
   StringBuilder builder = new StringBuilder();
   for (char c : str.toCharArray()) {
     if (TextUtils.htmlEncode(String.valueOf(c)).length() > 1) {
       builder.append(TextUtils.htmlEncode(String.valueOf(c)).toUpperCase());
     } else {
       builder.append(c);
     }
   }
   return builder.toString();
 }
 public void getXmlString(StringBuilder builder) {
   builder.append(
       "<profileGroup name=\""
           + TextUtils.htmlEncode(getName())
           + "\" default=\""
           + isDefaultGroup()
           + "\">\n");
   builder.append("<sound>" + TextUtils.htmlEncode(mSoundOverride.toString()) + "</sound>\n");
   builder.append("<ringer>" + TextUtils.htmlEncode(mRingerOverride.toString()) + "</ringer>\n");
   builder.append("<soundMode>" + mSoundMode + "</soundMode>\n");
   builder.append("<ringerMode>" + mRingerMode + "</ringerMode>\n");
   builder.append("<vibrateMode>" + mVibrateMode + "</vibrateMode>\n");
   builder.append("<lightsMode>" + mLightsMode + "</lightsMode>\n");
   builder.append("</profileGroup>\n");
 }
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_invite_contacts_confirm);
    // Get data from intent
    Bundle extras = getIntent().getExtras();
    if (extras != null) {
      inviteCodeText = extras.getString("inviteCodeText");
      arraySelectedUsersIds = extras.getStringArrayList("arraySelectedUsersIds");
    }

    String escapedUsername = TextUtils.htmlEncode(AppCAP.getLoggedInUserNickname());

    Resources res = getResources();
    String text =
        String.format(res.getString(R.string.activity_invite_confirm_header), escapedUsername);
    CharSequence styledText = Html.fromHtml(text);
    title = styledText.toString();
    ((CustomFontView) findViewById(R.id.confirm_header)).setText(styledText);
    text =
        String.format(
            res.getString(R.string.activity_invite_confirm_content),
            escapedUsername,
            inviteCodeText);
    styledText = Html.fromHtml(text);
    messageContent = styledText.toString();
    ((CustomFontView) findViewById(R.id.confirm_content)).setText(styledText);
  }
  @Override
  public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
      case R.id.menu_settings:
        startActivity(new Intent(this, ZumoPreferenceActivity.class));
        return true;

      case R.id.menu_run_tests:
        if (getMobileServiceURL().trim() == "") {
          startActivity(new Intent(this, ZumoPreferenceActivity.class));
        } else {
          runTests();
        }
        return true;

      case R.id.menu_check_all:
        changeCheckAllTests(true);
        return true;

      case R.id.menu_uncheck_all:
        changeCheckAllTests(false);
        return true;

      case R.id.menu_reset:
        refreshTestGroupsAndLog();
        return true;

      case R.id.menu_view_log:
        AlertDialog.Builder logDialogBuilder = new AlertDialog.Builder(this);
        logDialogBuilder.setTitle("Log");

        final WebView webView = new WebView(this);

        String logContent = TextUtils.htmlEncode(mLog.toString()).replace("\n", "<br />");
        String logHtml = "<html><body><pre>" + logContent + "</pre></body></html>";
        webView.loadData(logHtml, "text/html", "utf-8");

        logDialogBuilder.setPositiveButton(
            "Copy",
            new DialogInterface.OnClickListener() {

              @Override
              public void onClick(DialogInterface dialog, int which) {
                ClipboardManager clipboardManager =
                    (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
                clipboardManager.setText(mLog.toString());
              }
            });

        logDialogBuilder.setView(webView);

        logDialogBuilder.create().show();
        return true;

      default:
        return super.onOptionsItemSelected(item);
    }
  }
 public final String a(
     int paramInt1,
     String paramString1,
     String paramString2,
     int paramInt2,
     int paramInt3,
     boolean paramBoolean1,
     boolean paramBoolean2,
     boolean paramBoolean3,
     boolean paramBoolean4) {
   if (!e) {
     throw new IllegalStateException("must call startConversation first");
   }
   if (paramBoolean1) {}
   for (String str = "initial-load"; ; str = "") {
     a(
         l,
         new Object[] {
           Integer.valueOf(paramInt1),
           str,
           TextUtils.htmlEncode(b.getString(buj.ch)),
           TextUtils.htmlEncode(b.getString(buj.eO)),
           TextUtils.htmlEncode(b.getString(buj.cx)),
           TextUtils.htmlEncode(b.getString(buj.cE)),
           paramString1,
           paramString2,
           Integer.valueOf(paramInt2),
           Integer.valueOf(paramInt3),
           Boolean.valueOf(paramBoolean1),
           Boolean.valueOf(paramBoolean2),
           Boolean.valueOf(paramBoolean3),
           Boolean.valueOf(paramBoolean4),
           Boolean.valueOf(cxd.c()),
           TextUtils.htmlEncode(b.getString(buj.bX, new Object[] {b.getString(buj.p)}))
         });
     e = false;
     cvm.b(
         g,
         "rendered conversation of %d bytes, buffer capacity=%d",
         new Object[] {Integer.valueOf(d.length() << 1), Integer.valueOf(d.capacity() << 1)});
     return super.a();
   }
 }
Ejemplo n.º 7
0
  /** Called when the activity is first created. */
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.check_code);
    mCodeTextView = (TextView) findViewById(R.id.code_value);
    mCheckCodeTextView = (TextView) findViewById(R.id.check_code);
    mCounterValue = (TextView) findViewById(R.id.counter_value);

    Intent intent = getIntent();
    Bundle extras = intent.getExtras();
    String user = extras.getString("user");

    AccountDb accountDb = DependencyInjector.getAccountDb();
    AccountDb.OtpType type = accountDb.getType(user);
    if (type == AccountDb.OtpType.HOTP) {
      mCounterValue.setText(accountDb.getCounter(user).toString());
      findViewById(R.id.counter_area).setVisibility(View.VISIBLE);
    } else {
      findViewById(R.id.counter_area).setVisibility(View.GONE);
    }

    String secret = accountDb.getSecret(user);
    String checkCode = null;
    String errorMessage = null;
    try {
      checkCode = getCheckCode(secret);
    } catch (GeneralSecurityException e) {
      errorMessage = getString(R.string.general_security_exception);
    } catch (DecodingException e) {
      errorMessage = getString(R.string.decoding_exception);
    }
    if (errorMessage != null) {
      mCheckCodeTextView.setText(errorMessage);
      return;
    }
    mCodeTextView.setText(checkCode);
    String checkCodeMessage =
        String.format(getString(R.string.check_code), TextUtils.htmlEncode(user));
    CharSequence styledCheckCode = Html.fromHtml(checkCodeMessage);
    mCheckCodeTextView.setText(styledCheckCode);
    mCheckCodeTextView.setVisibility(View.VISIBLE);
    findViewById(R.id.code_area).setVisibility(View.VISIBLE);
  }
 public static void sendJavascript(String paramString) {
   paramString =
       "(function() { try { "
           + paramString
           + " } catch( e ) { console.log( 'Error running: \""
           + TextUtils.htmlEncode(paramString)
           + "\" -- ' + e ); } })()";
   application.runOnUiThread(
       new Runnable() {
         public void run() {
           WebView localWebView = AppHelper.getAppView();
           if ((localWebView != null)
               && (localWebView.getUrl() != null)
               && (!localWebView.getUrl().contains("about:blank"))) {
             Log.d("AppHelper", "Javascript: " + val$js);
             AppHelper.application.sendJavascript(val$js);
             return;
           }
           Log.d("AppHelper", "No Target for JS!");
         }
       });
 }
Ejemplo n.º 9
0
 @Override
 public void renderTable(
     StringBuilder output, String tableName, List<String> columns, List<List<String>> rows) {
   output.append(
       "<B><a name=\""
           + tableName
           + "\">"
           + tableName
           + "</a></B>"
           + CardetoConstants.HTML_RETURN
           + "\n");
   // display columns
   output.append("<table>\n<tbody>\n");
   if (columns != null && columns.size() > 0) {
     output.append("<tr>\n");
     for (String column : columns) {
       output.append("<td>\n");
       output.append("<B>" + column + "</B>\n");
       output.append("</td>\n");
     }
     output.append("</tr>\n");
   }
   // display rows
   for (List<String> row : rows) {
     output.append("<tr>\n");
     for (String data : row) {
       output.append("<td>\n");
       if (data != null) {
         output.append(TextUtils.htmlEncode(data) + "\n");
       }
       output.append("</td>\n");
     }
     output.append("</tr>\n");
   }
   output.append("</tbody>\n</table>\n");
   output.append(CardetoConstants.HTML_RETURN + "\n");
 }
  private boolean uploadOneSubmission(
      String id, String instanceFilePath, String jrFormId, String token, String formFilePath) {
    // if the token is null fail immediately
    if (token == null) {
      mResults.put(id, oauth_fail + Collect.getInstance().getString(R.string.invalid_oauth));
      return false;
    }

    HashMap<String, String> answersToUpload = new HashMap<String, String>();
    HashMap<String, String> photosToUpload = new HashMap<String, String>();
    HashMap<String, PhotoEntry> uploadedPhotos = new HashMap<String, PhotoEntry>();

    HttpTransport h = AndroidHttp.newCompatibleTransport();
    GoogleCredential gc = new GoogleCredential();
    gc.setAccessToken(token);

    PicasaClient client = new PicasaClient(h.createRequestFactory(gc));

    // get instance file
    File instanceFile = new File(instanceFilePath);

    // first check to see how many columns we have:
    ArrayList<String> columnNames = new ArrayList<String>();
    try {
      getColumns(formFilePath, columnNames);
    } catch (FileNotFoundException e2) {
      e2.printStackTrace();
      mResults.put(id, e2.getMessage());
      return false;
    } catch (XmlPullParserException e2) {
      e2.printStackTrace();
      mResults.put(id, e2.getMessage());
      return false;
    } catch (IOException e2) {
      e2.printStackTrace();
      mResults.put(id, e2.getMessage());
      return false;
    } catch (FormException e2) {
      e2.printStackTrace();
      mResults.put(id, e2.getMessage());
      return false;
    }

    if (columnNames.size() > 255) {
      mResults.put(
          id, Collect.getInstance().getString(R.string.sheets_max_columns, columnNames.size()));
      return false;
    }

    // make sure column names are legal
    for (String n : columnNames) {
      if (!isValidGoogleSheetsString(n)) {
        mResults.put(
            id, Collect.getInstance().getString(R.string.google_sheets_invalid_column_form, n));
        return false;
      }
    }

    // parses the instance file and populates the answers and photos
    // hashmaps.
    try {
      processInstanceXML(instanceFile, answersToUpload, photosToUpload);
    } catch (XmlPullParserException e) {
      e.printStackTrace();
      mResults.put(id, form_fail + e.getMessage());
      return false;
    } catch (FormException e) {
      mResults.put(id, form_fail + Collect.getInstance().getString(R.string.google_repeat_error));
      return false;
    } catch (FileNotFoundException e) {
      e.printStackTrace();
      mResults.put(id, form_fail + e.getMessage());
      return false;
    } catch (IOException e) {
      e.printStackTrace();
      mResults.put(id, form_fail + e.getMessage());
      return false;
    }

    try {
      Thread.sleep(GOOGLE_SLEEP_TIME);
    } catch (InterruptedException e3) {
      e3.printStackTrace();
    }

    // make sure column names in submission are legal (may be different than form)
    for (String n : answersToUpload.keySet()) {
      if (!isValidGoogleSheetsString(n)) {
        mResults.put(
            id, Collect.getInstance().getString(R.string.google_sheets_invalid_column_instance, n));
        return false;
      }
    }

    // if we have any photos to upload,
    // get the picasa album or create a new one
    // then upload the photos
    if (photosToUpload.size() > 0) {
      // First set up a picasa album to upload to:
      // maybe we should move this, because if we don't have any
      // photos we don't care...
      AlbumEntry albumToUse;
      try {
        albumToUse = getOrCreatePicasaAlbum(client, jrFormId);
      } catch (IOException e) {
        e.printStackTrace();
        GoogleAuthUtil.invalidateToken(Collect.getInstance(), token);
        mResults.put(id, picasa_fail + e.getMessage());
        return false;
      }

      try {
        uploadPhotosToPicasa(photosToUpload, uploadedPhotos, client, albumToUse, instanceFile);
      } catch (IOException e1) {
        e1.printStackTrace();
        mResults.put(id, picasa_fail + e1.getMessage());
        return false;
      }
    }

    // All photos have been sent to picasa (if there were any)
    // now upload data to Google Sheet

    String selection = InstanceColumns._ID + "=?";
    String[] selectionArgs = {id};

    Cursor cursor = null;
    String urlString = null;
    try {
      // see if the submission element was defined in the form
      cursor =
          Collect.getInstance()
              .getContentResolver()
              .query(InstanceColumns.CONTENT_URI, null, selection, selectionArgs, null);

      if (cursor.getCount() > 0) {
        cursor.moveToPosition(-1);
        while (cursor.moveToNext()) {
          int subIdx = cursor.getColumnIndex(InstanceColumns.SUBMISSION_URI);
          urlString = cursor.isNull(subIdx) ? null : cursor.getString(subIdx);

          // if we didn't find one in the content provider,
          // try to get from settings
          if (urlString == null) {
            SharedPreferences settings =
                PreferenceManager.getDefaultSharedPreferences(Collect.getInstance());
            urlString =
                settings.getString(
                    PreferencesActivity.KEY_GOOGLE_SHEETS_URL,
                    Collect.getInstance().getString(R.string.default_google_sheets_url));
          }
        }
      }
    } finally {
      if (cursor != null) {
        cursor.close();
      }
    }

    // now parse the url string if we have one
    final String googleHeader = "docs.google.com/spreadsheets/d/";
    String sheetId;
    if (urlString == null || urlString.length() < googleHeader.length()) {
      mResults.put(
          id, form_fail + Collect.getInstance().getString(R.string.invalid_sheet_id, urlString));
      return false;
    } else {
      int start = urlString.indexOf(googleHeader) + googleHeader.length();
      int end = urlString.indexOf("/", start);
      if (end == -1) {
        // if there wasn't a "/", just try to get the end
        end = urlString.length();
      }
      if (start == -1 || end == -1) {
        mResults.put(
            id, form_fail + Collect.getInstance().getString(R.string.invalid_sheet_id, urlString));
        return false;
      }
      sheetId = urlString.substring(start, end);
    }

    SpreadsheetService service = new SpreadsheetService("ODK-Collect");
    service.setAuthSubToken(token);

    // Define the URL to request.
    URL spreadsheetFeedURL = null;
    try {
      spreadsheetFeedURL =
          new URL("https://spreadsheets.google.com/feeds/worksheets/" + sheetId + "/private/full");
    } catch (MalformedURLException e) {
      e.printStackTrace();
      mResults.put(id, form_fail + e.getMessage());
      return false;
    }

    WorksheetQuery query = new WorksheetQuery(spreadsheetFeedURL);
    WorksheetFeed feed = null;
    try {
      feed = service.query(query, WorksheetFeed.class);
    } catch (IOException e) {
      e.printStackTrace();
      mResults.put(id, form_fail + e.getMessage());
      return false;
    } catch (ServiceException e) {
      e.printStackTrace();
      if (e.getLocalizedMessage().equalsIgnoreCase("forbidden")) {
        mResults.put(
            id, form_fail + Collect.getInstance().getString(R.string.google_sheets_access_denied));
      } else {
        mResults.put(id, form_fail + Html.fromHtml(e.getResponseBody()));
      }
      return false;
    }

    List<WorksheetEntry> spreadsheets = feed.getEntries();
    // get the first worksheet
    WorksheetEntry we = spreadsheets.get(0);

    // check the headers....
    URL headerFeedUrl = null;
    try {
      headerFeedUrl =
          new URI(
                  we.getCellFeedUrl().toString()
                      + "?min-row=1&max-row=1&min-col=1&max-col="
                      + we.getColCount()
                      + "&return-empty=true")
              .toURL();
    } catch (MalformedURLException e1) {
      e1.printStackTrace();
      mResults.put(id, form_fail + e1.getMessage());
      return false;
    } catch (URISyntaxException e1) {
      e1.printStackTrace();
      mResults.put(id, form_fail + e1.getMessage());
      return false;
    }

    CellFeed headerFeed = null;
    try {
      headerFeed = service.getFeed(headerFeedUrl, CellFeed.class);
    } catch (IOException e) {
      e.printStackTrace();
      mResults.put(id, form_fail + e.getMessage());
      return false;
    } catch (ServiceException e) {
      e.printStackTrace();
      mResults.put(id, form_fail + e.getMessage());
      return false;
    }

    boolean emptyheaders = true;

    // go through headers
    // if they're empty, resize and add
    for (CellEntry c : headerFeed.getEntries()) {
      if (c.getCell().getValue() != null) {
        emptyheaders = false;
        break;
      }
    }

    if (emptyheaders) {
      // if the headers were empty, resize the spreadsheet
      // and add the headers
      we.setColCount(columnNames.size());
      try {
        we.update();
      } catch (IOException e2) {
        e2.printStackTrace();
        mResults.put(id, form_fail + e2.getMessage());
        return false;
      } catch (ServiceException e2) {
        e2.printStackTrace();
        mResults.put(id, form_fail + e2.getMessage());
        return false;
      } catch (UnsupportedOperationException e) {
        e.printStackTrace();
        mResults.put(
            id, form_fail + Collect.getInstance().getString(R.string.google_sheets_update_error));
        return false;
      }

      // get the cell feed url
      URL cellFeedUrl = null;
      try {
        cellFeedUrl =
            new URI(
                    we.getCellFeedUrl().toString()
                        + "?min-row=1&max-row=1&min-col=1&max-col="
                        + columnNames.size()
                        + "&return-empty=true")
                .toURL();
      } catch (MalformedURLException e1) {
        e1.printStackTrace();
        mResults.put(id, form_fail + e1.getMessage());
        return false;
      } catch (URISyntaxException e1) {
        e1.printStackTrace();
        mResults.put(id, form_fail + e1.getMessage());
        return false;
      }

      // and the cell feed
      CellFeed cellFeed = null;
      try {
        cellFeed = service.getFeed(cellFeedUrl, CellFeed.class);
      } catch (IOException e) {
        e.printStackTrace();
        mResults.put(id, form_fail + e.getMessage());
        return false;
      } catch (ServiceException e) {
        e.printStackTrace();
        mResults.put(id, form_fail + e.getMessage());
        return false;
      }

      // write the headers
      for (int i = 0; i < cellFeed.getEntries().size(); i++) {
        CellEntry cell = cellFeed.getEntries().get(i);
        String column = columnNames.get(i);
        cell.changeInputValueLocal(column);
        try {
          cell.update();
        } catch (IOException e) {
          e.printStackTrace();
          mResults.put(id, form_fail + e.getMessage());
          return false;
        } catch (ServiceException e) {
          e.printStackTrace();
          mResults.put(id, form_fail + e.getMessage());
          return false;
        }
      }
    }

    // we may have updated the feed, so get a new one
    // update the feed
    try {
      headerFeedUrl =
          new URI(
                  we.getCellFeedUrl().toString()
                      + "?min-row=1&max-row=1&min-col=1&max-col="
                      + we.getColCount()
                      + "&return-empty=true")
              .toURL();
    } catch (MalformedURLException e3) {
      e3.printStackTrace();
      mResults.put(id, form_fail + e3.getMessage());
      return false;
    } catch (URISyntaxException e3) {
      e3.printStackTrace();
      mResults.put(id, form_fail + e3.getMessage());
      return false;
    }
    try {
      headerFeed = service.getFeed(headerFeedUrl, CellFeed.class);
    } catch (IOException e2) {
      e2.printStackTrace();
      mResults.put(id, form_fail + e2.getMessage());
      return false;
    } catch (ServiceException e2) {
      e2.printStackTrace();
      mResults.put(id, form_fail + e2.getMessage());
      return false;
    }

    // see if our columns match, now
    URL cellFeedUrl = null;
    try {
      cellFeedUrl =
          new URI(
                  we.getCellFeedUrl().toString()
                      + "?min-row=1&max-row=1&min-col=1&max-col="
                      + headerFeed.getEntries().size()
                      + "&return-empty=true")
              .toURL();
    } catch (MalformedURLException e1) {
      e1.printStackTrace();
      mResults.put(id, form_fail + e1.getMessage());
      return false;
    } catch (URISyntaxException e1) {
      e1.printStackTrace();
      mResults.put(id, form_fail + e1.getMessage());
      return false;
    }
    CellFeed cellFeed = null;
    try {
      cellFeed = service.getFeed(cellFeedUrl, CellFeed.class);
    } catch (IOException e) {
      e.printStackTrace();
      mResults.put(id, form_fail + e.getMessage());
      return false;
    } catch (ServiceException e) {
      e.printStackTrace();
      mResults.put(id, form_fail + e.getMessage());
      return false;
    }

    // first, get all the columns in the spreadsheet
    ArrayList<String> sheetCols = new ArrayList<String>();
    for (int i = 0; i < cellFeed.getEntries().size(); i++) {
      CellEntry cell = cellFeed.getEntries().get(i);
      sheetCols.add(cell.getPlainTextContent());
    }

    ArrayList<String> missingColumns = new ArrayList<String>();
    for (String col : columnNames) {
      if (!sheetCols.contains(col)) {
        missingColumns.add(col);
      }
    }

    if (missingColumns.size() > 0) {
      // we had some missing columns, so error out
      String missingString = "";
      for (int i = 0; i < missingColumns.size(); i++) {
        missingString += missingColumns.get(i);
        if (i < missingColumns.size() - 1) {
          missingString += ", ";
        }
      }
      mResults.put(
          id,
          form_fail
              + Collect.getInstance()
                  .getString(R.string.google_sheets_missing_columns, missingString));
      return false;
    }

    // if we get here.. all has matched
    // so write the values
    ListEntry row = new ListEntry();

    // add photos to answer set
    Iterator<String> photoIterator = uploadedPhotos.keySet().iterator();
    while (photoIterator.hasNext()) {
      String key = photoIterator.next();
      String url = uploadedPhotos.get(key).getImageLink();
      answersToUpload.put(key, url);
    }

    Iterator<String> answerIterator = answersToUpload.keySet().iterator();
    while (answerIterator.hasNext()) {
      String path = answerIterator.next();
      String answer = answersToUpload.get(path);
      // Check to see if answer is a location, if so, get rid of accuracy
      // and altitude
      // try to match a fairly specific pattern to determine
      // if it's a location
      // [-]#.# [-]#.# #.# #.#
      Pattern p =
          Pattern.compile(
              "^-?[0-9]+\\.[0-9]+\\s-?[0-9]+\\.[0-9]+\\s-?[0-9]+\\" + ".[0-9]+\\s[0-9]+\\.[0-9]+$");
      Matcher m = p.matcher(answer);
      if (m.matches()) {
        // get rid of everything after the second space
        int firstSpace = answer.indexOf(" ");
        int secondSpace = answer.indexOf(" ", firstSpace + 1);
        answer = answer.substring(0, secondSpace);
        answer = answer.replace(' ', ',');
      }
      row.getCustomElements().setValueLocal(TextUtils.htmlEncode(path), answer);
    }

    // Send the new row to the API for insertion.
    try {
      URL listFeedUrl = we.getListFeedUrl();
      row = service.insert(listFeedUrl, row);
    } catch (IOException e) {
      e.printStackTrace();
      mResults.put(id, form_fail + e.getMessage());
      return false;
    } catch (ServiceException e) {
      e.printStackTrace();
      if (e.getLocalizedMessage().equalsIgnoreCase("Forbidden")) {
        mResults.put(
            id, form_fail + Collect.getInstance().getString(R.string.google_sheets_access_denied));
      } else {
        mResults.put(id, form_fail + Html.fromHtml(e.getResponseBody()));
      }
      return false;
    }

    mResults.put(id, Collect.getInstance().getString(R.string.success));
    return true;
  }
Ejemplo n.º 11
0
 protected void dumpAttribute(PrintStream out, String name, String value) {
   out.print(" " + name + "=\"" + (value == null ? null : TextUtils.htmlEncode(value)) + "\"");
 }
    @Override
    protected Boolean doInBackground(Post... posts) {
      mErrorUnavailableVideoPress = false;
      mPost = posts[0];

      mPostUploadNotifier = new PostUploadNotifier(mPost);
      String postTitle =
          TextUtils.isEmpty(mPost.getTitle()) ? getString(R.string.untitled) : mPost.getTitle();
      String uploadingPostTitle = String.format(getString(R.string.posting_post), postTitle);
      String uploadingPostMessage =
          String.format(
              getString(R.string.sending_content),
              mPost.isPage()
                  ? getString(R.string.page).toLowerCase()
                  : getString(R.string.post).toLowerCase());
      mPostUploadNotifier.updateNotificationMessage(uploadingPostTitle, uploadingPostMessage);

      mBlog = WordPress.wpDB.instantiateBlogByLocalId(mPost.getLocalTableBlogId());
      if (mBlog == null) {
        mErrorMessage = mContext.getString(R.string.blog_not_found);
        return false;
      }

      // Create the XML-RPC client
      mClient =
          XMLRPCFactory.instantiate(mBlog.getUri(), mBlog.getHttpuser(), mBlog.getHttppassword());

      if (TextUtils.isEmpty(mPost.getPostStatus())) {
        mPost.setPostStatus(PostStatus.toString(PostStatus.PUBLISHED));
      }

      String descriptionContent = processPostMedia(mPost.getDescription());

      String moreContent = "";
      if (!TextUtils.isEmpty(mPost.getMoreText())) {
        moreContent = processPostMedia(mPost.getMoreText());
      }

      mPostUploadNotifier.updateNotificationMessage(uploadingPostTitle, uploadingPostMessage);

      // If media file upload failed, let's stop here and prompt the user
      if (mIsMediaError) {
        return false;
      }

      JSONArray categoriesJsonArray = mPost.getJSONCategories();
      String[] postCategories = null;
      if (categoriesJsonArray != null) {
        if (categoriesJsonArray.length() > 0) {
          mHasCategory = true;
        }

        postCategories = new String[categoriesJsonArray.length()];
        for (int i = 0; i < categoriesJsonArray.length(); i++) {
          try {
            postCategories[i] = TextUtils.htmlEncode(categoriesJsonArray.getString(i));
          } catch (JSONException e) {
            AppLog.e(T.POSTS, e);
          }
        }
      }

      Map<String, Object> contentStruct = new HashMap<String, Object>();

      if (!mPost.isPage() && mPost.isLocalDraft()) {
        // add the tagline
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(mContext);

        if (prefs.getBoolean(getString(R.string.pref_key_post_sig_enabled), false)) {
          String tagline = prefs.getString(getString(R.string.pref_key_post_sig), "");
          if (!TextUtils.isEmpty(tagline)) {
            String tag = "\n\n<span class=\"post_sig\">" + tagline + "</span>\n\n";
            if (TextUtils.isEmpty(moreContent)) descriptionContent += tag;
            else moreContent += tag;
          }
        }
      }

      // Post format
      if (!mPost.isPage()) {
        if (!TextUtils.isEmpty(mPost.getPostFormat())) {
          contentStruct.put("wp_post_format", mPost.getPostFormat());
        }
      }

      contentStruct.put("post_type", (mPost.isPage()) ? "page" : "post");
      contentStruct.put("title", mPost.getTitle());
      long pubDate = mPost.getDate_created_gmt();
      if (pubDate != 0) {
        Date date_created_gmt = new Date(pubDate);
        contentStruct.put("date_created_gmt", date_created_gmt);
        Date dateCreated = new Date(pubDate + (date_created_gmt.getTimezoneOffset() * 60000));
        contentStruct.put("dateCreated", dateCreated);
      }

      if (!TextUtils.isEmpty(moreContent)) {
        descriptionContent = descriptionContent.trim() + "<!--more-->" + moreContent;
        mPost.setMoreText("");
      }

      // get rid of the p and br tags that the editor adds.
      if (mPost.isLocalDraft()) {
        descriptionContent =
            descriptionContent.replace("<p>", "").replace("</p>", "\n").replace("<br>", "");
      }

      // gets rid of the weird character android inserts after images
      descriptionContent = descriptionContent.replaceAll("\uFFFC", "");

      contentStruct.put("description", descriptionContent);
      if (!mPost.isPage()) {
        contentStruct.put("mt_keywords", mPost.getKeywords());

        if (postCategories != null && postCategories.length > 0) {
          contentStruct.put("categories", postCategories);
        }
      }

      contentStruct.put("mt_excerpt", mPost.getPostExcerpt());
      contentStruct.put((mPost.isPage()) ? "page_status" : "post_status", mPost.getPostStatus());

      // Geolocation
      if (mPost.supportsLocation()) {
        JSONObject remoteGeoLatitude = mPost.getCustomField("geo_latitude");
        JSONObject remoteGeoLongitude = mPost.getCustomField("geo_longitude");
        JSONObject remoteGeoPublic = mPost.getCustomField("geo_public");

        Map<Object, Object> hLatitude = new HashMap<Object, Object>();
        Map<Object, Object> hLongitude = new HashMap<Object, Object>();
        Map<Object, Object> hPublic = new HashMap<Object, Object>();

        try {
          if (remoteGeoLatitude != null) {
            hLatitude.put("id", remoteGeoLatitude.getInt("id"));
          }

          if (remoteGeoLongitude != null) {
            hLongitude.put("id", remoteGeoLongitude.getInt("id"));
          }

          if (remoteGeoPublic != null) {
            hPublic.put("id", remoteGeoPublic.getInt("id"));
          }

          if (mPost.hasLocation()) {
            PostLocation location = mPost.getLocation();
            if (!hLatitude.containsKey("id")) {
              hLatitude.put("key", "geo_latitude");
            }

            if (!hLongitude.containsKey("id")) {
              hLongitude.put("key", "geo_longitude");
            }

            if (!hPublic.containsKey("id")) {
              hPublic.put("key", "geo_public");
            }

            hLatitude.put("value", location.getLatitude());
            hLongitude.put("value", location.getLongitude());
            hPublic.put("value", 1);
          }
        } catch (JSONException e) {
          AppLog.e(T.EDITOR, e);
        }

        if (!hLatitude.isEmpty() && !hLongitude.isEmpty() && !hPublic.isEmpty()) {
          Object[] geo = {hLatitude, hLongitude, hPublic};
          contentStruct.put("custom_fields", geo);
        }
      }

      // featured image
      if (featuredImageID != -1) {
        contentStruct.put("wp_post_thumbnail", featuredImageID);
      }

      if (!TextUtils.isEmpty(mPost.getQuickPostType())) {
        mClient.addQuickPostHeader(mPost.getQuickPostType());
      }

      contentStruct.put("wp_password", mPost.getPassword());

      Object[] params;
      if (mPost.isLocalDraft())
        params =
            new Object[] {
              mBlog.getRemoteBlogId(),
              mBlog.getUsername(),
              mBlog.getPassword(),
              contentStruct,
              false
            };
      else
        params =
            new Object[] {
              mPost.getRemotePostId(),
              mBlog.getUsername(),
              mBlog.getPassword(),
              contentStruct,
              false
            };

      try {
        EventBus.getDefault().post(new PostUploadStarted(mPost.getLocalTableBlogId()));

        if (mPost.isLocalDraft()) {
          Object object = mClient.call("metaWeblog.newPost", params);
          if (object instanceof String) {
            mPost.setRemotePostId((String) object);
          }
        } else {
          mClient.call("metaWeblog.editPost", params);
        }

        // Track any Analytics before modifying the post
        trackUploadAnalytics();

        mPost.setLocalDraft(false);
        mPost.setLocalChange(false);
        WordPress.wpDB.updatePost(mPost);

        // request the new/updated post from the server to ensure local copy matches server
        ApiHelper.updateSinglePost(
            mBlog.getLocalTableBlogId(), mPost.getRemotePostId(), mPost.isPage());

        return true;
      } catch (final XMLRPCException e) {
        setUploadPostErrorMessage(e);
      } catch (IOException e) {
        setUploadPostErrorMessage(e);
      } catch (XmlPullParserException e) {
        setUploadPostErrorMessage(e);
      }

      return false;
    }
    public String uploadMediaFile(MediaFile mediaFile, Blog blog) {
      String content = "";

      String curImagePath = mediaFile.getFilePath();
      if (curImagePath == null) {
        return null;
      }

      if (curImagePath.contains("video")) {
        // Upload the video
        XMLRPCClientInterface client =
            XMLRPCFactory.instantiate(blog.getUri(), blog.getHttpuser(), blog.getHttppassword());
        // create temp file for media upload
        String tempFileName = "wp-" + System.currentTimeMillis();
        try {
          context.openFileOutput(tempFileName, Context.MODE_PRIVATE);
        } catch (FileNotFoundException e) {
          mErrorMessage = getResources().getString(R.string.file_error_create);
          mIsMediaError = true;
          return null;
        }

        Uri videoUri = Uri.parse(curImagePath);
        File videoFile = null;
        String mimeType = "", xRes = "", yRes = "";

        if (videoUri.toString().contains("content:")) {

          String[] projection =
              new String[] {
                Video.Media._ID, Video.Media.DATA, Video.Media.MIME_TYPE, Video.Media.RESOLUTION
              };
          Cursor cur = context.getContentResolver().query(videoUri, projection, null, null, null);

          if (cur != null && cur.moveToFirst()) {

            int mimeTypeColumn, resolutionColumn, dataColumn;

            dataColumn = cur.getColumnIndex(Video.Media.DATA);
            mimeTypeColumn = cur.getColumnIndex(Video.Media.MIME_TYPE);
            resolutionColumn = cur.getColumnIndex(Video.Media.RESOLUTION);

            mediaFile = new MediaFile();

            String thumbData = cur.getString(dataColumn);
            mimeType = cur.getString(mimeTypeColumn);

            videoFile = new File(thumbData);
            mediaFile.setFilePath(videoFile.getPath());
            String resolution = cur.getString(resolutionColumn);
            if (resolution != null) {
              String[] resx = resolution.split("x");
              xRes = resx[0];
              yRes = resx[1];
            } else {
              // set the width of the video to the thumbnail width, else 640x480
              if (!blog.getMaxImageWidth().equals("Original Size")) {
                xRes = blog.getMaxImageWidth();
                yRes = String.valueOf(Math.round(Integer.valueOf(blog.getMaxImageWidth()) * 0.75));
              } else {
                xRes = "640";
                yRes = "480";
              }
            }
          }
        } else { // file is not in media library
          String filePath = videoUri.toString().replace("file://", "");
          mediaFile.setFilePath(filePath);
          videoFile = new File(filePath);
        }

        if (videoFile == null) {
          mErrorMessage = context.getResources().getString(R.string.error_media_upload);
          return null;
        }

        if (TextUtils.isEmpty(mimeType)) {
          mimeType = MediaUtils.getMediaFileMimeType(videoFile);
        }
        String videoName = MediaUtils.getMediaFileName(videoFile, mimeType);

        // try to upload the video
        Map<String, Object> m = new HashMap<String, Object>();
        m.put("name", videoName);
        m.put("type", mimeType);
        m.put("bits", mediaFile);
        m.put("overwrite", true);

        Object[] params = {1, blog.getUsername(), blog.getPassword(), m};

        FeatureSet featureSet = synchronousGetFeatureSet();
        boolean selfHosted = WordPress.currentBlog != null && !WordPress.currentBlog.isDotcomFlag();
        boolean isVideoEnabled =
            selfHosted || (featureSet != null && mFeatureSet.isVideopressEnabled());
        if (isVideoEnabled) {
          File tempFile;
          try {
            String fileExtension = MimeTypeMap.getFileExtensionFromUrl(videoName);
            tempFile = createTempUploadFile(fileExtension);
          } catch (IOException e) {
            mErrorMessage = getResources().getString(R.string.file_error_create);
            mIsMediaError = true;
            return null;
          }

          Object result = uploadFileHelper(client, params, tempFile);
          Map<?, ?> resultMap = (HashMap<?, ?>) result;
          if (resultMap != null && resultMap.containsKey("url")) {
            String resultURL = resultMap.get("url").toString();
            if (resultMap.containsKey("videopress_shortcode")) {
              resultURL = resultMap.get("videopress_shortcode").toString() + "\n";
            } else {
              resultURL =
                  String.format(
                      "<video width=\"%s\" height=\"%s\" controls=\"controls\"><source src=\"%s\" type=\"%s\" /><a href=\"%s\">Click to view video</a>.</video>",
                      xRes, yRes, resultURL, mimeType, resultURL);
            }
            content = content + resultURL;
          } else {
            return null;
          }
        } else {
          mErrorMessage = getString(R.string.media_no_video_message);
          mErrorUnavailableVideoPress = true;
          return null;
        }
      } else {
        // Upload the image
        curImagePath = mediaFile.getFilePath();

        Uri imageUri = Uri.parse(curImagePath);
        File imageFile = null;
        String mimeType = "", path = "";
        int orientation;

        if (imageUri.toString().contains("content:")) {
          String[] projection;
          Uri imgPath;

          projection = new String[] {Images.Media._ID, Images.Media.DATA, Images.Media.MIME_TYPE};

          imgPath = imageUri;

          Cursor cur = context.getContentResolver().query(imgPath, projection, null, null, null);
          if (cur != null && cur.moveToFirst()) {
            int dataColumn, mimeTypeColumn;
            dataColumn = cur.getColumnIndex(Images.Media.DATA);
            mimeTypeColumn = cur.getColumnIndex(Images.Media.MIME_TYPE);

            String thumbData = cur.getString(dataColumn);
            mimeType = cur.getString(mimeTypeColumn);
            imageFile = new File(thumbData);
            path = thumbData;
            mediaFile.setFilePath(imageFile.getPath());
          }
        } else { // file is not in media library
          path = imageUri.toString().replace("file://", "");
          imageFile = new File(path);
          mediaFile.setFilePath(path);
        }

        // check if the file exists
        if (imageFile == null) {
          mErrorMessage = context.getString(R.string.file_not_found);
          mIsMediaError = true;
          return null;
        }

        if (TextUtils.isEmpty(mimeType)) {
          mimeType = MediaUtils.getMediaFileMimeType(imageFile);
        }
        String fileName = MediaUtils.getMediaFileName(imageFile, mimeType);
        String fileExtension = MimeTypeMap.getFileExtensionFromUrl(fileName).toLowerCase();

        ImageHelper ih = new ImageHelper();
        orientation = ih.getImageOrientation(context, path);

        String resizedPictureURL = null;

        // We need to upload a resized version of the picture when the blog settings != original
        // size, or when
        // the user has selected a smaller size for the current picture in the picture settings
        // screen
        // We won't resize gif images to keep them awesome.
        boolean shouldUploadResizedVersion = false;
        // If it's not a gif and blog don't keep original size, there is a chance we need to resize
        if (!mimeType.equals("image/gif") && !blog.getMaxImageWidth().equals("Original Size")) {
          // check the picture settings
          int pictureSettingWidth = mediaFile.getWidth();
          BitmapFactory.Options options = new BitmapFactory.Options();
          options.inJustDecodeBounds = true;
          BitmapFactory.decodeFile(path, options);
          int imageHeight = options.outHeight;
          int imageWidth = options.outWidth;
          int[] dimensions = {imageWidth, imageHeight};
          if (dimensions[0] != 0 && dimensions[0] != pictureSettingWidth) {
            shouldUploadResizedVersion = true;
          }
        }

        boolean shouldAddImageWidthCSS = false;

        if (shouldUploadResizedVersion) {
          MediaFile resizedMediaFile = new MediaFile(mediaFile);
          // Create resized image
          byte[] bytes =
              ih.createThumbnailFromUri(
                  context, imageUri, resizedMediaFile.getWidth(), fileExtension, orientation);

          if (bytes == null) {
            // We weren't able to resize the image, so we will upload the full size image with css
            // to resize it
            shouldUploadResizedVersion = false;
            shouldAddImageWidthCSS = true;
          } else {
            // Save temp image
            String tempFilePath;
            File resizedImageFile;
            try {
              resizedImageFile = File.createTempFile("wp-image-", fileExtension);
              FileOutputStream out = new FileOutputStream(resizedImageFile);
              out.write(bytes);
              out.close();
              tempFilePath = resizedImageFile.getPath();
            } catch (IOException e) {
              AppLog.w(T.POSTS, "failed to create image temp file");
              mErrorMessage = context.getString(R.string.error_media_upload);
              mIsMediaError = true;
              return null;
            }

            // upload resized picture
            if (!TextUtils.isEmpty(tempFilePath)) {
              resizedMediaFile.setFilePath(tempFilePath);
              Map<String, Object> parameters = new HashMap<String, Object>();

              parameters.put("name", fileName);
              parameters.put("type", mimeType);
              parameters.put("bits", resizedMediaFile);
              parameters.put("overwrite", true);
              resizedPictureURL = uploadPicture(parameters, resizedMediaFile, blog);
              if (resizedPictureURL == null) {
                AppLog.w(T.POSTS, "failed to upload resized picture");
                return null;
              } else if (resizedImageFile != null && resizedImageFile.exists()) {
                resizedImageFile.delete();
              }
            } else {
              AppLog.w(T.POSTS, "failed to create resized picture");
              mErrorMessage = context.getString(R.string.out_of_memory);
              mIsMediaError = true;
              return null;
            }
          }
        }

        String fullSizeUrl = null;
        // Upload the full size picture if "Original Size" is selected in settings, or if 'link to
        // full size' is checked.
        if (!shouldUploadResizedVersion || blog.isFullSizeImage()) {
          // try to upload the image
          Map<String, Object> parameters = new HashMap<String, Object>();
          parameters.put("name", fileName);
          parameters.put("type", mimeType);
          parameters.put("bits", mediaFile);
          parameters.put("overwrite", true);

          fullSizeUrl = uploadPicture(parameters, mediaFile, blog);
          if (fullSizeUrl == null) return null;
        }

        String alignment = "";
        switch (mediaFile.getHorizontalAlignment()) {
          case 0:
            alignment = "alignnone";
            break;
          case 1:
            alignment = "alignleft";
            break;
          case 2:
            alignment = "aligncenter";
            break;
          case 3:
            alignment = "alignright";
            break;
        }

        String alignmentCSS = "class=\"" + alignment + " size-full\" ";

        if (shouldAddImageWidthCSS) {
          alignmentCSS += "style=\"max-width: " + mediaFile.getWidth() + "px\" ";
        }

        // Check if we uploaded a featured picture that is not added to the post content (normal
        // case)
        if ((fullSizeUrl != null && fullSizeUrl.equalsIgnoreCase(""))
            || (resizedPictureURL != null && resizedPictureURL.equalsIgnoreCase(""))) {
          return ""; // Not featured in post. Do not add to the content.
        }

        if (fullSizeUrl == null && resizedPictureURL != null) {
          fullSizeUrl = resizedPictureURL;
        } else if (fullSizeUrl != null && resizedPictureURL == null) {
          resizedPictureURL = fullSizeUrl;
        }

        String mediaTitle = TextUtils.isEmpty(mediaFile.getTitle()) ? "" : mediaFile.getTitle();

        content =
            content
                + "<a href=\""
                + fullSizeUrl
                + "\"><img title=\""
                + mediaTitle
                + "\" "
                + alignmentCSS
                + "alt=\"image\" src=\""
                + resizedPictureURL
                + "\" /></a>";

        if (!TextUtils.isEmpty(mediaFile.getCaption())) {
          content =
              String.format(
                  "[caption id=\"\" align=\"%s\" width=\"%d\" caption=\"%s\"]%s[/caption]",
                  alignment,
                  mediaFile.getWidth(),
                  TextUtils.htmlEncode(mediaFile.getCaption()),
                  content);
        }
      }
      return content;
    }
    @Override
    protected Boolean doInBackground(Post... posts) {
      mErrorUnavailableVideoPress = false;
      post = posts[0];

      // add the uploader to the notification bar
      nm = (NotificationManager) SystemServiceFactory.get(context, Context.NOTIFICATION_SERVICE);

      String postOrPage =
          (String)
              (post.isPage()
                  ? context.getResources().getText(R.string.page_id)
                  : context.getResources().getText(R.string.post_id));
      String message = context.getResources().getText(R.string.uploading) + " " + postOrPage;
      n = new Notification(R.drawable.notification_icon, message, System.currentTimeMillis());

      Intent notificationIntent =
          new Intent(context, post.isPage() ? PagesActivity.class : PostsActivity.class);
      notificationIntent.addFlags(
          Intent.FLAG_ACTIVITY_CLEAR_TOP
              | Intent.FLAG_ACTIVITY_NEW_TASK
              | IntentCompat.FLAG_ACTIVITY_CLEAR_TASK);
      notificationIntent.setAction(Intent.ACTION_MAIN);
      notificationIntent.addCategory(Intent.CATEGORY_LAUNCHER);
      notificationIntent.setData(
          (Uri.parse("custom://wordpressNotificationIntent" + post.getLocalTableBlogId())));
      notificationIntent.putExtra(PostsActivity.EXTRA_VIEW_PAGES, post.isPage());
      PendingIntent pendingIntent =
          PendingIntent.getActivity(context, 0, notificationIntent, Intent.FLAG_ACTIVITY_CLEAR_TOP);

      n.setLatestEventInfo(context, message, message, pendingIntent);

      notificationID = (new Random()).nextInt() + post.getLocalTableBlogId();
      nm.notify(notificationID, n); // needs a unique id

      Blog blog = WordPress.wpDB.instantiateBlogByLocalId(post.getLocalTableBlogId());
      if (blog == null) {
        mErrorMessage = context.getString(R.string.blog_not_found);
        return false;
      }

      if (TextUtils.isEmpty(post.getPostStatus())) {
        post.setPostStatus("publish");
      }
      Boolean publishThis = false;

      String descriptionContent = "", moreContent = "";
      int moreCount = 1;
      if (!TextUtils.isEmpty(post.getMoreText())) moreCount++;
      String imgTags = "<img[^>]+android-uri\\s*=\\s*['\"]([^'\"]+)['\"][^>]*>";
      Pattern pattern = Pattern.compile(imgTags);

      for (int x = 0; x < moreCount; x++) {

        if (x == 0) descriptionContent = post.getDescription();
        else moreContent = post.getMoreText();

        Matcher matcher;

        if (x == 0) {
          matcher = pattern.matcher(descriptionContent);
        } else {
          matcher = pattern.matcher(moreContent);
        }

        List<String> imageTags = new ArrayList<String>();
        while (matcher.find()) {
          imageTags.add(matcher.group());
        }

        for (String tag : imageTags) {

          Pattern p = Pattern.compile("android-uri=\"([^\"]+)\"");
          Matcher m = p.matcher(tag);
          if (m.find()) {
            String imgPath = m.group(1);
            if (!imgPath.equals("")) {
              MediaFile mf = WordPress.wpDB.getMediaFile(imgPath, post);

              if (mf != null) {
                String imgHTML = uploadMediaFile(mf, blog);
                if (imgHTML != null) {
                  if (x == 0) {
                    descriptionContent = descriptionContent.replace(tag, imgHTML);
                  } else {
                    moreContent = moreContent.replace(tag, imgHTML);
                  }
                } else {
                  if (x == 0) descriptionContent = descriptionContent.replace(tag, "");
                  else moreContent = moreContent.replace(tag, "");
                  mIsMediaError = true;
                }
              }
            }
          }
        }
      }

      // If media file upload failed, let's stop here and prompt the user
      if (mIsMediaError) return false;

      JSONArray categoriesJsonArray = post.getJSONCategories();
      String[] postCategories = null;
      if (categoriesJsonArray != null) {
        postCategories = new String[categoriesJsonArray.length()];
        for (int i = 0; i < categoriesJsonArray.length(); i++) {
          try {
            postCategories[i] = TextUtils.htmlEncode(categoriesJsonArray.getString(i));
          } catch (JSONException e) {
            AppLog.e(T.POSTS, e);
          }
        }
      }

      Map<String, Object> contentStruct = new HashMap<String, Object>();

      if (!post.isPage() && post.isLocalDraft()) {
        // add the tagline
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);

        if (prefs.getBoolean("wp_pref_signature_enabled", false)) {
          String tagline = prefs.getString("wp_pref_post_signature", "");
          if (!TextUtils.isEmpty(tagline)) {
            String tag = "\n\n<span class=\"post_sig\">" + tagline + "</span>\n\n";
            if (TextUtils.isEmpty(moreContent)) descriptionContent += tag;
            else moreContent += tag;
          }
        }
      }

      // post format
      if (!post.isPage()) {
        if (!TextUtils.isEmpty(post.getPostFormat())) {
          contentStruct.put("wp_post_format", post.getPostFormat());
        }
      }

      contentStruct.put("post_type", (post.isPage()) ? "page" : "post");
      contentStruct.put("title", post.getTitle());
      long pubDate = post.getDate_created_gmt();
      if (pubDate != 0) {
        Date date_created_gmt = new Date(pubDate);
        contentStruct.put("date_created_gmt", date_created_gmt);
        Date dateCreated = new Date(pubDate + (date_created_gmt.getTimezoneOffset() * 60000));
        contentStruct.put("dateCreated", dateCreated);
      }

      if (!moreContent.equals("")) {
        descriptionContent = descriptionContent.trim() + "<!--more-->" + moreContent;
        post.setMoreText("");
      }

      // get rid of the p and br tags that the editor adds.
      if (post.isLocalDraft()) {
        descriptionContent =
            descriptionContent.replace("<p>", "").replace("</p>", "\n").replace("<br>", "");
      }

      // gets rid of the weird character android inserts after images
      descriptionContent = descriptionContent.replaceAll("\uFFFC", "");

      contentStruct.put("description", descriptionContent);
      if (!post.isPage()) {
        contentStruct.put("mt_keywords", post.getKeywords());

        if (postCategories != null && postCategories.length > 0)
          contentStruct.put("categories", postCategories);
      }

      contentStruct.put("mt_excerpt", post.getPostExcerpt());

      contentStruct.put((post.isPage()) ? "page_status" : "post_status", post.getPostStatus());
      if (!post.isPage()) {
        if (post.getLatitude() > 0) {
          Map<Object, Object> hLatitude = new HashMap<Object, Object>();
          hLatitude.put("key", "geo_latitude");
          hLatitude.put("value", post.getLatitude());

          Map<Object, Object> hLongitude = new HashMap<Object, Object>();
          hLongitude.put("key", "geo_longitude");
          hLongitude.put("value", post.getLongitude());

          Map<Object, Object> hPublic = new HashMap<Object, Object>();
          hPublic.put("key", "geo_public");
          hPublic.put("value", 1);

          Object[] geo = {hLatitude, hLongitude, hPublic};

          contentStruct.put("custom_fields", geo);
        }
      }

      // featured image
      if (featuredImageID != -1) {
        contentStruct.put("wp_post_thumbnail", featuredImageID);
      }
      XMLRPCClientInterface client =
          XMLRPCFactory.instantiate(blog.getUri(), blog.getHttpuser(), blog.getHttppassword());
      if (!TextUtils.isEmpty(post.getQuickPostType())) {
        client.addQuickPostHeader(post.getQuickPostType());
      }
      n.setLatestEventInfo(context, message, message, n.contentIntent);
      nm.notify(notificationID, n);

      contentStruct.put("wp_password", post.getPassword());

      Object[] params;
      if (post.isLocalDraft() && !post.isUploaded())
        params =
            new Object[] {
              blog.getRemoteBlogId(),
              blog.getUsername(),
              blog.getPassword(),
              contentStruct,
              publishThis
            };
      else
        params =
            new Object[] {
              post.getRemotePostId(),
              blog.getUsername(),
              blog.getPassword(),
              contentStruct,
              publishThis
            };

      try {
        if (post.isLocalDraft() && !post.isUploaded()) {
          Object newPostId = client.call("metaWeblog.newPost", params);
          if (newPostId instanceof String) {
            post.setRemotePostId((String) newPostId);
          }
        } else {
          client.call("metaWeblog.editPost", params);
        }

        post.setUploaded(true);
        post.setLocalChange(false);
        WordPress.wpDB.updatePost(post);
        return true;
      } catch (final XMLRPCException e) {
        setUploadPostErrorMessage(e);
      } catch (IOException e) {
        setUploadPostErrorMessage(e);
      } catch (XmlPullParserException e) {
        setUploadPostErrorMessage(e);
      }

      return false;
    }