Revert "Bug 16749: Adjustments for koha-plack"
[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         dontmerge
112         UseAuthoritiesForTracings
113         CatalogModuleRelink
114         hide_marc
115         IntranetBiblioDefaultView
116         LabelMARCView
117         OpacSuppression
118         SeparateHoldings
119         UseControlNumber
120         advancedMARCeditor
121         DefaultClassificationSource
122         EasyAnalyticalRecords
123         autoBarcode
124         item-level_itypes
125         marcflavour
126         PrefillItem
127         z3950NormalizeAuthor
128         SpineLabelAutoPrint
129         SpineLabelShowPrintOnBibDetails
130         BlockReturnOfWithdrawnItems
131         CalculateFinesOnReturn
132         AgeRestrictionOverride
133         AllFinesNeedOverride
134         AllowFineOverride
135         AllowItemsOnHoldCheckout
136         AllowNotForLoanOverride
137         AllowRenewalLimitOverride
138         AllowReturnToBranch
139         AllowTooManyOverride
140         AutomaticItemReturn
141         AutoRemoveOverduesRestrictions
142         CircControl
143         HomeOrHoldingBranch
144         InProcessingToShelvingCart
145         IssueLostItem
146         IssuingInProcess
147         ManInvInNoissuesCharge
148         OverduesBlockCirc
149         RenewalPeriodBase
150         RenewalSendNotice
151         RentalsInNoissuesCharge
152         ReturnBeforeExpiry
153         ReturnToShelvingCart
154         TransfersMaxDaysWarning
155         UseBranchTransferLimits
156         useDaysMode
157         UseTransportCostMatrix
158         UseCourseReserves
159         finesCalendar
160         FinesIncludeGracePeriod
161         finesMode
162         RefundLostItemFeeOnReturn
163         WhenLostChargeReplacementFee
164         WhenLostForgiveFine
165         AllowHoldDateInFuture
166         AllowHoldPolicyOverride
167         AllowHoldsOnDamagedItems
168         AllowHoldsOnPatronsPossessions
169         AutoResumeSuspendedHolds
170         canreservefromotherbranches
171         decreaseLoanHighHolds
172         DisplayMultiPlaceHold
173         emailLibrarianWhenHoldIsPlaced
174         ExpireReservesMaxPickUpDelay
175         OPACAllowHoldDateInFuture
176         OPACAllowUserToChooseBranch
177         ReservesControlBranch
178         ReservesNeedReturns
179         SuspendHoldsIntranet
180         SuspendHoldsOpac
181         TransferWhenCancelAllWaitingHolds
182         AllowAllMessageDeletion
183         AllowOfflineCirculation
184         CircAutocompl
185         CircAutoPrintQuickSlip
186         DisplayClearScreenButton
187         FilterBeforeOverdueReport
188         FineNotifyAtCheckin
189         itemBarcodeFallbackSearch
190         itemBarcodeInputFilter
191         previousIssuesDefaultSortOrder
192         RecordLocalUseOnReturn
193         AudioAlerts
194         SpecifyDueDate
195         todaysIssuesDefaultSortOrder
196         UpdateTotalIssuesOnCirc
197         UseTablesortForCirc
198         WaitingNotifyAtCheckin
199         AllowSelfCheckReturns
200         AutoSelfCheckAllowed
201         FRBRizeEditions
202         OPACFRBRizeEditions
203         AmazonCoverImages
204         OPACAmazonCoverImages
205         Babeltheque
206         BakerTaylorEnabled
207         GoogleJackets
208         HTML5MediaEnabled
209         IDreamBooksReadometer
210         IDreamBooksResults
211         IDreamBooksReviews
212         LibraryThingForLibrariesEnabled
213         LocalCoverImages
214         OPACLocalCoverImages
215         NovelistSelectEnabled
216         XISBN
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         OPACShowBarcode
245         OPACShowCheckoutName
246         OpacShowFiltersPulldownMobile
247         OPACShowHoldQueueDetails
248         OpacShowLibrariesPulldownMobile
249         OpacShowRecentComments
250         OPACShowUnusedAuthorities
251         OpacStarRatings
252         opacthemes
253         OPACURLOpenInNewWindow
254         OpacAuthorities
255         opacbookbag
256         OpacBrowser
257         OpacBrowseResults
258         OpacCloud
259         OPACFinesTab
260         OpacHoldNotes
261         OpacItemLocation
262         OpacPasswordChange
263         OPACPatronDetails
264         OPACpatronimages
265         OPACPopupAuthorsSearch
266         OpacTopissue
267         opacuserlogin
268         QuoteOfTheDay
269         RequestOnOpac
270         reviewson
271         ShowReviewer
272         ShowReviewerPhoto
273         SocialNetworks
274         suggestion
275         AllowPurchaseSuggestionBranchChoice
276         OpacAllowPublicListCreation
277         OpacAllowSharingPrivateLists
278         OpacRenewalAllowed
279         OpacRenewalBranch
280         OPACViewOthersSuggestions
281         SearchMyLibraryFirst
282         AnonSuggestions
283         EnableOpacSearchHistory
284         OPACPrivacy
285         opacreadinghistory
286         TrackClicks
287         PatronSelfRegistration
288         OPACShelfBrowser
289         AutoEmailOpacUser
290         AutoEmailPrimaryAddress
291         autoMemberNum
292         BorrowerRenewalPeriodBase
293         checkdigit
294         EnableBorrowerFiles
295         EnhancedMessagingPreferences
296         ExtendedPatronAttributes
297         intranetreadinghistory
298         memberofinstitution
299         patronimages
300         TalkingTechItivaPhoneNotification
301         uppercasesurnames
302         IncludeSeeFromInSearches
303         OpacGroupResults
304         QueryAutoTruncate
305         QueryFuzzy
306         QueryStemming
307         QueryWeightFields
308         TraceCompleteSubfields
309         TraceSubjectSubdivisions
310         UseICU
311         UseQueryParser
312         defaultSortField
313         displayFacetCount
314         OPACdefaultSortField
315         OPACItemsResultsDisplay
316         expandedSearchOption
317         IntranetNumbersPreferPhrase
318         OPACNumbersPreferPhrase
319         opacSerialDefaultTab
320         RenewSerialAddsSuggestion
321         RoutingListAddReserves
322         RoutingSerials
323         SubscriptionHistory
324         Display856uAsImage
325         DisplayIconsXSLT
326         template
327         yuipath
328         HidePatronName
329         intranetbookbag
330         StaffDetailItemSelection
331         viewISBD
332         viewLabeledMARC
333         viewMARC
334         ILS-DI
335         OAI-PMH
336         version
337         /
338       )
339     {
340         $report->{systempreferences}{$_} = C4::Context->preference($_);
341     }
342     return $report;
343 }
344
345 =head2 ReportToCommunity
346
347   ReportToCommunity;
348
349 Send to hea.koha-community.org database informations
350
351 =cut
352
353 sub ReportToCommunity {
354     my $data = shift;
355     my $json = encode_json($data);
356
357     my $url = "https://hea.koha-community.org/upload.pl";
358     my $ua = LWP::UserAgent->new;
359     my $res = $ua->post(
360         $url,
361         'Content-type' => 'application/json;charset=utf-8',
362         Content => $json,
363     );
364     my $content = decode_json( $res->decoded_content );
365     if ( $content->{koha_id} ) {
366         C4::Context->set_preference( 'UsageStatsID', $content->{koha_id} );
367     }
368     if ( $content->{id} ) {
369         C4::Context->set_preference( 'UsageStatsPublicID', $content->{id} );
370     }
371 }
372
373 =head2 _count
374
375   $data = _count($table);
376
377 Count the number of records in $table tables
378
379 =cut
380
381 sub _count {
382     my $table = shift;
383
384     my $dbh = C4::Context->dbh;
385     my $sth = $dbh->prepare("SELECT count(*) from $table");
386     $sth->execute;
387     return $sth->fetchrow_array;
388 }
389
390 1;