瀏覽代碼

Merge branch 'develop' into refresh_folder_contents_when_browsed_into

Conflicts:
	src/com/owncloud/android/operations/SynchronizeFolderOperation.java
masensio 11 年之前
父節點
當前提交
d6267698e8
共有 44 個文件被更改,包括 1596 次插入288 次删除
  1. 2 2
      AndroidManifest.xml
  2. 2 2
      oc_jb_workaround/AndroidManifest.xml
  3. 9 4
      res/layout-land/account_setup.xml
  4. 23 9
      res/layout/account_setup.xml
  5. 33 0
      res/layout/sso_dialog.xml
  6. 1 1
      res/values-es/strings.xml
  7. 15 0
      res/values-tr/strings.xml
  8. 11 0
      res/values-zh-rCN/strings.xml
  9. 133 10
      res/values-zh-rTW/strings.xml
  10. 0 5
      res/values/branding.xml
  11. 0 5
      res/values/oauth2_configuration.xml
  12. 10 0
      res/values/setup.xml
  13. 8 1
      res/values/strings.xml
  14. 7 1
      res/values/styles.xml
  15. 7 1
      src/com/owncloud/android/authentication/AccountAuthenticator.java
  16. 85 0
      src/com/owncloud/android/authentication/AccountAuthenticatorActivity.java
  17. 48 2
      src/com/owncloud/android/authentication/AccountUtils.java
  18. 435 126
      src/com/owncloud/android/authentication/AuthenticatorActivity.java
  19. 175 0
      src/com/owncloud/android/authentication/SsoWebViewClient.java
  20. 4 4
      src/com/owncloud/android/datamodel/FileDataStorageManager.java
  21. 5 1
      src/com/owncloud/android/files/services/FileDownloader.java
  22. 57 48
      src/com/owncloud/android/files/services/FileUploader.java
  23. 24 10
      src/com/owncloud/android/network/OwnCloudClientUtils.java
  24. 3 0
      src/com/owncloud/android/operations/ChunkedUploadFileOperation.java
  25. 1 1
      src/com/owncloud/android/operations/CreateFolderOperation.java
  26. 9 8
      src/com/owncloud/android/operations/DownloadFileOperation.java
  27. 1 1
      src/com/owncloud/android/operations/ExistenceCheckOperation.java
  28. 2 2
      src/com/owncloud/android/operations/OAuth2GetAccessToken.java
  29. 1 1
      src/com/owncloud/android/operations/OwnCloudServerCheckOperation.java
  30. 21 10
      src/com/owncloud/android/operations/RemoteOperation.java
  31. 42 4
      src/com/owncloud/android/operations/RemoteOperationResult.java
  32. 1 1
      src/com/owncloud/android/operations/RemoveFileOperation.java
  33. 1 1
      src/com/owncloud/android/operations/RenameFileOperation.java
  34. 1 1
      src/com/owncloud/android/operations/SynchronizeFileOperation.java
  35. 15 6
      src/com/owncloud/android/operations/SynchronizeFolderOperation.java
  36. 1 1
      src/com/owncloud/android/operations/UpdateOCVersionOperation.java
  37. 1 1
      src/com/owncloud/android/operations/UploadFileOperation.java
  38. 2 0
      src/com/owncloud/android/providers/FileContentProvider.java
  39. 12 2
      src/com/owncloud/android/syncadapter/FileSyncAdapter.java
  40. 12 2
      src/com/owncloud/android/ui/activity/AccountSelectActivity.java
  41. 1 1
      src/com/owncloud/android/ui/activity/FileActivity.java
  42. 284 0
      src/com/owncloud/android/ui/dialog/SamlWebViewDialog.java
  43. 40 0
      src/com/owncloud/android/ui/dialog/SsoWebView.java
  44. 51 13
      src/eu/alefzero/webdav/WebdavClient.java

+ 2 - 2
AndroidManifest.xml

@@ -18,8 +18,8 @@
   along with this program.  If not, see <http://www.gnu.org/licenses/>.
  -->
 <manifest package="com.owncloud.android"
-    android:versionCode="104004"
-    android:versionName="1.4.4" xmlns:android="http://schemas.android.com/apk/res/android">
+    android:versionCode="104005"
+    android:versionName="1.4.5" xmlns:android="http://schemas.android.com/apk/res/android">
 
     <uses-permission android:name="android.permission.GET_ACCOUNTS" />
     <uses-permission android:name="android.permission.USE_CREDENTIALS" />

+ 2 - 2
oc_jb_workaround/AndroidManifest.xml

@@ -1,8 +1,8 @@
 <?xml version="1.0" encoding="utf-8"?>
 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
     package="com.owncloud.android.workaround.accounts"
-    android:versionCode="0100006"
-    android:versionName="1.0.6" >
+    android:versionCode="0100007"
+    android:versionName="1.0.7" >
 
     <uses-sdk
         android:minSdkVersion="16"

+ 9 - 4
res/layout-land/account_setup.xml

@@ -43,6 +43,7 @@
 		    android:layout_width="0dp"
 		    android:layout_height="match_parent"
 		    android:layout_weight="1"
+		    android:id="@+id/scroll"
 		    android:fillViewport="true"
 		    android:orientation="vertical" >
 						
@@ -50,7 +51,6 @@
 			    android:id="@+id/LinearLayout1"
 			    android:layout_width="match_parent"
 			    android:layout_height="wrap_content"
-			    android:focusable="true"
 			    android:gravity="center"
 			    android:orientation="vertical"
 			    android:padding="8dp" >
@@ -64,7 +64,14 @@
             		android:onClick="onRefreshClick"
 				    android:text="@string/auth_check_server"
 				    android:visibility="gone" />
-		
+				<TextView
+				    android:id="@+id/auth_message"
+				    android:layout_width="wrap_content"
+				    android:layout_height="wrap_content"
+				    android:layout_gravity="fill_horizontal"
+				    android:text="@string/auth_expired_basic_auth_toast" 
+				    android:visibility="gone"
+				    android:layout_marginBottom="10dp"/>
 			    <FrameLayout 
 	        		android:id="@+id/hostUrlFrame"
 					android:layout_width="match_parent"
@@ -116,7 +123,6 @@
 					android:onClick="onCheckClick"
 					android:text="@string/oauth_check_onoff"
 					android:textAppearance="?android:attr/textAppearanceSmall"
-					android:visibility="gone"
 					/>
 		
 				<EditText
@@ -129,7 +135,6 @@
 					android:singleLine="true"
 					android:inputType="textUri"
 					android:visibility="gone" >
-					<requestFocus />
 				</EditText>            
 				
 				<EditText

+ 23 - 9
res/layout/account_setup.xml

@@ -22,12 +22,13 @@
     android:layout_height="match_parent"
     android:layout_gravity="center"
     android:fillViewport="true"
-    android:orientation="vertical" >
+    android:orientation="vertical" 
+    android:id="@+id/scroll"
+    >
 
     <LinearLayout
         android:layout_width="match_parent"
         android:layout_height="wrap_content"
-        android:focusable="true"
         android:gravity="center"
         android:orientation="vertical"
         android:padding="8dp" >
@@ -49,6 +50,15 @@
             android:onClick="onRefreshClick"
             android:text="@string/auth_check_server"
             android:visibility="gone" />
+        
+        <TextView
+            android:id="@+id/auth_message"
+            android:layout_width="wrap_content"
+            android:layout_height="wrap_content"
+            android:layout_gravity="fill_horizontal"
+            android:text="@string/auth_expired_basic_auth_toast"
+            android:visibility="gone"
+            android:layout_marginBottom="10dp" />
 
 	    <FrameLayout 
 	        android:id="@+id/hostUrlFrame"
@@ -101,16 +111,17 @@
             android:onClick="onCheckClick"
             android:text="@string/oauth_check_onoff"
             android:textAppearance="?android:attr/textAppearanceSmall"
-            android:visibility="gone" />
+            />
 
         <EditText
             android:id="@+id/oAuthEntryPoint_1"
             android:layout_width="match_parent"
             android:layout_height="wrap_content"
             android:ems="10"
-            android:inputType="textUri"
-            android:singleLine="true"
+			android:enabled="false"
             android:text="@string/oauth2_url_endpoint_auth"
+            android:singleLine="true"
+            android:inputType="textUri"
             android:visibility="gone" >
         </EditText>
 
@@ -119,9 +130,10 @@
             android:layout_width="match_parent"
             android:layout_height="wrap_content"
             android:ems="10"
-            android:inputType="textUri"
-            android:singleLine="true"
+			android:enabled="false"
             android:text="@string/oauth2_url_endpoint_access"
+            android:singleLine="true"
+            android:inputType="textUri"
             android:visibility="gone" />
 
         <EditText
@@ -130,7 +142,8 @@
             android:layout_height="wrap_content"
             android:ems="10"
             android:hint="@string/auth_username"
-            android:inputType="textNoSuggestions" />
+            android:inputType="textNoSuggestions" 
+			/>
 
 		<EditText
 		    android:id="@+id/account_password"
@@ -139,7 +152,8 @@
 		    android:drawablePadding="5dp"
 		    android:ems="10"
 		    android:hint="@string/auth_password"
-		    android:inputType="textPassword" />
+		    android:inputType="textPassword" 
+            />
         
         <TextView
             android:id="@+id/auth_status_text"

+ 33 - 0
res/layout/sso_dialog.xml

@@ -0,0 +1,33 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+  ownCloud Android client application
+
+  Copyright (C) 2012-2013 ownCloud Inc.
+
+  This program is free software: you can redistribute it and/or modify
+  it under the terms of the GNU General Public License version 2,
+  as published by the Free Software Foundation.
+
+  This program is distributed in the hope that it will be useful,
+  but WITHOUT ANY WARRANTY; without even the implied warranty of
+  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+  GNU General Public License for more details.
+
+  You should have received a copy of the GNU General Public License
+  along with this program.  If not, see <http://www.gnu.org/licenses/>.
+-->
+<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
+    android:layout_width="wrap_content"
+    android:layout_height="wrap_content"
+    >
+    
+    <com.owncloud.android.ui.dialog.SsoWebView
+    	android:layout_width="wrap_content"
+    	android:layout_height="wrap_content"
+        android:id="@+id/sso_webview"
+        android:focusable="true"
+        android:focusableInTouchMode="true"
+        android:clickable="true"
+        />
+
+</RelativeLayout>

+ 1 - 1
res/values-es/strings.xml

@@ -203,7 +203,7 @@
   <string name="auth_not_found">Ruta errónea</string>
   <string name="auth_internal">Error interno en el servidor, código %1$d</string>
   <string name="auth_wtf_reenter_URL">Estado inesperado; por favor, introduzca la URL del servidor de nuevo</string>
-  <string name="auth_expired_oauth_token_toast">Su autorización ha expirado.\nPor favor, autorice de nuevo</string>
+  <string name="auth_expired_oauth_token_toast">Su autorización ha expirado. Por favor, autorice de nuevo</string>
   <string name="auth_expired_basic_auth_toast">Por favor, introduzca la contraseña actual.</string>
   <string name="crashlog_message">La aplicación finalizó inesperadamente. ¿Desea enviar un reporte de error?</string>
   <string name="crashlog_send_report">Enviar reporte</string>

+ 15 - 0
res/values-tr/strings.xml

@@ -19,6 +19,7 @@
   <string name="actionbar_mkdir">Klasör yarat</string>
   <string name="actionbar_search">Arama</string>
   <string name="actionbar_settings">Ayarlar</string>
+  <string name="actionbar_see_details">Detaylar</string>
   <string name="prefs_category_general">Genel</string>
   <string name="prefs_add_session">Yeni oturum ekle</string>
   <string name="prefs_create_img_thumbnails">Küçük resim oluştur</string>
@@ -49,6 +50,7 @@
   <string name="setup_title">ownCloud\'nıza bağlanin</string>
   <string name="setup_btn_connect">Bağlan</string>
   <string name="uploader_btn_upload_text">Yükle</string>
+  <string name="uploader_top_message">Yükleme dizinini seçiniz:</string>
   <string name="uploader_wrn_no_account_title">Hesap bulunamadi</string>
   <string name="uploader_wrn_no_account_text">Cihazınızda ownCloud hesabı bulunmamaktadır. Lütfen öncelikle bir hesap ayarı giriniz.</string>
   <string name="uploader_wrn_no_account_setup_btn_text">Kurulum</string>
@@ -76,6 +78,7 @@
   <string name="common_save_exit">Kaydet %amp; Kapat</string>
   <string name="common_exit">Çıkış</string>
   <string name="common_error">Hata</string>
+  <string name="common_loading">Yükleniyor...</string>
   <string name="common_error_unknown">Bilinmeyen hata</string>
   <string name="about_title">Hakkında</string>
   <string name="change_password">Parola değiştir</string>
@@ -97,6 +100,7 @@
   <string name="downloader_download_succeeded_content">%1$s başarıyla indirildi</string>
   <string name="downloader_download_failed_ticker">İndirilme başarısız</string>
   <string name="downloader_download_failed_content">%1$s indirilmesi tamamlanamadı</string>
+  <string name="downloader_not_downloaded_yet">Henüz indirilemedi</string>
   <string name="common_choose_account">Hesap seçiniz</string>
   <string name="sync_string_contacts">Kontaklar</string>
   <string name="sync_fail_ticker">Eşitleme başarısız</string>
@@ -125,6 +129,17 @@
   <string name="pincode_wrong">Yanlış ownCloud App PIN</string>
   <string name="pincode_removed">ownCloud App PIN kaldırıldı</string>
   <string name="pincode_stored">ownCloud App PIN saklandı</string>
+  <string name="media_notif_ticker">%1$s müzik çalar</string>
+  <string name="media_state_playing">%1$s (oynatılıyor)</string>
+  <string name="media_state_loading">%1$s (yükleniyor)</string>
+  <string name="media_event_done">%1$s yeniden oynatım sonlandırıldı</string>
+  <string name="media_err_nothing_to_play">Herhangi bir medya öğesi bulunamadı</string>
+  <string name="media_err_not_in_owncloud">Dosya doğru bir hesapta değil</string>
+  <string name="media_err_unsupported">Codec desteklenmiyor</string>
+  <string name="media_err_io">Medya öğesi okunamadı</string>
+  <string name="media_err_malformed">Medya öğesi doğru bir şekilde kodlanmadı</string>
+  <string name="media_err_timeout">Oynatmak için fazla deneme yapıldı</string>
+  <string name="media_err_invalid_progressive_playback">Medya öğesi aktarılamadı</string>
   <string-array name="prefs_trackmydevice_intervall_keys">
     <item>15 Dakika</item>
     <item>30 Dakika</item>

+ 11 - 0
res/values-zh-rCN/strings.xml

@@ -13,9 +13,12 @@
   <string name="main_settings">设置</string>
   <string name="main_tit_accsetup">设置账号</string>
   <string name="main_wrn_accsetup">设备上无 ownCloud 账号,要使用此 App,需要先创建一个账号。</string>
+  <string name="about_version">版本:%1</string>
+  <string name="actionbar_sync">刷新帐户</string>
   <string name="actionbar_upload">上传</string>
   <string name="actionbar_upload_from_apps">来自其它app的内容</string>
   <string name="actionbar_upload_files">文件</string>
+  <string name="actionbar_open_with">打开</string>
   <string name="actionbar_mkdir">创建目录</string>
   <string name="actionbar_search">搜索</string>
   <string name="actionbar_settings">设置</string>
@@ -36,6 +39,10 @@
   <string name="prefs_pincode_summary">保护您的owncloud客户端</string>
   <string name="prefs_instant_upload">开启即时上传</string>
   <string name="prefs_instant_upload_summary">即时上传相机拍摄的照片</string>
+  <string name="prefs_log_title">开启日志</string>
+  <string name="prefs_log_title_history">日志历史</string>
+  <string name="prefs_log_delete_history_button">删除历史</string>
+  <string name="auth_check_server">检查服务器</string>
   <string name="auth_host_url">服务器地址</string>
   <string name="auth_username">用户名</string>
   <string name="auth_password">密码</string>
@@ -105,12 +112,14 @@
   <string name="sync_string_contacts">联系人</string>
   <string name="sync_fail_ticker">同步失败</string>
   <string name="sync_fail_content"> %1$s同步未完成。</string>
+  <string name="sync_fail_content_unauthorized">密码错误%1$s</string>
   <string name="sync_conflicts_in_favourites_ticker">发现冲突</string>
   <string name="sync_conflicts_in_favourites_content">%1$d 文件无法同步</string>
   <string name="sync_fail_in_favourites_ticker">文件同步失败</string>
   <string name="sync_fail_in_favourites_content">无法同步 %1$d 文件内容(与 %2$d 冲突)</string>
   <string name="sync_foreign_files_forgotten_ticker">某些本地文件已被遗忘</string>
   <string name="sync_foreign_files_forgotten_content">%2$s目录中的%1$d个文件不能被复制到</string>
+  <string name="sync_foreign_files_forgotten_explanation">\"从 1.3.16 版起,从此设备上传的文件将被复制到本地的 %1$s 文件夹来防止当某个单一文件在多个账户间同步造成的数据损失。由于此项变化,此应用之前的版本上传的全部文件都已被复制到了 %2$s 文件夹。然而,账户同步期间有一个错误阻止了此操作的完成。您或许可以保持文件不动,并移除指向 %3$s 的链接,或将文件移动到 %1$s 文件夹中并将保持到 %4$s 的链接。下面列出的是本地文件,以及它们被链接到的 %5$s 中的远程文件。</string>
   <string name="foreign_files_move">移动所有</string>
   <string name="foreign_files_success">所有文件已被移动</string>
   <string name="foreign_files_fail">某些文件无法被移动</string>
@@ -183,8 +192,10 @@
   <string name="auth_bad_oc_version_title">不可辨识的owncloud服务器版本</string>
   <string name="auth_wrong_connection_title">无法建立连接</string>
   <string name="auth_secure_connection">加密连接已建立</string>
+  <string name="auth_unauthorized">用户名或密码错误!</string>
   <string name="auth_not_found">错误的路径</string>
   <string name="auth_internal">内部服务器错误,代码 %1$d</string>
+  <string name="auth_expired_basic_auth_toast">请输入当前密码:</string>
   <string name="crashlog_message">应用崩溃,是否提交崩溃报告?</string>
   <string name="crashlog_send_report">发送报告</string>
   <string name="crashlog_dont_send_report">不发送报告</string>

+ 133 - 10
res/values-zh-rTW/strings.xml

@@ -13,12 +13,17 @@
   <string name="main_settings">設定</string>
   <string name="main_tit_accsetup">設定帳號</string>
   <string name="main_wrn_accsetup">您尚未在裝置上設定您的 ownCloud 帳號,您必需建立一組帳號才能繼續使用。</string>
+  <string name="about_android">%1$s Android 應用程式</string>
+  <string name="about_version">版本 %1$s</string>
+  <string name="actionbar_sync">更新檔案列表</string>
   <string name="actionbar_upload">上傳檔案</string>
   <string name="actionbar_upload_from_apps">其他應用程序的內容</string>
   <string name="actionbar_upload_files">檔案</string>
+  <string name="actionbar_open_with">開啟方式</string>
   <string name="actionbar_mkdir">建立目錄</string>
   <string name="actionbar_search">搜尋</string>
   <string name="actionbar_settings">設定</string>
+  <string name="actionbar_see_details">詳細資料</string>
   <string name="prefs_category_general">一般</string>
   <string name="prefs_add_session">增加新連線</string>
   <string name="prefs_create_img_thumbnails">建立圖片縮圖</string>
@@ -31,11 +36,20 @@
   <string name="prefs_trackmydevice_interval_summary">每 %1$s 分鐘更新</string>
   <string name="prefs_accounts">帳號</string>
   <string name="prefs_manage_accounts">管理帳號</string>
+  <string name="prefs_pincode">App 密碼</string>
   <string name="prefs_pincode_summary">保護您的ownCloud用戶端</string>
   <string name="prefs_instant_upload">啟用即時上傳</string>
+  <string name="prefs_instant_upload_summary">即時上傳照相機拍攝的圖片</string>
+  <string name="prefs_log_title">啟用記錄</string>
+  <string name="prefs_log_summary">這個用來記錄執行的動作以找出問題點</string>
+  <string name="prefs_log_title_history">歷史記錄</string>
+  <string name="prefs_log_summary_history">顯示之前的記錄檔</string>
+  <string name="prefs_log_delete_history_button">刪除歷史記錄</string>
+  <string name="auth_check_server">檢查伺服器</string>
   <string name="auth_host_url">伺服器位址</string>
   <string name="auth_username">使用者名稱</string>
   <string name="auth_password">密碼</string>
