Upstream version 5.34.104.0
[platform/framework/web/crosswalk.git] / src / extensions / browser / extension_prefs.cc
1 // Copyright 2014 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 #include "extensions/browser/extension_prefs.h"
6
7 #include <iterator>
8
9 #include "base/command_line.h"
10 #include "base/prefs/pref_notifier.h"
11 #include "base/prefs/pref_service.h"
12 #include "base/strings/string_number_conversions.h"
13 #include "base/strings/string_util.h"
14 #include "base/value_conversions.h"
15 #include "chrome/browser/extensions/api/content_settings/content_settings_store.h"
16 #include "chrome/browser/extensions/api/preference/preference_api.h"
17 #include "components/user_prefs/pref_registry_syncable.h"
18 #include "extensions/browser/admin_policy.h"
19 #include "extensions/browser/app_sorting.h"
20 #include "extensions/browser/event_router.h"
21 #include "extensions/browser/extension_pref_store.h"
22 #include "extensions/browser/extension_prefs_factory.h"
23 #include "extensions/browser/pref_names.h"
24 #include "extensions/common/feature_switch.h"
25 #include "extensions/common/manifest.h"
26 #include "extensions/common/permissions/permission_set.h"
27 #include "extensions/common/permissions/permissions_info.h"
28 #include "extensions/common/url_pattern.h"
29 #include "extensions/common/user_script.h"
30 #include "ui/base/l10n/l10n_util.h"
31
32 using base::Value;
33 using base::DictionaryValue;
34 using base::ListValue;
35
36 namespace extensions {
37
38 namespace {
39
40 // Additional preferences keys, which are not needed by external clients.
41
42 // True if this extension is running. Note this preference stops getting updated
43 // during Chrome shutdown (and won't be updated on a browser crash) and so can
44 // be used at startup to determine whether the extension was running when Chrome
45 // was last terminated.
46 const char kPrefRunning[] = "running";
47
48 // Whether this extension had windows when it was last running.
49 const char kIsActive[] = "is_active";
50
51 // Where an extension was installed from. (see Manifest::Location)
52 const char kPrefLocation[] = "location";
53
54 // Enabled, disabled, killed, etc. (see Extension::State)
55 const char kPrefState[] = "state";
56
57 // The path to the current version's manifest file.
58 const char kPrefPath[] = "path";
59
60 // The dictionary containing the extension's manifest.
61 const char kPrefManifest[] = "manifest";
62
63 // The version number.
64 const char kPrefVersion[] = "manifest.version";
65
66 // Indicates whether an extension is blacklisted.
67 const char kPrefBlacklist[] = "blacklist";
68
69 // If extension is greylisted.
70 const char kPrefBlacklistState[] = "blacklist_state";
71
72 // The count of how many times we prompted the user to acknowledge an
73 // extension.
74 const char kPrefAcknowledgePromptCount[] = "ack_prompt_count";
75
76 // Indicates whether the user has acknowledged various types of extensions.
77 const char kPrefExternalAcknowledged[] = "ack_external";
78 const char kPrefBlacklistAcknowledged[] = "ack_blacklist";
79 const char kPrefWipeoutAcknowledged[] = "ack_wiped";
80
81 // Indicates whether the external extension was installed during the first
82 // run of this profile.
83 const char kPrefExternalInstallFirstRun[] = "external_first_run";
84
85 // Indicates whether to show an install warning when the user enables.
86 const char kExtensionDidEscalatePermissions[] = "install_warning_on_enable";
87
88 // DO NOT USE, use kPrefDisableReasons instead.
89 // Indicates whether the extension was updated while it was disabled.
90 const char kDeprecatedPrefDisableReason[] = "disable_reason";
91
92 // A bitmask of all the reasons an extension is disabled.
93 const char kPrefDisableReasons[] = "disable_reasons";
94
95 // The key for a serialized Time value indicating the start of the day (from the
96 // server's perspective) an extension last included a "ping" parameter during
97 // its update check.
98 const char kLastPingDay[] = "lastpingday";
99
100 // Similar to kLastPingDay, but for "active" instead of "rollcall" pings.
101 const char kLastActivePingDay[] = "last_active_pingday";
102
103 // A bit we use to keep track of whether we need to do an "active" ping.
104 const char kActiveBit[] = "active_bit";
105
106 // Path for settings specific to blacklist update.
107 const char kExtensionsBlacklistUpdate[] = "extensions.blacklistupdate";
108
109 // Path for the delayed install info dictionary preference. The actual string
110 // value is a legacy artifact for when delayed installs only pertained to
111 // updates that were waiting for idle.
112 const char kDelayedInstallInfo[] = "idle_install_info";
113
114 // Reason why the extension's install was delayed.
115 const char kDelayedInstallReason[] = "delay_install_reason";
116
117 // Path for the suggested page ordinal of a delayed extension install.
118 const char kPrefSuggestedPageOrdinal[] = "suggested_page_ordinal";
119
120 // A preference that, if true, will allow this extension to run in incognito
121 // mode.
122 const char kPrefIncognitoEnabled[] = "incognito";
123
124 // A preference to control whether an extension is allowed to inject script in
125 // pages with file URLs.
126 const char kPrefAllowFileAccess[] = "newAllowFileAccess";
127 // TODO(jstritar): As part of fixing http://crbug.com/91577, we revoked all
128 // extension file access by renaming the pref. We should eventually clean up
129 // the old flag and possibly go back to that name.
130 // const char kPrefAllowFileAccessOld[] = "allowFileAccess";
131
132 // A preference specifying if the user dragged the app on the NTP.
133 const char kPrefUserDraggedApp[] = "user_dragged_app_ntp";
134
135 // Preferences that hold which permissions the user has granted the extension.
136 // We explicitly keep track of these so that extensions can contain unknown
137 // permissions, for backwards compatibility reasons, and we can still prompt
138 // the user to accept them once recognized. We store the active permission
139 // permissions because they may differ from those defined in the manifest.
140 const char kPrefActivePermissions[] = "active_permissions";
141 const char kPrefGrantedPermissions[] = "granted_permissions";
142
143 // The preference names for PermissionSet values.
144 const char kPrefAPIs[] = "api";
145 const char kPrefManifestPermissions[] = "manifest_permissions";
146 const char kPrefExplicitHosts[] = "explicit_host";
147 const char kPrefScriptableHosts[] = "scriptable_host";
148
149 // The preference names for the old granted permissions scheme.
150 const char kPrefOldGrantedFullAccess[] = "granted_permissions.full";
151 const char kPrefOldGrantedHosts[] = "granted_permissions.host";
152 const char kPrefOldGrantedAPIs[] = "granted_permissions.api";
153
154 // A preference that indicates when an extension was installed.
155 const char kPrefInstallTime[] = "install_time";
156
157 // A preference which saves the creation flags for extensions.
158 const char kPrefCreationFlags[] = "creation_flags";
159
160 // A preference that indicates whether the extension was installed from the
161 // Chrome Web Store.
162 const char kPrefFromWebStore[] = "from_webstore";
163
164 // A preference that indicates whether the extension was installed from a
165 // mock App created from a bookmark.
166 const char kPrefFromBookmark[] = "from_bookmark";
167
168 // A preference that indicates whether the extension was installed as
169 // default apps.
170 const char kPrefWasInstalledByDefault[] = "was_installed_by_default";
171
172 // Key for Geometry Cache preference.
173 const char kPrefGeometryCache[] = "geometry_cache";
174
175 // A preference that indicates when an extension is last launched.
176 const char kPrefLastLaunchTime[] = "last_launch_time";
177
178 // A list of installed ids and a signature.
179 const char kInstallSignature[] = "extensions.install_signature";
180
181 // Provider of write access to a dictionary storing extension prefs.
182 class ScopedExtensionPrefUpdate : public DictionaryPrefUpdate {
183  public:
184   ScopedExtensionPrefUpdate(PrefService* service,
185                             const std::string& extension_id) :
186     DictionaryPrefUpdate(service, pref_names::kExtensions),
187     extension_id_(extension_id) {}
188
189   virtual ~ScopedExtensionPrefUpdate() {
190   }
191
192   // DictionaryPrefUpdate overrides:
193   virtual base::DictionaryValue* Get() OVERRIDE {
194     base::DictionaryValue* dict = DictionaryPrefUpdate::Get();
195     base::DictionaryValue* extension = NULL;
196     if (!dict->GetDictionary(extension_id_, &extension)) {
197       // Extension pref does not exist, create it.
198       extension = new base::DictionaryValue();
199       dict->SetWithoutPathExpansion(extension_id_, extension);
200     }
201     return extension;
202   }
203
204  private:
205   const std::string extension_id_;
206
207   DISALLOW_COPY_AND_ASSIGN(ScopedExtensionPrefUpdate);
208 };
209
210 std::string JoinPrefs(const std::string& parent, const char* child) {
211   return parent + "." + child;
212 }
213
214 // Checks if kPrefBlacklist is set to true in the base::DictionaryValue.
215 // Return false if the value is false or kPrefBlacklist does not exist.
216 // This is used to decide if an extension is blacklisted.
217 bool IsBlacklistBitSet(const base::DictionaryValue* ext) {
218   bool bool_value;
219   return ext->GetBoolean(kPrefBlacklist, &bool_value) && bool_value;
220 }
221
222 }  // namespace
223
224 //
225 // TimeProvider
226 //
227
228 ExtensionPrefs::TimeProvider::TimeProvider() {
229 }
230
231 ExtensionPrefs::TimeProvider::~TimeProvider() {
232 }
233
234 base::Time ExtensionPrefs::TimeProvider::GetCurrentTime() const {
235   return base::Time::Now();
236 }
237
238 //
239 // ScopedUpdate
240 //
241 template <typename T, base::Value::Type type_enum_value>
242 ExtensionPrefs::ScopedUpdate<T, type_enum_value>::ScopedUpdate(
243     ExtensionPrefs* prefs,
244     const std::string& extension_id,
245     const std::string& key)
246     : update_(prefs->pref_service(), pref_names::kExtensions),
247       extension_id_(extension_id),
248       key_(key) {
249   DCHECK(Extension::IdIsValid(extension_id_));
250 }
251
252 template <typename T, base::Value::Type type_enum_value>
253 ExtensionPrefs::ScopedUpdate<T, type_enum_value>::~ScopedUpdate() {
254 }
255
256 template <typename T, base::Value::Type type_enum_value>
257 T* ExtensionPrefs::ScopedUpdate<T, type_enum_value>::Get() {
258   base::DictionaryValue* dict = update_.Get();
259   base::DictionaryValue* extension = NULL;
260   base::Value* key_value = NULL;
261   if (!dict->GetDictionary(extension_id_, &extension) ||
262       !extension->Get(key_, &key_value)) {
263     return NULL;
264   }
265   return key_value->GetType() == type_enum_value ?
266       static_cast<T*>(key_value) :
267       NULL;
268 }
269
270 template <typename T, base::Value::Type type_enum_value>
271 T* ExtensionPrefs::ScopedUpdate<T, type_enum_value>::Create() {
272   base::DictionaryValue* dict = update_.Get();
273   base::DictionaryValue* extension = NULL;
274   base::Value* key_value = NULL;
275   T* value_as_t = NULL;
276   if (!dict->GetDictionary(extension_id_, &extension)) {
277     extension = new base::DictionaryValue;
278     dict->SetWithoutPathExpansion(extension_id_, extension);
279   }
280   if (!extension->Get(key_, &key_value)) {
281     value_as_t = new T;
282     extension->SetWithoutPathExpansion(key_, value_as_t);
283   } else {
284     CHECK(key_value->GetType() == type_enum_value);
285     value_as_t = static_cast<T*>(key_value);
286   }
287   return value_as_t;
288 }
289
290 // Explicit instantiations for Dictionary and List value types.
291 template class ExtensionPrefs::ScopedUpdate<base::DictionaryValue,
292                                             base::Value::TYPE_DICTIONARY>;
293 template class ExtensionPrefs::ScopedUpdate<base::ListValue,
294                                             base::Value::TYPE_LIST>;
295
296 //
297 // ExtensionPrefs
298 //
299
300 // static
301 ExtensionPrefs* ExtensionPrefs::Create(
302     PrefService* prefs,
303     const base::FilePath& root_dir,
304     ExtensionPrefValueMap* extension_pref_value_map,
305     scoped_ptr<AppSorting> app_sorting,
306     bool extensions_disabled) {
307   return ExtensionPrefs::Create(prefs,
308                                 root_dir,
309                                 extension_pref_value_map,
310                                 app_sorting.Pass(),
311                                 extensions_disabled,
312                                 make_scoped_ptr(new TimeProvider()));
313 }
314
315 // static
316 ExtensionPrefs* ExtensionPrefs::Create(
317     PrefService* pref_service,
318     const base::FilePath& root_dir,
319     ExtensionPrefValueMap* extension_pref_value_map,
320     scoped_ptr<AppSorting> app_sorting,
321     bool extensions_disabled,
322     scoped_ptr<TimeProvider> time_provider) {
323   return new ExtensionPrefs(pref_service,
324                             root_dir,
325                             extension_pref_value_map,
326                             app_sorting.Pass(),
327                             time_provider.Pass(),
328                             extensions_disabled);
329 }
330
331 ExtensionPrefs::~ExtensionPrefs() {
332 }
333
334 // static
335 ExtensionPrefs* ExtensionPrefs::Get(content::BrowserContext* context) {
336   return ExtensionPrefsFactory::GetInstance()->GetForBrowserContext(context);
337 }
338
339 static base::FilePath::StringType MakePathRelative(const base::FilePath& parent,
340                                              const base::FilePath& child) {
341   if (!parent.IsParent(child))
342     return child.value();
343
344   base::FilePath::StringType retval = child.value().substr(
345       parent.value().length());
346   if (base::FilePath::IsSeparator(retval[0]))
347     return retval.substr(1);
348   else
349     return retval;
350 }
351
352 void ExtensionPrefs::MakePathsRelative() {
353   const base::DictionaryValue* dict =
354       prefs_->GetDictionary(pref_names::kExtensions);
355   if (!dict || dict->empty())
356     return;
357
358   // Collect all extensions ids with absolute paths in |absolute_keys|.
359   std::set<std::string> absolute_keys;
360   for (base::DictionaryValue::Iterator i(*dict); !i.IsAtEnd(); i.Advance()) {
361     const base::DictionaryValue* extension_dict = NULL;
362     if (!i.value().GetAsDictionary(&extension_dict))
363       continue;
364     int location_value;
365     if (extension_dict->GetInteger(kPrefLocation, &location_value) &&
366         Manifest::IsUnpackedLocation(
367             static_cast<Manifest::Location>(location_value))) {
368       // Unpacked extensions can have absolute paths.
369       continue;
370     }
371     base::FilePath::StringType path_string;
372     if (!extension_dict->GetString(kPrefPath, &path_string))
373       continue;
374     base::FilePath path(path_string);
375     if (path.IsAbsolute())
376       absolute_keys.insert(i.key());
377   }
378   if (absolute_keys.empty())
379     return;
380
381   // Fix these paths.
382   DictionaryPrefUpdate update(prefs_, pref_names::kExtensions);
383   base::DictionaryValue* update_dict = update.Get();
384   for (std::set<std::string>::iterator i = absolute_keys.begin();
385        i != absolute_keys.end(); ++i) {
386     base::DictionaryValue* extension_dict = NULL;
387     if (!update_dict->GetDictionaryWithoutPathExpansion(*i, &extension_dict)) {
388       NOTREACHED() << "Control should never reach here for extension " << *i;
389       continue;
390     }
391     base::FilePath::StringType path_string;
392     extension_dict->GetString(kPrefPath, &path_string);
393     base::FilePath path(path_string);
394     extension_dict->SetString(kPrefPath,
395         MakePathRelative(install_directory_, path));
396   }
397 }
398
399 const base::DictionaryValue* ExtensionPrefs::GetExtensionPref(
400     const std::string& extension_id) const {
401   const base::DictionaryValue* extensions =
402       prefs_->GetDictionary(pref_names::kExtensions);
403   const base::DictionaryValue* extension_dict = NULL;
404   if (!extensions ||
405       !extensions->GetDictionary(extension_id, &extension_dict)) {
406     return NULL;
407   }
408   return extension_dict;
409 }
410
411 void ExtensionPrefs::UpdateExtensionPref(const std::string& extension_id,
412                                          const std::string& key,
413                                          base::Value* data_value) {
414   if (!Extension::IdIsValid(extension_id)) {
415     NOTREACHED() << "Invalid extension_id " << extension_id;
416     return;
417   }
418   ScopedExtensionPrefUpdate update(prefs_, extension_id);
419   if (data_value)
420     update->Set(key, data_value);
421   else
422     update->Remove(key, NULL);
423 }
424
425 void ExtensionPrefs::DeleteExtensionPrefs(const std::string& extension_id) {
426   extension_pref_value_map_->UnregisterExtension(extension_id);
427   content_settings_store_->UnregisterExtension(extension_id);
428   DictionaryPrefUpdate update(prefs_, pref_names::kExtensions);
429   base::DictionaryValue* dict = update.Get();
430   dict->Remove(extension_id, NULL);
431 }
432
433 bool ExtensionPrefs::ReadPrefAsBoolean(const std::string& extension_id,
434                                        const std::string& pref_key,
435                                        bool* out_value) const {
436   const base::DictionaryValue* ext = GetExtensionPref(extension_id);
437   if (!ext || !ext->GetBoolean(pref_key, out_value))
438     return false;
439
440   return true;
441 }
442
443 bool ExtensionPrefs::ReadPrefAsInteger(const std::string& extension_id,
444                                        const std::string& pref_key,
445                                        int* out_value) const {
446   const base::DictionaryValue* ext = GetExtensionPref(extension_id);
447   if (!ext || !ext->GetInteger(pref_key, out_value))
448     return false;
449
450   return true;
451 }
452
453 bool ExtensionPrefs::ReadPrefAsString(const std::string& extension_id,
454                                       const std::string& pref_key,
455                                       std::string* out_value) const {
456   const base::DictionaryValue* ext = GetExtensionPref(extension_id);
457   if (!ext || !ext->GetString(pref_key, out_value))
458     return false;
459
460   return true;
461 }
462
463 bool ExtensionPrefs::ReadPrefAsList(const std::string& extension_id,
464                                     const std::string& pref_key,
465                                     const base::ListValue** out_value) const {
466   const base::DictionaryValue* ext = GetExtensionPref(extension_id);
467   const base::ListValue* out = NULL;
468   if (!ext || !ext->GetList(pref_key, &out))
469     return false;
470   if (out_value)
471     *out_value = out;
472
473   return true;
474 }
475
476 bool ExtensionPrefs::ReadPrefAsDictionary(
477     const std::string& extension_id,
478     const std::string& pref_key,
479     const base::DictionaryValue** out_value) const {
480   const base::DictionaryValue* ext = GetExtensionPref(extension_id);
481   const base::DictionaryValue* out = NULL;
482   if (!ext || !ext->GetDictionary(pref_key, &out))
483     return false;
484   if (out_value)
485     *out_value = out;
486
487   return true;
488 }
489
490 bool ExtensionPrefs::HasPrefForExtension(
491     const std::string& extension_id) const {
492   return GetExtensionPref(extension_id) != NULL;
493 }
494
495 bool ExtensionPrefs::ReadPrefAsURLPatternSet(const std::string& extension_id,
496                                              const std::string& pref_key,
497                                              URLPatternSet* result,
498                                              int valid_schemes) {
499   const base::ListValue* value = NULL;
500   if (!ReadPrefAsList(extension_id, pref_key, &value))
501     return false;
502
503   bool allow_file_access = AllowFileAccess(extension_id);
504   return result->Populate(*value, valid_schemes, allow_file_access, NULL);
505 }
506
507 void ExtensionPrefs::SetExtensionPrefURLPatternSet(
508     const std::string& extension_id,
509     const std::string& pref_key,
510     const URLPatternSet& new_value) {
511   UpdateExtensionPref(extension_id, pref_key, new_value.ToValue().release());
512 }
513
514 bool ExtensionPrefs::ReadPrefAsBooleanAndReturn(
515     const std::string& extension_id,
516     const std::string& pref_key) const {
517   bool out_value = false;
518   return ReadPrefAsBoolean(extension_id, pref_key, &out_value) && out_value;
519 }
520
521 PermissionSet* ExtensionPrefs::ReadPrefAsPermissionSet(
522     const std::string& extension_id,
523     const std::string& pref_key) {
524   if (!GetExtensionPref(extension_id))
525     return NULL;
526
527   // Retrieve the API permissions. Please refer SetExtensionPrefPermissionSet()
528   // for api_values format.
529   APIPermissionSet apis;
530   const base::ListValue* api_values = NULL;
531   std::string api_pref = JoinPrefs(pref_key, kPrefAPIs);
532   if (ReadPrefAsList(extension_id, api_pref, &api_values)) {
533     APIPermissionSet::ParseFromJSON(api_values,
534                                     APIPermissionSet::kAllowInternalPermissions,
535                                     &apis, NULL, NULL);
536   }
537
538   // Retrieve the Manifest Keys permissions. Please refer to
539   // |SetExtensionPrefPermissionSet| for manifest_permissions_values format.
540   ManifestPermissionSet manifest_permissions;
541   const base::ListValue* manifest_permissions_values = NULL;
542   std::string manifest_permission_pref =
543       JoinPrefs(pref_key, kPrefManifestPermissions);
544   if (ReadPrefAsList(extension_id, manifest_permission_pref,
545                      &manifest_permissions_values)) {
546     ManifestPermissionSet::ParseFromJSON(
547         manifest_permissions_values, &manifest_permissions, NULL, NULL);
548   }
549
550   // Retrieve the explicit host permissions.
551   URLPatternSet explicit_hosts;
552   ReadPrefAsURLPatternSet(
553       extension_id, JoinPrefs(pref_key, kPrefExplicitHosts),
554       &explicit_hosts, Extension::kValidHostPermissionSchemes);
555
556   // Retrieve the scriptable host permissions.
557   URLPatternSet scriptable_hosts;
558   ReadPrefAsURLPatternSet(
559       extension_id, JoinPrefs(pref_key, kPrefScriptableHosts),
560       &scriptable_hosts, UserScript::ValidUserScriptSchemes());
561
562   return new PermissionSet(
563       apis, manifest_permissions, explicit_hosts, scriptable_hosts);
564 }
565
566 // Set the API or Manifest permissions.
567 // The format of api_values is:
568 // [ "permission_name1",   // permissions do not support detail.
569 //   "permission_name2",
570 //   {"permission_name3": value },
571 //   // permission supports detail, permission detail will be stored in value.
572 //   ...
573 // ]
574 template<typename T>
575 static base::ListValue* CreatePermissionList(const T& permissions) {
576   base::ListValue* values = new base::ListValue();
577   for (typename T::const_iterator i = permissions.begin();
578       i != permissions.end(); ++i) {
579     scoped_ptr<base::Value> detail(i->ToValue());
580     if (detail) {
581       base::DictionaryValue* tmp = new base::DictionaryValue();
582       tmp->Set(i->name(), detail.release());
583       values->Append(tmp);
584     } else {
585       values->Append(new base::StringValue(i->name()));
586     }
587   }
588   return values;
589 }
590
591 void ExtensionPrefs::SetExtensionPrefPermissionSet(
592     const std::string& extension_id,
593     const std::string& pref_key,
594     const PermissionSet* new_value) {
595   std::string api_pref = JoinPrefs(pref_key, kPrefAPIs);
596   base::ListValue* api_values = CreatePermissionList(new_value->apis());
597   UpdateExtensionPref(extension_id, api_pref, api_values);
598
599   std::string manifest_permissions_pref =
600       JoinPrefs(pref_key, kPrefManifestPermissions);
601   base::ListValue* manifest_permissions_values = CreatePermissionList(
602       new_value->manifest_permissions());
603   UpdateExtensionPref(extension_id,
604                       manifest_permissions_pref,
605                       manifest_permissions_values);
606
607   // Set the explicit host permissions.
608   if (!new_value->explicit_hosts().is_empty()) {
609     SetExtensionPrefURLPatternSet(extension_id,
610                                   JoinPrefs(pref_key, kPrefExplicitHosts),
611                                   new_value->explicit_hosts());
612   }
613
614   // Set the scriptable host permissions.
615   if (!new_value->scriptable_hosts().is_empty()) {
616     SetExtensionPrefURLPatternSet(extension_id,
617                                   JoinPrefs(pref_key, kPrefScriptableHosts),
618                                   new_value->scriptable_hosts());
619   }
620 }
621
622 int ExtensionPrefs::IncrementAcknowledgePromptCount(
623     const std::string& extension_id) {
624   int count = 0;
625   ReadPrefAsInteger(extension_id, kPrefAcknowledgePromptCount, &count);
626   ++count;
627   UpdateExtensionPref(extension_id, kPrefAcknowledgePromptCount,
628                       new base::FundamentalValue(count));
629   return count;
630 }
631
632 bool ExtensionPrefs::IsExternalExtensionAcknowledged(
633     const std::string& extension_id) {
634   return ReadPrefAsBooleanAndReturn(extension_id, kPrefExternalAcknowledged);
635 }
636
637 void ExtensionPrefs::AcknowledgeExternalExtension(
638     const std::string& extension_id) {
639   DCHECK(Extension::IdIsValid(extension_id));
640   UpdateExtensionPref(extension_id, kPrefExternalAcknowledged,
641                       new base::FundamentalValue(true));
642   UpdateExtensionPref(extension_id, kPrefAcknowledgePromptCount, NULL);
643 }
644
645 bool ExtensionPrefs::IsBlacklistedExtensionAcknowledged(
646     const std::string& extension_id) {
647   return ReadPrefAsBooleanAndReturn(extension_id, kPrefBlacklistAcknowledged);
648 }
649
650 void ExtensionPrefs::AcknowledgeBlacklistedExtension(
651     const std::string& extension_id) {
652   DCHECK(Extension::IdIsValid(extension_id));
653   UpdateExtensionPref(extension_id, kPrefBlacklistAcknowledged,
654                       new base::FundamentalValue(true));
655   UpdateExtensionPref(extension_id, kPrefAcknowledgePromptCount, NULL);
656 }
657
658 bool ExtensionPrefs::IsExternalInstallFirstRun(
659     const std::string& extension_id) {
660   return ReadPrefAsBooleanAndReturn(extension_id, kPrefExternalInstallFirstRun);
661 }
662
663 void ExtensionPrefs::SetExternalInstallFirstRun(
664     const std::string& extension_id) {
665   DCHECK(Extension::IdIsValid(extension_id));
666   UpdateExtensionPref(extension_id, kPrefExternalInstallFirstRun,
667                       new base::FundamentalValue(true));
668 }
669
670 bool ExtensionPrefs::HasWipeoutBeenAcknowledged(
671     const std::string& extension_id) {
672   return ReadPrefAsBooleanAndReturn(extension_id, kPrefWipeoutAcknowledged);
673 }
674
675 void ExtensionPrefs::SetWipeoutAcknowledged(
676     const std::string& extension_id,
677     bool value) {
678   UpdateExtensionPref(extension_id, kPrefWipeoutAcknowledged,
679                       value ? base::Value::CreateBooleanValue(value) : NULL);
680 }
681
682 bool ExtensionPrefs::SetAlertSystemFirstRun() {
683   if (prefs_->GetBoolean(pref_names::kAlertsInitialized)) {
684     return true;
685   }
686   prefs_->SetBoolean(pref_names::kAlertsInitialized, true);
687   return false;
688 }
689
690 bool ExtensionPrefs::ExtensionsBlacklistedByDefault() const {
691   return admin_policy::BlacklistedByDefault(
692       prefs_->GetList(pref_names::kInstallDenyList));
693 }
694
695 bool ExtensionPrefs::DidExtensionEscalatePermissions(
696     const std::string& extension_id) {
697   return ReadPrefAsBooleanAndReturn(extension_id,
698                                     kExtensionDidEscalatePermissions);
699 }
700
701 void ExtensionPrefs::SetDidExtensionEscalatePermissions(
702     const Extension* extension, bool did_escalate) {
703   UpdateExtensionPref(extension->id(), kExtensionDidEscalatePermissions,
704                       new base::FundamentalValue(did_escalate));
705 }
706
707 int ExtensionPrefs::GetDisableReasons(const std::string& extension_id) const {
708   int value = -1;
709   if (ReadPrefAsInteger(extension_id, kPrefDisableReasons, &value) &&
710       value >= 0) {
711     return value;
712   }
713   return Extension::DISABLE_NONE;
714 }
715
716 void ExtensionPrefs::AddDisableReason(const std::string& extension_id,
717                                       Extension::DisableReason disable_reason) {
718   int new_value = GetDisableReasons(extension_id) |
719       static_cast<int>(disable_reason);
720   UpdateExtensionPref(extension_id, kPrefDisableReasons,
721                       new base::FundamentalValue(new_value));
722 }
723
724 void ExtensionPrefs::RemoveDisableReason(
725     const std::string& extension_id,
726     Extension::DisableReason disable_reason) {
727   int new_value = GetDisableReasons(extension_id) &
728       ~static_cast<int>(disable_reason);
729   if (new_value == Extension::DISABLE_NONE) {
730     UpdateExtensionPref(extension_id, kPrefDisableReasons, NULL);
731   } else {
732     UpdateExtensionPref(extension_id, kPrefDisableReasons,
733                         new base::FundamentalValue(new_value));
734   }
735 }
736
737 void ExtensionPrefs::ClearDisableReasons(const std::string& extension_id) {
738   UpdateExtensionPref(extension_id, kPrefDisableReasons, NULL);
739 }
740
741 std::set<std::string> ExtensionPrefs::GetBlacklistedExtensions() {
742   std::set<std::string> ids;
743
744   const base::DictionaryValue* extensions =
745       prefs_->GetDictionary(pref_names::kExtensions);
746   if (!extensions)
747     return ids;
748
749   for (base::DictionaryValue::Iterator it(*extensions);
750        !it.IsAtEnd(); it.Advance()) {
751     if (!it.value().IsType(base::Value::TYPE_DICTIONARY)) {
752       NOTREACHED() << "Invalid pref for extension " << it.key();
753       continue;
754     }
755     if (IsBlacklistBitSet(
756             static_cast<const base::DictionaryValue*>(&it.value()))) {
757       ids.insert(it.key());
758     }
759   }
760
761   return ids;
762 }
763
764 void ExtensionPrefs::SetExtensionBlacklisted(const std::string& extension_id,
765                                              bool is_blacklisted) {
766   bool currently_blacklisted = IsExtensionBlacklisted(extension_id);
767   if (is_blacklisted == currently_blacklisted)
768     return;
769
770   // Always make sure the "acknowledged" bit is cleared since the blacklist bit
771   // is changing.
772   UpdateExtensionPref(extension_id, kPrefBlacklistAcknowledged, NULL);
773
774   if (is_blacklisted) {
775     UpdateExtensionPref(extension_id,
776                         kPrefBlacklist,
777                         new base::FundamentalValue(true));
778   } else {
779     UpdateExtensionPref(extension_id, kPrefBlacklist, NULL);
780     const base::DictionaryValue* dict = GetExtensionPref(extension_id);
781     if (dict && dict->empty())
782       DeleteExtensionPrefs(extension_id);
783   }
784 }
785
786 bool ExtensionPrefs::IsExtensionBlacklisted(const std::string& id) const {
787   const base::DictionaryValue* ext_prefs = GetExtensionPref(id);
788   return ext_prefs && IsBlacklistBitSet(ext_prefs);
789 }
790
791 namespace {
792
793 // Serializes |time| as a string value mapped to |key| in |dictionary|.
794 void SaveTime(base::DictionaryValue* dictionary,
795               const char* key,
796               const base::Time& time) {
797   if (!dictionary)
798     return;
799   std::string string_value = base::Int64ToString(time.ToInternalValue());
800   dictionary->SetString(key, string_value);
801 }
802
803 // The opposite of SaveTime. If |key| is not found, this returns an empty Time
804 // (is_null() will return true).
805 base::Time ReadTime(const base::DictionaryValue* dictionary, const char* key) {
806   if (!dictionary)
807     return base::Time();
808   std::string string_value;
809   int64 value;
810   if (dictionary->GetString(key, &string_value)) {
811     if (base::StringToInt64(string_value, &value)) {
812       return base::Time::FromInternalValue(value);
813     }
814   }
815   return base::Time();
816 }
817
818 }  // namespace
819
820 base::Time ExtensionPrefs::LastPingDay(const std::string& extension_id) const {
821   DCHECK(Extension::IdIsValid(extension_id));
822   return ReadTime(GetExtensionPref(extension_id), kLastPingDay);
823 }
824
825 void ExtensionPrefs::SetLastPingDay(const std::string& extension_id,
826                                     const base::Time& time) {
827   DCHECK(Extension::IdIsValid(extension_id));
828   ScopedExtensionPrefUpdate update(prefs_, extension_id);
829   SaveTime(update.Get(), kLastPingDay, time);
830 }
831
832 base::Time ExtensionPrefs::BlacklistLastPingDay() const {
833   return ReadTime(prefs_->GetDictionary(kExtensionsBlacklistUpdate),
834                   kLastPingDay);
835 }
836
837 void ExtensionPrefs::SetBlacklistLastPingDay(const base::Time& time) {
838   DictionaryPrefUpdate update(prefs_, kExtensionsBlacklistUpdate);
839   SaveTime(update.Get(), kLastPingDay, time);
840 }
841
842 base::Time ExtensionPrefs::LastActivePingDay(const std::string& extension_id) {
843   DCHECK(Extension::IdIsValid(extension_id));
844   return ReadTime(GetExtensionPref(extension_id), kLastActivePingDay);
845 }
846
847 void ExtensionPrefs::SetLastActivePingDay(const std::string& extension_id,
848                                           const base::Time& time) {
849   DCHECK(Extension::IdIsValid(extension_id));
850   ScopedExtensionPrefUpdate update(prefs_, extension_id);
851   SaveTime(update.Get(), kLastActivePingDay, time);
852 }
853
854 bool ExtensionPrefs::GetActiveBit(const std::string& extension_id) {
855   const base::DictionaryValue* dictionary = GetExtensionPref(extension_id);
856   bool result = false;
857   if (dictionary && dictionary->GetBoolean(kActiveBit, &result))
858     return result;
859   return false;
860 }
861
862 void ExtensionPrefs::SetActiveBit(const std::string& extension_id,
863                                   bool active) {
864   UpdateExtensionPref(extension_id, kActiveBit,
865                       new base::FundamentalValue(active));
866 }
867
868 void ExtensionPrefs::MigratePermissions(const ExtensionIdList& extension_ids) {
869   PermissionsInfo* info = PermissionsInfo::GetInstance();
870   for (ExtensionIdList::const_iterator ext_id =
871        extension_ids.begin(); ext_id != extension_ids.end(); ++ext_id) {
872     // An extension's granted permissions need to be migrated if the
873     // full_access bit is present. This bit was always present in the previous
874     // scheme and is never present now.
875     bool full_access;
876     const base::DictionaryValue* ext = GetExtensionPref(*ext_id);
877     if (!ext || !ext->GetBoolean(kPrefOldGrantedFullAccess, &full_access))
878       continue;
879
880     // Remove the full access bit (empty list will get trimmed).
881     UpdateExtensionPref(
882         *ext_id, kPrefOldGrantedFullAccess, new base::ListValue());
883
884     // Add the plugin permission if the full access bit was set.
885     if (full_access) {
886       const base::ListValue* apis = NULL;
887       base::ListValue* new_apis = NULL;
888
889       std::string granted_apis = JoinPrefs(kPrefGrantedPermissions, kPrefAPIs);
890       if (ext->GetList(kPrefOldGrantedAPIs, &apis))
891         new_apis = apis->DeepCopy();
892       else
893         new_apis = new base::ListValue();
894
895       std::string plugin_name = info->GetByID(APIPermission::kPlugin)->name();
896       new_apis->Append(new base::StringValue(plugin_name));
897       UpdateExtensionPref(*ext_id, granted_apis, new_apis);
898     }
899
900     // The granted permissions originally only held the effective hosts,
901     // which are a combination of host and user script host permissions.
902     // We now maintain these lists separately. For migration purposes, it
903     // does not matter how we treat the old effective hosts as long as the
904     // new effective hosts will be the same, so we move them to explicit
905     // host permissions.
906     const base::ListValue* hosts = NULL;
907     std::string explicit_hosts =
908         JoinPrefs(kPrefGrantedPermissions, kPrefExplicitHosts);
909     if (ext->GetList(kPrefOldGrantedHosts, &hosts)) {
910       UpdateExtensionPref(
911           *ext_id, explicit_hosts, hosts->DeepCopy());
912
913       // We can get rid of the old one by setting it to an empty list.
914       UpdateExtensionPref(*ext_id, kPrefOldGrantedHosts, new base::ListValue());
915     }
916   }
917 }
918
919 void ExtensionPrefs::MigrateDisableReasons(
920     const ExtensionIdList& extension_ids) {
921   for (ExtensionIdList::const_iterator ext_id =
922        extension_ids.begin(); ext_id != extension_ids.end(); ++ext_id) {
923     int value = -1;
924     if (ReadPrefAsInteger(*ext_id, kDeprecatedPrefDisableReason, &value)) {
925       int new_value = Extension::DISABLE_NONE;
926       switch (value) {
927         case Extension::DEPRECATED_DISABLE_USER_ACTION:
928           new_value = Extension::DISABLE_USER_ACTION;
929           break;
930         case Extension::DEPRECATED_DISABLE_PERMISSIONS_INCREASE:
931           new_value = Extension::DISABLE_PERMISSIONS_INCREASE;
932           break;
933         case Extension::DEPRECATED_DISABLE_RELOAD:
934           new_value = Extension::DISABLE_RELOAD;
935           break;
936       }
937
938       UpdateExtensionPref(*ext_id, kPrefDisableReasons,
939                           new base::FundamentalValue(new_value));
940       // Remove the old disable reason.
941       UpdateExtensionPref(*ext_id, kDeprecatedPrefDisableReason, NULL);
942     }
943   }
944 }
945
946 PermissionSet* ExtensionPrefs::GetGrantedPermissions(
947     const std::string& extension_id) {
948   CHECK(Extension::IdIsValid(extension_id));
949   return ReadPrefAsPermissionSet(extension_id, kPrefGrantedPermissions);
950 }
951
952 void ExtensionPrefs::AddGrantedPermissions(
953     const std::string& extension_id,
954     const PermissionSet* permissions) {
955   CHECK(Extension::IdIsValid(extension_id));
956
957   scoped_refptr<PermissionSet> granted_permissions(
958       GetGrantedPermissions(extension_id));
959
960   // The new granted permissions are the union of the already granted
961   // permissions and the newly granted permissions.
962   scoped_refptr<PermissionSet> new_perms(
963       PermissionSet::CreateUnion(
964           permissions, granted_permissions.get()));
965
966   SetExtensionPrefPermissionSet(
967       extension_id, kPrefGrantedPermissions, new_perms.get());
968 }
969
970 void ExtensionPrefs::RemoveGrantedPermissions(
971     const std::string& extension_id,
972     const PermissionSet* permissions) {
973   CHECK(Extension::IdIsValid(extension_id));
974
975   scoped_refptr<PermissionSet> granted_permissions(
976       GetGrantedPermissions(extension_id));
977
978   // The new granted permissions are the difference of the already granted
979   // permissions and the newly ungranted permissions.
980   scoped_refptr<PermissionSet> new_perms(
981       PermissionSet::CreateDifference(
982           granted_permissions.get(), permissions));
983
984   SetExtensionPrefPermissionSet(
985       extension_id, kPrefGrantedPermissions, new_perms.get());
986 }
987
988 PermissionSet* ExtensionPrefs::GetActivePermissions(
989     const std::string& extension_id) {
990   CHECK(Extension::IdIsValid(extension_id));
991   return ReadPrefAsPermissionSet(extension_id, kPrefActivePermissions);
992 }
993
994 void ExtensionPrefs::SetActivePermissions(
995     const std::string& extension_id,
996     const PermissionSet* permissions) {
997   SetExtensionPrefPermissionSet(
998       extension_id, kPrefActivePermissions, permissions);
999 }
1000
1001 void ExtensionPrefs::SetExtensionRunning(const std::string& extension_id,
1002     bool is_running) {
1003   base::Value* value = new base::FundamentalValue(is_running);
1004   UpdateExtensionPref(extension_id, kPrefRunning, value);
1005 }
1006
1007 bool ExtensionPrefs::IsExtensionRunning(const std::string& extension_id) {
1008   const base::DictionaryValue* extension = GetExtensionPref(extension_id);
1009   if (!extension)
1010     return false;
1011   bool running = false;
1012   extension->GetBoolean(kPrefRunning, &running);
1013   return running;
1014 }
1015
1016 void ExtensionPrefs::SetIsActive(const std::string& extension_id,
1017                                  bool is_active) {
1018   base::Value* value = new base::FundamentalValue(is_active);
1019   UpdateExtensionPref(extension_id, kIsActive, value);
1020 }
1021
1022 bool ExtensionPrefs::IsActive(const std::string& extension_id) {
1023   const base::DictionaryValue* extension = GetExtensionPref(extension_id);
1024   if (!extension)
1025     return false;
1026   bool is_active = false;
1027   extension->GetBoolean(kIsActive, &is_active);
1028   return is_active;
1029 }
1030
1031 bool ExtensionPrefs::IsIncognitoEnabled(const std::string& extension_id) const {
1032   return ReadPrefAsBooleanAndReturn(extension_id, kPrefIncognitoEnabled);
1033 }
1034
1035 void ExtensionPrefs::SetIsIncognitoEnabled(const std::string& extension_id,
1036                                            bool enabled) {
1037   UpdateExtensionPref(extension_id, kPrefIncognitoEnabled,
1038                       new base::FundamentalValue(enabled));
1039 }
1040
1041 bool ExtensionPrefs::AllowFileAccess(const std::string& extension_id) const {
1042   return ReadPrefAsBooleanAndReturn(extension_id, kPrefAllowFileAccess);
1043 }
1044
1045 void ExtensionPrefs::SetAllowFileAccess(const std::string& extension_id,
1046                                         bool allow) {
1047   UpdateExtensionPref(extension_id, kPrefAllowFileAccess,
1048                       new base::FundamentalValue(allow));
1049 }
1050
1051 bool ExtensionPrefs::HasAllowFileAccessSetting(
1052     const std::string& extension_id) const {
1053   const base::DictionaryValue* ext = GetExtensionPref(extension_id);
1054   return ext && ext->HasKey(kPrefAllowFileAccess);
1055 }
1056
1057 bool ExtensionPrefs::DoesExtensionHaveState(
1058     const std::string& id, Extension::State check_state) const {
1059   const base::DictionaryValue* extension = GetExtensionPref(id);
1060   int state = -1;
1061   if (!extension || !extension->GetInteger(kPrefState, &state))
1062     return false;
1063
1064   if (state < 0 || state >= Extension::NUM_STATES) {
1065     LOG(ERROR) << "Bad pref 'state' for extension '" << id << "'";
1066     return false;
1067   }
1068
1069   return state == check_state;
1070 }
1071
1072 bool ExtensionPrefs::IsExternalExtensionUninstalled(
1073     const std::string& id) const {
1074   return DoesExtensionHaveState(id, Extension::EXTERNAL_EXTENSION_UNINSTALLED);
1075 }
1076
1077 bool ExtensionPrefs::IsExtensionDisabled(
1078     const std::string& id) const {
1079   return DoesExtensionHaveState(id, Extension::DISABLED);
1080 }
1081
1082 ExtensionIdList ExtensionPrefs::GetToolbarOrder() {
1083   ExtensionIdList id_list_out;
1084   GetUserExtensionPrefIntoContainer(pref_names::kToolbar, &id_list_out);
1085   return id_list_out;
1086 }
1087
1088 void ExtensionPrefs::SetToolbarOrder(const ExtensionIdList& extension_ids) {
1089   SetExtensionPrefFromContainer(pref_names::kToolbar, extension_ids);
1090 }
1091
1092 bool ExtensionPrefs::GetKnownDisabled(ExtensionIdSet* id_set_out) {
1093   return GetUserExtensionPrefIntoContainer(pref_names::kKnownDisabled,
1094                                            id_set_out);
1095 }
1096
1097 void ExtensionPrefs::SetKnownDisabled(const ExtensionIdSet& extension_ids) {
1098   SetExtensionPrefFromContainer(pref_names::kKnownDisabled, extension_ids);
1099 }
1100
1101 void ExtensionPrefs::OnExtensionInstalled(
1102     const Extension* extension,
1103     Extension::State initial_state,
1104     bool blacklisted_for_malware,
1105     const syncer::StringOrdinal& page_ordinal) {
1106   ScopedExtensionPrefUpdate update(prefs_, extension->id());
1107   base::DictionaryValue* extension_dict = update.Get();
1108   const base::Time install_time = time_provider_->GetCurrentTime();
1109   PopulateExtensionInfoPrefs(extension, install_time, initial_state,
1110                              blacklisted_for_malware, extension_dict);
1111   FinishExtensionInfoPrefs(extension->id(), install_time,
1112                            extension->RequiresSortOrdinal(),
1113                            page_ordinal, extension_dict);
1114 }
1115
1116 void ExtensionPrefs::OnExtensionUninstalled(const std::string& extension_id,
1117                                             const Manifest::Location& location,
1118                                             bool external_uninstall) {
1119   app_sorting_->ClearOrdinals(extension_id);
1120
1121   // For external extensions, we save a preference reminding ourself not to try
1122   // and install the extension anymore (except when |external_uninstall| is
1123   // true, which signifies that the registry key was deleted or the pref file
1124   // no longer lists the extension).
1125   if (!external_uninstall && Manifest::IsExternalLocation(location)) {
1126     UpdateExtensionPref(extension_id, kPrefState,
1127                         new base::FundamentalValue(
1128                             Extension::EXTERNAL_EXTENSION_UNINSTALLED));
1129     extension_pref_value_map_->SetExtensionState(extension_id, false);
1130     content_settings_store_->SetExtensionState(extension_id, false);
1131   } else {
1132     DeleteExtensionPrefs(extension_id);
1133   }
1134 }
1135
1136 void ExtensionPrefs::SetExtensionState(const std::string& extension_id,
1137                                        Extension::State state) {
1138   UpdateExtensionPref(extension_id, kPrefState,
1139                       new base::FundamentalValue(state));
1140   bool enabled = (state == Extension::ENABLED);
1141   extension_pref_value_map_->SetExtensionState(extension_id, enabled);
1142   content_settings_store_->SetExtensionState(extension_id, enabled);
1143 }
1144
1145 void ExtensionPrefs::SetExtensionBlacklistState(const std::string& extension_id,
1146                                                 BlacklistState state) {
1147   SetExtensionBlacklisted(extension_id, state == BLACKLISTED_MALWARE);
1148   UpdateExtensionPref(extension_id, kPrefBlacklistState,
1149                       new base::FundamentalValue(state));
1150 }
1151
1152 BlacklistState ExtensionPrefs::GetExtensionBlacklistState(
1153     const std::string& extension_id) {
1154   if (IsExtensionBlacklisted(extension_id))
1155     return BLACKLISTED_MALWARE;
1156   const base::DictionaryValue* ext_prefs = GetExtensionPref(extension_id);
1157   int int_value;
1158   if (ext_prefs && ext_prefs->GetInteger(kPrefBlacklistState, &int_value))
1159     return static_cast<BlacklistState>(int_value);
1160
1161   return NOT_BLACKLISTED;
1162 }
1163
1164 std::string ExtensionPrefs::GetVersionString(const std::string& extension_id) {
1165   const base::DictionaryValue* extension = GetExtensionPref(extension_id);
1166   if (!extension)
1167     return std::string();
1168
1169   std::string version;
1170   extension->GetString(kPrefVersion, &version);
1171
1172   return version;
1173 }
1174
1175 void ExtensionPrefs::UpdateManifest(const Extension* extension) {
1176   if (!Manifest::IsUnpackedLocation(extension->location())) {
1177     const base::DictionaryValue* extension_dict =
1178         GetExtensionPref(extension->id());
1179     if (!extension_dict)
1180       return;
1181     const base::DictionaryValue* old_manifest = NULL;
1182     bool update_required =
1183         !extension_dict->GetDictionary(kPrefManifest, &old_manifest) ||
1184         !extension->manifest()->value()->Equals(old_manifest);
1185     if (update_required) {
1186       UpdateExtensionPref(extension->id(), kPrefManifest,
1187                           extension->manifest()->value()->DeepCopy());
1188     }
1189   }
1190 }
1191
1192 base::FilePath ExtensionPrefs::GetExtensionPath(
1193     const std::string& extension_id) {
1194   const base::DictionaryValue* dict = GetExtensionPref(extension_id);
1195   if (!dict)
1196     return base::FilePath();
1197
1198   std::string path;
1199   if (!dict->GetString(kPrefPath, &path))
1200     return base::FilePath();
1201
1202   return install_directory_.Append(base::FilePath::FromUTF8Unsafe(path));
1203 }
1204
1205 scoped_ptr<ExtensionInfo> ExtensionPrefs::GetInstalledInfoHelper(
1206     const std::string& extension_id,
1207     const base::DictionaryValue* extension) const {
1208   int location_value;
1209   if (!extension->GetInteger(kPrefLocation, &location_value))
1210     return scoped_ptr<ExtensionInfo>();
1211
1212   base::FilePath::StringType path;
1213   if (!extension->GetString(kPrefPath, &path))
1214     return scoped_ptr<ExtensionInfo>();
1215
1216   // Make path absolute. Unpacked extensions will already have absolute paths,
1217   // otherwise make it so.
1218   Manifest::Location location = static_cast<Manifest::Location>(location_value);
1219   if (!Manifest::IsUnpackedLocation(location)) {
1220     DCHECK(location == Manifest::COMPONENT ||
1221            !base::FilePath(path).IsAbsolute());
1222     path = install_directory_.Append(path).value();
1223   }
1224
1225   // Only the following extension types have data saved in the preferences.
1226   if (location != Manifest::INTERNAL &&
1227       !Manifest::IsUnpackedLocation(location) &&
1228       !Manifest::IsExternalLocation(location)) {
1229     NOTREACHED();
1230     return scoped_ptr<ExtensionInfo>();
1231   }
1232
1233   const base::DictionaryValue* manifest = NULL;
1234   if (!Manifest::IsUnpackedLocation(location) &&
1235       !extension->GetDictionary(kPrefManifest, &manifest)) {
1236     LOG(WARNING) << "Missing manifest for extension " << extension_id;
1237     // Just a warning for now.
1238   }
1239
1240   return scoped_ptr<ExtensionInfo>(new ExtensionInfo(
1241       manifest, extension_id, base::FilePath(path), location));
1242 }
1243
1244 scoped_ptr<ExtensionInfo> ExtensionPrefs::GetInstalledExtensionInfo(
1245     const std::string& extension_id) const {
1246   const base::DictionaryValue* ext = NULL;
1247   const base::DictionaryValue* extensions =
1248       prefs_->GetDictionary(pref_names::kExtensions);
1249   if (!extensions ||
1250       !extensions->GetDictionaryWithoutPathExpansion(extension_id, &ext))
1251     return scoped_ptr<ExtensionInfo>();
1252   int state_value;
1253   if (!ext->GetInteger(kPrefState, &state_value) ||
1254       state_value == Extension::ENABLED_COMPONENT) {
1255     // Old preferences files may not have kPrefState for component extensions.
1256     return scoped_ptr<ExtensionInfo>();
1257   }
1258
1259   if (state_value == Extension::EXTERNAL_EXTENSION_UNINSTALLED) {
1260     LOG(WARNING) << "External extension with id " << extension_id
1261                  << " has been uninstalled by the user";
1262     return scoped_ptr<ExtensionInfo>();
1263   }
1264
1265   return GetInstalledInfoHelper(extension_id, ext);
1266 }
1267
1268 scoped_ptr<ExtensionPrefs::ExtensionsInfo>
1269 ExtensionPrefs::GetInstalledExtensionsInfo() const {
1270   scoped_ptr<ExtensionsInfo> extensions_info(new ExtensionsInfo);
1271
1272   const base::DictionaryValue* extensions =
1273       prefs_->GetDictionary(pref_names::kExtensions);
1274   for (base::DictionaryValue::Iterator extension_id(*extensions);
1275        !extension_id.IsAtEnd(); extension_id.Advance()) {
1276     if (!Extension::IdIsValid(extension_id.key()))
1277       continue;
1278
1279     scoped_ptr<ExtensionInfo> info =
1280         GetInstalledExtensionInfo(extension_id.key());
1281     if (info)
1282       extensions_info->push_back(linked_ptr<ExtensionInfo>(info.release()));
1283   }
1284
1285   return extensions_info.Pass();
1286 }
1287
1288 scoped_ptr<ExtensionPrefs::ExtensionsInfo>
1289 ExtensionPrefs::GetUninstalledExtensionsInfo() const {
1290   scoped_ptr<ExtensionsInfo> extensions_info(new ExtensionsInfo);
1291
1292   const base::DictionaryValue* extensions =
1293       prefs_->GetDictionary(pref_names::kExtensions);
1294   for (base::DictionaryValue::Iterator extension_id(*extensions);
1295        !extension_id.IsAtEnd(); extension_id.Advance()) {
1296     const base::DictionaryValue* ext = NULL;
1297     if (!Extension::IdIsValid(extension_id.key()) ||
1298         !IsExternalExtensionUninstalled(extension_id.key()) ||
1299         !extension_id.value().GetAsDictionary(&ext))
1300       continue;
1301
1302     scoped_ptr<ExtensionInfo> info =
1303         GetInstalledInfoHelper(extension_id.key(), ext);
1304     if (info)
1305       extensions_info->push_back(linked_ptr<ExtensionInfo>(info.release()));
1306   }
1307
1308   return extensions_info.Pass();
1309 }
1310
1311 void ExtensionPrefs::SetDelayedInstallInfo(
1312     const Extension* extension,
1313     Extension::State initial_state,
1314     bool blacklisted_for_malware,
1315     DelayReason delay_reason,
1316     const syncer::StringOrdinal& page_ordinal) {
1317   base::DictionaryValue* extension_dict = new base::DictionaryValue();
1318   PopulateExtensionInfoPrefs(extension, time_provider_->GetCurrentTime(),
1319                              initial_state, blacklisted_for_malware,
1320                              extension_dict);
1321
1322   // Add transient data that is needed by FinishDelayedInstallInfo(), but
1323   // should not be in the final extension prefs. All entries here should have
1324   // a corresponding Remove() call in FinishDelayedInstallInfo().
1325   if (extension->RequiresSortOrdinal()) {
1326     extension_dict->SetString(
1327         kPrefSuggestedPageOrdinal,
1328         page_ordinal.IsValid() ? page_ordinal.ToInternalValue()
1329                                : std::string());
1330   }
1331   extension_dict->SetInteger(kDelayedInstallReason,
1332                              static_cast<int>(delay_reason));
1333
1334   UpdateExtensionPref(extension->id(), kDelayedInstallInfo, extension_dict);
1335 }
1336
1337 bool ExtensionPrefs::RemoveDelayedInstallInfo(
1338     const std::string& extension_id) {
1339   if (!GetExtensionPref(extension_id))
1340     return false;
1341   ScopedExtensionPrefUpdate update(prefs_, extension_id);
1342   bool result = update->Remove(kDelayedInstallInfo, NULL);
1343   return result;
1344 }
1345
1346 bool ExtensionPrefs::FinishDelayedInstallInfo(
1347     const std::string& extension_id) {
1348   CHECK(Extension::IdIsValid(extension_id));
1349   ScopedExtensionPrefUpdate update(prefs_, extension_id);
1350   base::DictionaryValue* extension_dict = update.Get();
1351   base::DictionaryValue* pending_install_dict = NULL;
1352   if (!extension_dict->GetDictionary(kDelayedInstallInfo,
1353                                      &pending_install_dict)) {
1354     return false;
1355   }
1356
1357   // Retrieve and clear transient values populated by SetDelayedInstallInfo().
1358   // Also do any other data cleanup that makes sense.
1359   std::string serialized_ordinal;
1360   syncer::StringOrdinal suggested_page_ordinal;
1361   bool needs_sort_ordinal = false;
1362   if (pending_install_dict->GetString(kPrefSuggestedPageOrdinal,
1363                                       &serialized_ordinal)) {
1364     suggested_page_ordinal = syncer::StringOrdinal(serialized_ordinal);
1365     needs_sort_ordinal = true;
1366     pending_install_dict->Remove(kPrefSuggestedPageOrdinal, NULL);
1367   }
1368   pending_install_dict->Remove(kDelayedInstallReason, NULL);
1369
1370   const base::Time install_time = time_provider_->GetCurrentTime();
1371   pending_install_dict->Set(
1372       kPrefInstallTime,
1373       new base::StringValue(
1374           base::Int64ToString(install_time.ToInternalValue())));
1375
1376   // Commit the delayed install data.
1377   for (base::DictionaryValue::Iterator it(*pending_install_dict); !it.IsAtEnd();
1378        it.Advance()) {
1379     extension_dict->Set(it.key(), it.value().DeepCopy());
1380   }
1381   FinishExtensionInfoPrefs(extension_id, install_time, needs_sort_ordinal,
1382                            suggested_page_ordinal, extension_dict);
1383   return true;
1384 }
1385
1386 scoped_ptr<ExtensionInfo> ExtensionPrefs::GetDelayedInstallInfo(
1387     const std::string& extension_id) const {
1388   const base::DictionaryValue* extension_prefs =
1389       GetExtensionPref(extension_id);
1390   if (!extension_prefs)
1391     return scoped_ptr<ExtensionInfo>();
1392
1393   const base::DictionaryValue* ext = NULL;
1394   if (!extension_prefs->GetDictionary(kDelayedInstallInfo, &ext))
1395     return scoped_ptr<ExtensionInfo>();
1396
1397   return GetInstalledInfoHelper(extension_id, ext);
1398 }
1399
1400 ExtensionPrefs::DelayReason ExtensionPrefs::GetDelayedInstallReason(
1401     const std::string& extension_id) const {
1402   const base::DictionaryValue* extension_prefs =
1403       GetExtensionPref(extension_id);
1404   if (!extension_prefs)
1405     return DELAY_REASON_NONE;
1406
1407   const base::DictionaryValue* ext = NULL;
1408   if (!extension_prefs->GetDictionary(kDelayedInstallInfo, &ext))
1409     return DELAY_REASON_NONE;
1410
1411   int delay_reason;
1412   if (!ext->GetInteger(kDelayedInstallReason, &delay_reason))
1413     return DELAY_REASON_NONE;
1414
1415   return static_cast<DelayReason>(delay_reason);
1416 }
1417
1418 scoped_ptr<ExtensionPrefs::ExtensionsInfo> ExtensionPrefs::
1419     GetAllDelayedInstallInfo() const {
1420   scoped_ptr<ExtensionsInfo> extensions_info(new ExtensionsInfo);
1421
1422   const base::DictionaryValue* extensions =
1423       prefs_->GetDictionary(pref_names::kExtensions);
1424   for (base::DictionaryValue::Iterator extension_id(*extensions);
1425        !extension_id.IsAtEnd(); extension_id.Advance()) {
1426     if (!Extension::IdIsValid(extension_id.key()))
1427       continue;
1428
1429     scoped_ptr<ExtensionInfo> info = GetDelayedInstallInfo(extension_id.key());
1430     if (info)
1431       extensions_info->push_back(linked_ptr<ExtensionInfo>(info.release()));
1432   }
1433
1434   return extensions_info.Pass();
1435 }
1436
1437 bool ExtensionPrefs::WasAppDraggedByUser(const std::string& extension_id) {
1438   return ReadPrefAsBooleanAndReturn(extension_id, kPrefUserDraggedApp);
1439 }
1440
1441 void ExtensionPrefs::SetAppDraggedByUser(const std::string& extension_id) {
1442   UpdateExtensionPref(extension_id, kPrefUserDraggedApp,
1443                       new base::FundamentalValue(true));
1444 }
1445
1446 bool ExtensionPrefs::IsFromWebStore(
1447     const std::string& extension_id) const {
1448   const base::DictionaryValue* dictionary = GetExtensionPref(extension_id);
1449   bool result = false;
1450   if (dictionary && dictionary->GetBoolean(kPrefFromWebStore, &result))
1451     return result;
1452   return false;
1453 }
1454
1455 bool ExtensionPrefs::IsFromBookmark(
1456     const std::string& extension_id) const {
1457   const base::DictionaryValue* dictionary = GetExtensionPref(extension_id);
1458   bool result = false;
1459   if (dictionary && dictionary->GetBoolean(kPrefFromBookmark, &result))
1460     return result;
1461   return false;
1462 }
1463
1464 int ExtensionPrefs::GetCreationFlags(const std::string& extension_id) const {
1465   int creation_flags = Extension::NO_FLAGS;
1466   if (!ReadPrefAsInteger(extension_id, kPrefCreationFlags, &creation_flags)) {
1467     // Since kPrefCreationFlags was added later, it will be missing for
1468     // previously installed extensions.
1469     if (IsFromBookmark(extension_id))
1470       creation_flags |= Extension::FROM_BOOKMARK;
1471     if (IsFromWebStore(extension_id))
1472       creation_flags |= Extension::FROM_WEBSTORE;
1473     if (WasInstalledByDefault(extension_id))
1474       creation_flags |= Extension::WAS_INSTALLED_BY_DEFAULT;
1475   }
1476   return creation_flags;
1477 }
1478
1479 int ExtensionPrefs::GetDelayedInstallCreationFlags(
1480     const std::string& extension_id) const {
1481   int creation_flags = Extension::NO_FLAGS;
1482   const base::DictionaryValue* delayed_info = NULL;
1483   if (ReadPrefAsDictionary(extension_id, kDelayedInstallInfo, &delayed_info)) {
1484     delayed_info->GetInteger(kPrefCreationFlags, &creation_flags);
1485   }
1486   return creation_flags;
1487 }
1488
1489 bool ExtensionPrefs::WasInstalledByDefault(
1490     const std::string& extension_id) const {
1491   const base::DictionaryValue* dictionary = GetExtensionPref(extension_id);
1492   bool result = false;
1493   if (dictionary &&
1494       dictionary->GetBoolean(kPrefWasInstalledByDefault, &result))
1495     return result;
1496   return false;
1497 }
1498
1499 base::Time ExtensionPrefs::GetInstallTime(
1500     const std::string& extension_id) const {
1501   const base::DictionaryValue* extension = GetExtensionPref(extension_id);
1502   if (!extension) {
1503     NOTREACHED();
1504     return base::Time();
1505   }
1506   std::string install_time_str;
1507   if (!extension->GetString(kPrefInstallTime, &install_time_str))
1508     return base::Time();
1509   int64 install_time_i64 = 0;
1510   if (!base::StringToInt64(install_time_str, &install_time_i64))
1511     return base::Time();
1512   return base::Time::FromInternalValue(install_time_i64);
1513 }
1514
1515 base::Time ExtensionPrefs::GetLastLaunchTime(
1516     const std::string& extension_id) const {
1517   const base::DictionaryValue* extension = GetExtensionPref(extension_id);
1518   if (!extension)
1519     return base::Time();
1520
1521   std::string launch_time_str;
1522   if (!extension->GetString(kPrefLastLaunchTime, &launch_time_str))
1523     return base::Time();
1524   int64 launch_time_i64 = 0;
1525   if (!base::StringToInt64(launch_time_str, &launch_time_i64))
1526     return base::Time();
1527   return base::Time::FromInternalValue(launch_time_i64);
1528 }
1529
1530 void ExtensionPrefs::SetLastLaunchTime(const std::string& extension_id,
1531                                        const base::Time& time) {
1532   DCHECK(Extension::IdIsValid(extension_id));
1533   ScopedExtensionPrefUpdate update(prefs_, extension_id);
1534   SaveTime(update.Get(), kPrefLastLaunchTime, time);
1535 }
1536
1537 void ExtensionPrefs::GetExtensions(ExtensionIdList* out) {
1538   CHECK(out);
1539
1540   scoped_ptr<ExtensionsInfo> extensions_info(GetInstalledExtensionsInfo());
1541
1542   for (size_t i = 0; i < extensions_info->size(); ++i) {
1543     ExtensionInfo* info = extensions_info->at(i).get();
1544     out->push_back(info->extension_id);
1545   }
1546 }
1547
1548 // static
1549 ExtensionIdList ExtensionPrefs::GetExtensionsFrom(
1550     const PrefService* pref_service) {
1551   ExtensionIdList result;
1552
1553   const base::DictionaryValue* extension_prefs = NULL;
1554   const base::Value* extension_prefs_value =
1555       pref_service->GetUserPrefValue(pref_names::kExtensions);
1556   if (!extension_prefs_value ||
1557       !extension_prefs_value->GetAsDictionary(&extension_prefs)) {
1558     return result;  // Empty set
1559   }
1560
1561   for (base::DictionaryValue::Iterator it(*extension_prefs); !it.IsAtEnd();
1562        it.Advance()) {
1563     const base::DictionaryValue* ext = NULL;
1564     if (!it.value().GetAsDictionary(&ext)) {
1565       NOTREACHED() << "Invalid pref for extension " << it.key();
1566       continue;
1567     }
1568     if (!IsBlacklistBitSet(ext))
1569       result.push_back(it.key());
1570   }
1571   return result;
1572 }
1573
1574 void ExtensionPrefs::FixMissingPrefs(const ExtensionIdList& extension_ids) {
1575   // Fix old entries that did not get an installation time entry when they
1576   // were installed or don't have a preferences field.
1577   for (ExtensionIdList::const_iterator ext_id = extension_ids.begin();
1578        ext_id != extension_ids.end(); ++ext_id) {
1579     if (GetInstallTime(*ext_id) == base::Time()) {
1580       VLOG(1) << "Could not parse installation time of extension "
1581               << *ext_id << ". It was probably installed before setting "
1582               << kPrefInstallTime << " was introduced. Updating "
1583               << kPrefInstallTime << " to the current time.";
1584       const base::Time install_time = time_provider_->GetCurrentTime();
1585       UpdateExtensionPref(*ext_id,
1586                           kPrefInstallTime,
1587                           new base::StringValue(base::Int64ToString(
1588                               install_time.ToInternalValue())));
1589     }
1590   }
1591 }
1592
1593 void ExtensionPrefs::InitPrefStore() {
1594   if (extensions_disabled_) {
1595     extension_pref_value_map_->NotifyInitializationCompleted();
1596     return;
1597   }
1598
1599   // When this is called, the PrefService is initialized and provides access
1600   // to the user preferences stored in a JSON file.
1601   ExtensionIdList extension_ids;
1602   GetExtensions(&extension_ids);
1603   // Create empty preferences dictionary for each extension (these dictionaries
1604   // are pruned when persisting the preferences to disk).
1605   for (ExtensionIdList::iterator ext_id = extension_ids.begin();
1606        ext_id != extension_ids.end(); ++ext_id) {
1607     ScopedExtensionPrefUpdate update(prefs_, *ext_id);
1608     // This creates an empty dictionary if none is stored.
1609     update.Get();
1610   }
1611
1612   FixMissingPrefs(extension_ids);
1613   MigratePermissions(extension_ids);
1614   MigrateDisableReasons(extension_ids);
1615   app_sorting_->Initialize(extension_ids);
1616
1617   PreferenceAPI::InitExtensionControlledPrefs(this, extension_pref_value_map_);
1618
1619   extension_pref_value_map_->NotifyInitializationCompleted();
1620 }
1621
1622 bool ExtensionPrefs::HasIncognitoPrefValue(const std::string& pref_key) {
1623   bool has_incognito_pref_value = false;
1624   extension_pref_value_map_->GetEffectivePrefValue(pref_key,
1625                                                    true,
1626                                                    &has_incognito_pref_value);
1627   return has_incognito_pref_value;
1628 }
1629
1630 URLPatternSet ExtensionPrefs::GetAllowedInstallSites() {
1631   URLPatternSet result;
1632   const base::ListValue* list =
1633       prefs_->GetList(pref_names::kAllowedInstallSites);
1634   CHECK(list);
1635
1636   for (size_t i = 0; i < list->GetSize(); ++i) {
1637     std::string entry_string;
1638     URLPattern entry(URLPattern::SCHEME_ALL);
1639     if (!list->GetString(i, &entry_string) ||
1640         entry.Parse(entry_string) != URLPattern::PARSE_SUCCESS) {
1641       LOG(ERROR) << "Invalid value for preference: "
1642                  << pref_names::kAllowedInstallSites << "." << i;
1643       continue;
1644     }
1645     result.AddPattern(entry);
1646   }
1647
1648   return result;
1649 }
1650
1651 const base::DictionaryValue* ExtensionPrefs::GetGeometryCache(
1652     const std::string& extension_id) const {
1653   const base::DictionaryValue* extension_prefs = GetExtensionPref(extension_id);
1654   if (!extension_prefs)
1655     return NULL;
1656
1657   const base::DictionaryValue* ext = NULL;
1658   if (!extension_prefs->GetDictionary(kPrefGeometryCache, &ext))
1659     return NULL;
1660
1661   return ext;
1662 }
1663
1664 void ExtensionPrefs::SetGeometryCache(
1665     const std::string& extension_id,
1666     scoped_ptr<base::DictionaryValue> cache) {
1667   UpdateExtensionPref(extension_id, kPrefGeometryCache, cache.release());
1668 }
1669
1670 const base::DictionaryValue* ExtensionPrefs::GetInstallSignature() {
1671   return prefs_->GetDictionary(kInstallSignature);
1672 }
1673
1674 void ExtensionPrefs::SetInstallSignature(
1675     const base::DictionaryValue* signature) {
1676   if (signature) {
1677     prefs_->Set(kInstallSignature, *signature);
1678     DVLOG(1) << "SetInstallSignature - saving";
1679   } else {
1680     DVLOG(1) << "SetInstallSignature - clearing";
1681     prefs_->ClearPref(kInstallSignature);
1682   }
1683 }
1684
1685
1686 ExtensionPrefs::ExtensionPrefs(
1687     PrefService* prefs,
1688     const base::FilePath& root_dir,
1689     ExtensionPrefValueMap* extension_pref_value_map,
1690     scoped_ptr<AppSorting> app_sorting,
1691     scoped_ptr<TimeProvider> time_provider,
1692     bool extensions_disabled)
1693     : prefs_(prefs),
1694       install_directory_(root_dir),
1695       extension_pref_value_map_(extension_pref_value_map),
1696       app_sorting_(app_sorting.Pass()),
1697       content_settings_store_(new ContentSettingsStore()),
1698       time_provider_(time_provider.Pass()),
1699       extensions_disabled_(extensions_disabled) {
1700   app_sorting_->SetExtensionScopedPrefs(this);
1701   MakePathsRelative();
1702   InitPrefStore();
1703 }
1704
1705 void ExtensionPrefs::SetNeedsStorageGarbageCollection(bool value) {
1706   prefs_->SetBoolean(pref_names::kStorageGarbageCollect, value);
1707 }
1708
1709 bool ExtensionPrefs::NeedsStorageGarbageCollection() {
1710   return prefs_->GetBoolean(pref_names::kStorageGarbageCollect);
1711 }
1712
1713 // static
1714 void ExtensionPrefs::RegisterProfilePrefs(
1715     user_prefs::PrefRegistrySyncable* registry) {
1716   registry->RegisterDictionaryPref(
1717       pref_names::kExtensions,
1718       user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
1719   registry->RegisterListPref(pref_names::kToolbar,
1720                              user_prefs::PrefRegistrySyncable::SYNCABLE_PREF);
1721   registry->RegisterIntegerPref(
1722       pref_names::kToolbarSize,
1723       -1,  // default value
1724       user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
1725   registry->RegisterDictionaryPref(
1726       kExtensionsBlacklistUpdate,
1727       user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
1728   registry->RegisterListPref(pref_names::kInstallAllowList,
1729                              user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
1730   registry->RegisterListPref(pref_names::kInstallDenyList,
1731                              user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
1732   registry->RegisterDictionaryPref(
1733       pref_names::kInstallForceList,
1734       user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
1735   registry->RegisterListPref(pref_names::kAllowedTypes,
1736                              user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
1737   registry->RegisterBooleanPref(
1738       pref_names::kStorageGarbageCollect,
1739       false,  // default value
1740       user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
1741   registry->RegisterInt64Pref(
1742       pref_names::kLastUpdateCheck,
1743       0,  // default value
1744       user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
1745   registry->RegisterInt64Pref(
1746       pref_names::kNextUpdateCheck,
1747       0,  // default value
1748       user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
1749   registry->RegisterListPref(pref_names::kAllowedInstallSites,
1750                              user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
1751   registry->RegisterStringPref(
1752       pref_names::kLastChromeVersion,
1753       std::string(),  // default value
1754       user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
1755   registry->RegisterListPref(pref_names::kKnownDisabled,
1756                              user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
1757 #if defined(TOOLKIT_VIEWS)
1758   registry->RegisterIntegerPref(
1759       pref_names::kBrowserActionContainerWidth,
1760       0,
1761       user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
1762 #endif
1763   registry->RegisterDictionaryPref(
1764       kInstallSignature,
1765       user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
1766
1767   registry->RegisterListPref(pref_names::kNativeMessagingBlacklist,
1768                              user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
1769   registry->RegisterListPref(pref_names::kNativeMessagingWhitelist,
1770                              user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
1771   registry->RegisterBooleanPref(
1772       pref_names::kNativeMessagingUserLevelHosts,
1773       true,  // default value
1774       user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
1775 }
1776
1777 template <class ExtensionIdContainer>
1778 bool ExtensionPrefs::GetUserExtensionPrefIntoContainer(
1779     const char* pref,
1780     ExtensionIdContainer* id_container_out) {
1781   DCHECK(id_container_out->empty());
1782
1783   const base::Value* user_pref_value = prefs_->GetUserPrefValue(pref);
1784   const base::ListValue* user_pref_as_list;
1785   if (!user_pref_value || !user_pref_value->GetAsList(&user_pref_as_list))
1786     return false;
1787
1788   std::insert_iterator<ExtensionIdContainer> insert_iterator(
1789       *id_container_out, id_container_out->end());
1790   std::string extension_id;
1791   for (base::ListValue::const_iterator value_it = user_pref_as_list->begin();
1792        value_it != user_pref_as_list->end(); ++value_it) {
1793     if (!(*value_it)->GetAsString(&extension_id)) {
1794       NOTREACHED();
1795       continue;
1796     }
1797     insert_iterator = extension_id;
1798   }
1799   return true;
1800 }
1801
1802 template <class ExtensionIdContainer>
1803 void ExtensionPrefs::SetExtensionPrefFromContainer(
1804     const char* pref,
1805     const ExtensionIdContainer& strings) {
1806   ListPrefUpdate update(prefs_, pref);
1807   base::ListValue* list_of_values = update.Get();
1808   list_of_values->Clear();
1809   for (typename ExtensionIdContainer::const_iterator iter = strings.begin();
1810        iter != strings.end(); ++iter) {
1811     list_of_values->Append(new base::StringValue(*iter));
1812   }
1813 }
1814
1815 void ExtensionPrefs::PopulateExtensionInfoPrefs(
1816     const Extension* extension,
1817     const base::Time install_time,
1818     Extension::State initial_state,
1819     bool blacklisted_for_malware,
1820     base::DictionaryValue* extension_dict) {
1821   // Leave the state blank for component extensions so that old chrome versions
1822   // loading new profiles do not fail in GetInstalledExtensionInfo. Older
1823   // Chrome versions would only check for an omitted state.
1824   if (initial_state != Extension::ENABLED_COMPONENT)
1825     extension_dict->Set(kPrefState, new base::FundamentalValue(initial_state));
1826
1827   extension_dict->Set(kPrefLocation,
1828                       new base::FundamentalValue(extension->location()));
1829   extension_dict->Set(kPrefCreationFlags,
1830                       new base::FundamentalValue(extension->creation_flags()));
1831   extension_dict->Set(kPrefFromWebStore,
1832                       new base::FundamentalValue(extension->from_webstore()));
1833   extension_dict->Set(kPrefFromBookmark,
1834                       new base::FundamentalValue(extension->from_bookmark()));
1835   extension_dict->Set(
1836       kPrefWasInstalledByDefault,
1837       new base::FundamentalValue(extension->was_installed_by_default()));
1838   extension_dict->Set(kPrefInstallTime,
1839                       new base::StringValue(
1840                           base::Int64ToString(install_time.ToInternalValue())));
1841   if (blacklisted_for_malware)
1842     extension_dict->Set(kPrefBlacklist, new base::FundamentalValue(true));
1843
1844   base::FilePath::StringType path = MakePathRelative(install_directory_,
1845                                                      extension->path());
1846   extension_dict->Set(kPrefPath, new base::StringValue(path));
1847   // We store prefs about LOAD extensions, but don't cache their manifest
1848   // since it may change on disk.
1849   if (!Manifest::IsUnpackedLocation(extension->location())) {
1850     extension_dict->Set(kPrefManifest,
1851                         extension->manifest()->value()->DeepCopy());
1852   }
1853 }
1854
1855 void ExtensionPrefs::FinishExtensionInfoPrefs(
1856     const std::string& extension_id,
1857     const base::Time install_time,
1858     bool needs_sort_ordinal,
1859     const syncer::StringOrdinal& suggested_page_ordinal,
1860     base::DictionaryValue* extension_dict) {
1861   // Reinitializes various preferences with empty dictionaries.
1862   if (!extension_dict->HasKey(pref_names::kPrefPreferences)) {
1863     extension_dict->Set(pref_names::kPrefPreferences,
1864                         new base::DictionaryValue);
1865   }
1866
1867   if (!extension_dict->HasKey(pref_names::kPrefIncognitoPreferences)) {
1868     extension_dict->Set(pref_names::kPrefIncognitoPreferences,
1869                         new base::DictionaryValue);
1870   }
1871
1872   if (!extension_dict->HasKey(pref_names::kPrefRegularOnlyPreferences)) {
1873     extension_dict->Set(pref_names::kPrefRegularOnlyPreferences,
1874                         new base::DictionaryValue);
1875   }
1876
1877   if (!extension_dict->HasKey(pref_names::kPrefContentSettings))
1878     extension_dict->Set(pref_names::kPrefContentSettings, new base::ListValue);
1879
1880   if (!extension_dict->HasKey(pref_names::kPrefIncognitoContentSettings)) {
1881     extension_dict->Set(pref_names::kPrefIncognitoContentSettings,
1882                         new base::ListValue);
1883   }
1884
1885   // If this point has been reached, any pending installs should be considered
1886   // out of date.
1887   extension_dict->Remove(kDelayedInstallInfo, NULL);
1888
1889   // Clear state that may be registered from a previous install.
1890   extension_dict->Remove(EventRouter::kRegisteredEvents, NULL);
1891
1892   // FYI, all code below here races on sudden shutdown because |extension_dict|,
1893   // |app_sorting_|, |extension_pref_value_map_|, and |content_settings_store_|
1894   // are updated non-transactionally. This is probably not fixable without
1895   // nested transactional updates to pref dictionaries.
1896   if (needs_sort_ordinal)
1897     app_sorting_->EnsureValidOrdinals(extension_id, suggested_page_ordinal);
1898
1899   bool is_enabled = false;
1900   int initial_state;
1901   if (extension_dict->GetInteger(kPrefState, &initial_state)) {
1902     is_enabled = initial_state == Extension::ENABLED;
1903   }
1904
1905   extension_pref_value_map_->RegisterExtension(extension_id, install_time,
1906                                                is_enabled);
1907   content_settings_store_->RegisterExtension(extension_id, install_time,
1908                                              is_enabled);
1909 }
1910
1911 }  // namespace extensions