Bug 24735: Remove QueryParser-related code
[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         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         AllowItemsOnHoldCheckoutSIP
138         AllowItemsOnHoldCheckoutSCO
139         AllowNotForLoanOverride
140         AllowRenewalLimitOverride
141         AllowReturnToBranch
142         AllowTooManyOverride
143         AutomaticItemReturn
144         AutoRemoveOverduesRestrictions
145         CircControl
146         HomeOrHoldingBranch
147         IssueLostItem
148         IssuingInProcess
149         ManInvInNoissuesCharge
150         OverduesBlockCirc
151         RenewalPeriodBase
152         RenewalSendNotice
153         RentalsInNoissuesCharge
154         ReturnBeforeExpiry
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         PatronAutoComplete
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         OpenLibraryCovers
218         OpenLibrarySearch
219         UseKohaPlugins
220         SyndeticsEnabled
221         TagsEnabled
222         CalendarFirstDayOfWeek
223         opaclanguagesdisplay
224         AuthoritiesLog
225         BorrowersLog
226         CataloguingLog
227         FinesLog
228         IssueLog
229         LetterLog
230         ReturnLog
231         SubscriptionLog
232         BiblioDefaultView
233         COinSinOPACResults
234         DisplayOPACiconsXSLT
235         hidelostitems
236         HighlightOwnItemsOnOPAC
237         OpacAddMastheadLibraryPulldown
238         OPACDisplay856uAsImage
239         OpacHighlightedWords
240         OpacKohaUrl
241         OpacMaintenance
242         OpacPublic
243         OpacSeparateHoldings
244         OPACShowCheckoutName
245         OpacShowFiltersPulldownMobile
246         OPACShowHoldQueueDetails
247         OpacShowRecentComments
248         OPACShowUnusedAuthorities
249         OpacStarRatings
250         opacthemes
251         OPACURLOpenInNewWindow
252         OpacAuthorities
253         opacbookbag
254         OpacBrowser
255         OpacBrowseResults
256         OpacCloud
257         OPACFinesTab
258         OpacHoldNotes
259         OpacItemLocation
260         OpacPasswordChange
261         OPACPatronDetails
262         OPACpatronimages
263         OPACPopupAuthorsSearch
264         OpacTopissue
265         opacuserlogin
266         QuoteOfTheDay
267         RequestOnOpac
268         reviewson
269         ShowReviewer
270         ShowReviewerPhoto
271         SocialNetworks
272         suggestion
273         AllowPurchaseSuggestionBranchChoice
274         OpacAllowPublicListCreation
275         OpacAllowSharingPrivateLists
276         OpacRenewalAllowed
277         OpacRenewalBranch
278         OPACViewOthersSuggestions
279         SearchMyLibraryFirst
280         AnonSuggestions
281         EnableOpacSearchHistory
282         OPACPrivacy
283         opacreadinghistory
284         TrackClicks
285         PatronSelfRegistration
286         OPACShelfBrowser
287         AutoEmailOpacUser
288         AutoEmailPrimaryAddress
289         autoMemberNum
290         BorrowerRenewalPeriodBase
291         EnableBorrowerFiles
292         EnhancedMessagingPreferences
293         ExtendedPatronAttributes
294         intranetreadinghistory
295         patronimages
296         TalkingTechItivaPhoneNotification
297         uppercasesurnames
298         IncludeSeeFromInSearches
299         OpacGroupResults
300         QueryAutoTruncate
301         QueryFuzzy
302         QueryStemming
303         QueryWeightFields
304         TraceCompleteSubfields
305         TraceSubjectSubdivisions
306         UseICU
307         defaultSortField
308         displayFacetCount
309         OPACdefaultSortField
310         OPACItemsResultsDisplay
311         expandedSearchOption
312         IntranetNumbersPreferPhrase
313         OPACNumbersPreferPhrase
314         opacSerialDefaultTab
315         RenewSerialAddsSuggestion
316         RoutingListAddReserves
317         RoutingSerials
318         SubscriptionHistory
319         Display856uAsImage
320         DisplayIconsXSLT
321         template
322         yuipath
323         HidePatronName
324         intranetbookbag
325         StaffDetailItemSelection
326         viewISBD
327         viewLabeledMARC
328         viewMARC
329         ILS-DI
330         OAI-PMH
331         version
332         /
333       )
334     {
335         $report->{systempreferences}{$_} = C4::Context->preference($_);
336     }
337     return $report;
338 }
339
340 =head2 ReportToCommunity
341
342   ReportToCommunity;
343
344 Send to hea.koha-community.org database informations
345
346 =cut
347
348 sub ReportToCommunity {
349     my $data = shift;
350     my $json = encode_json($data);
351
352     my $url = "https://hea.koha-community.org/upload.pl";
353     my $ua = LWP::UserAgent->new;
354     my $res = $ua->post(
355         $url,
356         'Content-type' => 'application/json;charset=utf-8',
357         Content => $json,
358     );
359     my $content = decode_json( $res->decoded_content );
360     if ( $content->{koha_id} ) {
361         C4::Context->set_preference( 'UsageStatsID', $content->{koha_id} );
362     }
363     if ( $content->{id} ) {
364         C4::Context->set_preference( 'UsageStatsPublicID', $content->{id} );
365     }
366 }
367
368 =head2 _count
369
370   $data = _count($table);
371
372 Count the number of records in $table tables
373
374 =cut
375
376 sub _count {
377     my $table = shift;
378
379     my $dbh = C4::Context->dbh;
380     my $sth = $dbh->prepare("SELECT count(*) from $table");
381     $sth->execute;
382     return $sth->fetchrow_array;
383 }
384
385 1;