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