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