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