Bug 5786 - Move AllowOnShelfHolds and OPACItemHolds system prefs to the Circulation...
[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
27
28 C4::UsageStats
29
30 =head1 DESCRIPTION
31
32 This package contains what is needed to report Koha statistics to hea
33 hea.koha-community.org is the server that centralize Koha setups informations
34 Koha libraries are encouraged to provide informations about their collections,
35 their structure,...
36
37 =head2 NeedUpdate
38
39   $needUpdateYN = C4::UsageStats::NeedUpdate;
40
41 Returns Y (1) if the last update is more than 1 month old
42 This way, even if the cronjob is run every minute, the webservice will be called
43 only once a month !
44
45 =cut
46
47 sub NeedUpdate {
48     my $lastupdated = C4::Context->preference('UsageStatsLastUpdateTime') || 0;
49     my $now = strftime( "%s", localtime );
50
51     # Need to launch cron.
52     return 1 if $now - $lastupdated >= 2592000;
53
54     # Data don't need to be updated
55     return 0;
56 }
57
58 sub BuildReport {
59     my $report = {
60         library => {
61             id   => C4::Context->preference('UsageStatsID')          || 0,
62             name => C4::Context->preference('UsageStatsLibraryName') || q||,
63             url => C4::Context->preference('UsageStatsLibraryUrl')   || q||,
64             type => C4::Context->preference('UsageStatsLibraryType') || q||,
65             country => C4::Context->preference('UsageStatsCountry') || q||,
66         },
67     };
68
69     # Get database volumetry.
70     foreach (
71         qw/biblio items auth_header old_issues old_reserves borrowers aqorders subscription/
72       )
73     {
74         $report->{volumetry}{$_} = _count($_);
75     }
76
77     # Get systempreferences.
78     foreach (
79         qw/
80         AcqCreateItem
81         AcqWarnOnDuplicateInvoice
82         AcqViewBaskets
83         BasketConfirmations
84         OrderPdfFormat
85         casAuthentication
86         casLogout
87         AllowPkiAuth
88         DebugLevel
89         delimiter
90         noItemTypeImages
91         virtualshelves
92         AutoLocation
93         IndependentBranches
94         SessionStorage
95         Persona
96         AuthDisplayHierarchy
97         AutoCreateAuthorities
98         BiblioAddsAuthorities
99         dontmerge
100         UseAuthoritiesForTracings
101         CatalogModuleRelink
102         hide_marc
103         IntranetBiblioDefaultView
104         LabelMARCView
105         OpacSuppression
106         SeparateHoldings
107         UseControlNumber
108         advancedMARCeditor
109         DefaultClassificationSource
110         EasyAnalyticalRecords
111         autoBarcode
112         item-level_itypes
113         marcflavour
114         PrefillItem
115         z3950NormalizeAuthor
116         SpineLabelAutoPrint
117         SpineLabelShowPrintOnBibDetails
118         BlockReturnOfWithdrawnItems
119         CalculateFinesOnReturn
120         AgeRestrictionOverride
121         AllFinesNeedOverride
122         AllowFineOverride
123         AllowItemsOnHoldCheckout
124         AllowNotForLoanOverride
125         AllowRenewalLimitOverride
126         AllowReturnToBranch
127         AllowTooManyOverride
128         AutomaticItemReturn
129         AutoRemoveOverduesRestrictions
130         CircControl
131         HomeOrHoldingBranch
132         HomeOrHoldingBranchReturn
133         InProcessingToShelvingCart
134         IssueLostItem
135         IssuingInProcess
136         ManInvInNoissuesCharge
137         OverduesBlockCirc
138         RenewalPeriodBase
139         RenewalSendNotice
140         RentalsInNoissuesCharge
141         ReturnBeforeExpiry
142         ReturnToShelvingCart
143         TransfersMaxDaysWarning
144         UseBranchTransferLimits
145         useDaysMode
146         UseTransportCostMatrix
147         UseCourseReserves
148         finesCalendar
149         FinesIncludeGracePeriod
150         finesMode
151         RefundLostItemFeeOnReturn
152         WhenLostChargeReplacementFee
153         WhenLostForgiveFine
154         AllowHoldDateInFuture
155         AllowHoldPolicyOverride
156         AllowHoldsOnDamagedItems
157         AllowHoldsOnPatronsPossessions
158         AutoResumeSuspendedHolds
159         canreservefromotherbranches
160         decreaseLoanHighHolds
161         DisplayMultiPlaceHold
162         emailLibrarianWhenHoldIsPlaced
163         ExpireReservesMaxPickUpDelay
164         OPACAllowHoldDateInFuture
165         OPACAllowUserToChooseBranch
166         ReservesControlBranch
167         ReservesNeedReturns
168         SuspendHoldsIntranet
169         SuspendHoldsOpac
170         TransferWhenCancelAllWaitingHolds
171         AllowAllMessageDeletion
172         AllowOfflineCirculation
173         CircAutocompl
174         CircAutoPrintQuickSlip
175         DisplayClearScreenButton
176         FilterBeforeOverdueReport
177         FineNotifyAtCheckin
178         itemBarcodeFallbackSearch
179         itemBarcodeInputFilter
180         previousIssuesDefaultSortOrder
181         RecordLocalUseOnReturn
182         soundon
183         SpecifyDueDate
184         todaysIssuesDefaultSortOrder
185         UpdateTotalIssuesOnCirc
186         UseTablesortForCirc
187         WaitingNotifyAtCheckin
188         AllowSelfCheckReturns
189         AutoSelfCheckAllowed
190         FRBRizeEditions
191         OPACFRBRizeEditions
192         AmazonCoverImages
193         OPACAmazonCoverImages
194         Babeltheque
195         BakerTaylorEnabled
196         GoogleJackets
197         HTML5MediaEnabled
198         IDreamBooksReadometer
199         IDreamBooksResults
200         IDreamBooksReviews
201         LibraryThingForLibrariesEnabled
202         LocalCoverImages
203         OPACLocalCoverImages
204         NovelistSelectEnabled
205         XISBN
206         OpenLibraryCovers
207         UseKohaPlugins
208         SyndeticsEnabled
209         TagsEnabled
210         CalendarFirstDayOfWeek
211         opaclanguagesdisplay
212         AuthoritiesLog
213         BorrowersLog
214         CataloguingLog
215         FinesLog
216         IssueLog
217         LetterLog
218         ReturnLog
219         SubscriptionLog
220         AuthorisedValueImages
221         BiblioDefaultView
222         COinSinOPACResults
223         DisplayOPACiconsXSLT
224         hidelostitems
225         HighlightOwnItemsOnOPAC
226         OpacAddMastheadLibraryPulldown
227         OPACDisplay856uAsImage
228         OpacHighlightedWords
229         OpacKohaUrl
230         OpacMaintenance
231         OpacPublic
232         OpacSeparateHoldings
233         OPACShowBarcode
234         OPACShowCheckoutName
235         OpacShowFiltersPulldownMobile
236         OPACShowHoldQueueDetails
237         OpacShowLibrariesPulldownMobile
238         OpacShowRecentComments
239         OPACShowUnusedAuthorities
240         OpacStarRatings
241         opacthemes
242         OPACURLOpenInNewWindow
243         OpacAuthorities
244         opacbookbag
245         OpacBrowser
246         OpacBrowseResults
247         OpacCloud
248         OPACFinesTab
249         OpacHoldNotes
250         OpacItemLocation
251         OpacPasswordChange
252         OPACPatronDetails
253         OPACpatronimages
254         OPACPopupAuthorsSearch
255         OpacTopissue
256         opacuserlogin
257         QuoteOfTheDay
258         RequestOnOpac
259         reviewson
260         ShowReviewer
261         ShowReviewerPhoto
262         SocialNetworks
263         suggestion
264         AllowPurchaseSuggestionBranchChoice
265         OpacAllowPublicListCreation
266         OpacAllowSharingPrivateLists
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;