+  <string name="auth_register">新增到 %1$s?</string>
   <string name="new_session_uri_error">錯誤的位址</string>
   <string name="new_session_session_name_error">錯誤的連線名稱</string>
   <string name="sync_string_files">檔案</string>
@@ -47,21 +61,26 @@
   <string name="setup_title">連線至您的 %1$s</string>
   <string name="setup_btn_connect">連線</string>
   <string name="uploader_btn_upload_text">上傳</string>
+  <string name="uploader_top_message">選取上傳目錄:</string>
   <string name="uploader_wrn_no_account_title">找不到帳號</string>
   <string name="uploader_wrn_no_account_text">在您的裝置上找不到ownCloud的帳號. 請先設定一組帳號.</string>
   <string name="uploader_wrn_no_account_setup_btn_text">設定</string>
   <string name="uploader_wrn_no_account_quit_btn_text">離開</string>
   <string name="uploader_wrn_no_content_title">沒有上載的內容</string>
   <string name="uploader_wrn_no_content_text">沒接到任何內容。沒有什麼可上載。</string>
+  <string name="uploader_error_forbidden_content">%1$s 並沒有被允許存取分享的內容</string>
   <string name="uploader_info_uploading">上傳中</string>
   <string name="uploader_btn_create_dir_text">建立上傳目錄</string>
+  <string name="file_list_empty">這個目錄目前是空的</string>
   <string name="filedetails_select_file">在檔案上輕觸來顯示更多資訊。</string>
   <string name="filedetails_size">容量:</string>
   <string name="filedetails_type">類型:</string>
   <string name="filedetails_created">建立:</string>
   <string name="filedetails_modified">修改:</string>
   <string name="filedetails_download">下載</string>
+  <string name="filedetails_sync_file">更新檔案列表</string>
   <string name="filedetails_redownload">重新下載</string>
+  <string name="filedetails_renamed_in_upload_msg">檔案名稱在上傳時已被更改為 %1$s</string>
   <string name="common_yes">是</string>
   <string name="common_no">否</string>
   <string name="common_ok">好</string>
@@ -71,6 +90,7 @@
   <string name="common_save_exit">儲存並離開</string>
   <string name="common_exit">離開ownCloud</string>
   <string name="common_error">錯誤</string>
+  <string name="common_loading">載入 …</string>
   <string name="common_error_unknown">未知的錯誤</string>
   <string name="about_title">關於</string>
   <string name="change_password">變更密碼</string>
@@ -79,31 +99,71 @@
   <string name="upload_chooser_title">更新自 ...</string>
   <string name="uploader_info_dirname">目錄名稱</string>
   <string name="uploader_upload_in_progress_ticker">更新中 ...</string>
+  <string name="uploader_upload_in_progress_content">%1$d%% 上傳中 %2$s</string>
   <string name="uploader_upload_succeeded_ticker">更新成功</string>
   <string name="uploader_upload_succeeded_content_single">%1$s 已成功地上傳</string>
   <string name="uploader_upload_succeeded_content_multiple">%1$d 檔案已成功地上傳</string>
   <string name="uploader_upload_failed_ticker">上傳失敗</string>
+  <string name="uploader_upload_failed_content_single">上傳 %1$s 未完成</string>
+  <string name="uploader_upload_failed_content_multiple">上傳失敗: %1$d/%2$d 檔案已上傳</string>
   <string name="downloader_download_in_progress_ticker">下載中 ...</string>
+  <string name="downloader_download_in_progress_content">%1$d%% 下載中 %2$s</string>
   <string name="downloader_download_succeeded_ticker">下載成功</string>
+  <string name="downloader_download_succeeded_content">%1$s 已成功下載</string>
   <string name="downloader_download_failed_ticker">下載失敗</string>
+  <string name="downloader_download_failed_content">下載 %1$s 未完成</string>
+  <string name="downloader_not_downloaded_yet">尚未下載</string>
   <string name="common_choose_account">選擇帳號</string>
   <string name="sync_string_contacts">通訊錄</string>
   <string name="sync_fail_ticker">同步失敗</string>
+  <string name="sync_fail_content">同步 %1$s 未完成</string>
+  <string name="sync_fail_content_unauthorized">無效的密碼 %1$s</string>
   <string name="sync_conflicts_in_favourites_ticker">出現衝突</string>
+  <string name="sync_conflicts_in_favourites_content">%1$d 持續同步未被同步的檔案</string>
+  <string name="sync_fail_in_favourites_ticker">同步檔案失敗</string>
+  <string name="sync_fail_in_favourites_content">%1$d 未被同步 (%2$d 衝突)</string>
+  <string name="sync_foreign_files_forgotten_ticker">有些本地端的檔案已遺失</string>
+  <string name="sync_foreign_files_forgotten_content">%1$d 檔案於 %2$s 目錄未被複製</string>
+  <string name="sync_foreign_files_forgotten_explanation">在 1.3.16 之前, 檔案上傳到本地的 %1$s 目錄以避免在多帳戶內同步造成遺失.\n\n由於這個改變, 所以在之前版本上傳的檔案被複製到 %2$s 目錄中. 為了避免同步發生問題. 你可以保留那些檔案並刪除連結 %3$s, 或搬移檔案到 %1$s 目錄並取得連結到 %4$s.\n\n下面列表是本地檔案, 與被連結遠端檔案 %5$s.</string>
   <string name="foreign_files_move">移動全部</string>
   <string name="foreign_files_success">所有文件已被移動</string>
-  <string name="foreign_files_fail">一些文件無法移動</string>
+  <string name="foreign_files_fail">部份文件無法被移動</string>
+  <string name="foreign_files_local_text">本地: %1$s</string>
+  <string name="foreign_files_remote_text">遠端: %1$s</string>
+  <string name="upload_query_move_foreign_files">無足夠的空間可以複製檔案到 %1$s 目錄. 是否使用移動的方式來處理? </string>
   <string name="use_ssl">使用安全連線</string>
   <string name="location_no_provider">%1$s 無法追蹤您的裝置,請檢查定位服務設定</string>
-  <string name="pincode_enter_pin_code">請輸入您的 App PIN</string>
-  <string name="pincode_enter_new_pin_code">請輸入您的新 App PIN</string>
-  <string name="pincode_configure_your_pin">輸入您的 App PIN</string>
-  <string name="pincode_reenter_your_pincode">請重新輸入您的 App PIN</string>
-  <string name="pincode_remove_your_pincode">移除您的 App PIN</string>
-  <string name="pincode_mismatch">App PIN 不相符</string>
-  <string name="pincode_wrong">App PIN 不正確</string>
-  <string name="pincode_removed">App PIN 已移除</string>
-  <string name="pincode_stored">App PIN 已儲存</string>
+  <string name="pincode_enter_pin_code">請輸入您的 App 密碼</string>
+  <string name="pincode_enter_new_pin_code">請輸入您的新 App 密碼</string>
+  <string name="pincode_configure_your_pin">輸入您的 App 密碼</string>
+  <string name="pincode_configure_your_pin_explanation">這個密碼在你每次啟動這程式時都會被要求輸入</string>
+  <string name="pincode_reenter_your_pincode">請重新輸入您的 App 密碼</string>
+  <string name="pincode_remove_your_pincode">移除您的 App 密碼</string>
+  <string name="pincode_mismatch">App 密碼不相符</string>
+  <string name="pincode_wrong">App 密碼不正確</string>
+  <string name="pincode_removed">App 密碼已移除</string>
+  <string name="pincode_stored">App 密碼已儲存</string>
+  <string name="media_notif_ticker">%1$s 音樂播放器</string>
+  <string name="media_state_playing">%1$s (播放中)</string>
+  <string name="media_state_loading">%1$s (載入中)</string>
+  <string name="media_event_done">%1$s 已播放</string>
+  <string name="media_err_nothing_to_play">沒有發現音樂媒體</string>
+  <string name="media_err_no_account">沒有提供的帳戶</string>
+  <string name="media_err_not_in_owncloud">檔案不存在於有效的帳戶中</string>
+  <string name="media_err_unsupported">未支援的媒體編碼</string>
+  <string name="media_err_io">無法讀取媒體檔案</string>
+  <string name="media_err_malformed">媒體檔案未被正確的編碼</string>
+  <string name="media_err_timeout">太多次嘗試播放</string>
+  <string name="media_err_invalid_progressive_playback">媒體檔案無法在網路播放</string>
+  <string name="media_err_unknown">媒體檔案無法在正常的播放軟體播放</string>
+  <string name="media_err_security_ex">在播放 %1$s 時發生安全性的錯誤</string>
+  <string name="media_err_io_ex">在播放 %1$s 時發生輸入錯誤</string>
+  <string name="media_err_unexpected">在播放 %1$s 時發生未知的錯誤</string>
+  <string name="media_previous_description">回到上一首按鍵</string>
+  <string name="media_rewind_description">重新播放按鍵</string>
+  <string name="media_play_pause_description">播放或暫停按鍵</string>
+  <string name="media_forward_description">快轉按鍵</string>
+  <string name="media_next_description">下一首按鍵</string>
   <string-array name="prefs_trackmydevice_intervall_keys">
     <item>15 分鐘</item>
     <item>30 分鐘</item>
@@ -114,17 +174,20 @@
     <item>30</item>
     <item>60</item>
   </string-array>
+  <string name="auth_trying_to_login">嘗試登入…</string>
   <string name="auth_no_net_conn_title">沒有網際網路連線</string>
   <string name="auth_no_net_conn_message">沒有偵測到網際網路連線,請檢查您的連線然後再試一次。</string>
   <string name="auth_connect_anyway">繼續連線</string>
   <string name="auth_nossl_plain_ok_title">安全連線不可用。</string>
   <string name="auth_nossl_plain_ok_message">無法與伺服器建立安全連線,可以使用不安全連線(未加密)以繼續,您可以繼續或取消。</string>
   <string name="auth_connection_established">連線已建立</string>
+  <string name="auth_testing_connection">測試連線中…</string>
   <string name="auth_not_configured_title">伺服器設定有問題</string>
   <string name="auth_not_configured_message">看起來您的伺服器並未被正確設定,請聯絡服務管理者以取得協助。</string>
   <string name="auth_unknown_error_title">發生未知的錯誤!</string>
   <string name="auth_unknown_error_message">發生未知的錯誤,請聯絡支援服務並附上您的記錄檔。</string>
   <string name="auth_unknown_host_title">找不到伺服器</string>
+  <string name="auth_unknown_host_message">無法找到伺服器. 請檢查是否正確輸入並再試一次.</string>
   <string name="auth_incorrect_path_title">找不到伺服器</string>
   <string name="auth_incorrect_path_message">在指定的路徑找不到伺服器,請檢查您的路徑然後再試一次。</string>
   <string name="auth_timeout_title">伺服器回應逾時</string>
@@ -134,36 +197,96 @@
   <string name="auth_bad_oc_version_title">無法辨識的ownCloud伺服器版本</string>
   <string name="auth_wrong_connection_title">無法建立連線</string>
   <string name="auth_secure_connection">安全連線已建立</string>
+  <string name="auth_unauthorized">錯誤的使用者或密碼</string>
+  <string name="auth_oauth_error">未成功登入</string>
+  <string name="auth_oauth_error_access_denied">被授登伺服器拒絕登入</string>
+  <string name="auth_not_found"> 錯誤的路徑</string>
+  <string name="auth_internal">內部錯誤, 代碼 %1$d</string>
+  <string name="auth_wtf_reenter_URL">未知的狀態; 請再輸入一次伺服器的名稱</string>
+  <string name="auth_expired_oauth_token_toast">你的登入授權已過期.\n請再次登入</string>
+  <string name="auth_expired_basic_auth_toast">請輸入目錄的密碼</string>
+  <string name="crashlog_message">程式未預期的錯誤. 你要寄送錯誤的分析報告嗎?</string>
   <string name="crashlog_send_report">發送報告</string>
   <string name="crashlog_dont_send_report">不要發送報告</string>
+  <string name="extensions_avail_title">延伸功能可以使用!</string>
+  <string name="extensions_avail_message">你的伺服器支援某些延伸功能. 你是否要使用他們?</string>
   <string name="fd_keep_in_sync">讓檔案保持最新的</string>
   <string name="common_share">分享</string>
   <string name="common_rename">重新命名</string>
   <string name="common_remove">移除</string>
   <string name="confirmation_remove_alert">您真的要移除 %1$s ?</string>
+  <string name="confirmation_remove_folder_alert">您真的要移除 %1$s 與裡頭的檔案?</string>
   <string name="confirmation_remove_local">只有本地</string>
+  <string name="confirmation_remove_folder_local">只有本地</string>
   <string name="confirmation_remove_remote">從伺服器移除</string>
+  <string name="confirmation_remove_remote_and_local">遠端與本地</string>
   <string name="remove_success_msg">成功地移除</string>
+  <string name="remove_fail_msg">刪除失敗</string>
   <string name="rename_dialog_title">輸入新名稱</string>
   <string name="rename_local_fail_msg">本地的複本無法被重新命名; 請嘗試一個不同的新名稱</string>
   <string name="rename_server_fail_msg">重新命名失敗</string>
+  <string name="sync_file_fail_msg">無法檢查遠端的檔案</string>
+  <string name="sync_file_nothing_to_do_msg">檔案與同步</string>
   <string name="create_dir_fail_msg">資料夾無法被建立</string>
   <string name="wait_a_moment">請稍後</string>
+  <string name="filedisplay_unexpected_bad_get_content">未知的問題; 請選擇其他程式開啟檔案</string>
   <string name="filedisplay_no_file_selected">沒有挑選檔案</string>
+  <string name="oauth_host_url">oAuth2 網址</string>
+  <string name="oauth_check_onoff">以 oAuth2 方式登入.</string>
+  <string name="oauth_login_connection">連線到 oAuth2 伺服器…</string>
+  <string name="oauth_code_validation_message">請打開瀏覽器連到:\n%1$s.\n檢查碼為:\n%2$s</string>
+  <string name="oauth_connection_url_unavailable">無法連線到該網址.</string>
   <string name="ssl_validator_title">警告</string>
+  <string name="ssl_validator_header">這個網站的憑證無法被驗證</string>
+  <string name="ssl_validator_reason_cert_not_trusted">- 這個伺服器使用未被信任的憑證</string>
+  <string name="ssl_validator_reason_cert_expired">- 這個伺服器的憑證已過期</string>
+  <string name="ssl_validator_reason_cert_not_yet_valid">- 這個伺服器的憑證有效期限不正確</string>
+  <string name="ssl_validator_reason_hostname_not_verified">- 這個伺服器的憑證與使用的伺服器名稱不一樣</string>
+  <string name="ssl_validator_certificate_not_available">無法取得伺服器的憑證</string>
+  <string name="ssl_validator_question">你是否要信任這個伺服器的憑證?</string>
+  <string name="ssl_validator_not_saved">無法儲存憑證</string>
   <string name="ssl_validator_btn_details_see">細節</string>
   <string name="ssl_validator_btn_details_hide">隱藏</string>
+  <string name="ssl_validator_label_subject">發行給:</string>
+  <string name="ssl_validator_label_issuer">發行者:</string>
+  <string name="ssl_validator_label_CN">網站:</string>
   <string name="ssl_validator_label_O">組織:</string>
   <string name="ssl_validator_label_OU">組織部門:</string>
   <string name="ssl_validator_label_C">國家:</string>
   <string name="ssl_validator_label_ST">省:</string>
   <string name="ssl_validator_label_L">地點:</string>
+  <string name="ssl_validator_label_validity">有效期限:</string>
   <string name="ssl_validator_label_validity_from">從:</string>
   <string name="ssl_validator_label_validity_to">至:</string>
   <string name="ssl_validator_label_signature">簽名:</string>
+  <string name="ssl_validator_label_signature_algorithm">演算法:</string>
+  <string name="placeholder_sentence">這是佔位的資訊</string>
+  <string name="placeholder_filename">placeholder.txt</string>
+  <string name="placeholder_filetype">PNG 圖檔</string>
+  <string name="placeholder_filesize">389 KB</string>
+  <string name="placeholder_timestamp">2012/05/18 12:23 PM</string>
+  <string name="placeholder_media_time">12:23:45</string>
+  <string name="instant_upload_on_wifi">只使用 WiFi 上傳</string>
+  <string name="instant_upload_path">/InstantUpload</string>
   <string name="conflict_title">更新衝突</string>
+  <string name="conflict_message">遠端檔案 %s 未同步到本地. 繼續將取代伺服器上的文件.</string>
   <string name="conflict_keep_both">都保留</string>
   <string name="conflict_overwrite">覆寫</string>
   <string name="conflict_dont_upload">不要上載</string>
+  <string name="preview_image_description">圖片預覽</string>
+  <string name="preview_image_error_unknown_format">無法顯示圖片</string>
+  <string name="preview_image_error_out_of_memory">\"沒有足夠的記憶體來顯示圖片</string>
   <!--we need to improve the communication of errors to the user-->
+  <string name="error__upload__local_file_not_copied">%1$s 無法被複製到本地目錄 %2$s</string>
+  <string name="actionbar_failed_instant_upload">即時上傳失敗</string>
+  <string name="failed_upload_headline_text">即時上傳失敗</string>
+  <string name="failed_upload_headline_hint">所有即時上傳失敗的記錄</string>
+  <string name="failed_upload_all_cb">全部選取</string>
+  <string name="failed_upload_headline_retryall_btn">重新上傳選取的檔案</string>
+  <string name="failed_upload_headline_delete_all_btn">刪除所有被選取的檔案</string>
+  <string name="failed_upload_retry_text">重新上傳這個檔案: </string>
+  <string name="failed_upload_load_more_images">載入更多的檔案</string>
+  <string name="failed_upload_retry_do_nothing_text">未連線, 所以無法使用上傳功能</string>
+  <string name="failed_upload_failure_text">失敗訊息: </string>
+  <string name="failed_upload_quota_exceeded_text">請檢查你的伺服器設定, 可能你的額度已超過.</string>
 </resources>

+ 0 - 5
res/values/branding.xml

@@ -1,5 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<resources>
-    <string name="server_url"></string>
-    <bool name="show_server_url_input">true</bool>
-</resources>

+ 0 - 5
res/values/oauth2_configuration.xml

@@ -1,10 +1,5 @@
 <?xml version="1.0" encoding="utf-8"?>
 <resources>
-    <!-- Flag to configure OAuth availability in the app.
-    	 3 valid values now: on, off, optional	
-     -->
-    <string name="oauth2_mode">off</string>
-    
     <!-- constants that must be respected by the authorization server; if changed, the app must be rebuild -->
     <string name="oauth2_redirect_scheme">owncloud</string>
     <string name="oauth2_redirect_uri">owncloud://callback</string>

+ 10 - 0
res/values/setup.xml

@@ -0,0 +1,10 @@
+<?xml version="1.0" encoding="utf-8"?>
+<resources>
+    <string name="server_url"></string>
+    <bool name="show_server_url_input">true</bool>
+    
+    <!-- Flags to setup the authentication methods available in the app -->
+    <string name="auth_method_oauth2">off</string>
+    <string name="auth_method_saml_web_sso">off</string>
+    
+</resources>

+ 8 - 1
res/values/strings.xml

@@ -49,6 +49,7 @@
     <string name="prefs_log_delete_history_button">Delete History</string>
     
     <string name="auth_check_server">Check Server</string>
+    <string name="auth_account_name">Account name</string>
     <string name="auth_host_url">Server address</string>
     <string name="auth_username">Username</string>
     <string name="auth_password">Password</string>
@@ -189,6 +190,8 @@
     <string name="auth_testing_connection">Testing connection&#8230;</string>
     <string name="auth_not_configured_title">Malformed server configuration</string>
     <string name="auth_not_configured_message">It seems that your server instance is not correctly configured. Contact your administrator for more details.</string>
+    <string name="auth_account_not_new">An account for the same user and server already exists in the device</string>
+    <string name="auth_account_not_the_same">The entered user does not match the user of this account</string>
     <string name="auth_unknown_error_title">Unknown error occurred!</string>
     <string name="auth_unknown_error_message">An unknown error occurred. Please contact support and include logs from your device.</string>
     <string name="auth_unknown_host_title">Couldn\'t find host</string>
