1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
|
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/extensions/api/history/history_api.h"
#include <utility>
#include "base/bind.h"
#include "base/bind_helpers.h"
#include "base/callback.h"
#include "base/command_line.h"
#include "base/json/json_writer.h"
#include "base/lazy_instance.h"
#include "base/location.h"
#include "base/memory/scoped_ptr.h"
#include "base/single_thread_task_runner.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/utf_string_conversions.h"
#include "base/task/cancelable_task_tracker.h"
#include "base/thread_task_runner_handle.h"
#include "base/time/time.h"
#include "base/values.h"
#include "chrome/browser/extensions/activity_log/activity_log.h"
#include "chrome/browser/history/history_service_factory.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/extensions/api/history.h"
#include "chrome/common/pref_names.h"
#include "components/history/core/browser/history_service.h"
#include "components/history/core/browser/history_types.h"
#include "components/prefs/pref_service.h"
#include "extensions/browser/event_router.h"
#include "extensions/browser/extension_system_provider.h"
#include "extensions/browser/extensions_browser_client.h"
namespace extensions {
using api::history::HistoryItem;
using api::history::VisitItem;
typedef std::vector<linked_ptr<api::history::HistoryItem> >
HistoryItemList;
typedef std::vector<linked_ptr<api::history::VisitItem> >
VisitItemList;
namespace AddUrl = api::history::AddUrl;
namespace DeleteUrl = api::history::DeleteUrl;
namespace DeleteRange = api::history::DeleteRange;
namespace GetVisits = api::history::GetVisits;
namespace OnVisited = api::history::OnVisited;
namespace OnVisitRemoved = api::history::OnVisitRemoved;
namespace Search = api::history::Search;
namespace {
const char kInvalidUrlError[] = "Url is invalid.";
const char kDeleteProhibitedError[] = "Browsing history is not allowed to be "
"deleted.";
double MilliSecondsFromTime(const base::Time& time) {
return 1000 * time.ToDoubleT();
}
scoped_ptr<HistoryItem> GetHistoryItem(const history::URLRow& row) {
scoped_ptr<HistoryItem> history_item(new HistoryItem());
history_item->id = base::Int64ToString(row.id());
history_item->url.reset(new std::string(row.url().spec()));
history_item->title.reset(new std::string(base::UTF16ToUTF8(row.title())));
history_item->last_visit_time.reset(
new double(MilliSecondsFromTime(row.last_visit())));
history_item->typed_count.reset(new int(row.typed_count()));
history_item->visit_count.reset(new int(row.visit_count()));
return history_item;
}
scoped_ptr<VisitItem> GetVisitItem(const history::VisitRow& row) {
scoped_ptr<VisitItem> visit_item(new VisitItem());
visit_item->id = base::Int64ToString(row.url_id);
visit_item->visit_id = base::Int64ToString(row.visit_id);
visit_item->visit_time.reset(
new double(MilliSecondsFromTime(row.visit_time)));
visit_item->referring_visit_id = base::Int64ToString(row.referring_visit);
api::history::TransitionType transition = api::history::TRANSITION_TYPE_LINK;
switch (row.transition & ui::PAGE_TRANSITION_CORE_MASK) {
case ui::PAGE_TRANSITION_LINK:
transition = api::history::TRANSITION_TYPE_LINK;
break;
case ui::PAGE_TRANSITION_TYPED:
transition = api::history::TRANSITION_TYPE_TYPED;
break;
case ui::PAGE_TRANSITION_AUTO_BOOKMARK:
transition = api::history::TRANSITION_TYPE_AUTO_BOOKMARK;
break;
case ui::PAGE_TRANSITION_AUTO_SUBFRAME:
transition = api::history::TRANSITION_TYPE_AUTO_SUBFRAME;
break;
case ui::PAGE_TRANSITION_MANUAL_SUBFRAME:
transition = api::history::TRANSITION_TYPE_MANUAL_SUBFRAME;
break;
case ui::PAGE_TRANSITION_GENERATED:
transition = api::history::TRANSITION_TYPE_GENERATED;
break;
case ui::PAGE_TRANSITION_AUTO_TOPLEVEL:
transition = api::history::TRANSITION_TYPE_AUTO_TOPLEVEL;
break;
case ui::PAGE_TRANSITION_FORM_SUBMIT:
transition = api::history::TRANSITION_TYPE_FORM_SUBMIT;
break;
case ui::PAGE_TRANSITION_RELOAD:
transition = api::history::TRANSITION_TYPE_RELOAD;
break;
case ui::PAGE_TRANSITION_KEYWORD:
transition = api::history::TRANSITION_TYPE_KEYWORD;
break;
case ui::PAGE_TRANSITION_KEYWORD_GENERATED:
transition = api::history::TRANSITION_TYPE_KEYWORD_GENERATED;
break;
default:
DCHECK(false);
}
visit_item->transition = transition;
return visit_item;
}
} // namespace
HistoryEventRouter::HistoryEventRouter(Profile* profile,
history::HistoryService* history_service)
: profile_(profile), history_service_observer_(this) {
DCHECK(profile);
history_service_observer_.Add(history_service);
}
HistoryEventRouter::~HistoryEventRouter() {
}
void HistoryEventRouter::OnURLVisited(history::HistoryService* history_service,
ui::PageTransition transition,
const history::URLRow& row,
const history::RedirectList& redirects,
base::Time visit_time) {
scoped_ptr<HistoryItem> history_item = GetHistoryItem(row);
scoped_ptr<base::ListValue> args = OnVisited::Create(*history_item);
DispatchEvent(profile_, events::HISTORY_ON_VISITED,
api::history::OnVisited::kEventName, std::move(args));
}
void HistoryEventRouter::OnURLsDeleted(history::HistoryService* history_service,
bool all_history,
bool expired,
const history::URLRows& deleted_rows,
const std::set<GURL>& favicon_urls) {
OnVisitRemoved::Removed removed;
removed.all_history = all_history;
std::vector<std::string>* urls = new std::vector<std::string>();
for (const auto& row : deleted_rows)
urls->push_back(row.url().spec());
removed.urls.reset(urls);
scoped_ptr<base::ListValue> args = OnVisitRemoved::Create(removed);
DispatchEvent(profile_, events::HISTORY_ON_VISIT_REMOVED,
api::history::OnVisitRemoved::kEventName, std::move(args));
}
void HistoryEventRouter::DispatchEvent(Profile* profile,
events::HistogramValue histogram_value,
const std::string& event_name,
scoped_ptr<base::ListValue> event_args) {
if (profile && EventRouter::Get(profile)) {
scoped_ptr<Event> event(
new Event(histogram_value, event_name, std::move(event_args)));
event->restrict_to_browser_context = profile;
EventRouter::Get(profile)->BroadcastEvent(std::move(event));
}
}
HistoryAPI::HistoryAPI(content::BrowserContext* context)
: browser_context_(context) {
EventRouter* event_router = EventRouter::Get(browser_context_);
event_router->RegisterObserver(this, api::history::OnVisited::kEventName);
event_router->RegisterObserver(this,
api::history::OnVisitRemoved::kEventName);
}
HistoryAPI::~HistoryAPI() {
}
void HistoryAPI::Shutdown() {
history_event_router_.reset();
EventRouter::Get(browser_context_)->UnregisterObserver(this);
}
static base::LazyInstance<BrowserContextKeyedAPIFactory<HistoryAPI> >
g_factory = LAZY_INSTANCE_INITIALIZER;
// static
BrowserContextKeyedAPIFactory<HistoryAPI>* HistoryAPI::GetFactoryInstance() {
return g_factory.Pointer();
}
template <>
void BrowserContextKeyedAPIFactory<HistoryAPI>::DeclareFactoryDependencies() {
DependsOn(ActivityLog::GetFactoryInstance());
DependsOn(HistoryServiceFactory::GetInstance());
DependsOn(ExtensionsBrowserClient::Get()->GetExtensionSystemFactory());
}
void HistoryAPI::OnListenerAdded(const EventListenerInfo& details) {
Profile* profile = Profile::FromBrowserContext(browser_context_);
history_event_router_.reset(new HistoryEventRouter(
profile, HistoryServiceFactory::GetForProfile(
profile, ServiceAccessType::EXPLICIT_ACCESS)));
EventRouter::Get(browser_context_)->UnregisterObserver(this);
}
bool HistoryFunction::ValidateUrl(const std::string& url_string, GURL* url) {
GURL temp_url(url_string);
if (!temp_url.is_valid()) {
error_ = kInvalidUrlError;
return false;
}
url->Swap(&temp_url);
return true;
}
bool HistoryFunction::VerifyDeleteAllowed() {
PrefService* prefs = GetProfile()->GetPrefs();
if (!prefs->GetBoolean(prefs::kAllowDeletingBrowserHistory)) {
error_ = kDeleteProhibitedError;
return false;
}
return true;
}
base::Time HistoryFunction::GetTime(double ms_from_epoch) {
// The history service has seconds resolution, while javascript Date() has
// milliseconds resolution.
double seconds_from_epoch = ms_from_epoch / 1000.0;
// Time::FromDoubleT converts double time 0 to empty Time object. So we need
// to do special handling here.
return (seconds_from_epoch == 0) ?
base::Time::UnixEpoch() : base::Time::FromDoubleT(seconds_from_epoch);
}
HistoryFunctionWithCallback::HistoryFunctionWithCallback() {
}
HistoryFunctionWithCallback::~HistoryFunctionWithCallback() {
}
bool HistoryFunctionWithCallback::RunAsync() {
AddRef(); // Balanced in SendAysncRepose() and below.
bool retval = RunAsyncImpl();
if (false == retval)
Release();
return retval;
}
void HistoryFunctionWithCallback::SendAsyncResponse() {
base::ThreadTaskRunnerHandle::Get()->PostTask(
FROM_HERE,
base::Bind(&HistoryFunctionWithCallback::SendResponseToCallback, this));
}
void HistoryFunctionWithCallback::SendResponseToCallback() {
SendResponse(true);
Release(); // Balanced in RunAsync().
}
bool HistoryGetVisitsFunction::RunAsyncImpl() {
scoped_ptr<GetVisits::Params> params(GetVisits::Params::Create(*args_));
EXTENSION_FUNCTION_VALIDATE(params.get());
GURL url;
if (!ValidateUrl(params->details.url, &url))
return false;
history::HistoryService* hs = HistoryServiceFactory::GetForProfile(
GetProfile(), ServiceAccessType::EXPLICIT_ACCESS);
hs->QueryURL(url,
true, // Retrieve full history of a URL.
base::Bind(&HistoryGetVisitsFunction::QueryComplete,
base::Unretained(this)),
&task_tracker_);
return true;
}
void HistoryGetVisitsFunction::QueryComplete(
bool success,
const history::URLRow& url_row,
const history::VisitVector& visits) {
VisitItemList visit_item_vec;
if (success && !visits.empty()) {
for (history::VisitVector::const_iterator iterator = visits.begin();
iterator != visits.end();
++iterator) {
visit_item_vec.push_back(make_linked_ptr(
GetVisitItem(*iterator).release()));
}
}
results_ = GetVisits::Results::Create(visit_item_vec);
SendAsyncResponse();
}
bool HistorySearchFunction::RunAsyncImpl() {
scoped_ptr<Search::Params> params(Search::Params::Create(*args_));
EXTENSION_FUNCTION_VALIDATE(params.get());
base::string16 search_text = base::UTF8ToUTF16(params->query.text);
history::QueryOptions options;
options.SetRecentDayRange(1);
options.max_count = 100;
if (params->query.start_time.get())
options.begin_time = GetTime(*params->query.start_time);
if (params->query.end_time.get())
options.end_time = GetTime(*params->query.end_time);
if (params->query.max_results.get())
options.max_count = *params->query.max_results;
history::HistoryService* hs = HistoryServiceFactory::GetForProfile(
GetProfile(), ServiceAccessType::EXPLICIT_ACCESS);
hs->QueryHistory(search_text,
options,
base::Bind(&HistorySearchFunction::SearchComplete,
base::Unretained(this)),
&task_tracker_);
return true;
}
void HistorySearchFunction::SearchComplete(history::QueryResults* results) {
HistoryItemList history_item_vec;
if (results && !results->empty()) {
for (history::QueryResults::URLResultVector::const_iterator iterator =
results->begin();
iterator != results->end();
++iterator) {
history_item_vec.push_back(make_linked_ptr(
GetHistoryItem(**iterator).release()));
}
}
results_ = Search::Results::Create(history_item_vec);
SendAsyncResponse();
}
bool HistoryAddUrlFunction::RunAsync() {
scoped_ptr<AddUrl::Params> params(AddUrl::Params::Create(*args_));
EXTENSION_FUNCTION_VALIDATE(params.get());
GURL url;
if (!ValidateUrl(params->details.url, &url))
return false;
history::HistoryService* hs = HistoryServiceFactory::GetForProfile(
GetProfile(), ServiceAccessType::EXPLICIT_ACCESS);
hs->AddPage(url, base::Time::Now(), history::SOURCE_EXTENSION);
SendResponse(true);
return true;
}
bool HistoryDeleteUrlFunction::RunAsync() {
scoped_ptr<DeleteUrl::Params> params(DeleteUrl::Params::Create(*args_));
EXTENSION_FUNCTION_VALIDATE(params.get());
if (!VerifyDeleteAllowed())
return false;
GURL url;
if (!ValidateUrl(params->details.url, &url))
return false;
history::HistoryService* hs = HistoryServiceFactory::GetForProfile(
GetProfile(), ServiceAccessType::EXPLICIT_ACCESS);
hs->DeleteURL(url);
// Also clean out from the activity log. If the activity log testing flag is
// set then don't clean so testers can see what potentially malicious
// extensions have been trying to clean from their logs.
if (!base::CommandLine::ForCurrentProcess()->HasSwitch(
switches::kEnableExtensionActivityLogTesting)) {
ActivityLog* activity_log = ActivityLog::GetInstance(GetProfile());
DCHECK(activity_log);
activity_log->RemoveURL(url);
}
SendResponse(true);
return true;
}
bool HistoryDeleteRangeFunction::RunAsyncImpl() {
scoped_ptr<DeleteRange::Params> params(DeleteRange::Params::Create(*args_));
EXTENSION_FUNCTION_VALIDATE(params.get());
if (!VerifyDeleteAllowed())
return false;
base::Time start_time = GetTime(params->range.start_time);
base::Time end_time = GetTime(params->range.end_time);
std::set<GURL> restrict_urls;
history::HistoryService* hs = HistoryServiceFactory::GetForProfile(
GetProfile(), ServiceAccessType::EXPLICIT_ACCESS);
hs->ExpireHistoryBetween(
restrict_urls,
start_time,
end_time,
base::Bind(&HistoryDeleteRangeFunction::DeleteComplete,
base::Unretained(this)),
&task_tracker_);
// Also clean from the activity log unless in testing mode.
if (!base::CommandLine::ForCurrentProcess()->HasSwitch(
switches::kEnableExtensionActivityLogTesting)) {
ActivityLog* activity_log = ActivityLog::GetInstance(GetProfile());
DCHECK(activity_log);
activity_log->RemoveURLs(restrict_urls);
}
return true;
}
void HistoryDeleteRangeFunction::DeleteComplete() {
SendAsyncResponse();
}
bool HistoryDeleteAllFunction::RunAsyncImpl() {
if (!VerifyDeleteAllowed())
return false;
std::set<GURL> restrict_urls;
history::HistoryService* hs = HistoryServiceFactory::GetForProfile(
GetProfile(), ServiceAccessType::EXPLICIT_ACCESS);
hs->ExpireHistoryBetween(
restrict_urls,
base::Time(), // Unbounded beginning...
base::Time(), // ...and the end.
base::Bind(&HistoryDeleteAllFunction::DeleteComplete,
base::Unretained(this)),
&task_tracker_);
// Also clean from the activity log unless in testing mode.
if (!base::CommandLine::ForCurrentProcess()->HasSwitch(
switches::kEnableExtensionActivityLogTesting)) {
ActivityLog* activity_log = ActivityLog::GetInstance(GetProfile());
DCHECK(activity_log);
activity_log->RemoveURLs(restrict_urls);
}
return true;
}
void HistoryDeleteAllFunction::DeleteComplete() {
SendAsyncResponse();
}
} // namespace extensions
|