Bug 11926: Add new sysprefs and fix encoding issues
[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 =head1 NAME C4::UsageStats
27
28 =head1 DESCRIPTION
29
30 This package contains what is needed to report Koha statistics to hea
31 hea.koha-community.org is the server that centralize Koha setups informations
32 Koha libraries are encouraged to provide informations about their collections,
33 their structure,...
34
35 =head2 NeedUpdate
36
37   $needUpdateYN = C4::UsageStats::NeedUpdate;
38
39 Returns Y (1) if the last update is more than 1 month old
40 This way, even if the cronjob is run every minute, the webservice will be called
41 only once a month !
42
43 =cut
44
45 sub NeedUpdate {
46     my $lastupdated = C4::Context->preference('UsageStatsLastUpdateTime') || 0;
47     my $now = strftime( "%s", localtime );
48
49     # Need to launch cron.
50     return 1 if $now - $lastupdated >= 2592000;
51
52     # Data don't need to be updated
53     return 0;
54 }
55
56 sub BuildReport {
57     my $report = {
58         library => {
59             id   => C4::Context->preference('UsageStatsID')          || 0,
60             name => C4::Context->preference('UsageStatsLibraryName') || q||,
61             url => C4::Context->preference('UsageStatsLibraryUrl')   || q||,
62             type => C4::Context->preference('UsageStatsLibraryType') || q||,
63             country => C4::Context->preference('UsageStatsCountry') || q||,
64         },
65     };
66
67     # Get database volumetry.
68     foreach (
69         qw/biblio auth_header old_issues old_reserves borrowers aqorders subscription/
70       )
71     {
72         $report->{volumetry}{$_} = _count($_);
73     }
74
75     # Get systempreferences.
76     foreach (
77         qw/
78         AcqCreateItem
79         AcqWarnOnDuplicateInvoice
80         AcqViewBaskets
81         BasketConfirmations
82         OrderPdfFormat
83         casAuthentication
84         casLogout
85         AllowPkiAuth
86         DebugLevel
87         delimiter
88         noItemTypeImages
89         virtualshelves
90         AutoLocation
91         IndependentBranches
92         SessionStorage
93         Persona
94         AuthDisplayHierarchy
95         AutoCreateAuthorities
96         BiblioAddsAuthorities
97         dontmerge
98         UseAuthoritiesForTracings
99         CatalogModuleRelink
100         hide_marc
101         IntranetBiblioDefaultView
102         LabelMARCView
103         OpacSuppression
104         SeparateHoldings
105         UseControlNumber
106         advancedMARCeditor
107         DefaultClassificationSource
108         EasyAnalyticalRecords
109         autoBarcode
110         item-level_itypes
111         marcflavour
112         PrefillItem
113         z3950NormalizeAuthor
114         SpineLabelAutoPrint
115         SpineLabelShowPrintOnBibDetails
116         BlockReturnOfWithdrawnItems
117         CalculateFinesOnReturn
118         AgeRestrictionOverride
119         AllFinesNeedOverride
120         AllowFineOverride
121         AllowItemsOnHoldCheckout
122         AllowNotForLoanOverride
123         AllowRenewalLimitOverride
124         AllowReturnToBranch
125         AllowTooManyOverride
126         AutomaticItemReturn
127         AutoRemoveOverduesRestrictions
128         CircControl
129         HomeOrHoldingBranch
130         HomeOrHoldingBranchReturn
131         InProcessingToShelvingCart
132         IssueLostItem
133         IssuingInProcess
134         ManInvInNoissuesCharge
135         OverduesBlockCirc
136         RenewalPeriodBase
137         RenewalSendNotice
138         RentalsInNoissuesCharge
139         ReturnBeforeExpiry
140         ReturnToShelvingCart
141         TransfersMaxDaysWarning
142         UseBranchTransferLimits
143         useDaysMode
144         UseTransportCostMatrix
145         UseCourseReserves
146         finesCalendar
147         FinesIncludeGracePeriod
148         finesMode
149         RefundLostItemFeeOnReturn
150         WhenLostChargeReplacementFee
151         WhenLostForgiveFine
152         AllowHoldDateInFuture
153         AllowHoldPolicyOverride
154         AllowHoldsOnDamagedItems
155         AllowHoldsOnPatronsPossessions
156         AllowOnShelfHolds
157         AutoResumeSuspendedHolds
158         canreservefromotherbranches
159         decreaseLoanHighHolds
160         DisplayMultiPlaceHold
161         emailLibrarianWhenHoldIsPlaced
162         ExpireReservesMaxPickUpDelay
163         OPACAllowHoldDateInFuture
164         OPACAllowUserToChooseBranch
165         ReservesControlBranch
166         ReservesNeedReturns
167         SuspendHoldsIntranet
168         SuspendHoldsOpac
169         TransferWhenCancelAllWaitingHolds
170         AllowAllMessageDeletion
171         AllowOfflineCirculation
172         CircAutocompl
173         CircAutoPrintQuickSlip
174         DisplayClearScreenButton
175         FilterBeforeOverdueReport
176         FineNotifyAtCheckin
177         itemBarcodeFallbackSearch
178         itemBarcodeInputFilter
179         previousIssuesDefaultSortOrder
180         RecordLocalUseOnReturn
181         soundon
182         SpecifyDueDate
183         todaysIssuesDefaultSortOrder
184         UpdateTotalIssuesOnCirc
185         UseTablesortForCirc
186         WaitingNotifyAtCheckin
187         AllowSelfCheckReturns
188         AutoSelfCheckAllowed
189         FRBRizeEditions
190         OPACFRBRizeEditions
191         AmazonCoverImages
192         OPACAmazonCoverImages
193         Babeltheque
194         BakerTaylorEnabled
195         GoogleJackets
196         HTML5MediaEnabled
197         IDreamBooksReadometer
198         IDreamBooksResults
199         IDreamBooksReviews
200         LibraryThingForLibrariesEnabled
201         LocalCoverImages
202         OPACLocalCoverImages
203         NovelistSelectEnabled
204         XISBN
205         OpenLibraryCovers
206         UseKohaPlugins
207         SyndeticsEnabled
208         TagsEnabled
209         CalendarFirstDayOfWeek
210         opaclanguagesdisplay
211         AuthoritiesLog
212         BorrowersLog
213         CataloguingLog
214         FinesLog
215         IssueLog
216         LetterLog
217         ReturnLog
218         SubscriptionLog
219         AuthorisedValueImages
220         BiblioDefaultView
221         COinSinOPACResults
222         DisplayOPACiconsXSLT
223         hidelostitems
224         HighlightOwnItemsOnOPAC
225         OpacAddMastheadLibraryPulldown
226         OPACDisplay856uAsImage
227         OpacHighlightedWords
228         OpacKohaUrl
229         OpacMaintenance
230         OpacPublic
231         OpacSeparateHoldings
232         OPACShowBarcode
233         OPACShowCheckoutName
234         OpacShowFiltersPulldownMobile
235         OPACShowHoldQueueDetails
236         OpacShowLibrariesPulldownMobile
237         OpacShowRecentComments
238         OPACShowUnusedAuthorities
239         OpacStarRatings
240         opacthemes
241         OPACURLOpenInNewWindow
242         OpacAuthorities
243         opacbookbag
244         OpacBrowser
245         OpacBrowseResults
246         OpacCloud
247         OPACFinesTab
248         OpacHoldNotes
249         OpacItemLocation
250         OpacPasswordChange
251         OPACPatronDetails
252         OPACpatronimages
253         OPACPopupAuthorsSearch
254         OpacTopissue
255         opacuserlogin
256         QuoteOfTheDay
257         RequestOnOpac
258         reviewson
259         ShowReviewer
260         ShowReviewerPhoto
261         SocialNetworks
262         suggestion
263         AllowPurchaseSuggestionBranchChoice
264         OpacAllowPublicListCreation
265         OpacAllowSharingPrivateLists
266         OPACItemHolds
267         OpacRenewalAllowed
268         OpacRenewalBranch
269         OPACViewOthersSuggestions
270         SearchMyLibraryFirst
271         singleBranchMode
272         AnonSuggestions
273         EnableOpacSearchHistory
274         OPACPrivacy
275         opacreadinghistory
276         TrackClicks
277         PatronSelfRegistration
278         OPACShelfBrowser
279         AddPatronLists
280         AutoEmailOpacUser
281         AutoEmailPrimaryAddress
282         autoMemberNum
283         BorrowerRenewalPeriodBase
284         checkdigit
285         EnableBorrowerFiles
286         EnhancedMessagingPreferences
287         ExtendedPatronAttributes
288         intranetreadinghistory
289         memberofinstitution
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         UseQueryParser
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         StaffAuthorisedValueImages
318         template
319         yuipath
320         HidePatronName
321         intranetbookbag
322         StaffDetailItemSelection
323         viewISBD
324         viewLabeledMARC
325         viewMARC
326         ILS-DI
327         OAI-PMH
328         version
329         /
330       )
331     {
332         $report->{systempreferences}{$_} = C4::Context->preference($_);
333     }
334     return $report;
335 }
336
337 =head2 ReportToCommunity
338
339   ReportToCommunity;
340
341 Send to hea.koha-community.org database informations
342
343 =cut
344
345 sub ReportToCommunity {
346     my $data = shift;
347     my $json = encode_json($data);
348
349     my $url = "http://hea.koha-community.org/upload.pl";
350     my $ua = LWP::UserAgent->new;
351     my $res = $ua->post(
352         $url,
353         'Content-type' => 'application/json;charset=utf-8',
354         Content => $json,
355     );
356     my $content = decode_json( $res->decoded_content );
357     C4::Context->set_preference( 'UsageStatsID',
358         $content->{library}{id} );
359 }
360
361 =head2 _count
362
363   $data = _count($table);
364
365 Count the number of records in $table tables
366
367 =cut
368
369 sub _count {
370     my $table = shift;
371
372     my $dbh = C4::Context->dbh;
373     my $sth = $dbh->prepare("SELECT count(*) from $table");
374     $sth->execute;
375     return $sth->fetchrow_array;
376 }
377
378 1;