@@ -208,8 +211,12 @@
     <string name="auth_not_found">Wrong path given</string>
     <string name="auth_internal">Internal server error, code %1$d</string>
     <string name="auth_wtf_reenter_URL">Unexpected state; please, enter the server URL again</string>
-    <string name="auth_expired_oauth_token_toast">Your authorization expired.\nPlease, authorize again</string>
+    <string name="auth_expired_oauth_token_toast">Your authorization expired. Please, authorize again</string>
     <string name="auth_expired_basic_auth_toast">Please, enter the current password</string>
+    <string name="auth_expired_saml_sso_token_toast">Your session expired. Please connect again</string>
+	<string name="auth_connecting_auth_server">Connecting to authentication server…</string>
+	<string name="auth_follow_auth_server">Follow instructions above to get authenticated</string>
+	<string name="auth_unsupported_auth_method">The server does not support this authentication method</string>    
     
     <string name="crashlog_message">Application terminated unexpectedly. Would you like to submit a crash report?</string>
     <string name="crashlog_send_report">Send report</string>

+ 7 - 1
res/values/styles.xml

@@ -20,7 +20,7 @@
 <resources xmlns:android="http://schemas.android.com/apk/res/android">
 	<style name="Animations" />
 
-	<!-- Default ownCloud app style -->
+	<!-- General ownCloud app style -->
 	<style name="Theme.ownCloud" parent="style/Theme.Sherlock.Light.DarkActionBar">
     	<item name="android:actionBarStyle">@style/Theme.ownCloud.Widget.ActionBar</item>
     	<item name="actionBarStyle">@style/Theme.ownCloud.Widget.ActionBar</item>
@@ -47,6 +47,12 @@
     	<item name="android:shadowDy">1</item>
     	<item name="android:backgroundSplit">@drawable/split_action_bg</item>
 	</style>
+
+		
+	<!-- Dialogs -->
+	<style name="Theme.ownCloud.Dialog" parent="style/Theme.Sherlock.Light.Dialog">
+	</style>
+	
 	
 	<!-- PopDownMenu -->
 	<style name="Animations.PopDownMenu" />

+ 7 - 1
src/com/owncloud/android/authentication/AccountAuthenticator.java

