Bug 18066: Hea V2
[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 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         dontmerge
112         UseAuthoritiesForTracings
113         CatalogModuleRelink
114         hide_marc
115         IntranetBiblioDefaultView
116         LabelMARCView
117         OpacSuppression
118         SeparateHoldings
119         UseControlNumber
120         advancedMARCeditor
121         DefaultClassificationSource
122         EasyAnalyticalRecords
123         autoBarcode
124         item-level_itypes
125         marcflavour
126         PrefillItem
127         z3950NormalizeAuthor
128         SpineLabelAutoPrint
129         SpineLabelShowPrintOnBibDetails
130         BlockReturnOfWithdrawnItems
131         CalculateFinesOnReturn
132         AgeRestrictionOverride
133         AllFinesNeedOverride
134         AllowFineOverride
135         AllowItemsOnHoldCheckout
136         AllowItemsOnHoldCheckoutSCO
137         AllowNotForLoanOverride
138         AllowRenewalLimitOverride
139         AllowReturnToBranch
140         AllowTooManyOverride
141         AutomaticItemReturn
142         AutoRemoveOverduesRestrictions
143         CircControl
144         HomeOrHoldingBranch
145         InProcessingToShelvingCart
146         IssueLostItem
147         IssuingInProcess
148         ManInvInNoissuesCharge
149         OverduesBlockCirc
150         RenewalPeriodBase
151         RenewalSendNotice
152         RentalsInNoissuesCharge
153         ReturnBeforeExpiry
154         ReturnToShelvingCart
155         TransfersMaxDaysWarning
156         UseBranchTransferLimits
157         useDaysMode
158         UseTransportCostMatrix
159         UseCourseReserves
160         finesCalendar
161         FinesIncludeGracePeriod
162         finesMode
163         RefundLostOnReturnControl
164         WhenLostChargeReplacementFee
165         WhenLostForgiveFine
166         AllowHoldDateInFuture
167         AllowHoldPolicyOverride
168         AllowHoldsOnDamagedItems
169         AllowHoldsOnPatronsPossessions
170         AutoResumeSuspendedHolds
171         canreservefromotherbranches
172         decreaseLoanHighHolds
173         DisplayMultiPlaceHold
174         emailLibrarianWhenHoldIsPlaced
175         ExpireReservesMaxPickUpDelay
176         OPACAllowHoldDateInFuture
177         OPACAllowUserToChooseBranch
178         ReservesControlBranch
179         ReservesNeedReturns
180         SuspendHoldsIntranet
181         SuspendHoldsOpac
182         TransferWhenCancelAllWaitingHolds
183         AllowAllMessageDeletion
184         AllowOfflineCirculation
185         CircAutocompl
186         CircAutoPrintQuickSlip
187         DisplayClearScreenButton
188         FilterBeforeOverdueReport
189         FineNotifyAtCheckin
190         itemBarcodeFallbackSearch
191         itemBarcodeInputFilter
192         previousIssuesDefaultSortOrder
193         RecordLocalUseOnReturn
194         AudioAlerts
195         SpecifyDueDate
196         todaysIssuesDefaultSortOrder
197         UpdateTotalIssuesOnCirc
198         UseTablesortForCirc
199         WaitingNotifyAtCheckin
200         AllowSelfCheckReturns
201         AutoSelfCheckAllowed
202         FRBRizeEditions
203         OPACFRBRizeEditions
204         AmazonCoverImages
205         OPACAmazonCoverImages
206         Babeltheque
207         BakerTaylorEnabled
208         GoogleJackets
209         HTML5MediaEnabled
210         IDreamBooksReadometer
211         IDreamBooksResults
212         IDreamBooksReviews
213         LibraryThingForLibrariesEnabled
214         LocalCoverImages
215         OPACLocalCoverImages
216         NovelistSelectEnabled
217         XISBN
218         OpenLibraryCovers
219         OpenLibrarySearch
220         UseKohaPlugins
221         SyndeticsEnabled
222         TagsEnabled
223         CalendarFirstDayOfWeek
224         opaclanguagesdisplay
225         AuthoritiesLog
226         BorrowersLog
227         CataloguingLog
228         FinesLog
229         IssueLog
230         LetterLog
231         ReturnLog
232         SubscriptionLog
233         BiblioDefaultView
234         COinSinOPACResults
235         DisplayOPACiconsXSLT
236         hidelostitems
237         HighlightOwnItemsOnOPAC
238         OpacAddMastheadLibraryPulldown
239         OPACDisplay856uAsImage
240         OpacHighlightedWords
241         OpacKohaUrl
242         OpacMaintenance
243         OpacPublic
244         OpacSeparateHoldings
245         OPACShowBarcode
246         OPACShowCheckoutName
247         OpacShowFiltersPulldownMobile
248         OPACShowHoldQueueDetails
249         OpacShowLibrariesPulldownMobile
250         OpacShowRecentComments
251         OPACShowUnusedAuthorities
252         OpacStarRatings
253         opacthemes
254         OPACURLOpenInNewWindow
255         OpacAuthorities
256         opacbookbag
257         OpacBrowser
258         OpacBrowseResults
259         OpacCloud
260         OPACFinesTab
261         OpacHoldNotes
262         OpacItemLocation
263         OpacPasswordChange
264         OPACPatronDetails
265         OPACpatronimages
266         OPACPopupAuthorsSearch
267         OpacTopissue
268         opacuserlogin
269         QuoteOfTheDay
270         RequestOnOpac
271         reviewson
272         ShowReviewer
273         ShowReviewerPhoto
274         SocialNetworks
275         suggestion
276         AllowPurchaseSuggestionBranchChoice
277         OpacAllowPublicListCreation
278         OpacAllowSharingPrivateLists
279         OpacRenewalAllowed
280         OpacRenewalBranch
281         OPACViewOthersSuggestions
282         SearchMyLibraryFirst
283         AnonSuggestions
284         EnableOpacSearchHistory
285         OPACPrivacy
286         opacreadinghistory
287         TrackClicks
288         PatronSelfRegistration
289         OPACShelfBrowser
290         AutoEmailOpacUser
291         AutoEmailPrimaryAddress
292         autoMemberNum
293         BorrowerRenewalPeriodBase
294         checkdigit
295         EnableBorrowerFiles
296         EnhancedMessagingPreferences
297         ExtendedPatronAttributes
298         intranetreadinghistory
299         memberofinstitution
300         patronimages
301         TalkingTechItivaPhoneNotification
302         uppercasesurnames
303         IncludeSeeFromInSearches
304         OpacGroupResults
305         QueryAutoTruncate
306         QueryFuzzy
307         QueryStemming
308         QueryWeightFields
309         TraceCompleteSubfields
310         TraceSubjectSubdivisions
311         UseICU
312         UseQueryParser
313         defaultSortField
314         displayFacetCount
315         OPACdefaultSortField
316         OPACItemsResultsDisplay
317         expandedSearchOption
318         IntranetNumbersPreferPhrase
319         OPACNumbersPreferPhrase
320         opacSerialDefaultTab
321         RenewSerialAddsSuggestion
322         RoutingListAddReserves
323         RoutingSerials
324         SubscriptionHistory
325         Display856uAsImage
326         DisplayIconsXSLT
327         template
328         yuipath
329         HidePatronName
330         intranetbookbag
331         StaffDetailItemSelection
332         viewISBD
333         viewLabeledMARC
334         viewMARC
335         ILS-DI
336         OAI-PMH
337         version
338         /
339       )
340     {
341         $report->{systempreferences}{$_} = C4::Context->preference($_);
342     }
343     return $report;
344 }
345
346 =head2 ReportToCommunity
347
348   ReportToCommunity;
349
350 Send to hea.koha-community.org database informations
351
352 =cut
353
354 sub ReportToCommunity {
355     my $data = shift;
356     my $json = encode_json($data);
357
358     my $url = "http://hea.koha-community.org/upload.pl";
359     my $ua = LWP::UserAgent->new;
360     my $res = $ua->post(
361         $url,
362         'Content-type' => 'application/json;charset=utf-8',
363         Content => $json,
364     );
365     my $content = decode_json( $res->decoded_content );
366     if ( $content->{koha_id} ) {
367         C4::Context->set_preference( 'UsageStatsID', $content->{koha_id} );
368     }
369     if ( $content->{id} ) {
370         C4::Context->set_preference( 'UsageStatsPublicID', $content->{id} );
371     }
372 }
373
374 =head2 _count
375
376   $data = _count($table);
377
378 Count the number of records in $table tables
379
380 =cut
381
382 sub _count {
383     my $table = shift;
384
385     my $dbh = C4::Context->dbh;
386     my $sth = $dbh->prepare("SELECT count(*) from $table");
387     $sth->execute;
388     return $sth->fetchrow_array;
389 }
390
391 1;