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