Bug 29697: Deal with the degraded view in detail.pl
[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         BiblioAddsAuthorities
156         AuthorityMergeLimit
157         AuthorityMergeMode
158         UseAuthoritiesForTracings
159         CatalogModuleRelink
160         hide_marc
161         IntranetBiblioDefaultView
162         LabelMARCView
163         OpacSuppression
164         SeparateHoldings
165         UseControlNumber
166         advancedMARCeditor
167         DefaultClassificationSource
168         EasyAnalyticalRecords
169         autoBarcode
170         item-level_itypes
171         marcflavour
172         PrefillItem
173         z3950NormalizeAuthor
174         SpineLabelAutoPrint
175         SpineLabelShowPrintOnBibDetails
176         BlockReturnOfLostItems
177         BlockReturnOfWithdrawnItems
178         CalculateFinesOnReturn
179         AgeRestrictionOverride
180         AllFinesNeedOverride
181         AllowFineOverride
182         AllowItemsOnHoldCheckoutSIP
183         AllowItemsOnHoldCheckoutSCO
184         AllowNotForLoanOverride
185         AllowRenewalLimitOverride
186         AllowReturnToBranch
187         AllowTooManyOverride
188         AutomaticItemReturn
189         AutoRemoveOverduesRestrictions
190         CircControl
191         HomeOrHoldingBranch
192         IssueLostItem
193         IssuingInProcess
194         ManInvInNoissuesCharge
195         OverduesBlockCirc
196         RenewalPeriodBase
197         RenewalSendNotice
198         RentalsInNoissuesCharge
199         ReturnBeforeExpiry
200         TransfersMaxDaysWarning
201         UseBranchTransferLimits
202         UseTransportCostMatrix
203         UseCourseReserves
204         finesCalendar
205         FinesIncludeGracePeriod
206         finesMode
207         RefundLostOnReturnControl
208         WhenLostChargeReplacementFee
209         WhenLostForgiveFine
210         AllowHoldDateInFuture
211         AllowHoldItemTypeSelection
212         AllowHoldPolicyOverride
213         AllowHoldsOnDamagedItems
214         AllowHoldsOnPatronsPossessions
215         AutoResumeSuspendedHolds
216         canreservefromotherbranches
217         decreaseLoanHighHolds
218         DisplayMultiPlaceHold
219         emailLibrarianWhenHoldIsPlaced
220         ExpireReservesMaxPickUpDelay
221         OPACAllowHoldDateInFuture
222         OPACAllowUserToChooseBranch
223         ReservesControlBranch
224         ReservesNeedReturns
225         SuspendHoldsIntranet
226         SuspendHoldsOpac
227         TransferWhenCancelAllWaitingHolds
228         AllowAllMessageDeletion
229         AllowOfflineCirculation
230         PatronAutoComplete
231         CircAutoPrintQuickSlip
232         DisplayClearScreenButton
233         FilterBeforeOverdueReport
234         FineNotifyAtCheckin
235         itemBarcodeFallbackSearch
236         itemBarcodeInputFilter
237         previousIssuesDefaultSortOrder
238         RecordLocalUseOnReturn
239         AudioAlerts
240         SpecifyDueDate
241         todaysIssuesDefaultSortOrder
242         UpdateTotalIssuesOnCirc
243         UseTablesortForCirc
244         WaitingNotifyAtCheckin
245         SCOAllowCheckin
246         AutoSelfCheckAllowed
247         FRBRizeEditions
248         OPACFRBRizeEditions
249         AmazonCoverImages
250         OPACAmazonCoverImages
251         Babeltheque
252         BakerTaylorEnabled
253         GoogleJackets
254         HTML5MediaEnabled
255         LibraryThingForLibrariesEnabled
256         LocalCoverImages
257         OPACLocalCoverImages
258         NovelistSelectEnabled
259         OpenLibraryCovers
260         OpenLibrarySearch
261         SyndeticsEnabled
262         TagsEnabled
263         CalendarFirstDayOfWeek
264         opaclanguagesdisplay
265         AcquisitionLog
266         AuthoritiesLog
267         BorrowersLog
268         CataloguingLog
269         FinesLog
270         IssueLog
271         ClaimsLog
272         ReturnLog
273         SubscriptionLog
274         BiblioDefaultView
275         COinSinOPACResults
276         DisplayOPACiconsXSLT
277         hidelostitems
278         OpacAddMastheadLibraryPulldown
279         OPACDisplay856uAsImage
280         OpacHighlightedWords
281         OpacKohaUrl
282         OpacMaintenance
283         OpacPublic
284         OpacSeparateHoldings
285         OPACShowCheckoutName
286         OpacShowFiltersPulldownMobile
287         OPACShowHoldQueueDetails
288         OpacShowRecentComments
289         OPACShowUnusedAuthorities
290         OpacStarRatings
291         opacthemes
292         OPACURLOpenInNewWindow
293         OpacAuthorities
294         opacbookbag
295         OpacBrowser
296         OpacBrowseResults
297         OpacCloud
298         OPACFinesTab
299         OpacHoldNotes
300         OpacItemLocation
301         OpacPasswordChange
302         OPACPatronDetails
303         OPACpatronimages
304         OPACPopupAuthorsSearch
305         OpacTopissue
306         opacuserlogin
307         QuoteOfTheDay
308         OPACHoldRequests
309         OPACComments
310         ShowReviewer
311         ShowReviewerPhoto
312         SocialNetworks
313         suggestion
314         OpacAllowPublicListCreation
315         OpacAllowSharingPrivateLists
316         OpacRenewalAllowed
317         OpacRenewalBranch
318         OPACViewOthersSuggestions
319         SearchMyLibraryFirst
320         AnonSuggestions
321         EnableOpacSearchHistory
322         OPACPrivacy
323         opacreadinghistory
324         TrackClicks
325         PatronSelfRegistration
326         OPACShelfBrowser
327         AutoEmailNewUser
328         AutoEmailPrimaryAddress
329         autoMemberNum
330         BorrowerRenewalPeriodBase
331         EnableBorrowerFiles
332         EnhancedMessagingPreferences
333         ExtendedPatronAttributes
334         intranetreadinghistory
335         patronimages
336         TalkingTechItivaPhoneNotification
337         uppercasesurnames
338         IncludeSeeFromInSearches
339         QueryAutoTruncate
340         QueryFuzzy
341         QueryStemming
342         QueryWeightFields
343         TraceCompleteSubfields
344         TraceSubjectSubdivisions
345         UseICUStyleQuotes
346         defaultSortField
347         displayFacetCount
348         OPACdefaultSortField
349         expandedSearchOption
350         IntranetNumbersPreferPhrase
351         OPACNumbersPreferPhrase
352         opacSerialDefaultTab
353         RenewSerialAddsSuggestion
354         RoutingListAddReserves
355         RoutingSerials
356         SubscriptionHistory
357         Display856uAsImage
358         DisplayIconsXSLT
359         template
360         yuipath
361         HidePatronName
362         intranetbookbag
363         StaffDetailItemSelection
364         viewISBD
365         viewLabeledMARC
366         viewMARC
367         ILS-DI
368         OAI-PMH
369         version
370         /;
371
372     return \@preferences;
373 }
374
375 =head2 _count
376
377   $data = _count($table);
378
379 Count the number of records in $table tables
380
381 =cut
382
383 sub _count {
384     my $table = shift;
385
386     my $dbh = C4::Context->dbh;
387     my $sth = $dbh->prepare("SELECT count(*) from $table");
388     $sth->execute;
389     return $sth->fetchrow_array;
390 }
391
392 1;