@@ -46,6 +46,7 @@ public class AccountAuthenticator extends AbstractAccountAuthenticator {
     public static final String AUTH_TOKEN_TYPE_PASSWORD = "owncloud.password";
     public static final String AUTH_TOKEN_TYPE_ACCESS_TOKEN = "owncloud.oauth2.access_token";
     public static final String AUTH_TOKEN_TYPE_REFRESH_TOKEN = "owncloud.oauth2.refresh_token";
+    public static final String AUTH_TOKEN_TYPE_SAML_WEB_SSO_SESSION_COOKIE = "owncloud.saml.web_sso.session_cookie";
 
     public static final String KEY_AUTH_TOKEN_TYPE = "authTokenType";
     public static final String KEY_REQUIRED_FEATURES = "requiredFeatures";
@@ -75,6 +76,10 @@ public class AccountAuthenticator extends AbstractAccountAuthenticator {
      * Flag signaling if the ownCloud server can be accessed with OAuth2 access tokens.
      */
     public static final String KEY_SUPPORTS_OAUTH2 = "oc_supports_oauth2";
+    /**
+     * Flag signaling if the ownCloud server can be accessed with session cookies from SAML-based web single-sign-on.
+     */
+    public static final String KEY_SUPPORTS_SAML_WEB_SSO = "oc_supports_saml_web_sso";
     
     private static final String TAG = AccountAuthenticator.class.getSimpleName();
     
@@ -254,7 +259,8 @@ public class AccountAuthenticator extends AbstractAccountAuthenticator {
         if (!authTokenType.equals(AUTH_TOKEN_TYPE) &&
             !authTokenType.equals(AUTH_TOKEN_TYPE_PASSWORD) &&
             !authTokenType.equals(AUTH_TOKEN_TYPE_ACCESS_TOKEN) &&
-            !authTokenType.equals(AUTH_TOKEN_TYPE_REFRESH_TOKEN) ) {
+            !authTokenType.equals(AUTH_TOKEN_TYPE_REFRESH_TOKEN) &&
+            !authTokenType.equals(AUTH_TOKEN_TYPE_SAML_WEB_SSO_SESSION_COOKIE)) {
             throw new UnsupportedAuthTokenTypeException();
         }
     }

+ 85 - 0
src/com/owncloud/android/authentication/AccountAuthenticatorActivity.java

@@ -0,0 +1,85 @@
+/*
+ * Copyright (C) 2009 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.owncloud.android.authentication;
+
+import android.accounts.AccountAuthenticatorResponse;
+import android.accounts.AccountManager;
+import android.os.Bundle;
+
+import com.actionbarsherlock.app.SherlockFragmentActivity;
+
+
+/*
+ * Base class for implementing an Activity that is used to help implement an AbstractAccountAuthenticator. 
+ * If the AbstractAccountAuthenticator needs to use an activity to handle the request then it can have the activity extend 
+ * AccountAuthenticatorActivity. The AbstractAccountAuthenticator passes in the response to the intent using the following:
+ * intent.putExtra(AccountManager.KEY_ACCOUNT_AUTHENTICATOR_RESPONSE, response);
+ * 
+ * The activity then sets the result that is to be handed to the response via setAccountAuthenticatorResult(android.os.Bundle). 
+ * This result will be sent as the result of the request when the activity finishes. If this is never set or if it is set to null 
+ * then error AccountManager.ERROR_CODE_CANCELED will be called on the response.
+ */
+
+public class AccountAuthenticatorActivity extends SherlockFragmentActivity {
+
+    private AccountAuthenticatorResponse mAccountAuthenticatorResponse = null;
+    private Bundle mResultBundle = null;
+
+
+    /**
+     * Set the result that is to be sent as the result of the request that caused this Activity to be launched.
+     * If result is null or this method is never called then the request will be canceled.
+     * 
+     * @param result this is returned as the result of the AbstractAccountAuthenticator request
+     */
+    public final void setAccountAuthenticatorResult(Bundle result) {
+        mResultBundle = result;
+    }
+
+    /**
+     * Retreives the AccountAuthenticatorResponse from either the intent of the icicle, if the
+     * icicle is non-zero.
+     * @param icicle the save instance data of this Activity, may be null
+     */
+    protected void onCreate(Bundle icicle) {
+        super.onCreate(icicle);
+
+        mAccountAuthenticatorResponse =
+                getIntent().getParcelableExtra(AccountManager.KEY_ACCOUNT_AUTHENTICATOR_RESPONSE);
+
+        if (mAccountAuthenticatorResponse != null) {
+            mAccountAuthenticatorResponse.onRequestContinued();
+        }
+    }
+    
+    /**
+     * Sends the result or a Constants.ERROR_CODE_CANCELED error if a result isn't present.
+     */
+    public void finish() {
+        if (mAccountAuthenticatorResponse != null) {
+            // send the result bundle back if set, otherwise send an error.
+            if (mResultBundle != null) {
+                mAccountAuthenticatorResponse.onResult(mResultBundle);
+            } else {
+                mAccountAuthenticatorResponse.onError(AccountManager.ERROR_CODE_CANCELED,
+                        "canceled");
+            }
+            mAccountAuthenticatorResponse = null;
+        }
+        super.finish();
+    }
+}

+ 48 - 2
src/com/owncloud/android/authentication/AccountUtils.java

@@ -32,6 +32,7 @@ public class AccountUtils {
     public static final String WEBDAV_PATH_2_0 = "/files/webdav.php";
     public static final String WEBDAV_PATH_4_0 = "/remote.php/webdav";
     private static final String ODAV_PATH = "/remote.php/odav";
+    private static final String SAML_SSO_PATH = "/remote.php/webdav";
     public static final String CARDDAV_PATH_2_0 = "/apps/contacts/carddav.php";
     public static final String CARDDAV_PATH_4_0 = "/remote/carddav.php";
     public static final String STATUS_PATH = "/status.php";
@@ -74,6 +75,20 @@ public class AccountUtils {
     }
 
     
+    public static boolean exists(Account account, Context context) {
+        Account[] ocAccounts = AccountManager.get(context).getAccountsByType(
+                AccountAuthenticator.ACCOUNT_TYPE);
+
+        if (account != null && account.name != null) {
+            for (Account ac : ocAccounts) {
+                if (ac.name.equals(account.name)) {
+                    return true;
+                }
+            }
+        }
+        return false;
+    }
+    
 
     /**
      * Checks, whether or not there are any ownCloud accounts setup.
@@ -115,11 +130,41 @@ public class AccountUtils {
      * @param version version of owncloud
      * @return webdav path for given OC version, null if OC version unknown
      */
-    public static String getWebdavPath(OwnCloudVersion version, boolean supportsOAuth) {
+    public static String getWebdavPath(OwnCloudVersion version, boolean supportsOAuth, boolean supportsSamlSso) {
         if (version != null) {
             if (supportsOAuth) {
                 return ODAV_PATH;
             }
+            if (supportsSamlSso) {
+                return SAML_SSO_PATH;
+            }
+            if (version.compareTo(OwnCloudVersion.owncloud_v4) >= 0)
+                return WEBDAV_PATH_4_0;
+            if (version.compareTo(OwnCloudVersion.owncloud_v3) >= 0
+                    || version.compareTo(OwnCloudVersion.owncloud_v2) >= 0)
+                return WEBDAV_PATH_2_0;
+            if (version.compareTo(OwnCloudVersion.owncloud_v1) >= 0)
+                return WEBDAV_PATH_1_2;
+        }
+        return null;
+    }
+    
+    /**
+     * Returns the proper URL path to access the WebDAV interface of an ownCloud server,
+     * according to its version and the authorization method used.
+     * 
+     * @param   version         Version of ownCloud server.
+     * @param   authTokenType   Authorization token type, matching some of the AUTH_TOKEN_TYPE_* constants in {@link AccountAuthenticator}. 
+     * @return                  WebDAV path for given OC version and authorization method, null if OC version is unknown.
+     */
+    public static String getWebdavPath(OwnCloudVersion version, String authTokenType) {
+        if (version != null) {
+            if (AccountAuthenticator.AUTH_TOKEN_TYPE_ACCESS_TOKEN.equals(authTokenType)) {
+                return ODAV_PATH;
+            }
+            if (AccountAuthenticator.AUTH_TOKEN_TYPE_SAML_WEB_SSO_SESSION_COOKIE.equals(authTokenType)) {
+                return SAML_SSO_PATH;
+            }
             if (version.compareTo(OwnCloudVersion.owncloud_v4) >= 0)
                 return WEBDAV_PATH_4_0;
             if (version.compareTo(OwnCloudVersion.owncloud_v3) >= 0
@@ -143,8 +188,9 @@ public class AccountUtils {
         String baseurl = ama.getUserData(account, AccountAuthenticator.KEY_OC_BASE_URL);
         String strver  = ama.getUserData(account, AccountAuthenticator.KEY_OC_VERSION);
         boolean supportsOAuth = (ama.getUserData(account, AccountAuthenticator.KEY_SUPPORTS_OAUTH2) != null);
+        boolean supportsSamlSso = (ama.getUserData(account, AccountAuthenticator.KEY_SUPPORTS_SAML_WEB_SSO) != null);
         OwnCloudVersion ver = new OwnCloudVersion(strver);
-        String webdavpath = getWebdavPath(ver, supportsOAuth);
+        String webdavpath = getWebdavPath(ver, supportsOAuth, supportsSamlSso);
 
         if (baseurl == null || webdavpath == null) 
             throw new AccountNotFoundException(account, "Account not found", null);

+ 435 - 126
src/com/owncloud/android/authentication/AuthenticatorActivity.java

@@ -18,21 +18,7 @@
 
 package com.owncloud.android.authentication;
 
-import com.owncloud.android.Log_OC;
-import com.owncloud.android.ui.dialog.SslValidatorDialog;
-import com.owncloud.android.ui.dialog.SslValidatorDialog.OnSslValidatorListener;
-import com.owncloud.android.utils.OwnCloudVersion;
-import com.owncloud.android.network.OwnCloudClientUtils;
-import com.owncloud.android.operations.OwnCloudServerCheckOperation;
-import com.owncloud.android.operations.ExistenceCheckOperation;
-import com.owncloud.android.operations.OAuth2GetAccessToken;
-import com.owncloud.android.operations.OnRemoteOperationListener;
-import com.owncloud.android.operations.RemoteOperation;
-import com.owncloud.android.operations.RemoteOperationResult;
-import com.owncloud.android.operations.RemoteOperationResult.ResultCode;
-
 import android.accounts.Account;
-import android.accounts.AccountAuthenticatorActivity;
 import android.accounts.AccountManager;
 import android.app.AlertDialog;
 import android.app.Dialog;
@@ -47,6 +33,7 @@ import android.net.Uri;
 import android.os.Bundle;
 import android.os.Handler;
 import android.preference.PreferenceManager;
+import android.support.v4.app.Fragment;
 import android.text.Editable;
 import android.text.InputType;
 import android.text.TextWatcher;
@@ -57,14 +44,28 @@ import android.view.View.OnFocusChangeListener;
 import android.view.View.OnTouchListener;
 import android.view.Window;
 import android.view.inputmethod.EditorInfo;
+import android.widget.Button;
 import android.widget.CheckBox;
 import android.widget.EditText;
-import android.widget.Button;
 import android.widget.TextView;
-import android.widget.Toast;
 import android.widget.TextView.OnEditorActionListener;
 
+import com.actionbarsherlock.app.SherlockDialogFragment;
+import com.owncloud.android.Log_OC;
 import com.owncloud.android.R;
+import com.owncloud.android.authentication.SsoWebViewClient.SsoWebViewClientListener;
+import com.owncloud.android.network.OwnCloudClientUtils;
+import com.owncloud.android.operations.ExistenceCheckOperation;
+import com.owncloud.android.operations.OAuth2GetAccessToken;
+import com.owncloud.android.operations.OnRemoteOperationListener;
+import com.owncloud.android.operations.OwnCloudServerCheckOperation;
+import com.owncloud.android.operations.RemoteOperation;
+import com.owncloud.android.operations.RemoteOperationResult;
+import com.owncloud.android.operations.RemoteOperationResult.ResultCode;
+import com.owncloud.android.ui.dialog.SamlWebViewDialog;
+import com.owncloud.android.ui.dialog.SslValidatorDialog;
+import com.owncloud.android.ui.dialog.SslValidatorDialog.OnSslValidatorListener;
+import com.owncloud.android.utils.OwnCloudVersion;
 
 import eu.alefzero.webdav.WebdavClient;
 
@@ -75,7 +76,7 @@ import eu.alefzero.webdav.WebdavClient;
  * @author David A. Velasco
  */
 public class AuthenticatorActivity extends AccountAuthenticatorActivity
-implements  OnRemoteOperationListener, OnSslValidatorListener, OnFocusChangeListener, OnEditorActionListener {
+implements  OnRemoteOperationListener, OnSslValidatorListener, OnFocusChangeListener, OnEditorActionListener, SsoWebViewClientListener{
 
     private static final String TAG = AuthenticatorActivity.class.getSimpleName();
 
@@ -85,6 +86,8 @@ implements  OnRemoteOperationListener, OnSslValidatorListener, OnFocusChangeList
     public static final String EXTRA_ACTION = "ACTION";
     public static final String EXTRA_ENFORCED_UPDATE = "ENFORCE_UPDATE";
 
+    private static final String KEY_AUTH_MESSAGE_VISIBILITY = "AUTH_MESSAGE_VISIBILITY";
+    private static final String KEY_AUTH_MESSAGE_TEXT = "AUTH_MESSAGE_TEXT";
     private static final String KEY_HOST_URL_TEXT = "HOST_URL_TEXT";
     private static final String KEY_OC_VERSION = "OC_VERSION";
     private static final String KEY_ACCOUNT = "ACCOUNT";
@@ -98,11 +101,13 @@ implements  OnRemoteOperationListener, OnSslValidatorListener, OnFocusChangeList
     private static final String KEY_AUTH_STATUS_TEXT = "AUTH_STATUS_TEXT";
     private static final String KEY_AUTH_STATUS_ICON = "AUTH_STATUS_ICON";
     private static final String KEY_REFRESH_BUTTON_ENABLED = "KEY_REFRESH_BUTTON_ENABLED";
+    
+    private static final String KEY_OC_USERNAME_EQUALS = "oc_username=";
 
-    private static final String OAUTH_MODE_ON = "on";
-    private static final String OAUTH_MODE_OFF = "off";
-    private static final String OAUTH_MODE_OPTIONAL = "optional";
-
+    private static final String AUTH_ON = "on";
+    private static final String AUTH_OFF = "off";
+    private static final String AUTH_OPTIONAL = "optional";
+    
     private static final int DIALOG_LOGIN_PROGRESS = 0;
     private static final int DIALOG_SSL_VALIDATOR = 1;
     private static final int DIALOG_CERT_NOT_SAVED = 2;
@@ -111,12 +116,16 @@ implements  OnRemoteOperationListener, OnSslValidatorListener, OnFocusChangeList
     public static final byte ACTION_CREATE = 0;
     public static final byte ACTION_UPDATE_TOKEN = 1;
 
+    private static final String TAG_SAML_DIALOG = "samlWebViewDialog";
+    
     private String mHostBaseUrl;
     private OwnCloudVersion mDiscoveredVersion;
 
-    private int mServerStatusText, mServerStatusIcon;
+    private String mAuthMessageText;
+    private int mAuthMessageVisibility, mServerStatusText, mServerStatusIcon;
     private boolean mServerIsChecked, mServerIsValid, mIsSslConn;
     private int mAuthStatusText, mAuthStatusIcon;    
+    private TextView mAuthStatusLayout;
 
     private final Handler mHandler = new Handler();
     private Thread mOperationThread;
@@ -131,21 +140,29 @@ implements  OnRemoteOperationListener, OnSslValidatorListener, OnFocusChangeList
     private byte mAction;
     private Account mAccount;
 
+    private TextView mAuthMessage;
+    
     private EditText mHostUrlInput;
+    private boolean mHostUrlInputEnabled;
     private View mRefreshButton;
+
+    private String mAuthTokenType;
+    
     private EditText mUsernameInput;
     private EditText mPasswordInput;
+    
     private CheckBox mOAuth2Check;
-    private String mOAuthAccessToken;
-    private View mOkButton;
-    private TextView mAuthStatusLayout;
-
+    
     private TextView mOAuthAuthEndpointText;
     private TextView mOAuthTokenEndpointText;
     
-    private boolean mRefreshButtonEnabled;
+    private SamlWebViewDialog mSamlDialog;
     
-    private boolean mHostUrlInputEnabled;
+    private View mOkButton;
+    
+    private String mAuthToken;
+    
+    private boolean mResumed; // Control if activity is resumed
 
 
     /**
@@ -160,6 +177,7 @@ implements  OnRemoteOperationListener, OnSslValidatorListener, OnFocusChangeList
 
         /// set view and get references to view elements
         setContentView(R.layout.account_setup);
+        mAuthMessage = (TextView) findViewById(R.id.auth_message);
         mHostUrlInput = (EditText) findViewById(R.id.hostUrlInput);
         mHostUrlInput.setText(getString(R.string.server_url));  // valid although R.string.server_url is an empty string
         mUsernameInput = (EditText) findViewById(R.id.account_username);
@@ -199,7 +217,9 @@ implements  OnRemoteOperationListener, OnSslValidatorListener, OnFocusChangeList
         }
 
         if (savedInstanceState == null) {
+            mResumed = false;
             /// connection state and info
+            mAuthMessageVisibility = View.GONE;
             mServerStatusText = mServerStatusIcon = 0;
             mServerIsValid = false;
             mServerIsChecked = false;
@@ -207,9 +227,6 @@ implements  OnRemoteOperationListener, OnSslValidatorListener, OnFocusChangeList
             mAuthStatusText = mAuthStatusIcon = 0;
 
             /// retrieve extras from intent
-            String tokenType = getIntent().getExtras().getString(AccountAuthenticator.KEY_AUTH_TOKEN_TYPE);
-            boolean oAuthRequired = AccountAuthenticator.AUTH_TOKEN_TYPE_ACCESS_TOKEN.equals(tokenType) || OAUTH_MODE_ON.equals(getString(R.string.oauth2_mode));
-
             mAccount = getIntent().getExtras().getParcelable(EXTRA_ACCOUNT);
             if (mAccount != null) {
                 String ocVersion = mAccountMgr.getUserData(mAccount, AccountAuthenticator.KEY_OC_VERSION);
@@ -220,18 +237,19 @@ implements  OnRemoteOperationListener, OnSslValidatorListener, OnFocusChangeList
                 mHostUrlInput.setText(mHostBaseUrl);
                 String userName = mAccount.name.substring(0, mAccount.name.lastIndexOf('@'));
                 mUsernameInput.setText(userName);
-                oAuthRequired = (mAccountMgr.getUserData(mAccount, AccountAuthenticator.KEY_SUPPORTS_OAUTH2) != null);
             }
-            mOAuth2Check.setChecked(oAuthRequired);
-            changeViewByOAuth2Check(oAuthRequired);
+            initAuthorizationMethod();  // checks intent and setup.xml to determine mCurrentAuthorizationMethod
             mJustCreated = true;
             
             if (mAction == ACTION_UPDATE_TOKEN || !mHostUrlInputEnabled) {
                 checkOcServer(); 
             }
-
+            
         } else {
+            mResumed = true;
             /// connection state and info
+            mAuthMessageVisibility = savedInstanceState.getInt(KEY_AUTH_MESSAGE_VISIBILITY);
+            mAuthMessageText = savedInstanceState.getString(KEY_AUTH_MESSAGE_TEXT);
             mServerIsValid = savedInstanceState.getBoolean(KEY_SERVER_VALID);
             mServerIsChecked = savedInstanceState.getBoolean(KEY_SERVER_CHECKED);
             mServerStatusText = savedInstanceState.getInt(KEY_SERVER_STATUS_TEXT);
@@ -252,6 +270,11 @@ implements  OnRemoteOperationListener, OnSslValidatorListener, OnFocusChangeList
 
             // account data, if updating
             mAccount = savedInstanceState.getParcelable(KEY_ACCOUNT);
+            mAuthTokenType = savedInstanceState.getString(AccountAuthenticator.KEY_AUTH_TOKEN_TYPE);
+            if (mAuthTokenType == null) {
+                mAuthTokenType =  AccountAuthenticator.AUTH_TOKEN_TYPE_PASSWORD;
+                
+            }
 
             // check if server check was interrupted by a configuration change
             if (savedInstanceState.getBoolean(KEY_SERVER_CHECK_IN_PROGRESS, false)) {
@@ -264,9 +287,16 @@ implements  OnRemoteOperationListener, OnSslValidatorListener, OnFocusChangeList
 
         }
 
+        if (mAuthMessageVisibility== View.VISIBLE) {
+            showAuthMessage(mAuthMessageText);
+        }
+        else {
+            hideAuthMessage();
+        }
+        adaptViewAccordingToAuthenticationMethod();
         showServerStatus();
         showAuthStatus();
-
+        
         if (mAction == ACTION_UPDATE_TOKEN) {
             /// lock things that should not change
             mHostUrlInput.setEnabled(false);
@@ -280,14 +310,17 @@ implements  OnRemoteOperationListener, OnSslValidatorListener, OnFocusChangeList
         if (mServerIsChecked && !mServerIsValid && refreshButtonEnabled) showRefreshButton();
         mOkButton.setEnabled(mServerIsValid); // state not automatically recovered in configuration changes
 
-        if (!OAUTH_MODE_OPTIONAL.equals(getString(R.string.oauth2_mode))) {
+        if (AccountAuthenticator.AUTH_TOKEN_TYPE_SAML_WEB_SSO_SESSION_COOKIE.equals(mAuthTokenType) || 
+                !AUTH_OPTIONAL.equals(getString(R.string.auth_method_oauth2))) {
             mOAuth2Check.setVisibility(View.GONE);
         }
 
         mPasswordInput.setText("");     // clean password to avoid social hacking (disadvantage: password in removed if the device is turned aside)
 
-        /// bind view elements to listeners
+        /// bind view elements to listeners and other friends
         mHostUrlInput.setOnFocusChangeListener(this);
+        mHostUrlInput.setImeOptions(EditorInfo.IME_ACTION_NEXT);
+        mHostUrlInput.setOnEditorActionListener(this);
         mHostUrlInput.addTextChangedListener(new TextWatcher() {
 
             @Override
@@ -298,12 +331,20 @@ implements  OnRemoteOperationListener, OnSslValidatorListener, OnFocusChangeList
             }
 
             @Override
-            public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
+            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
+            }
 
             @Override
-            public void onTextChanged(CharSequence s, int start, int before, int count) {}
-
+            public void onTextChanged(CharSequence s, int start, int before, int count) {
+                if (!mResumed) {
+                    mAuthStatusIcon = 0;
+                    mAuthStatusText = 0;
+                    showAuthStatus();                    
+                }
+                mResumed = false;
+            }
         });
+        
         mPasswordInput.setOnFocusChangeListener(this);
         mPasswordInput.setImeOptions(EditorInfo.IME_ACTION_DONE);
         mPasswordInput.setOnEditorActionListener(this);
@@ -315,7 +356,60 @@ implements  OnRemoteOperationListener, OnSslValidatorListener, OnFocusChangeList
                 }
                 return true;
             }
-        });
+        });
+        
+        findViewById(R.id.scroll).setOnTouchListener(new OnTouchListener() {
+            @Override
+            public boolean onTouch(View view, MotionEvent event) {
+                if (event.getAction() == MotionEvent.ACTION_DOWN) {
+                    if (AccountAuthenticator.AUTH_TOKEN_TYPE_SAML_WEB_SSO_SESSION_COOKIE.equals(mAuthTokenType) &&
+                            mHostUrlInput.hasFocus()) {
+                        checkOcServer();
+                    }
+                }
+                return false;
+            }
+        });
+    }
+    
+   
+
+    private void initAuthorizationMethod() {
+        boolean oAuthRequired = false;
+        boolean samlWebSsoRequired = false;
+
+        mAuthTokenType = getIntent().getExtras().getString(AccountAuthenticator.KEY_AUTH_TOKEN_TYPE);
+        mAccount = getIntent().getExtras().getParcelable(EXTRA_ACCOUNT);
+        
+        // TODO could be a good moment to validate the received token type, if not null
+        
+        if (mAuthTokenType == null) {    
+            if (mAccount != null) {
+                /// same authentication method than the one used to create the account to update
+                oAuthRequired = (mAccountMgr.getUserData(mAccount, AccountAuthenticator.KEY_SUPPORTS_OAUTH2) != null);
+                samlWebSsoRequired = (mAccountMgr.getUserData(mAccount, AccountAuthenticator.KEY_SUPPORTS_SAML_WEB_SSO) != null);
+            
+            } else {
+                /// use the one set in setup.xml
+                oAuthRequired = AUTH_ON.equals(getString(R.string.auth_method_oauth2));
+                samlWebSsoRequired = AUTH_ON.equals(getString(R.string.auth_method_saml_web_sso));            
+            }
+            if (oAuthRequired) {
+                mAuthTokenType = AccountAuthenticator.AUTH_TOKEN_TYPE_ACCESS_TOKEN;
+            } else if (samlWebSsoRequired) {
+                mAuthTokenType = AccountAuthenticator.AUTH_TOKEN_TYPE_SAML_WEB_SSO_SESSION_COOKIE;
+            } else {
+                mAuthTokenType = AccountAuthenticator.AUTH_TOKEN_TYPE_PASSWORD;
+            }
+        }
+    
+        if (mAccount != null) {
+            String userName = mAccount.name.substring(0, mAccount.name.lastIndexOf('@'));
+            mUsernameInput.setText(userName);
+        }
+        
+        mOAuth2Check.setChecked(AccountAuthenticator.AUTH_TOKEN_TYPE_ACCESS_TOKEN.equals(mAuthTokenType));
+        
     }
 
     /**
@@ -331,6 +425,8 @@ implements  OnRemoteOperationListener, OnSslValidatorListener, OnFocusChangeList
         super.onSaveInstanceState(outState);
 
         /// connection state and info
+        outState.putInt(KEY_AUTH_MESSAGE_VISIBILITY, mAuthMessage.getVisibility());
+        outState.putString(KEY_AUTH_MESSAGE_TEXT, mAuthMessage.getText().toString());
         outState.putInt(KEY_SERVER_STATUS_TEXT, mServerStatusText);
         outState.putInt(KEY_SERVER_STATUS_ICON, mServerStatusIcon);
         outState.putBoolean(KEY_SERVER_VALID, mServerIsValid);
@@ -351,10 +447,11 @@ implements  OnRemoteOperationListener, OnSslValidatorListener, OnFocusChangeList
         if (mAccount != null) {
             outState.putParcelable(KEY_ACCOUNT, mAccount);
         }
+        outState.putString(AccountAuthenticator.KEY_AUTH_TOKEN_TYPE, mAuthTokenType);
         
         // refresh button enabled
-        //outState.putBoolean(KEY_REFRESH_BUTTON_ENABLED, mRefreshButtonEnabled);
         outState.putBoolean(KEY_REFRESH_BUTTON_ENABLED, (mRefreshButton.getVisibility() == View.VISIBLE));
+        
 
     }
 
@@ -383,13 +480,17 @@ implements  OnRemoteOperationListener, OnSslValidatorListener, OnFocusChangeList
     @Override
     protected void onResume() {
         super.onResume();
-        // the state of mOAuth2Check is automatically recovered between configuration changes, but not before onCreate() finishes; so keep the next lines here
-        changeViewByOAuth2Check(mOAuth2Check.isChecked());  
         if (mAction == ACTION_UPDATE_TOKEN && mJustCreated && getIntent().getBooleanExtra(EXTRA_ENFORCED_UPDATE, false)) {
-            if (mOAuth2Check.isChecked())
-                Toast.makeText(this, R.string.auth_expired_oauth_token_toast, Toast.LENGTH_LONG).show();
-            else
-                Toast.makeText(this, R.string.auth_expired_basic_auth_toast, Toast.LENGTH_LONG).show();
+            if (AccountAuthenticator.AUTH_TOKEN_TYPE_ACCESS_TOKEN.equals(mAuthTokenType)) {
+                //Toast.makeText(this, R.string.auth_expired_oauth_token_toast, Toast.LENGTH_LONG).show();
+                showAuthMessage(getString(R.string.auth_expired_oauth_token_toast));
+            } else if (AccountAuthenticator.AUTH_TOKEN_TYPE_SAML_WEB_SSO_SESSION_COOKIE.equals(mAuthTokenType)) {
+                //Toast.makeText(this, R.string.auth_expired_saml_sso_token_toast, Toast.LENGTH_LONG).show();
+                showAuthMessage(getString(R.string.auth_expired_saml_sso_token_toast));
+            } else {
+                //Toast.makeText(this, R.string.auth_expired_basic_auth_toast, Toast.LENGTH_LONG).show();
+                showAuthMessage(getString(R.string.auth_expired_basic_auth_toast));
+            }
         }
 
         if (mNewCapturedUriFromOAuth2Redirection != null) {
@@ -397,6 +498,7 @@ implements  OnRemoteOperationListener, OnSslValidatorListener, OnFocusChangeList
         }
 
         mJustCreated = false;
+        
     }
 
 
@@ -418,7 +520,7 @@ implements  OnRemoteOperationListener, OnSslValidatorListener, OnFocusChangeList
                 getString(R.string.oauth2_grant_type),
                 queryParameters);
         //WebdavClient client = OwnCloudClientUtils.createOwnCloudClient(Uri.parse(getString(R.string.oauth2_url_endpoint_access)), getApplicationContext());
-        WebdavClient client = OwnCloudClientUtils.createOwnCloudClient(Uri.parse(mOAuthTokenEndpointText.getText().toString().trim()), getApplicationContext());
+        WebdavClient client = OwnCloudClientUtils.createOwnCloudClient(Uri.parse(mOAuthTokenEndpointText.getText().toString().trim()), getApplicationContext(), true);
         operation.execute(client, this, mHandler);
     }
 
@@ -482,7 +584,7 @@ implements  OnRemoteOperationListener, OnSslValidatorListener, OnFocusChangeList
             mServerStatusIcon = R.drawable.progress_small;
             showServerStatus();
             mOcServerChkOperation = new  OwnCloudServerCheckOperation(uri, this);
-            WebdavClient client = OwnCloudClientUtils.createOwnCloudClient(Uri.parse(uri), this);
+            WebdavClient client = OwnCloudClientUtils.createOwnCloudClient(Uri.parse(uri), this, true);
             mOperationThread = mOcServerChkOperation.execute(client, this, mHandler);
         } else {
             mServerStatusText = 0;
@@ -582,9 +684,10 @@ implements  OnRemoteOperationListener, OnSslValidatorListener, OnFocusChangeList
             return;
         }
 
-        if (mOAuth2Check.isChecked()) {
+        if (AccountAuthenticator.AUTH_TOKEN_TYPE_ACCESS_TOKEN.equals(mAuthTokenType)) {
             startOauthorization();
-
+        } else if (AccountAuthenticator.AUTH_TOKEN_TYPE_SAML_WEB_SSO_SESSION_COOKIE.equals(mAuthTokenType)) { 
+            startSamlBasedFederatedSingleSignOnAuthorization();
         } else {
             checkBasicAuthorization();
         }
@@ -597,7 +700,7 @@ implements  OnRemoteOperationListener, OnSslValidatorListener, OnFocusChangeList
      */
     private void checkBasicAuthorization() {
         /// get the path to the root folder through WebDAV from the version server
-        String webdav_path = AccountUtils.getWebdavPath(mDiscoveredVersion, false);
+        String webdav_path = AccountUtils.getWebdavPath(mDiscoveredVersion, mAuthTokenType);
 
         /// get basic credentials entered by user
         String username = mUsernameInput.getText().toString();
@@ -608,7 +711,7 @@ implements  OnRemoteOperationListener, OnSslValidatorListener, OnFocusChangeList
 
         /// test credentials accessing the root folder
         mAuthCheckOperation = new  ExistenceCheckOperation("", this, false);
-        WebdavClient client = OwnCloudClientUtils.createOwnCloudClient(Uri.parse(mHostBaseUrl + webdav_path), this);
+        WebdavClient client = OwnCloudClientUtils.createOwnCloudClient(Uri.parse(mHostBaseUrl + webdav_path), this, true);
         client.setBasicCredentials(username, password);
         mOperationThread = mAuthCheckOperation.execute(client, this, mHandler);
     }
@@ -623,6 +726,7 @@ implements  OnRemoteOperationListener, OnSslValidatorListener, OnFocusChangeList
         mAuthStatusIcon = R.drawable.progress_small;
         mAuthStatusText = R.string.oauth_login_connection;
         showAuthStatus();
+        
 
         // GET AUTHORIZATION request
         //Uri uri = Uri.parse(getString(R.string.oauth2_url_endpoint_auth));
@@ -640,6 +744,27 @@ implements  OnRemoteOperationListener, OnSslValidatorListener, OnFocusChangeList
     }
 
 
+    /**
+     * Starts the Web Single Sign On flow to get access to the root folder
+     * in the server.
+     */
+    private void startSamlBasedFederatedSingleSignOnAuthorization() {
+        // be gentle with the user
+        mAuthStatusIcon = R.drawable.progress_small;
+        mAuthStatusText = R.string.auth_connecting_auth_server;
+        showAuthStatus();
+        showDialog(DIALOG_LOGIN_PROGRESS);
+        
+        /// get the path to the root folder through WebDAV from the version server
+        String webdav_path = AccountUtils.getWebdavPath(mDiscoveredVersion, mAuthTokenType);
+
+        /// test credentials accessing the root folder
+        mAuthCheckOperation = new  ExistenceCheckOperation("", this, false);
+        WebdavClient client = OwnCloudClientUtils.createOwnCloudClient(Uri.parse(mHostBaseUrl + webdav_path), this, false);
+        mOperationThread = mAuthCheckOperation.execute(client, this, mHandler);
+      
+    }
+
     /**
      * Callback method invoked when a RemoteOperation executed by this Activity finishes.
      * 
@@ -655,9 +780,41 @@ implements  OnRemoteOperationListener, OnSslValidatorListener, OnFocusChangeList
             onGetOAuthAccessTokenFinish((OAuth2GetAccessToken)operation, result);
 
         } else if (operation instanceof ExistenceCheckOperation)  {
-            onAuthorizationCheckFinish((ExistenceCheckOperation)operation, result);
-
+            if (AccountAuthenticator.AUTH_TOKEN_TYPE_SAML_WEB_SSO_SESSION_COOKIE.equals(mAuthTokenType)) {
+                onSamlBasedFederatedSingleSignOnAuthorizationStart(operation, result);
+                
+            } else {
+                onAuthorizationCheckFinish((ExistenceCheckOperation)operation, result);
+            }
+        }
+    }
+    
+    
+    private void onSamlBasedFederatedSingleSignOnAuthorizationStart(RemoteOperation operation, RemoteOperationResult result) {
+        try {
+            dismissDialog(DIALOG_LOGIN_PROGRESS);
+        } catch (IllegalArgumentException e) {
+            // NOTHING TO DO ; can't find out what situation that leads to the exception in this code, but user logs signal that it happens
+        }
+        
+        //if (result.isTemporalRedirection() && result.isIdPRedirection()) {
+        if (result.isIdPRedirection()) {
+            String url = result.getRedirectedLocation();
+            String targetUrl = mHostBaseUrl + AccountUtils.getWebdavPath(mDiscoveredVersion, mAuthTokenType);
+            
+            // Show dialog
+            mSamlDialog = SamlWebViewDialog.newInstance(url, targetUrl);            
+            mSamlDialog.show(getSupportFragmentManager(), TAG_SAML_DIALOG);
+            
+            mAuthStatusIcon = 0;
+            mAuthStatusText = 0;
+            
+        } else {
+            mAuthStatusIcon = R.drawable.common_error;
+            mAuthStatusText = R.string.auth_unsupported_auth_method;
+            
         }
+        showAuthStatus();
     }
 
 
@@ -723,7 +880,6 @@ implements  OnRemoteOperationListener, OnSslValidatorListener, OnFocusChangeList
             }
 
         }
-        Log_OC.d(TAG, "URL Normalize " + url);
         return (url != null ? url : "");
     }
 
@@ -883,6 +1039,12 @@ implements  OnRemoteOperationListener, OnSslValidatorListener, OnFocusChangeList
         case OAUTH2_ERROR_ACCESS_DENIED:
             mAuthStatusText = R.string.auth_oauth_error_access_denied;
             break;
+        case ACCOUNT_NOT_NEW:
+            mAuthStatusText = R.string.auth_account_not_new;
+            break;
+        case ACCOUNT_NOT_THE_SAME:
+            mAuthStatusText = R.string.auth_account_not_the_same;
+            break;
         case UNHANDLED_HTTP_CODE:
         case UNKNOWN_ERROR:
             mAuthStatusText = R.string.auth_unknown_error_title;
@@ -908,17 +1070,17 @@ implements  OnRemoteOperationListener, OnSslValidatorListener, OnFocusChangeList
             // NOTHING TO DO ; can't find out what situation that leads to the exception in this code, but user logs signal that it happens
         }
 
-        String webdav_path = AccountUtils.getWebdavPath(mDiscoveredVersion, true);
+        String webdav_path = AccountUtils.getWebdavPath(mDiscoveredVersion, mAuthTokenType);
         if (result.isSuccess() && webdav_path != null) {
             /// be gentle with the user
             showDialog(DIALOG_LOGIN_PROGRESS);
 
             /// time to test the retrieved access token on the ownCloud server
-            mOAuthAccessToken = ((OAuth2GetAccessToken)operation).getResultTokenMap().get(OAuth2Constants.KEY_ACCESS_TOKEN);
-            Log_OC.d(TAG, "Got ACCESS TOKEN: " + mOAuthAccessToken);
+            mAuthToken = ((OAuth2GetAccessToken)operation).getResultTokenMap().get(OAuth2Constants.KEY_ACCESS_TOKEN);
+            Log_OC.d(TAG, "Got ACCESS TOKEN: " + mAuthToken);
             mAuthCheckOperation = new ExistenceCheckOperation("", this, false);
-            WebdavClient client = OwnCloudClientUtils.createOwnCloudClient(Uri.parse(mHostBaseUrl + webdav_path), this);
-            client.setBearerCredentials(mOAuthAccessToken);
+            WebdavClient client = OwnCloudClientUtils.createOwnCloudClient(Uri.parse(mHostBaseUrl + webdav_path), this, true);
+            client.setBearerCredentials(mAuthToken);
             mAuthCheckOperation.execute(client, this, mHandler);
 
         } else {
@@ -947,14 +1109,17 @@ implements  OnRemoteOperationListener, OnSslValidatorListener, OnFocusChangeList
         if (result.isSuccess()) {
             Log_OC.d(TAG, "Successful access - time to save the account");
 
+            boolean success = false;
             if (mAction == ACTION_CREATE) {
-                createAccount();
+                success = createAccount();
 
             } else {
-                updateToken();
+                success = updateToken();
             }
 
-            finish();
+            if (success) {
+                finish();
+            }
 
         } else if (result.isServerFail() || result.isException()) {
             /// if server fail or exception in authorization, the UI is updated as when a server check failed
@@ -987,6 +1152,7 @@ implements  OnRemoteOperationListener, OnSslValidatorListener, OnFocusChangeList
             showAuthStatus();
             Log_OC.d(TAG, "Access failed: " + result.getLogMessage());
         }
+
     }
 
 
@@ -994,20 +1160,39 @@ implements  OnRemoteOperationListener, OnSslValidatorListener, OnFocusChangeList
      * Sets the proper response to get that the Account Authenticator that started this activity saves 
      * a new authorization token for mAccount.
      */
-    private void updateToken() {
+    private boolean updateToken() {
         Bundle response = new Bundle();
         response.putString(AccountManager.KEY_ACCOUNT_NAME, mAccount.name);
         response.putString(AccountManager.KEY_ACCOUNT_TYPE, mAccount.type);
-        boolean isOAuth = mOAuth2Check.isChecked();
-        if (isOAuth) {
-            response.putString(AccountManager.KEY_AUTHTOKEN, mOAuthAccessToken);
+        
+        if (AccountAuthenticator.AUTH_TOKEN_TYPE_ACCESS_TOKEN.equals(mAuthTokenType)) { 
+            response.putString(AccountManager.KEY_AUTHTOKEN, mAuthToken);
+            // the next line is necessary; by now, notifications are calling directly to the AuthenticatorActivity to update, without AccountManager intervention
+            mAccountMgr.setAuthToken(mAccount, mAuthTokenType, mAuthToken);
+            
+        } else if (AccountAuthenticator.AUTH_TOKEN_TYPE_SAML_WEB_SSO_SESSION_COOKIE.equals(mAuthTokenType)) {
+            String username = getUserNameForSamlSso();
+            if (!mUsernameInput.getText().toString().equals(username)) {
+                // fail - not a new account, but an existing one; disallow
+                RemoteOperationResult result = new RemoteOperationResult(ResultCode.ACCOUNT_NOT_THE_SAME); 
+                updateAuthStatusIconAndText(result);
+                showAuthStatus();
+                Log_OC.d(TAG, result.getLogMessage());
+                
+                return false;
+            }
+            
+            response.putString(AccountManager.KEY_AUTHTOKEN, mAuthToken);
             // the next line is necessary; by now, notifications are calling directly to the AuthenticatorActivity to update, without AccountManager intervention
-            mAccountMgr.setAuthToken(mAccount, AccountAuthenticator.AUTH_TOKEN_TYPE_ACCESS_TOKEN, mOAuthAccessToken);
+            mAccountMgr.setAuthToken(mAccount, mAuthTokenType, mAuthToken);
+            
         } else {
             response.putString(AccountManager.KEY_AUTHTOKEN, mPasswordInput.getText().toString());
             mAccountMgr.setPassword(mAccount, mPasswordInput.getText().toString());
         }
         setAccountAuthenticatorResult(response);
+        
+        return true;
     }
 
 
@@ -1018,13 +1203,17 @@ implements  OnRemoteOperationListener, OnSslValidatorListener, OnFocusChangeList
      * 
      * TODO Decide how to name the OAuth accounts
      */
-    private void createAccount() {
+    private boolean createAccount() {
         /// create and save new ownCloud account
-        boolean isOAuth = mOAuth2Check.isChecked();
+        boolean isOAuth = AccountAuthenticator.AUTH_TOKEN_TYPE_ACCESS_TOKEN.equals(mAuthTokenType);
+        boolean isSaml =  AccountAuthenticator.AUTH_TOKEN_TYPE_SAML_WEB_SSO_SESSION_COOKIE.equals(mAuthTokenType);
 
         Uri uri = Uri.parse(mHostBaseUrl);
         String username = mUsernameInput.getText().toString().trim();
-        if (isOAuth) {
+        if (isSaml) {
+            username = getUserNameForSamlSso();
+            
+        } else if (isOAuth) {
             username = "OAuth_user" + (new java.util.Random(System.currentTimeMillis())).nextLong();
         }            
         String accountName = username + "@" + uri.getHost();
@@ -1032,45 +1221,78 @@ implements  OnRemoteOperationListener, OnSslValidatorListener, OnFocusChangeList
             accountName += ":" + uri.getPort();
         }
         mAccount = new Account(accountName, AccountAuthenticator.ACCOUNT_TYPE);
-        if (isOAuth) {
-            mAccountMgr.addAccountExplicitly(mAccount, "", null);  // with our implementation, the password is never input in the app
+        if (AccountUtils.exists(mAccount, getApplicationContext())) {
+            // fail - not a new account, but an existing one; disallow
+            RemoteOperationResult result = new RemoteOperationResult(ResultCode.ACCOUNT_NOT_NEW); 
+            updateAuthStatusIconAndText(result);
+            showAuthStatus();
+            Log_OC.d(TAG, result.getLogMessage());
+            return false;
+            
         } else {
-            mAccountMgr.addAccountExplicitly(mAccount, mPasswordInput.getText().toString(), null);
-        }
-
-        /// add the new account as default in preferences, if there is none already
-        Account defaultAccount = AccountUtils.getCurrentOwnCloudAccount(this);
-        if (defaultAccount == null) {
-            SharedPreferences.Editor editor = PreferenceManager
-                    .getDefaultSharedPreferences(this).edit();
-            editor.putString("select_oc_account", accountName);
-            editor.commit();
+        
+            if (isOAuth || isSaml) {
+                mAccountMgr.addAccountExplicitly(mAccount, "", null);  // with external authorizations, the password is never input in the app
+            } else {
+                mAccountMgr.addAccountExplicitly(mAccount, mPasswordInput.getText().toString(), null);
+            }
+    
+            /// add the new account as default in preferences, if there is none already
+            Account defaultAccount = AccountUtils.getCurrentOwnCloudAccount(this);
+            if (defaultAccount == null) {
+                SharedPreferences.Editor editor = PreferenceManager
+                        .getDefaultSharedPreferences(this).edit();
+                editor.putString("select_oc_account", accountName);
+                editor.commit();
+            }
+    
+            /// prepare result to return to the Authenticator
+            //  TODO check again what the Authenticator makes with it; probably has the same effect as addAccountExplicitly, but it's not well done
+            final Intent intent = new Intent();       
+            intent.putExtra(AccountManager.KEY_ACCOUNT_TYPE,    AccountAuthenticator.ACCOUNT_TYPE);
+            intent.putExtra(AccountManager.KEY_ACCOUNT_NAME,    mAccount.name);
+            /*if (!isOAuth)
+                intent.putExtra(AccountManager.KEY_AUTHTOKEN,   AccountAuthenticator.ACCOUNT_TYPE); */
+            intent.putExtra(AccountManager.KEY_USERDATA,        username);
+            if (isOAuth || isSaml) {
+                mAccountMgr.setAuthToken(mAccount, mAuthTokenType, mAuthToken);
+            }
+            /// add user data to the new account; TODO probably can be done in the last parameter addAccountExplicitly, or in KEY_USERDATA
+            mAccountMgr.setUserData(mAccount, AccountAuthenticator.KEY_OC_VERSION,    mDiscoveredVersion.toString());
+            mAccountMgr.setUserData(mAccount, AccountAuthenticator.KEY_OC_BASE_URL,   mHostBaseUrl);
+            if (isSaml) {
+                mAccountMgr.setUserData(mAccount, AccountAuthenticator.KEY_SUPPORTS_SAML_WEB_SSO, "TRUE"); 
+            } else if (isOAuth) {
+                mAccountMgr.setUserData(mAccount, AccountAuthenticator.KEY_SUPPORTS_OAUTH2, "TRUE");  
+            }
+    
+            setAccountAuthenticatorResult(intent.getExtras());
+            setResult(RESULT_OK, intent);
+    
+            /// immediately request for the synchronization of the new account
+            Bundle bundle = new Bundle();
+            bundle.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true);
+            ContentResolver.requestSync(mAccount, AccountAuthenticator.AUTHORITY, bundle);
+            syncAccount();
+//          Bundle bundle = new Bundle();
+//          bundle.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true);
+//          ContentResolver.requestSync(mAccount, AccountAuthenticator.AUTHORITY, bundle);
+            return true;
         }
+    }
 
-        /// prepare result to return to the Authenticator
-        //  TODO check again what the Authenticator makes with it; probably has the same effect as addAccountExplicitly, but it's not well done
-        final Intent intent = new Intent();       
-        intent.putExtra(AccountManager.KEY_ACCOUNT_TYPE,    AccountAuthenticator.ACCOUNT_TYPE);
-        intent.putExtra(AccountManager.KEY_ACCOUNT_NAME,    mAccount.name);
-        if (!isOAuth)
-            intent.putExtra(AccountManager.KEY_AUTHTOKEN,   AccountAuthenticator.ACCOUNT_TYPE); // TODO check this; not sure it's right; maybe
-        intent.putExtra(AccountManager.KEY_USERDATA,        username);
-        if (isOAuth) {
-            mAccountMgr.setAuthToken(mAccount, AccountAuthenticator.AUTH_TOKEN_TYPE_ACCESS_TOKEN, mOAuthAccessToken);
+    
+    private String getUserNameForSamlSso() {
+        if (mAuthToken != null) {
+            String [] cookies = mAuthToken.split(";");
+            for (int i=0; i<cookies.length; i++) {
+                if (cookies[i].startsWith(KEY_OC_USERNAME_EQUALS )) {
+                    String value = Uri.decode(cookies[i].substring(KEY_OC_USERNAME_EQUALS.length()));
+                    return value;
+                }
+            }
         }
-        /// add user data to the new account; TODO probably can be done in the last parameter addAccountExplicitly, or in KEY_USERDATA
-        mAccountMgr.setUserData(mAccount, AccountAuthenticator.KEY_OC_VERSION,    mDiscoveredVersion.toString());
-        mAccountMgr.setUserData(mAccount, AccountAuthenticator.KEY_OC_BASE_URL,   mHostBaseUrl);
-        if (isOAuth)
-            mAccountMgr.setUserData(mAccount, AccountAuthenticator.KEY_SUPPORTS_OAUTH2, "TRUE");  // TODO this flag should be unnecessary
-
-        setAccountAuthenticatorResult(intent.getExtras());
-        setResult(RESULT_OK, intent);
-
-        /// immediately request for the synchronization of the new account
-        Bundle bundle = new Bundle();
-        bundle.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true);
-        ContentResolver.requestSync(mAccount, AccountAuthenticator.AUTHORITY, bundle);
+        return "";
     }
 
 
@@ -1259,33 +1481,43 @@ implements  OnRemoteOperationListener, OnSslValidatorListener, OnFocusChangeList
      * @param view      'View password' 'button'
      */
     public void onCheckClick(View view) {
-        CheckBox oAuth2Check = (CheckBox)view;      
-        changeViewByOAuth2Check(oAuth2Check.isChecked());
-
+        CheckBox oAuth2Check = (CheckBox)view;
+        if (oAuth2Check.isChecked()) {
+            mAuthTokenType = AccountAuthenticator.AUTH_TOKEN_TYPE_ACCESS_TOKEN;
+        } else {
+            mAuthTokenType = AccountAuthenticator.AUTH_TOKEN_TYPE_PASSWORD;
+        }
+        adaptViewAccordingToAuthenticationMethod();
     }
 
+    
     /**
-     * Changes the visibility of input elements depending upon the kind of authorization
-     * chosen by the user: basic or OAuth
-     * 
-     * @param checked       'True' when OAuth is selected.
+     * Changes the visibility of input elements depending on
+     * the current authorization method.
      */
-    public void changeViewByOAuth2Check(Boolean checked) {
-
-        if (checked) {
+    private void adaptViewAccordingToAuthenticationMethod () {
+        if (AccountAuthenticator.AUTH_TOKEN_TYPE_ACCESS_TOKEN.equals(mAuthTokenType)) {
+            // OAuth 2 authorization
             mOAuthAuthEndpointText.setVisibility(View.VISIBLE);
             mOAuthTokenEndpointText.setVisibility(View.VISIBLE);
             mUsernameInput.setVisibility(View.GONE);
             mPasswordInput.setVisibility(View.GONE);
+            
+        } else if (AccountAuthenticator.AUTH_TOKEN_TYPE_SAML_WEB_SSO_SESSION_COOKIE.equals(mAuthTokenType)) {
+            // SAML-based web Single Sign On
+            mOAuthAuthEndpointText.setVisibility(View.GONE);
+            mOAuthTokenEndpointText.setVisibility(View.GONE);
+            mUsernameInput.setVisibility(View.GONE);
+            mPasswordInput.setVisibility(View.GONE);
         } else {
+            // basic HTTP authorization
             mOAuthAuthEndpointText.setVisibility(View.GONE);
             mOAuthTokenEndpointText.setVisibility(View.GONE);
             mUsernameInput.setVisibility(View.VISIBLE);
             mPasswordInput.setVisibility(View.VISIBLE);
-        }     
-
-    }    
-
+        }
+    }
+    
     /**
      * Called from SslValidatorDialog when a new server certificate was correctly saved.
      */
@@ -1306,15 +1538,20 @@ implements  OnRemoteOperationListener, OnSslValidatorListener, OnFocusChangeList
     /**
      *  Called when the 'action' button in an IME is pressed ('enter' in software keyboard).
      * 
-     *  Used to trigger the authorization check when the user presses 'enter' after writing the password.
+     *  Used to trigger the authentication check when the user presses 'enter' after writing the password, 
+     *  or to throw the server test when the only field on screen is the URL input field.
      */
     @Override
     public boolean onEditorAction(TextView inputField, int actionId, KeyEvent event) {
-        if (inputField != null && inputField.equals(mPasswordInput) && 
-                actionId == EditorInfo.IME_ACTION_DONE) {
+        if (actionId == EditorInfo.IME_ACTION_DONE && inputField != null && inputField.equals(mPasswordInput)) {
             if (mOkButton.isEnabled()) {
                 mOkButton.performClick();
             }
+            
+        } else if (actionId == EditorInfo.IME_ACTION_NEXT && inputField != null && inputField.equals(mHostUrlInput)) {
+            if (AccountAuthenticator.AUTH_TOKEN_TYPE_SAML_WEB_SSO_SESSION_COOKIE.equals(mAuthTokenType)) {
+                checkOcServer();
+            }
         }
         return false;   // always return false to grant that the software keyboard is hidden anyway
     }
@@ -1352,4 +1589,76 @@ implements  OnRemoteOperationListener, OnSslValidatorListener, OnFocusChangeList
         public abstract boolean onDrawableTouch(final MotionEvent event);
     }
 
+
+    public void onSamlDialogSuccess(String sessionCookie){
+        mAuthToken = sessionCookie;
+        
+        if (sessionCookie != null && sessionCookie.length() > 0) {
+            mAuthToken = sessionCookie;
+            boolean success = false;
+            if (mAction == ACTION_CREATE) {
+                success = createAccount();
+        
+            } else {
+                success = updateToken();
+            }
+            if (success) {
+                finish();
+            }
+        }
+
+            
+    }
+
+
+    @Override
+    public void onSsoFinished(String sessionCookies) {
+        //Toast.makeText(this, "got cookies: " + sessionCookie, Toast.LENGTH_LONG).show();
+
+        if (sessionCookies != null && sessionCookies.length() > 0) {
+            Log_OC.d(TAG, "Successful SSO - time to save the account");
+            onSamlDialogSuccess(sessionCookies);
+            Fragment fd = getSupportFragmentManager().findFragmentByTag(TAG_SAML_DIALOG);
+            if (fd != null && fd instanceof SherlockDialogFragment) {
+                Dialog d = ((SherlockDialogFragment)fd).getDialog();
+                if (d != null && d.isShowing()) {
+                    d.dismiss();
+                }
+            }
+
+        } else { 
+            // TODO - show fail
+            Log_OC.d(TAG, "SSO failed");
+        }
+    
+    }
+    
+    /** Show auth_message 
+     * 
+     * @param message
+     */
+    private void showAuthMessage(String message) {
+       mAuthMessage.setVisibility(View.VISIBLE);
+       mAuthMessage.setText(message);
+    }
+    
+    private void hideAuthMessage() {
+        mAuthMessage.setVisibility(View.GONE);
+    }
+
+    private void syncAccount(){
+        /// immediately request for the synchronization of the new account
+        Bundle bundle = new Bundle();
+        bundle.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true);
+        ContentResolver.requestSync(mAccount, AccountAuthenticator.AUTHORITY, bundle);
+    }
+    
+    @Override
+    public boolean onTouchEvent(MotionEvent event) {
+        if (AccountAuthenticator.AUTH_TOKEN_TYPE_SAML_WEB_SSO_SESSION_COOKIE.equals(mAuthTokenType) &&
+                mHostUrlInput.hasFocus() && event.getAction() == MotionEvent.ACTION_DOWN) {
+            checkOcServer();
+        }
+        return super.onTouchEvent(event);
+    }
 }

+ 175 - 0
src/com/owncloud/android/authentication/SsoWebViewClient.java

@@ -0,0 +1,175 @@
+/* ownCloud Android client application
+ *   Copyright (C) 2012-2013 ownCloud Inc.
+ *
+ *   This program is free software: you can redistribute it and/or modify
+ *   it under the terms of the GNU General Public License version 2,
+ *   as published by the Free Software Foundation.
+ *
+ *   This program is distributed in the hope that it will be useful,
+ *   but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *   GNU General Public License for more details.
+ *
+ *   You should have received a copy of the GNU General Public License
+ *   along with this program.  If not, see <http://www.gnu.org/licenses/>.
+ *
+ */
+
+package com.owncloud.android.authentication;
+
+import java.lang.ref.WeakReference;
+
+import com.owncloud.android.Log_OC;
+
+import android.graphics.Bitmap;
+import android.os.Handler;
+import android.os.Message;
+import android.view.View;
+import android.webkit.CookieManager;
+import android.webkit.WebView;
+import android.webkit.WebViewClient;
+
+
+/**
+ * Custom {@link WebViewClient} client aimed to catch the end of a single-sign-on process 
+ * running in the {@link WebView} that is attached to.
+ * 
+ * Assumes that the single-sign-on is kept thanks to a cookie set at the end of the
+ * authentication process.
+ *   
+ * @author David A. Velasco
+ */
+public class SsoWebViewClient extends WebViewClient {
+        
+    private static final String TAG = SsoWebViewClient.class.getSimpleName();
+    
+    public interface SsoWebViewClientListener {
+        public void onSsoFinished(String sessionCookie);
+    }
+    
+    private Handler mListenerHandler;
+    private WeakReference<SsoWebViewClientListener> mListenerRef;
+    private String mTargetUrl;
+    private String mLastReloadedUrlAtError;
+    
+    public SsoWebViewClient (Handler listenerHandler, SsoWebViewClientListener listener) {
+        mListenerHandler = listenerHandler;
+        mListenerRef = new WeakReference<SsoWebViewClient.SsoWebViewClientListener>(listener);
+        mTargetUrl = "fake://url.to.be.set";
+        mLastReloadedUrlAtError = null;
+    }
+    
+    public String getTargetUrl() {
+        return mTargetUrl;
+    }
+    
+    public void setTargetUrl(String targetUrl) {
+        mTargetUrl = targetUrl;
+    }
+
+    @Override
+    public void onPageStarted (WebView view, String url, Bitmap favicon) {
+        Log_OC.d(TAG, "onPageStarted : " + url);
+        super.onPageStarted(view, url, favicon);
+    }
+    
+    @Override
+    public void onFormResubmission (WebView view, Message dontResend, Message resend) {
+        Log_OC.d(TAG, "onFormResubMission ");
+
+        // necessary to grant reload of last page when device orientation is changed after sending a form
+        resend.sendToTarget();
+    }
+
+    @Override
+    public boolean shouldOverrideUrlLoading(WebView view, String url) {
+        return false;
+    }
+    
+    @Override
+    public void onReceivedError (WebView view, int errorCode, String description, String failingUrl) {
+        Log_OC.e(TAG, "onReceivedError : " + failingUrl + ", code " + errorCode + ", description: " + description);
+        if (!failingUrl.equals(mLastReloadedUrlAtError)) {
+            view.reload();
+            mLastReloadedUrlAtError = failingUrl;
+        } else {
+            mLastReloadedUrlAtError = null;
+            super.onReceivedError(view, errorCode, description, failingUrl);
+        }
+    }
+    
+    @Override
+    public void onPageFinished (WebView view, String url) {
+        Log_OC.d(TAG, "onPageFinished : " + url);
+        mLastReloadedUrlAtError = null;
+        if (url.startsWith(mTargetUrl)) {
+            view.setVisibility(View.GONE);
+            CookieManager cookieManager = CookieManager.getInstance();
+            final String cookies = cookieManager.getCookie(url);
+            //Log_OC.d(TAG, "Cookies: " + cookies);
+            if (mListenerHandler != null && mListenerRef != null) {
+                // this is good idea because onPageFinished is not running in the UI thread
+                mListenerHandler.post(new Runnable() {
+                    @Override
+                    public void run() {
+                        SsoWebViewClientListener listener = mListenerRef.get();
+                        if (listener != null) {
+                            listener.onSsoFinished(cookies);
+                        }
+                    }
+                });
+            }
+        }
+
+    }
+    
+    /*
+    @Override
+    public void doUpdateVisitedHistory (WebView view, String url, boolean isReload) {
+        Log_OC.d(TAG, "doUpdateVisitedHistory : " + url);
+    }
+    
+    @Override
+    public void onReceivedSslError (WebView view, SslErrorHandler handler, SslError error) {
+        Log_OC.d(TAG, "onReceivedSslError : " + error);
+    }
+    
+    @Override
+    public void onReceivedHttpAuthRequest (WebView view, HttpAuthHandler handler, String host, String realm) {
+        Log_OC.d(TAG, "onReceivedHttpAuthRequest : " + host);
+    }
+
+    @Override
+    public WebResourceResponse shouldInterceptRequest (WebView view, String url) {
+        Log_OC.d(TAG, "shouldInterceptRequest : " + url);
+        return null;
+    }
+    
+    @Override
+    public void onLoadResource (WebView view, String url) {
+        Log_OC.d(TAG, "onLoadResource : " + url);   
+    }
+    
+    @Override
+    public void onReceivedLoginRequest (WebView view, String realm, String account, String args) {
+        Log_OC.d(TAG, "onReceivedLoginRequest : " + realm + ", " + account + ", " + args);
+    }
+    
+    @Override
+    public void onScaleChanged (WebView view, float oldScale, float newScale) {
+        Log_OC.d(TAG, "onScaleChanged : " + oldScale + " -> " + newScale);
+        super.onScaleChanged(view, oldScale, newScale);
+    }
+
+    @Override
+    public void onUnhandledKeyEvent (WebView view, KeyEvent event) {
+        Log_OC.d(TAG, "onUnhandledKeyEvent : " + event);
+    }
+    
+    @Override
+    public boolean shouldOverrideKeyEvent (WebView view, KeyEvent event) {
+        Log_OC.d(TAG, "shouldOverrideKeyEvent : " + event);
+        return false;
+    }
+    */
+}

+ 4 - 4
src/com/owncloud/android/datamodel/FileDataStorageManager.java

@@ -561,16 +561,16 @@ public class FileDataStorageManager implements DataStorageManager {
                 try {
                     c = getContentProvider().query(ProviderTableMeta.CONTENT_URI, 
                             null,
-                            ProviderTableMeta.FILE_ACCOUNT_OWNER + "=? AND " + ProviderTableMeta.FILE_PATH + " LIKE ?",
-                            new String[] { mAccount.name, dir.getRemotePath() + "%" }, null);
+                            ProviderTableMeta.FILE_ACCOUNT_OWNER + "=? AND " + ProviderTableMeta.FILE_PATH + " LIKE ? ",
+                            new String[] { mAccount.name, dir.getRemotePath() + "%"  }, ProviderTableMeta.FILE_PATH + " ASC ");
                 } catch (RemoteException e) {
                     Log_OC.e(TAG, e.getMessage());
                 }
             } else {
                 c = getContentResolver().query(ProviderTableMeta.CONTENT_URI, 
                         null,
-                        ProviderTableMeta.FILE_ACCOUNT_OWNER + "=? AND " + ProviderTableMeta.FILE_PATH + " LIKE ?",
-                        new String[] { mAccount.name, dir.getRemotePath() + "%" }, null);
+                        ProviderTableMeta.FILE_ACCOUNT_OWNER + "=? AND " + ProviderTableMeta.FILE_PATH + " LIKE ? ",
+                        new String[] { mAccount.name, dir.getRemotePath() + "%"  }, ProviderTableMeta.FILE_PATH + " ASC ");
             }
 
             /// 2. prepare a batch of update operations to change all the descendants

+ 5 - 1
src/com/owncloud/android/files/services/FileDownloader.java

@@ -28,6 +28,7 @@ import java.util.Vector;
 import java.util.concurrent.ConcurrentHashMap;
 import java.util.concurrent.ConcurrentMap;
 
+import com.owncloud.android.authentication.AccountAuthenticator;
 import com.owncloud.android.authentication.AuthenticatorActivity;
 import com.owncloud.android.datamodel.FileDataStorageManager;
 import com.owncloud.android.datamodel.OCFile;
@@ -463,7 +464,10 @@ public class FileDownloader extends Service implements OnDatatransferProgressLis
             int contentId = (downloadResult.isSuccess()) ? R.string.downloader_download_succeeded_content : R.string.downloader_download_failed_content;
             Notification finalNotification = new Notification(R.drawable.icon, getString(tickerId), System.currentTimeMillis());
             finalNotification.flags |= Notification.FLAG_AUTO_CANCEL;
-            boolean needsToUpdateCredentials = (downloadResult.getCode() == ResultCode.UNAUTHORIZED);
+            boolean needsToUpdateCredentials = (downloadResult.getCode() == ResultCode.UNAUTHORIZED ||
+                                                // (downloadResult.isTemporalRedirection() && downloadResult.isIdPRedirection()
+                                                  (downloadResult.isIdPRedirection()
+                                                        && AccountAuthenticator.AUTH_TOKEN_TYPE_SAML_WEB_SSO_SESSION_COOKIE.equals(mDownloadClient.getAuthTokenType())));
             if (needsToUpdateCredentials) {
                 // let the user update credentials with one click
                 Intent updateAccountCredentials = new Intent(this, AuthenticatorActivity.class);

+ 57 - 48
src/com/owncloud/android/files/services/FileUploader.java

@@ -579,7 +579,7 @@ public class FileUploader extends Service implements OnDatatransferProgressListe
                 mUploadClient.exhaustResponse(propfind.getResponseBodyAsStream());
             }
 
-            result = new RemoteOperationResult(isMultiStatus, status);
+            result = new RemoteOperationResult(isMultiStatus, status, propfind.getResponseHeaders());
             Log_OC.i(TAG, "Update: synchronizing properties for uploaded " + mCurrentUpload.getRemotePath() + ": "
                     + result.getLogMessage());
 
@@ -791,7 +791,13 @@ public class FileUploader extends Service implements OnDatatransferProgressListe
             Notification finalNotification = new Notification(R.drawable.icon,
                     getString(R.string.uploader_upload_failed_ticker), System.currentTimeMillis());
             finalNotification.flags |= Notification.FLAG_AUTO_CANCEL;
-            if (uploadResult.getCode() == ResultCode.UNAUTHORIZED) {
+            String content = null;
+            
+            boolean needsToUpdateCredentials = (uploadResult.getCode() == ResultCode.UNAUTHORIZED ||
+                    //(uploadResult.isTemporalRedirection() && uploadResult.isIdPRedirection() && 
+                    (uploadResult.isIdPRedirection() &&
+                            AccountAuthenticator.AUTH_TOKEN_TYPE_SAML_WEB_SSO_SESSION_COOKIE.equals(mUploadClient.getAuthTokenType())));
+            if (needsToUpdateCredentials) {
                 // let the user update credentials with one click
                 Intent updateAccountCredentials = new Intent(this, AuthenticatorActivity.class);
                 updateAccountCredentials.putExtra(AuthenticatorActivity.EXTRA_ACCOUNT, upload.getAccount());
@@ -801,62 +807,65 @@ public class FileUploader extends Service implements OnDatatransferProgressListe
                 updateAccountCredentials.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
                 updateAccountCredentials.addFlags(Intent.FLAG_FROM_BACKGROUND);
                 finalNotification.contentIntent = PendingIntent.getActivity(this, (int)System.currentTimeMillis(), updateAccountCredentials, PendingIntent.FLAG_ONE_SHOT);
+                content =  String.format(getString(R.string.uploader_upload_failed_content_single), upload.getFileName());
+                finalNotification.setLatestEventInfo(getApplicationContext(),
+                        getString(R.string.uploader_upload_failed_ticker), content, finalNotification.contentIntent);
                 mUploadClient = null;   // grant that future retries on the same account will get the fresh credentials
             } else {
                 // TODO put something smart in the contentIntent below
-                finalNotification.contentIntent = PendingIntent.getActivity(getApplicationContext(), (int)System.currentTimeMillis(), new Intent(), 0);
-            }
+            //    finalNotification.contentIntent = PendingIntent.getActivity(getApplicationContext(), (int)System.currentTimeMillis(), new Intent(), 0);
+            //}
             
-            String content = null;
-            if (uploadResult.getCode() == ResultCode.LOCAL_STORAGE_FULL
-                    || uploadResult.getCode() == ResultCode.LOCAL_STORAGE_NOT_COPIED) {
-                // TODO we need a class to provide error messages for the users
-                // from a RemoteOperationResult and a RemoteOperation
-                content = String.format(getString(R.string.error__upload__local_file_not_copied), upload.getFileName(),
-                        getString(R.string.app_name));
-            } else if (uploadResult.getCode() == ResultCode.QUOTA_EXCEEDED) {
-                content = getString(R.string.failed_upload_quota_exceeded_text);
-            } else {
-                content = String
-                        .format(getString(R.string.uploader_upload_failed_content_single), upload.getFileName());
-            }
+                if (uploadResult.getCode() == ResultCode.LOCAL_STORAGE_FULL
+                        || uploadResult.getCode() == ResultCode.LOCAL_STORAGE_NOT_COPIED) {
+                    // TODO we need a class to provide error messages for the users
+                    // from a RemoteOperationResult and a RemoteOperation
+                    content = String.format(getString(R.string.error__upload__local_file_not_copied), upload.getFileName(),
+                            getString(R.string.app_name));
+                } else if (uploadResult.getCode() == ResultCode.QUOTA_EXCEEDED) {
+                    content = getString(R.string.failed_upload_quota_exceeded_text);
+                } else {
+                    content = String
+                            .format(getString(R.string.uploader_upload_failed_content_single), upload.getFileName());
+                }
 
-            // we add only for instant-uploads the InstantUploadActivity and the
-            // db entry
-            Intent detailUploadIntent = null;
-            if (upload.isInstant() && InstantUploadActivity.IS_ENABLED) {
-                detailUploadIntent = new Intent(this, InstantUploadActivity.class);
-                detailUploadIntent.putExtra(FileUploader.KEY_ACCOUNT, upload.getAccount());
-            } else {
-                detailUploadIntent = new Intent(this, FailedUploadActivity.class);
-                detailUploadIntent.putExtra(FailedUploadActivity.MESSAGE, content);
-            }
-            finalNotification.contentIntent = PendingIntent.getActivity(getApplicationContext(),
-                    (int) System.currentTimeMillis(), detailUploadIntent, PendingIntent.FLAG_UPDATE_CURRENT
-                            | PendingIntent.FLAG_ONE_SHOT);
-
-            if (upload.isInstant()) {
-                DbHandler db = null;
-                try {
-                    db = new DbHandler(this.getBaseContext());
-                    String message = uploadResult.getLogMessage() + " errorCode: " + uploadResult.getCode();
-                    Log_OC.e(TAG, message + " Http-Code: " + uploadResult.getHttpCode());
-                    if (uploadResult.getCode() == ResultCode.QUOTA_EXCEEDED) {
-                        message = getString(R.string.failed_upload_quota_exceeded_text);
-                    }
-                    if (db.updateFileState(upload.getOriginalStoragePath(), DbHandler.UPLOAD_STATUS_UPLOAD_FAILED,
-                            message) == 0) {
-                        db.putFileForLater(upload.getOriginalStoragePath(), upload.getAccount().name, message);
-                    }
-                } finally {
-                    if (db != null) {
-                        db.close();
+                // we add only for instant-uploads the InstantUploadActivity and the
+                // db entry
+                Intent detailUploadIntent = null;
+                if (upload.isInstant() && InstantUploadActivity.IS_ENABLED) {
+                    detailUploadIntent = new Intent(this, InstantUploadActivity.class);
+                    detailUploadIntent.putExtra(FileUploader.KEY_ACCOUNT, upload.getAccount());
+                } else {
+                    detailUploadIntent = new Intent(this, FailedUploadActivity.class);
+                    detailUploadIntent.putExtra(FailedUploadActivity.MESSAGE, content);
+                }
+                finalNotification.contentIntent = PendingIntent.getActivity(getApplicationContext(),
+                        (int) System.currentTimeMillis(), detailUploadIntent, PendingIntent.FLAG_UPDATE_CURRENT
+                        | PendingIntent.FLAG_ONE_SHOT);
+
+                if (upload.isInstant()) {
+                    DbHandler db = null;
+                    try {
+                        db = new DbHandler(this.getBaseContext());
+                        String message = uploadResult.getLogMessage() + " errorCode: " + uploadResult.getCode();
+                        Log_OC.e(TAG, message + " Http-Code: " + uploadResult.getHttpCode());
+                        if (uploadResult.getCode() == ResultCode.QUOTA_EXCEEDED) {
+                            message = getString(R.string.failed_upload_quota_exceeded_text);
+                        }
+                        if (db.updateFileState(upload.getOriginalStoragePath(), DbHandler.UPLOAD_STATUS_UPLOAD_FAILED,
+                                message) == 0) {
+                            db.putFileForLater(upload.getOriginalStoragePath(), upload.getAccount().name, message);
+                        }
+                    } finally {
+                        if (db != null) {
+                            db.close();
+                        }
                     }
                 }
             }
             finalNotification.setLatestEventInfo(getApplicationContext(),
                     getString(R.string.uploader_upload_failed_ticker), content, finalNotification.contentIntent);
-
+            
             mNotificationManager.notify(R.string.uploader_upload_failed_ticker, finalNotification);
         }
 

+ 24 - 10
src/com/owncloud/android/network/OwnCloudClientUtils.java

@@ -32,6 +32,7 @@ import javax.net.ssl.SSLContext;
 import javax.net.ssl.TrustManager;
 
 import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager;
+import org.apache.commons.httpclient.methods.GetMethod;
 import org.apache.commons.httpclient.protocol.Protocol;
 import org.apache.http.conn.ssl.BrowserCompatHostnameVerifier;
 import org.apache.http.conn.ssl.X509HostnameVerifier;
@@ -90,12 +91,18 @@ public class OwnCloudClientUtils {
         //Log_OC.d(TAG, "Creating WebdavClient associated to " + account.name);
        
         Uri uri = Uri.parse(AccountUtils.constructFullURLForAccount(appContext, account));
-        WebdavClient client = createOwnCloudClient(uri, appContext);
         AccountManager am = AccountManager.get(appContext);
-        if (am.getUserData(account, AccountAuthenticator.KEY_SUPPORTS_OAUTH2) != null) {    // TODO avoid a call to getUserData here
+        boolean isOauth2 = am.getUserData(account, AccountAuthenticator.KEY_SUPPORTS_OAUTH2) != null;   // TODO avoid calling to getUserData here
+        boolean isSamlSso = am.getUserData(account, AccountAuthenticator.KEY_SUPPORTS_SAML_WEB_SSO) != null;
+        WebdavClient client = createOwnCloudClient(uri, appContext, !isSamlSso);
+        if (isOauth2) {    
             String accessToken = am.blockingGetAuthToken(account, AccountAuthenticator.AUTH_TOKEN_TYPE_ACCESS_TOKEN, false);
             client.setBearerCredentials(accessToken);   // TODO not assume that the access token is a bearer token
         
+        } else if (isSamlSso) {    // TODO avoid a call to getUserData here
+            String accessToken = am.blockingGetAuthToken(account, AccountAuthenticator.AUTH_TOKEN_TYPE_SAML_WEB_SSO_SESSION_COOKIE, false);
+            client.setSsoSessionCookie(accessToken);
+            
         } else {
             String username = account.name.substring(0, account.name.lastIndexOf('@'));
             //String password = am.getPassword(account);
@@ -109,16 +116,25 @@ public class OwnCloudClientUtils {
     
     public static WebdavClient createOwnCloudClient (Account account, Context appContext, Activity currentActivity) throws OperationCanceledException, AuthenticatorException, IOException, AccountNotFoundException {
         Uri uri = Uri.parse(AccountUtils.constructFullURLForAccount(appContext, account));
-        WebdavClient client = createOwnCloudClient(uri, appContext);
         AccountManager am = AccountManager.get(appContext);
-        if (am.getUserData(account, AccountAuthenticator.KEY_SUPPORTS_OAUTH2) != null) {    // TODO avoid a call to getUserData here
+        boolean isOauth2 = am.getUserData(account, AccountAuthenticator.KEY_SUPPORTS_OAUTH2) != null;   // TODO avoid calling to getUserData here
+        boolean isSamlSso = am.getUserData(account, AccountAuthenticator.KEY_SUPPORTS_SAML_WEB_SSO) != null;
+        WebdavClient client = createOwnCloudClient(uri, appContext, !isSamlSso);
+        
+        if (isOauth2) {    // TODO avoid a call to getUserData here
             AccountManagerFuture<Bundle> future =  am.getAuthToken(account, AccountAuthenticator.AUTH_TOKEN_TYPE_ACCESS_TOKEN, null, currentActivity, null, null);
             Bundle result = future.getResult();
             String accessToken = result.getString(AccountManager.KEY_AUTHTOKEN);
-            //String accessToken = am.blockingGetAuthToken(account, AccountAuthenticator.AUTH_TOKEN_TYPE_ACCESS_TOKEN, false);
             if (accessToken == null) throw new AuthenticatorException("WTF!");
             client.setBearerCredentials(accessToken);   // TODO not assume that the access token is a bearer token
-            
+
+        } else if (isSamlSso) {    // TODO avoid a call to getUserData here
+            AccountManagerFuture<Bundle> future =  am.getAuthToken(account, AccountAuthenticator.AUTH_TOKEN_TYPE_SAML_WEB_SSO_SESSION_COOKIE, null, currentActivity, null, null);
+            Bundle result = future.getResult();
+            String accessToken = result.getString(AccountManager.KEY_AUTHTOKEN);
+            if (accessToken == null) throw new AuthenticatorException("WTF!");
+            client.setSsoSessionCookie(accessToken);
+
         } else {
             String username = account.name.substring(0, account.name.lastIndexOf('@'));
             //String password = am.getPassword(account);
@@ -139,10 +155,7 @@ public class OwnCloudClientUtils {
      * @param context   Android context where the WebdavClient is being created.
      * @return          A WebdavClient object ready to be used
      */
-    public static WebdavClient createOwnCloudClient(Uri uri, Context context) {
-        //Log_OC.d(TAG, "Creating WebdavClient for " + uri);
-        
-        //allowSelfsignedCertificates(true);
+    public static WebdavClient createOwnCloudClient(Uri uri, Context context, boolean followRedirects) {
         try {
             registerAdvancedSslContext(true, context);
         }  catch (GeneralSecurityException e) {
@@ -156,6 +169,7 @@ public class OwnCloudClientUtils {
         
         client.setDefaultTimeouts(DEFAULT_DATA_TIMEOUT, DEFAULT_CONNECTION_TIMEOUT);
         client.setBaseUri(uri);
+        client.setFollowRedirects(followRedirects);
         
         return client;
     }

+ 3 - 0
src/com/owncloud/android/operations/ChunkedUploadFileOperation.java

@@ -68,6 +68,9 @@ public class ChunkedUploadFileOperation extends UploadFileOperation {
             String uriPrefix = client.getBaseUri() + WebdavUtils.encodePath(getRemotePath()) + "-chunking-" + Math.abs((new Random()).nextInt(9000)+1000) + "-" ;
             long chunkCount = (long) Math.ceil((double)file.length() / CHUNK_SIZE);
             for (int chunkIndex = 0; chunkIndex < chunkCount ; chunkIndex++, offset += CHUNK_SIZE) {
+                if (mPutMethod != null) {
+                    mPutMethod.releaseConnection();    // let the connection available for other methods
+                }
                 mPutMethod = new PutMethod(uriPrefix + chunkCount + "-" + chunkIndex);
                 mPutMethod.addRequestHeader(OC_CHUNKED_HEADER, OC_CHUNKED_HEADER);
                 ((ChunkFromFileChannelRequestEntity)mEntity).setOffset(offset);

+ 1 - 1
src/com/owncloud/android/operations/CreateFolderOperation.java

@@ -77,7 +77,7 @@ public class CreateFolderOperation extends RemoteOperation {
                 mStorageManager.saveFile(newDir);
             }
 
-            result = new RemoteOperationResult(mkcol.succeeded(), status);
+            result = new RemoteOperationResult(mkcol.succeeded(), status, mkcol.getResponseHeaders());
             Log_OC.d(TAG, "Create directory " + mRemotePath + ": " + result.getLogMessage());
             client.exhaustResponse(mkcol.getResponseBodyAsStream());
                 

+ 9 - 8
src/com/owncloud/android/operations/DownloadFileOperation.java

@@ -58,6 +58,7 @@ public class DownloadFileOperation extends RemoteOperation {
     private Set<OnDatatransferProgressListener> mDataTransferListeners = new HashSet<OnDatatransferProgressListener>();
     private final AtomicBoolean mCancellationRequested = new AtomicBoolean(false);
     private long mModificationTimestamp = 0;
+    private GetMethod mGet;
 
     
     public DownloadFileOperation(Account account, OCFile file) {
@@ -154,7 +155,7 @@ public class DownloadFileOperation extends RemoteOperation {
             if (!moved)
                 result = new RemoteOperationResult(RemoteOperationResult.ResultCode.LOCAL_STORAGE_NOT_MOVED);
             else
-                result = new RemoteOperationResult(isSuccess(status), status);
+                result = new RemoteOperationResult(isSuccess(status), status, (mGet != null ? mGet.getResponseHeaders() : null));
             Log_OC.i(TAG, "Download of " + mFile.getRemotePath() + " to " + getSavePath() + ": " + result.getLogMessage());
             
         } catch (Exception e) {
@@ -174,15 +175,15 @@ public class DownloadFileOperation extends RemoteOperation {
     protected int downloadFile(WebdavClient client, File targetFile) throws HttpException, IOException, OperationCancelledException {
         int status = -1;
         boolean savedFile = false;
-        GetMethod get = new GetMethod(client.getBaseUri() + WebdavUtils.encodePath(mFile.getRemotePath()));
+        mGet = new GetMethod(client.getBaseUri() + WebdavUtils.encodePath(mFile.getRemotePath()));
         Iterator<OnDatatransferProgressListener> it = null;
         
         FileOutputStream fos = null;
         try {
-            status = client.executeMethod(get);
+            status = client.executeMethod(mGet);
             if (isSuccess(status)) {
                 targetFile.createNewFile();
-                BufferedInputStream bis = new BufferedInputStream(get.getResponseBodyAsStream());
+                BufferedInputStream bis = new BufferedInputStream(mGet.getResponseBodyAsStream());
                 fos = new FileOutputStream(targetFile);
                 long transferred = 0;
 
@@ -191,7 +192,7 @@ public class DownloadFileOperation extends RemoteOperation {
                 while ((readResult = bis.read(bytes)) != -1) {
                     synchronized(mCancellationRequested) {
                         if (mCancellationRequested.get()) {
-                            get.abort();
+                            mGet.abort();
                             throw new OperationCancelledException();
                         }
                     }
@@ -205,14 +206,14 @@ public class DownloadFileOperation extends RemoteOperation {
                     }
                 }
                 savedFile = true;
-                Header modificationTime = get.getResponseHeader("Last-Modified");
+                Header modificationTime = mGet.getResponseHeader("Last-Modified");
                 if (modificationTime != null) {
                     Date d = WebdavUtils.parseResponseDate((String) modificationTime.getValue());
                     mModificationTimestamp = (d != null) ? d.getTime() : 0;
                 }
                 
             } else {
-                client.exhaustResponse(get.getResponseBodyAsStream());
+                client.exhaustResponse(mGet.getResponseBodyAsStream());
             }
                 
         } finally {
@@ -220,7 +221,7 @@ public class DownloadFileOperation extends RemoteOperation {
             if (!savedFile && targetFile.exists()) {
                 targetFile.delete();
             }
-            get.releaseConnection();    // let the connection available for other methods
+            mGet.releaseConnection();    // let the connection available for other methods
         }
         return status;
     }

+ 1 - 1
src/com/owncloud/android/operations/ExistenceCheckOperation.java

@@ -69,7 +69,7 @@ public class ExistenceCheckOperation extends RemoteOperation {
             int status = client.executeMethod(head, TIMEOUT, TIMEOUT);
             client.exhaustResponse(head.getResponseBodyAsStream());
             boolean success = (status == HttpStatus.SC_OK && !mSuccessIfAbsent) || (status == HttpStatus.SC_NOT_FOUND && mSuccessIfAbsent);
-            result = new RemoteOperationResult(success, status);
+            result = new RemoteOperationResult(success, status, head.getResponseHeaders());
             Log_OC.d(TAG, "Existence check for " + client.getBaseUri() + mPath + " targeting for " + (mSuccessIfAbsent ? " absence " : " existence ") + "finished with HTTP status " + status + (!success?"(FAIL)":""));
             
         } catch (Exception e) {

+ 2 - 2
src/com/owncloud/android/operations/OAuth2GetAccessToken.java

@@ -80,12 +80,12 @@ public class OAuth2GetAccessToken extends RemoteOperation {
                         result = new RemoteOperationResult(ResultCode.OAUTH2_ERROR);
                     
                     } else {
-                        result = new RemoteOperationResult(true, status);
+                        result = new RemoteOperationResult(true, status, postMethod.getResponseHeaders());
                     }
                     
                 } else {
                     client.exhaustResponse(postMethod.getResponseBodyAsStream());
-                    result = new RemoteOperationResult(false, status);
+                    result = new RemoteOperationResult(false, status, postMethod.getResponseHeaders());
                 }
             }
             

+ 1 - 1
src/com/owncloud/android/operations/OwnCloudServerCheckOperation.java

@@ -80,7 +80,7 @@ public class OwnCloudServerCheckOperation extends RemoteOperation {
                 }
                 
             } else {
-                mLatestResult = new RemoteOperationResult(false, status);
+                mLatestResult = new RemoteOperationResult(false, status, get.getResponseHeaders());
             }
 
         } catch (JSONException e) {

+ 21 - 10
src/com/owncloud/android/operations/RemoteOperation.java

@@ -242,18 +242,28 @@ public abstract class RemoteOperation implements Runnable {
                 result = run(mClient);
         
             repeat = false;
-            if (mCallerActivity != null && mAccount != null && mContext != null && !result.isSuccess() && result.getCode() == ResultCode.UNAUTHORIZED) {
-                /// fail due to lack of authorization in an operation performed in foreground
-                AccountManager am = AccountManager.get(mContext);
+            if (mCallerActivity != null && mAccount != null && mContext != null && !result.isSuccess() &&
+//                    (result.getCode() == ResultCode.UNAUTHORIZED || (result.isTemporalRedirection() && result.isIdPRedirection()))) {
+                    (result.getCode() == ResultCode.UNAUTHORIZED || result.isIdPRedirection())) {
+                /// possible fail due to lack of authorization in an operation performed in foreground
                 Credentials cred = mClient.getCredentials();
-                if (cred instanceof BearerCredentials) {
-                    am.invalidateAuthToken(AccountAuthenticator.ACCOUNT_TYPE, ((BearerCredentials)cred).getAccessToken());
-                } else {
-                    am.clearPassword(mAccount);
+                String ssoSessionCookie = mClient.getSsoSessionCookie();
+                if (cred != null || ssoSessionCookie != null) {
+                    /// confirmed : unauthorized operation
+                    AccountManager am = AccountManager.get(mContext);
+                    boolean bearerAuthorization = (cred != null && cred instanceof BearerCredentials);
+                    boolean samlBasedSsoAuthorization = (cred == null && ssoSessionCookie != null);
+                    if (bearerAuthorization) {
+                        am.invalidateAuthToken(AccountAuthenticator.ACCOUNT_TYPE, ((BearerCredentials)cred).getAccessToken());
+                    } else if (samlBasedSsoAuthorization ) {
+                        am.invalidateAuthToken(AccountAuthenticator.ACCOUNT_TYPE, ssoSessionCookie);
+                    } else {
+                        am.clearPassword(mAccount);
+                    }
+                    mClient = null;
+                    repeat = true;  // when repeated, the creation of a new OwnCloudClient after erasing the saved credentials will trigger the login activity
+                    result = null;
                 }
-                mClient = null;
-                repeat = true;  // when repeated, the creation of a new OwnCloudClient after erasing the saved credentials will trigger the login activity
-                result = null;
             }
         } while (repeat);
         
@@ -278,4 +288,5 @@ public abstract class RemoteOperation implements Runnable {
         return mClient;
     }
 
+
 }

+ 42 - 4
src/com/owncloud/android/operations/RemoteOperationResult.java

@@ -28,6 +28,7 @@ import java.net.UnknownHostException;
 import javax.net.ssl.SSLException;
 
 import org.apache.commons.httpclient.ConnectTimeoutException;
+import org.apache.commons.httpclient.Header;
 import org.apache.commons.httpclient.HttpException;
 import org.apache.commons.httpclient.HttpStatus;
 import org.apache.jackrabbit.webdav.DavException;
@@ -50,7 +51,7 @@ import com.owncloud.android.network.CertificateCombinedException;
 public class RemoteOperationResult implements Serializable {
 
     /** Generated - should be refreshed every time the class changes!! */
-    private static final long serialVersionUID = 6106167714625712390L;
+    private static final long serialVersionUID = -4415103901492836870L;
 
     
     private static final String TAG = "RemoteOperationResult";
@@ -85,20 +86,23 @@ public class RemoteOperationResult implements Serializable {
         OAUTH2_ERROR_ACCESS_DENIED,
         QUOTA_EXCEEDED, 
         ACCOUNT_NOT_FOUND, 
-        ACCOUNT_EXCEPTION
+        ACCOUNT_EXCEPTION, 
+        ACCOUNT_NOT_NEW, 
+        ACCOUNT_NOT_THE_SAME
     }
 
     private boolean mSuccess = false;
     private int mHttpCode = -1;
     private Exception mException = null;
     private ResultCode mCode = ResultCode.UNKNOWN_ERROR;
+    private String mRedirectedLocation;
 
     public RemoteOperationResult(ResultCode code) {
         mCode = code;
         mSuccess = (code == ResultCode.OK || code == ResultCode.OK_SSL || code == ResultCode.OK_NO_SSL || code == ResultCode.OK_NO_CHANGES_ON_DIR);
     }
 
-    public RemoteOperationResult(boolean success, int httpCode) {
+    private RemoteOperationResult(boolean success, int httpCode) {
         mSuccess = success;
         mHttpCode = httpCode;
 
@@ -124,10 +128,24 @@ public class RemoteOperationResult implements Serializable {
                 break;
             default:
                 mCode = ResultCode.UNHANDLED_HTTP_CODE;
-                Log_OC.d(TAG, "RemoteOperationResult has prcessed UNHANDLED_HTTP_CODE: " + httpCode);
+                Log_OC.d(TAG, "RemoteOperationResult has processed UNHANDLED_HTTP_CODE: " + httpCode);
             }
         }
     }
+    
+    public RemoteOperationResult(boolean success, int httpCode, Header[] headers) {
+        this(success, httpCode);
+        if (headers != null) {
+            Header current;
+            for (int i=0; i<headers.length; i++) {
+                current = headers[i];
+                if ("Location".equals(current.getName())) {
+                    mRedirectedLocation = current.getValue();
+                    break;
+                }
+            }
+        }
+    }    
 
     public RemoteOperationResult(Exception e) {
         mException = e;
@@ -282,6 +300,12 @@ public class RemoteOperationResult implements Serializable {
 
         } else if (mCode == ResultCode.LOCAL_STORAGE_NOT_MOVED) {
             return "Error while moving file to final directory";
+
+        } else if (mCode == ResultCode.ACCOUNT_NOT_NEW) {
+            return "Account already existing when creating a new one";
+
+        } else if (mCode == ResultCode.ACCOUNT_NOT_THE_SAME) {
+            return "Authenticated with a different account than the one updating";
         }
 
         return "Operation finished with HTTP status code " + mHttpCode + " (" + (isSuccess() ? "success" : "fail") + ")";
@@ -296,4 +320,18 @@ public class RemoteOperationResult implements Serializable {
         return (mException != null);
     }
 
+    public boolean isTemporalRedirection() {
+        return (mHttpCode == 302 || mHttpCode == 307);
+    }
+
+    public String getRedirectedLocation() {
+        return mRedirectedLocation;
+    }
+    
+    public boolean isIdPRedirection() {
+        return (mRedirectedLocation != null &&
+                (mRedirectedLocation.toUpperCase().contains("SAML") || 
+                mRedirectedLocation.toLowerCase().contains("wayf")));
+    }
+
 }

+ 1 - 1
src/com/owncloud/android/operations/RemoveFileOperation.java

@@ -88,7 +88,7 @@ public class RemoveFileOperation extends RemoteOperation {
                 }
             }
             delete.getResponseBodyAsString();   // exhaust the response, although not interesting
-            result = new RemoteOperationResult((delete.succeeded() || status == HttpStatus.SC_NOT_FOUND), status);
+            result = new RemoteOperationResult((delete.succeeded() || status == HttpStatus.SC_NOT_FOUND), status, delete.getResponseHeaders());
             Log_OC.i(TAG, "Remove " + mFileToRemove.getRemotePath() + ": " + result.getLogMessage());
             
         } catch (Exception e) {

+ 1 - 1
src/com/owncloud/android/operations/RenameFileOperation.java

@@ -136,7 +136,7 @@ public class RenameFileOperation extends RemoteOperation {
             }
             
             move.getResponseBodyAsString(); // exhaust response, although not interesting
-            result = new RemoteOperationResult(move.succeeded(), status);
+            result = new RemoteOperationResult(move.succeeded(), status, move.getResponseHeaders());
             Log_OC.i(TAG, "Rename " + mFile.getRemotePath() + " to " + mNewRemotePath + ": " + result.getLogMessage());
             
         } catch (Exception e) {

+ 1 - 1
src/com/owncloud/android/operations/SynchronizeFileOperation.java

@@ -101,7 +101,7 @@ public class SynchronizeFileOperation extends RemoteOperation {
                         
                     } else {
                         client.exhaustResponse(propfind.getResponseBodyAsStream());
-                        result = new RemoteOperationResult(false, status);
+                        result = new RemoteOperationResult(false, status, propfind.getResponseHeaders());
                     }
                 }
                 

+ 15 - 6
src/com/owncloud/android/operations/SynchronizeFolderOperation.java

@@ -29,6 +29,7 @@ import java.util.List;
 import java.util.Map;
 import java.util.Vector;
 
+import org.apache.commons.httpclient.Header;
 import org.apache.http.HttpStatus;
 import org.apache.jackrabbit.webdav.MultiStatus;
 import org.apache.jackrabbit.webdav.client.methods.PropFindMethod;
@@ -237,9 +238,9 @@ public class SynchronizeFolderOperation extends RemoteOperation {
                         } else {
                             mFailsInFavouritesFound++;
                             if (contentsResult.getException() != null) {
-                                Log_OC.d(TAG, "Error while synchronizing favourites : " +  contentsResult.getLogMessage(), contentsResult.getException());
+                                Log_OC.e(TAG, "Error while synchronizing favourites : " +  contentsResult.getLogMessage(), contentsResult.getException());
                             } else {
-                                Log_OC.d(TAG, "Error while synchronizing favourites : " + contentsResult.getLogMessage());
+                                Log_OC.e(TAG, "Error while synchronizing favourites : " + contentsResult.getLogMessage());
                             }
                         }
                     }   // won't let these fails break the synchronization process
@@ -278,21 +279,29 @@ public class SynchronizeFolderOperation extends RemoteOperation {
                     result = new RemoteOperationResult(ResultCode.SYNC_CONFLICT);   // should be different result, but will do the job
 
                 } else {
-                    result = new RemoteOperationResult(true, status);
+                    result = new RemoteOperationResult(true, status, query.getResponseHeaders());
                 }
             } else {
-                result = new RemoteOperationResult(false, status);
+                result = new RemoteOperationResult(false, status, query.getResponseHeaders());
             }
             Log_OC.i(TAG, "Synchronizing " + mAccount.name + ", folder " + mRemotePath + ": " + result.getLogMessage());
 
-
         } catch (Exception e) {
             result = new RemoteOperationResult(e);
-            Log_OC.e(TAG, "Synchronizing " + mAccount.name + ", folder " + mRemotePath + ": " + result.getLogMessage(), result.getException());
+            
 
         } finally {
             if (query != null)
                 query.releaseConnection();  // let the connection available for other methods
+            if (result.isSuccess()) {
+                Log_OC.i(TAG, "Synchronizing " + mAccount.name + ", folder " + mRemotePath + ": " + result.getLogMessage());
+            } else {
+                if (result.isException()) {
+                    Log_OC.e(TAG, "Synchronizing " + mAccount.name + ", folder " + mRemotePath + ": " + result.getLogMessage(), result.getException());
+                } else {
+                    Log_OC.e(TAG, "Synchronizing " + mAccount.name + ", folder " + mRemotePath + ": " + result.getLogMessage());
+                }
+            }
         }
 
         return result;

+ 1 - 1
src/com/owncloud/android/operations/UpdateOCVersionOperation.java

@@ -65,7 +65,7 @@ public class UpdateOCVersionOperation extends RemoteOperation {
             int status = client.executeMethod(get);
             if (status != HttpStatus.SC_OK) {
                 client.exhaustResponse(get.getResponseBodyAsStream());
-                result = new RemoteOperationResult(false, status);
+                result = new RemoteOperationResult(false, status, get.getResponseHeaders());
                 
             } else {
                 String response = get.getResponseBodyAsString();

+ 1 - 1
src/com/owncloud/android/operations/UploadFileOperation.java

@@ -304,7 +304,7 @@ public class UploadFileOperation extends RemoteOperation {
                 }
             }
 
-            result = new RemoteOperationResult(isSuccess(status), status);
+            result = new RemoteOperationResult(isSuccess(status), status, (mPutMethod != null ? mPutMethod.getResponseHeaders() : null));
 
         } catch (Exception e) {
             // TODO something cleaner with cancellations

+ 2 - 0
src/com/owncloud/android/providers/FileContentProvider.java

@@ -189,6 +189,8 @@ public class FileContentProvider extends ContentProvider {
         }
 
         SQLiteDatabase db = mDbHelper.getReadableDatabase();
+        // DB case_sensitive
+        db.execSQL("PRAGMA case_sensitive_like = true");
         Cursor c = sqlQuery.query(db, projection, selection, selectionArgs,
                 null, null, order);
 

+ 12 - 2
src/com/owncloud/android/syncadapter/FileSyncAdapter.java

@@ -28,6 +28,7 @@ import org.apache.jackrabbit.webdav.DavException;
 
 import com.owncloud.android.Log_OC;
 import com.owncloud.android.R;
+import com.owncloud.android.authentication.AccountAuthenticator;
 import com.owncloud.android.authentication.AuthenticatorActivity;
 import com.owncloud.android.datamodel.DataStorageManager;
 import com.owncloud.android.datamodel.FileDataStorageManager;
@@ -223,7 +224,10 @@ public class FileSyncAdapter extends AbstractOwnCloudSyncAdapter {
             sendStickyBroadcast(true, remotePath, null);
             
         } else {
-            if (result.getCode() == RemoteOperationResult.ResultCode.UNAUTHORIZED) {
+            if (result.getCode() == RemoteOperationResult.ResultCode.UNAUTHORIZED ||
+                   // (result.isTemporalRedirection() && result.isIdPRedirection() &&
+                    ( result.isIdPRedirection() && 
+                            AccountAuthenticator.AUTH_TOKEN_TYPE_SAML_WEB_SSO_SESSION_COOKIE.equals(getClient().getAuthTokenType()))) {
                 mSyncResult.stats.numAuthExceptions++;
                 
             } else if (result.getException() instanceof DavException) {
@@ -304,7 +308,13 @@ public class FileSyncAdapter extends AbstractOwnCloudSyncAdapter {
     private void notifyFailedSynchronization() {
         Notification notification = new Notification(R.drawable.icon, getContext().getString(R.string.sync_fail_ticker), System.currentTimeMillis());
         notification.flags |= Notification.FLAG_AUTO_CANCEL;
-        boolean needsToUpdateCredentials = (mLastFailedResult != null && mLastFailedResult.getCode() == ResultCode.UNAUTHORIZED);
+        boolean needsToUpdateCredentials = (mLastFailedResult != null && 
+                                             (  mLastFailedResult.getCode() == ResultCode.UNAUTHORIZED ||
+                                                // (mLastFailedResult.isTemporalRedirection() && mLastFailedResult.isIdPRedirection() && 
+                                                ( mLastFailedResult.isIdPRedirection() && 
+                                                 AccountAuthenticator.AUTH_TOKEN_TYPE_SAML_WEB_SSO_SESSION_COOKIE.equals(getClient().getAuthTokenType()))
+                                             )
+                                           );
         // TODO put something smart in the contentIntent below for all the possible errors
         notification.contentIntent = PendingIntent.getActivity(getContext().getApplicationContext(), (int)System.currentTimeMillis(), new Intent(), 0);
         if (needsToUpdateCredentials) {

+ 12 - 2
src/com/owncloud/android/ui/activity/AccountSelectActivity.java

@@ -50,6 +50,7 @@ import com.actionbarsherlock.view.MenuItem;
 import com.owncloud.android.authentication.AccountAuthenticator;
 import com.owncloud.android.authentication.AuthenticatorActivity;
 import com.owncloud.android.authentication.AccountUtils;
+import com.owncloud.android.ui.activity.FileActivity.AccountCreationCallback;
 import com.owncloud.android.Log_OC;
 
 import com.owncloud.android.R;
@@ -133,11 +134,20 @@ public class AccountSelectActivity extends SherlockListActivity implements
     @Override
     public boolean onMenuItemSelected(int featureId, MenuItem item) {
         if (item.getItemId() == R.id.createAccount) {
-            Intent intent = new Intent(
+            /*Intent intent = new Intent(
                     android.provider.Settings.ACTION_ADD_ACCOUNT);
             intent.putExtra("authorities",
                     new String[] { AccountAuthenticator.AUTHORITY });
-            startActivity(intent);
+            startActivity(intent);*/
+            AccountManager am = AccountManager.get(getApplicationContext());
+            am.addAccount(AccountAuthenticator.ACCOUNT_TYPE, 
+                            null,
+                            null, 
+                            null, 
+                            this, 
+                            null,                        
+                            null);
+            
             return true;
         }
         return false;

+ 1 - 1
src/com/owncloud/android/ui/activity/FileActivity.java

@@ -174,7 +174,7 @@ public abstract class FileActivity extends SherlockFragmentActivity {
     private void createFirstAccount() {
         AccountManager am = AccountManager.get(getApplicationContext());
         am.addAccount(AccountAuthenticator.ACCOUNT_TYPE, 
-                        AccountAuthenticator.AUTH_TOKEN_TYPE_PASSWORD,
+                        null,
                         null, 
                         null, 
                         this, 

+ 284 - 0
src/com/owncloud/android/ui/dialog/SamlWebViewDialog.java

@@ -0,0 +1,284 @@
+/* ownCloud Android client application
+ *   Copyright (C) 2012-2013 ownCloud Inc.
+ *
+ *   This program is free software: you can redistribute it and/or modify
+ *   it under the terms of the GNU General Public License version 2,
+ *   as published by the Free Software Foundation.
+ *
+ *   This program is distributed in the hope that it will be useful,
+ *   but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *   GNU General Public License for more details.
+ *
+ *   You should have received a copy of the GNU General Public License
+ *   along with this program.  If not, see <http://www.gnu.org/licenses/>.
+ *
+ */
+
+package com.owncloud.android.ui.dialog;
+
+import android.annotation.SuppressLint;
+import android.app.Activity;
+import android.app.Dialog;
+import android.content.DialogInterface;
+import android.os.Bundle;
+import android.os.Handler;
+import android.support.v4.app.FragmentTransaction;
+import android.support.v4.app.FragmentManager;
+import android.view.LayoutInflater;
+import android.view.View;
+import android.view.ViewGroup;
+import android.webkit.CookieManager;
+import android.webkit.CookieSyncManager;
+import android.webkit.WebBackForwardList;
+import android.webkit.WebSettings;
+import android.webkit.WebView;
+
+import com.actionbarsherlock.app.SherlockDialogFragment;
+import com.owncloud.android.Log_OC;
+import com.owncloud.android.R;
+import com.owncloud.android.authentication.SsoWebViewClient;
+import com.owncloud.android.authentication.SsoWebViewClient.SsoWebViewClientListener;
+
+import eu.alefzero.webdav.WebdavClient;
+
+/**
+ * Dialog to show the WebView for SAML Authentication
+ * 
+ * @author Maria Asensio
+ * @author David A. Velasco
+ */
+public class SamlWebViewDialog extends SherlockDialogFragment {
+
+    public final String SAML_DIALOG_TAG = "SamlWebViewDialog";
+    
+    private final static String TAG =  SamlWebViewDialog.class.getSimpleName();
+
+    private static final String ARG_INITIAL_URL = "INITIAL_URL";
+    private static final String ARG_TARGET_URL = "TARGET_URL";
+    private static final String KEY_WEBVIEW_STATE = "WEBVIEW_STATE";
+    
+    private WebView mSsoWebView;
+    private SsoWebViewClient mWebViewClient;
+    
+    private String mInitialUrl;
+    private String mTargetUrl;
+    
+    private Handler mHandler;
+
+    private SsoWebViewClientListener mSsoWebViewClientListener;
+
+    //private View mSsoRootView;
+
+
+    /**
+     * Public factory method to get dialog instances.
+     * 
+     * @param handler
+     * @param Url           Url to open at WebView
+     * @param targetURL     mHostBaseUrl + AccountUtils.getWebdavPath(mDiscoveredVersion, mCurrentAuthTokenType)
+     * @return              New dialog instance, ready to show.
+     */
+    public static SamlWebViewDialog newInstance(String url, String targetUrl) {
+        Log_OC.d(TAG, "New instance");
+        SamlWebViewDialog fragment = new SamlWebViewDialog();
+        Bundle args = new Bundle();
+        args.putString(ARG_INITIAL_URL, url);
+        args.putString(ARG_TARGET_URL, targetUrl);
+        fragment.setArguments(args);
+        return fragment;
+    }
+    
+    
+    public SamlWebViewDialog() {
+        super();
+        Log_OC.d(TAG, "constructor");
+    }
+    
+    
+    @Override
+    public void onAttach(Activity activity) {
+        Log_OC.d(TAG, "onAttach");
+        super.onAttach(activity);
+        try {
+            mSsoWebViewClientListener = (SsoWebViewClientListener) activity;
+            mHandler = new Handler();
+            mWebViewClient = new SsoWebViewClient(mHandler, mSsoWebViewClientListener);
+            
+       } catch (ClassCastException e) {
+            throw new ClassCastException(activity.toString() + " must implement " + SsoWebViewClientListener.class.getSimpleName());
+        }
+    }
+
+    
+    @SuppressLint("SetJavaScriptEnabled")
+    @Override
+    public void onCreate(Bundle savedInstanceState) {
+        Log_OC.d(TAG, "onCreate");
+        super.onCreate(savedInstanceState);
+        
+        CookieSyncManager.createInstance(getActivity());
+
+        if (savedInstanceState == null) {
+            mInitialUrl = getArguments().getString(ARG_INITIAL_URL);
+            mTargetUrl = getArguments().getString(ARG_TARGET_URL);
+        } else {
+            mInitialUrl = savedInstanceState.getString(ARG_INITIAL_URL);
+            mTargetUrl = savedInstanceState.getString(ARG_TARGET_URL);
+        }
+        
+        setStyle(SherlockDialogFragment.STYLE_NO_TITLE, R.style.Theme_ownCloud_Dialog);
+    }
+    
+    @Override
+    public Dialog onCreateDialog(Bundle savedInstanceState) {
+        Log_OC.d(TAG, "onCreateDialog");
+
+        /*
+        // build the dialog
+        AlertDialog.Builder builder = new AlertDialog.Builder(getSherlockActivity());
+        if (mSsoRootView.getParent() != null) {
+            ((ViewGroup)(mSsoRootView.getParent())).removeView(mSsoRootView);
+        }
+        builder.setView(mSsoRootView);
+        //builder.setView(mSsoWebView);
+        Dialog dialog = builder.create();
+        */
+        
+        return super.onCreateDialog(savedInstanceState);
+    }
+
+    @SuppressLint("SetJavaScriptEnabled")
+    @Override
+    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
+        Log_OC.d(TAG, "onCreateView");
+        
+        // Inflate layout of the dialog  
+        View rootView = inflater.inflate(R.layout.sso_dialog, container, false);  // null parent view because it will go in the dialog layout
+        mSsoWebView  = (WebView) rootView.findViewById(R.id.sso_webview);
+            
+        mWebViewClient.setTargetUrl(mTargetUrl);
+        mSsoWebView.setWebViewClient(mWebViewClient);
+        
+        if (savedInstanceState == null) {
+            Log_OC.d(TAG,  "   initWebView start");
+            CookieManager cookieManager = CookieManager.getInstance();
+            cookieManager.setAcceptCookie(true);
+            cookieManager.removeAllCookie();
+            mSsoWebView.loadUrl(mInitialUrl);
+            
+        } else {
+            Log_OC.d(TAG, "   restoreWebView start");
+            WebBackForwardList history = mSsoWebView.restoreState(savedInstanceState.getBundle(KEY_WEBVIEW_STATE));
+            if (history == null) {
+                Log_OC.e(TAG, "Error restoring WebView state ; back to starting URL");
+                mSsoWebView.loadUrl(mInitialUrl);
+            }
+        }
+
+        WebSettings webSettings = mSsoWebView.getSettings();
+        webSettings.setJavaScriptEnabled(true);
+        webSettings.setBuiltInZoomControls(true);
+        webSettings.setLoadWithOverviewMode(false);
+        webSettings.setSavePassword(false);
+        webSettings.setUserAgentString(WebdavClient.USER_AGENT);
+        webSettings.setSaveFormData(false);
+        
+        return rootView;
+    }
+
+    @Override
+    public void onSaveInstanceState(Bundle outState) {
+        Log_OC.d(SAML_DIALOG_TAG, "onSaveInstanceState being CALLED");
+        super.onSaveInstanceState(outState);
+        
+        // save URLs
+        outState.putString(ARG_INITIAL_URL, mInitialUrl);
+        outState.putString(ARG_TARGET_URL, mTargetUrl);
+        
+        // Save the state of the WebView
+        Bundle webviewState = new Bundle();
+        mSsoWebView.saveState(webviewState);
+        outState.putBundle(KEY_WEBVIEW_STATE, webviewState);
+    }
+
+    @Override
+    public void onDestroyView() {
+        Log_OC.d(TAG, "onDestroyView");
+        
+        mSsoWebView.setWebViewClient(null);
+        
+        // Work around bug: http://code.google.com/p/android/issues/detail?id=17423
+        Dialog dialog = getDialog();
+        if ((dialog != null)) {
+            dialog.setOnDismissListener(null);
+            //dialog.dismiss();
+            //dialog.setDismissMessage(null);
+        }
+        
+        super.onDestroyView();
+    }
+    
+    @Override
+    public void onDestroy() {
+        Log_OC.d(TAG, "onDestroy");
+        super.onDestroy();
+    }
+
+    @Override
+    public void onDetach() {
+        Log_OC.d(TAG, "onDetach");
+        mSsoWebViewClientListener = null;
+        mWebViewClient = null;
+        super.onDetach();
+    }
+    
+    @Override
+    public void onCancel (DialogInterface dialog) {
+        Log_OC.d(SAML_DIALOG_TAG, "onCancel");
+        super.onCancel(dialog);
+    }
+    
+    @Override
+    public void onDismiss (DialogInterface dialog) {
+        Log_OC.d(SAML_DIALOG_TAG, "onDismiss");
+        super.onDismiss(dialog);
+    }
+    
+    @Override
+    public void onStart() {
+        Log_OC.d(SAML_DIALOG_TAG, "onStart");
+        super.onStart();
+    }
+
+    @Override
+    public void onStop() {
+        Log_OC.d(SAML_DIALOG_TAG, "onStop");
+        super.onStop();
+    }
+
+    @Override
+    public void onResume() {
+        Log_OC.d(SAML_DIALOG_TAG, "onResume");
+        super.onResume();
+    }
+
+    @Override
+    public void onPause() {
+        Log_OC.d(SAML_DIALOG_TAG, "onPause");
+        super.onPause();
+    }
+    
+    @Override
+    public int show (FragmentTransaction transaction, String tag) {
+        Log_OC.d(SAML_DIALOG_TAG, "show (transaction)");
+        return super.show(transaction, tag);
+    }
+
+    @Override
+    public void show (FragmentManager manager, String tag) {
+        Log_OC.d(SAML_DIALOG_TAG, "show (manager)");
+        super.show(manager, tag);
+    }
+
+}

+ 40 - 0
src/com/owncloud/android/ui/dialog/SsoWebView.java

@@ -0,0 +1,40 @@
+/* ownCloud Android client application
+ *   Copyright (C) 2012-2013 ownCloud Inc.
+ *
+ *   This program is free software: you can redistribute it and/or modify
+ *   it under the terms of the GNU General Public License version 2,
+ *   as published by the Free Software Foundation.
+ *
+ *   This program is distributed in the hope that it will be useful,
+ *   but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *   GNU General Public License for more details.
+ *
+ *   You should have received a copy of the GNU General Public License
+ *   along with this program.  If not, see <http://www.gnu.org/licenses/>.
+ *
+ */
+
+package com.owncloud.android.ui.dialog;
+
+import android.content.Context;
+import android.util.AttributeSet;
+import android.webkit.WebView;
+
+public class SsoWebView extends WebView {
+    
+    public SsoWebView(Context context) {
+        super(context);
+    }
+    
+    public SsoWebView(Context context, AttributeSet attr) {
+        super(context, attr);
+    }
+    
+    @Override
+    public boolean onCheckIsTextEditor () {
+        return false;
+    }
+    
+}
+

+ 51 - 13
src/eu/alefzero/webdav/WebdavClient.java

@@ -18,37 +18,30 @@
 
 package eu.alefzero.webdav;
 
-import java.io.BufferedInputStream;
-import java.io.File;
-import java.io.FileOutputStream;
 import java.io.IOException;
 import java.io.InputStream;
 import java.util.ArrayList;
 import java.util.List;
 
 import org.apache.commons.httpclient.Credentials;
-import org.apache.commons.httpclient.HostConfiguration;
 import org.apache.commons.httpclient.HttpClient;
 import org.apache.commons.httpclient.HttpConnectionManager;
 import org.apache.commons.httpclient.HttpException;
 import org.apache.commons.httpclient.HttpMethod;
 import org.apache.commons.httpclient.HttpMethodBase;
-import org.apache.commons.httpclient.HttpState;
 import org.apache.commons.httpclient.HttpVersion;
 import org.apache.commons.httpclient.UsernamePasswordCredentials;
 import org.apache.commons.httpclient.auth.AuthPolicy;
 import org.apache.commons.httpclient.auth.AuthScope;
-import org.apache.commons.httpclient.methods.GetMethod;
+import org.apache.commons.httpclient.cookie.CookiePolicy;
 import org.apache.commons.httpclient.methods.HeadMethod;
-import org.apache.commons.httpclient.methods.PutMethod;
 import org.apache.commons.httpclient.params.HttpMethodParams;
 import org.apache.http.HttpStatus;
 import org.apache.http.params.CoreProtocolPNames;
-import org.apache.jackrabbit.webdav.client.methods.DavMethod;
-import org.apache.jackrabbit.webdav.client.methods.DeleteMethod;
 
 import com.owncloud.android.Log_OC;
 
+import com.owncloud.android.authentication.AccountAuthenticator;
 import com.owncloud.android.network.BearerAuthScheme;
 import com.owncloud.android.network.BearerCredentials;
 
@@ -57,10 +50,12 @@ import android.net.Uri;
 public class WebdavClient extends HttpClient {
     private Uri mUri;
     private Credentials mCredentials;
+    private boolean mFollowRedirects;
+    private String mSsoSessionCookie;
+    private String mAuthTokenType;
     final private static String TAG = "WebdavClient";
-    private static final String USER_AGENT = "Android-ownCloud";
+    public static final String USER_AGENT = "Android-ownCloud";
     
-    private OnDatatransferProgressListener mDataTransferListener;
     static private byte[] sExhaustBuffer = new byte[1024];
     
     /**
@@ -71,6 +66,9 @@ public class WebdavClient extends HttpClient {
         Log_OC.d(TAG, "Creating WebdavClient");
         getParams().setParameter(HttpMethodParams.USER_AGENT, USER_AGENT);
         getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
+        mFollowRedirects = true;
+        mSsoSessionCookie = null;
+        mAuthTokenType = AccountAuthenticator.AUTH_TOKEN_TYPE_PASSWORD;
     }
 
     public void setBearerCredentials(String accessToken) {
@@ -82,6 +80,8 @@ public class WebdavClient extends HttpClient {
         
         mCredentials = new BearerCredentials(accessToken);
         getState().setCredentials(AuthScope.ANY, mCredentials);
+        mSsoSessionCookie = null;
+        mAuthTokenType = AccountAuthenticator.AUTH_TOKEN_TYPE_ACCESS_TOKEN;
     }
 
     public void setBasicCredentials(String username, String password) {
@@ -92,8 +92,19 @@ public class WebdavClient extends HttpClient {
         getParams().setAuthenticationPreemptive(true);
         mCredentials = new UsernamePasswordCredentials(username, password);
         getState().setCredentials(AuthScope.ANY, mCredentials);
+        mSsoSessionCookie = null;
+        mAuthTokenType = AccountAuthenticator.AUTH_TOKEN_TYPE_PASSWORD;
     }
     
+    public void setSsoSessionCookie(String accessToken) {
+        getParams().setAuthenticationPreemptive(false);
+        getParams().setCookiePolicy(CookiePolicy.IGNORE_COOKIES);
+        mSsoSessionCookie = accessToken;
+        mCredentials = null;
+        mAuthTokenType = AccountAuthenticator.AUTH_TOKEN_TYPE_SAML_WEB_SSO_SESSION_COOKIE;
+    }
+    
+    
     /**
      * Check if a file exists in the OC server
      * 
@@ -145,6 +156,21 @@ public class WebdavClient extends HttpClient {
             getHttpConnectionManager().getParams().setConnectionTimeout(oldConnectionTimeout);
         }
     }
+    
+    
+    @Override
+    public int executeMethod(HttpMethod method) throws IOException, HttpException {
+        try {
+            method.setFollowRedirects(mFollowRedirects);
+        } catch (Exception e) {
+            
+        }
+        if (mSsoSessionCookie != null && mSsoSessionCookie.length() > 0) {
+            method.setRequestHeader("Cookie", mSsoSessionCookie);
+        }
+        return super.executeMethod(method);
+    }
+
 
     /**
      * Exhausts a not interesting HTTP response. Encouraged by HttpClient documentation.
@@ -185,6 +211,18 @@ public class WebdavClient extends HttpClient {
 
     public final Credentials getCredentials() {
         return mCredentials;
-    }
-
+    }
+    
+    public final String getSsoSessionCookie() {
+        return mSsoSessionCookie;
+    }
+
+    public void setFollowRedirects(boolean followRedirects) {
+        mFollowRedirects = followRedirects;
+    }
+
+    public String getAuthTokenType() {
+        return mAuthTokenType;
+    }
+
 }