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