Bug 11559: Supporting changes for Rancor
[koha.git] / C4 / UsageStats.pm
1 package C4::UsageStats;
2
3 # This file is part of Koha.
4 #
5 # Copyright 2014 BibLibre
6 #
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.
11 #
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.
16 #
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>.
19
20 use Modern::Perl;
21 use C4::Context;
22 use POSIX qw(strftime);
23 use LWP::UserAgent;
24 use JSON;
25
26 =head1 NAME
27
28 C4::UsageStats
29
30 =head1 DESCRIPTION
31
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,...
36
37 =head2 NeedUpdate
38
39   $needUpdateYN = C4::UsageStats::NeedUpdate;
40
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 !
44
45 =cut
46
47 sub NeedUpdate {
48     my $lastupdated = C4::Context->preference('UsageStatsLastUpdateTime') || 0;
49     my $now = strftime( "%s", localtime );
50
51     # Need to launch cron.
52     return 1 if $now - $lastupdated >= 2592000;
53
54     # Data don't need to be updated
55     return 0;
56 }
57
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||,
66         },
67     };
68
69     # Get database volumetry.
70     foreach (
71         qw/biblio items auth_header old_issues old_reserves borrowers aqorders subscription/
72       )
73     {
74         $report->{volumetry}{$_} = _count($_);
75     }
76
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         InProcessingToShelvingCart
133         IssueLostItem
134         IssuingInProcess
135         ManInvInNoissuesCharge
136         OverduesBlockCirc
137         RenewalPeriodBase
138         RenewalSendNotice
139         RentalsInNoissuesCharge
140         ReturnBeforeExpiry
141         ReturnToShelvingCart
142         TransfersMaxDaysWarning
143         UseBranchTransferLimits
144         useDaysMode
145         UseTransportCostMatrix
146         UseCourseReserves
147         finesCalendar
148         FinesIncludeGracePeriod
149         finesMode
150         RefundLostItemFeeOnReturn
151         WhenLostChargeReplacementFee
152         WhenLostForgiveFine
153         AllowHoldDateInFuture
154         AllowHoldPolicyOverride
155         AllowHoldsOnDamagedItems
156         AllowHoldsOnPatronsPossessions
157         AutoResumeSuspendedHolds
158         canreservefromotherbranches
159         decreaseLoanHighHolds
160         DisplayMultiPlaceHold
161         emailLibrarianWhenHoldIsPlaced
162         ExpireReservesMaxPickUpDelay
163         OPACAllowHoldDateInFuture
164         OPACAllowUserToChooseBranch
165         ReservesControlBranch
166         ReservesNeedReturns
167         SuspendHoldsIntranet
168         SuspendHoldsOpac
169         TransferWhenCancelAllWaitingHolds
170         AllowAllMessageDeletion
171         AllowOfflineCirculation
172         CircAutocompl
173         CircAutoPrintQuickSlip
174         DisplayClearScreenButton
175         FilterBeforeOverdueReport
176         FineNotifyAtCheckin
177         itemBarcodeFallbackSearch
178         itemBarcodeInputFilter
179         previousIssuesDefaultSortOrder
180         RecordLocalUseOnReturn
181         soundon
182         SpecifyDueDate
183         todaysIssuesDefaultSortOrder
184         UpdateTotalIssuesOnCirc
185         UseTablesortForCirc
186         WaitingNotifyAtCheckin
187         AllowSelfCheckReturns
188         AutoSelfCheckAllowed
189         FRBRizeEditions
190         OPACFRBRizeEditions
191         AmazonCoverImages
192         OPACAmazonCoverImages
193         Babeltheque
194         BakerTaylorEnabled
195         GoogleJackets
196         HTML5MediaEnabled
197         IDreamBooksReadometer
198         IDreamBooksResults
199         IDreamBooksReviews
200         LibraryThingForLibrariesEnabled
201         LocalCoverImages
202         OPACLocalCoverImages
203         NovelistSelectEnabled
204         XISBN
205         OpenLibraryCovers
206         UseKohaPlugins
207         SyndeticsEnabled
208         TagsEnabled
209         CalendarFirstDayOfWeek
210         opaclanguagesdisplay
211         AuthoritiesLog
212         BorrowersLog
213         CataloguingLog
214         FinesLog
215         IssueLog
216         LetterLog
217         ReturnLog
218         SubscriptionLog
219         AuthorisedValueImages
220         BiblioDefaultView
221         COinSinOPACResults
222         DisplayOPACiconsXSLT
223         hidelostitems
224         HighlightOwnItemsOnOPAC
225         OpacAddMastheadLibraryPulldown
226         OPACDisplay856uAsImage
227         OpacHighlightedWords
228         OpacKohaUrl
229         OpacMaintenance
230         OpacPublic
231         OpacSeparateHoldings
232         OPACShowBarcode
233         OPACShowCheckoutName
234         OpacShowFiltersPulldownMobile
235         OPACShowHoldQueueDetails
236         OpacShowLibrariesPulldownMobile
237         OpacShowRecentComments
238         OPACShowUnusedAuthorities
239         OpacStarRatings
240         opacthemes
241         OPACURLOpenInNewWindow
242         OpacAuthorities
243         opacbookbag
244         OpacBrowser
245         OpacBrowseResults
246         OpacCloud
247         OPACFinesTab
248         OpacHoldNotes
249         OpacItemLocation
250         OpacPasswordChange
251         OPACPatronDetails
252         OPACpatronimages
253         OPACPopupAuthorsSearch
254         OpacTopissue
255         opacuserlogin
256         QuoteOfTheDay
257         RequestOnOpac
258         reviewson
259         ShowReviewer
260         ShowReviewerPhoto
261         SocialNetworks
262         suggestion
263         AllowPurchaseSuggestionBranchChoice
264         OpacAllowPublicListCreation
265         OpacAllowSharingPrivateLists
266         OpacRenewalAllowed
267         OpacRenewalBranch
268         OPACViewOthersSuggestions
269         SearchMyLibraryFirst
270         singleBranchMode
271         AnonSuggestions
272         EnableOpacSearchHistory
273         OPACPrivacy
274         opacreadinghistory
275         TrackClicks
276         PatronSelfRegistration
277         OPACShelfBrowser
278         AutoEmailOpacUser
279         AutoEmailPrimaryAddress
280         autoMemberNum
281         BorrowerRenewalPeriodBase
282         checkdigit
283         EnableBorrowerFiles
284         EnhancedMessagingPreferences
285         ExtendedPatronAttributes
286         intranetreadinghistory
287         memberofinstitution
288         patronimages
289         TalkingTechItivaPhoneNotification
290         uppercasesurnames
291         IncludeSeeFromInSearches
292         OpacGroupResults
293         QueryAutoTruncate
294         QueryFuzzy
295         QueryStemming
296         QueryWeightFields
297         TraceCompleteSubfields
298         TraceSubjectSubdivisions
299         UseICU
300         UseQueryParser
301         defaultSortField
302         displayFacetCount
303         OPACdefaultSortField
304         OPACItemsResultsDisplay
305         expandedSearchOption
306         IntranetNumbersPreferPhrase
307         OPACNumbersPreferPhrase
308         opacSerialDefaultTab
309         RenewSerialAddsSuggestion
310         RoutingListAddReserves
311         RoutingSerials
312         SubscriptionHistory
313         Display856uAsImage
314         DisplayIconsXSLT
315         StaffAuthorisedValueImages
316         template
317         yuipath
318         HidePatronName
319         intranetbookbag
320         StaffDetailItemSelection
321         viewISBD
322         viewLabeledMARC
323         viewMARC
324         ILS-DI
325         OAI-PMH
326         version
327         /
328       )
329     {
330         $report->{systempreferences}{$_} = C4::Context->preference($_);
331     }
332     return $report;
333 }
334
335 =head2 ReportToCommunity
336
337   ReportToCommunity;
338
339 Send to hea.koha-community.org database informations
340
341 =cut
342
343 sub ReportToCommunity {
344     my $data = shift;
345     my $json = encode_json($data);
346
347     my $url = "http://hea.koha-community.org/upload.pl";
348     my $ua = LWP::UserAgent->new;
349     my $res = $ua->post(
350         $url,
351         'Content-type' => 'application/json;charset=utf-8',
352         Content => $json,
353     );
354     my $content = decode_json( $res->decoded_content );
355     C4::Context->set_preference( 'UsageStatsID',
356         $content->{library}{id} );
357 }
358
359 =head2 _count
360
361   $data = _count($table);
362
363 Count the number of records in $table tables
364
365 =cut
366
367 sub _count {
368     my $table = shift;
369
370     my $dbh = C4::Context->dbh;
371     my $sth = $dbh->prepare("SELECT count(*) from $table");
372     $sth->execute;
373     return $sth->fetchrow_array;
374 }
375
376 1;