Bug 13274: Mock new_dbh in t::lib::Mocks
[koha.git] / C4 / UsageStats.pm
blob627fba5671c80f925324537296e9bdf88ccbf2e2
1 package C4::UsageStats;
3 # This file is part of Koha.
5 # Copyright 2014 BibLibre
7 # Koha is free software; you can redistribute it and/or modify it
8 # under the terms of the GNU General Public License as published by
9 # the Free Software Foundation; either version 3 of the License, or
10 # (at your option) any later version.
12 # Koha is distributed in the hope that it will be useful, but
13 # WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 # GNU General Public License for more details.
17 # You should have received a copy of the GNU General Public License
18 # along with Koha; if not, see <http://www.gnu.org/licenses>.
20 use Modern::Perl;
21 use C4::Context;
22 use POSIX qw(strftime);
23 use LWP::UserAgent;
24 use JSON;
26 =head1 NAME
28 C4::UsageStats
30 =head1 DESCRIPTION
32 This package contains what is needed to report Koha statistics to hea
33 hea.koha-community.org is the server that centralize Koha setups informations
34 Koha libraries are encouraged to provide informations about their collections,
35 their structure,...
37 =head2 NeedUpdate
39 $needUpdateYN = C4::UsageStats::NeedUpdate;
41 Returns Y (1) if the last update is more than 1 month old
42 This way, even if the cronjob is run every minute, the webservice will be called
43 only once a month !
45 =cut
47 sub NeedUpdate {
48 my $lastupdated = C4::Context->preference('UsageStatsLastUpdateTime') || 0;
49 my $now = strftime( "%s", localtime );
51 # Need to launch cron.
52 return 1 if $now - $lastupdated >= 2592000;
54 # Data don't need to be updated
55 return 0;
58 sub BuildReport {
59 my $report = {
60 library => {
61 id => C4::Context->preference('UsageStatsID') || 0,
62 name => C4::Context->preference('UsageStatsLibraryName') || q||,
63 url => C4::Context->preference('UsageStatsLibraryUrl') || q||,
64 type => C4::Context->preference('UsageStatsLibraryType') || q||,
65 country => C4::Context->preference('UsageStatsCountry') || q||,
69 # Get database volumetry.
70 foreach (
71 qw/biblio items auth_header old_issues old_reserves borrowers aqorders subscription/
74 $report->{volumetry}{$_} = _count($_);
77 # Get systempreferences.
78 foreach (
79 qw/
80 AcqCreateItem
81 AcqWarnOnDuplicateInvoice
82 AcqViewBaskets
83 BasketConfirmations
84 OrderPdfFormat
85 casAuthentication
86 casLogout
87 AllowPkiAuth
88 DebugLevel
89 delimiter
90 noItemTypeImages
91 virtualshelves
92 AutoLocation
93 IndependentBranches
94 SessionStorage
95 Persona
96 AuthDisplayHierarchy
97 AutoCreateAuthorities
98 BiblioAddsAuthorities
99 dontmerge
100 UseAuthoritiesForTracings
101 CatalogModuleRelink
102 hide_marc
103 IntranetBiblioDefaultView
104 LabelMARCView
105 OpacSuppression
106 SeparateHoldings
107 UseControlNumber
108 advancedMARCeditor
109 DefaultClassificationSource
110 EasyAnalyticalRecords
111 autoBarcode
112 item-level_itypes
113 marcflavour
114 PrefillItem
115 z3950NormalizeAuthor
116 SpineLabelAutoPrint
117 SpineLabelShowPrintOnBibDetails
118 BlockReturnOfWithdrawnItems
119 CalculateFinesOnReturn
120 AgeRestrictionOverride
121 AllFinesNeedOverride
122 AllowFineOverride
123 AllowItemsOnHoldCheckout
124 AllowNotForLoanOverride
125 AllowRenewalLimitOverride
126 AllowReturnToBranch
127 AllowTooManyOverride
128 AutomaticItemReturn
129 AutoRemoveOverduesRestrictions
130 CircControl
131 HomeOrHoldingBranch
132 HomeOrHoldingBranchReturn
133 InProcessingToShelvingCart
134 IssueLostItem
135 IssuingInProcess
136 ManInvInNoissuesCharge
137 OverduesBlockCirc
138 RenewalPeriodBase
139 RenewalSendNotice
140 RentalsInNoissuesCharge
141 ReturnBeforeExpiry
142 ReturnToShelvingCart
143 TransfersMaxDaysWarning
144 UseBranchTransferLimits
145 useDaysMode
146 UseTransportCostMatrix
147 UseCourseReserves
148 finesCalendar
149 FinesIncludeGracePeriod
150 finesMode
151 RefundLostItemFeeOnReturn
152 WhenLostChargeReplacementFee
153 WhenLostForgiveFine
154 AllowHoldDateInFuture
155 AllowHoldPolicyOverride
156 AllowHoldsOnDamagedItems
157 AllowHoldsOnPatronsPossessions
158 AllowOnShelfHolds
159 AutoResumeSuspendedHolds
160 canreservefromotherbranches
161 decreaseLoanHighHolds
162 DisplayMultiPlaceHold
163 emailLibrarianWhenHoldIsPlaced
164 ExpireReservesMaxPickUpDelay
165 OPACAllowHoldDateInFuture
166 OPACAllowUserToChooseBranch
167 ReservesControlBranch
168 ReservesNeedReturns
169 SuspendHoldsIntranet
170 SuspendHoldsOpac
171 TransferWhenCancelAllWaitingHolds
172 AllowAllMessageDeletion
173 AllowOfflineCirculation
174 CircAutocompl
175 CircAutoPrintQuickSlip
176 DisplayClearScreenButton
177 FilterBeforeOverdueReport
178 FineNotifyAtCheckin
179 itemBarcodeFallbackSearch
180 itemBarcodeInputFilter
181 previousIssuesDefaultSortOrder
182 RecordLocalUseOnReturn
183 soundon
184 SpecifyDueDate
185 todaysIssuesDefaultSortOrder
186 UpdateTotalIssuesOnCirc
187 UseTablesortForCirc
188 WaitingNotifyAtCheckin
189 AllowSelfCheckReturns
190 AutoSelfCheckAllowed
191 FRBRizeEditions
192 OPACFRBRizeEditions
193 AmazonCoverImages
194 OPACAmazonCoverImages
195 Babeltheque
196 BakerTaylorEnabled
197 GoogleJackets
198 HTML5MediaEnabled
199 IDreamBooksReadometer
200 IDreamBooksResults
201 IDreamBooksReviews
202 LibraryThingForLibrariesEnabled
203 LocalCoverImages
204 OPACLocalCoverImages
205 NovelistSelectEnabled
206 XISBN
207 OpenLibraryCovers
208 UseKohaPlugins
209 SyndeticsEnabled
210 TagsEnabled
211 CalendarFirstDayOfWeek
212 opaclanguagesdisplay
213 AuthoritiesLog
214 BorrowersLog
215 CataloguingLog
216 FinesLog
217 IssueLog
218 LetterLog
219 ReturnLog
220 SubscriptionLog
221 AuthorisedValueImages
222 BiblioDefaultView
223 COinSinOPACResults
224 DisplayOPACiconsXSLT
225 hidelostitems
226 HighlightOwnItemsOnOPAC
227 OpacAddMastheadLibraryPulldown
228 OPACDisplay856uAsImage
229 OpacHighlightedWords
230 OpacKohaUrl
231 OpacMaintenance
232 OpacPublic
233 OpacSeparateHoldings
234 OPACShowBarcode
235 OPACShowCheckoutName
236 OpacShowFiltersPulldownMobile
237 OPACShowHoldQueueDetails
238 OpacShowLibrariesPulldownMobile
239 OpacShowRecentComments
240 OPACShowUnusedAuthorities
241 OpacStarRatings
242 opacthemes
243 OPACURLOpenInNewWindow
244 OpacAuthorities
245 opacbookbag
246 OpacBrowser
247 OpacBrowseResults
248 OpacCloud
249 OPACFinesTab
250 OpacHoldNotes
251 OpacItemLocation
252 OpacPasswordChange
253 OPACPatronDetails
254 OPACpatronimages
255 OPACPopupAuthorsSearch
256 OpacTopissue
257 opacuserlogin
258 QuoteOfTheDay
259 RequestOnOpac
260 reviewson
261 ShowReviewer
262 ShowReviewerPhoto
263 SocialNetworks
264 suggestion
265 AllowPurchaseSuggestionBranchChoice
266 OpacAllowPublicListCreation
267 OpacAllowSharingPrivateLists
268 OPACItemHolds
269 OpacRenewalAllowed
270 OpacRenewalBranch
271 OPACViewOthersSuggestions
272 SearchMyLibraryFirst
273 singleBranchMode
274 AnonSuggestions
275 EnableOpacSearchHistory
276 OPACPrivacy
277 opacreadinghistory
278 TrackClicks
279 PatronSelfRegistration
280 OPACShelfBrowser
281 AddPatronLists
282 AutoEmailOpacUser
283 AutoEmailPrimaryAddress
284 autoMemberNum
285 BorrowerRenewalPeriodBase
286 checkdigit
287 EnableBorrowerFiles
288 EnhancedMessagingPreferences
289 ExtendedPatronAttributes
290 intranetreadinghistory
291 memberofinstitution
292 patronimages
293 TalkingTechItivaPhoneNotification
294 uppercasesurnames
295 IncludeSeeFromInSearches
296 OpacGroupResults
297 QueryAutoTruncate
298 QueryFuzzy
299 QueryStemming
300 QueryWeightFields
301 TraceCompleteSubfields
302 TraceSubjectSubdivisions
303 UseICU
304 UseQueryParser
305 defaultSortField
306 displayFacetCount
307 OPACdefaultSortField
308 OPACItemsResultsDisplay
309 expandedSearchOption
310 IntranetNumbersPreferPhrase
311 OPACNumbersPreferPhrase
312 opacSerialDefaultTab
313 RenewSerialAddsSuggestion
314 RoutingListAddReserves
315 RoutingSerials
316 SubscriptionHistory
317 Display856uAsImage
318 DisplayIconsXSLT
319 StaffAuthorisedValueImages
320 template
321 yuipath
322 HidePatronName
323 intranetbookbag
324 StaffDetailItemSelection
325 viewISBD
326 viewLabeledMARC
327 viewMARC
328 ILS-DI
329 OAI-PMH
330 version
334 $report->{systempreferences}{$_} = C4::Context->preference($_);
336 return $report;
339 =head2 ReportToCommunity
341 ReportToCommunity;
343 Send to hea.koha-community.org database informations
345 =cut
347 sub ReportToCommunity {
348 my $data = shift;
349 my $json = encode_json($data);
351 my $url = "http://hea.koha-community.org/upload.pl";
352 my $ua = LWP::UserAgent->new;
353 my $res = $ua->post(
354 $url,
355 'Content-type' => 'application/json;charset=utf-8',
356 Content => $json,
358 my $content = decode_json( $res->decoded_content );
359 C4::Context->set_preference( 'UsageStatsID',
360 $content->{library}{id} );
363 =head2 _count
365 $data = _count($table);
367 Count the number of records in $table tables
369 =cut
371 sub _count {
372 my $table = shift;
374 my $dbh = C4::Context->dbh;
375 my $sth = $dbh->prepare("SELECT count(*) from $table");
376 $sth->execute;
377 return $sth->fetchrow_array;