Bug 35231: Resolve crash on unexisting patron in Auth
[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 qw( decode_json encode_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 ( @{ _shared_preferences() } )
91     {
92         $report->{systempreferences}{$_} = C4::Context->preference($_);
93     }
94     return $report;
95 }
96
97 =head2 ReportToCommunity
98
99   ReportToCommunity;
100
101 Send to hea.koha-community.org database informations
102
103 =cut
104
105 sub ReportToCommunity {
106     my $data = shift;
107     my $json = encode_json($data);
108
109     my $url = "https://hea.koha-community.org/upload.pl";
110     my $ua = LWP::UserAgent->new;
111     my $res = $ua->post(
112         $url,
113         'Content-type' => 'application/json;charset=utf-8',
114         Content => $json,
115     );
116     my $content = decode_json( $res->decoded_content );
117     if ( $content->{koha_id} ) {
118         C4::Context->set_preference( 'UsageStatsID', $content->{koha_id} );
119     }
120     if ( $content->{id} ) {
121         C4::Context->set_preference( 'UsageStatsPublicID', $content->{id} );
122     }
123 }
124
125 =head2 _shared_preferences
126
127     my $preferences = C4::UsageStats::_shared_preferences
128
129 Returns an I<arreyref> with the system preferences to be shared.
130
131 =cut
132
133 sub _shared_preferences {
134
135     my @preferences = qw/
136         AcqCreateItem
137         AcqWarnOnDuplicateInvoice
138         AcqViewBaskets
139         BasketConfirmations
140         OrderPdfFormat
141         casAuthentication
142         casLogout
143         AllowPKIAuth
144         DebugLevel
145         CSVDelimiter
146         noItemTypeImages
147         OpacNoItemTypeImages
148         virtualshelves
149         AutoLocation
150         IndependentBranches
151         SessionStorage
152         Persona
153         AuthDisplayHierarchy
154         AutoCreateAuthorities
155         AutoLinkBiblios
156         RequireChoosingExistingAuthority
157         AuthorityMergeLimit
158         AuthorityMergeMode
159         UseAuthoritiesForTracings
160         CatalogModuleRelink
161         hide_marc
162         IntranetBiblioDefaultView
163         LabelMARCView
164         OpacSuppression
165         SeparateHoldings
166         UseControlNumber
167         advancedMARCeditor
168         DefaultClassificationSource
169         EasyAnalyticalRecords
170         autoBarcode
171         item-level_itypes
172         marcflavour
173         PrefillItem
174         z3950NormalizeAuthor
175         SpineLabelAutoPrint
176         SpineLabelShowPrintOnBibDetails
177         BlockReturnOfLostItems
178         BlockReturnOfWithdrawnItems
179         CalculateFinesOnReturn
180         AgeRestrictionOverride
181         AllFinesNeedOverride
182         AllowFineOverride
183         AllowItemsOnHoldCheckoutSIP
184         AllowItemsOnHoldCheckoutSCO
185         AllowNotForLoanOverride
186         AllowRenewalLimitOverride
187         AllowReturnToBranch
188         AllowTooManyOverride
189         AutomaticItemReturn
190         AutoRemoveOverduesRestrictions
191         CircControl
192         HomeOrHoldingBranch
193         IssueLostItem
194         IssuingInProcess
195         OverduesBlockCirc
196         RenewalPeriodBase
197         RenewalSendNotice
198         ReturnBeforeExpiry
199         TransfersMaxDaysWarning
200         UseBranchTransferLimits
201         UseTransportCostMatrix
202         UseCourseReserves
203         finesCalendar
204         FinesIncludeGracePeriod
205         finesMode
206         RefundLostOnReturnControl
207         WhenLostChargeReplacementFee
208         WhenLostForgiveFine
209         AllowHoldDateInFuture
210         AllowHoldItemTypeSelection
211         AllowHoldPolicyOverride
212         AllowHoldsOnDamagedItems
213         AllowHoldsOnPatronsPossessions
214         AutoResumeSuspendedHolds
215         canreservefromotherbranches
216         decreaseLoanHighHolds
217         DisplayMultiPlaceHold
218         emailLibrarianWhenHoldIsPlaced
219         ExpireReservesMaxPickUpDelay
220         OPACAllowHoldDateInFuture
221         OPACAllowUserToChooseBranch
222         ReservesControlBranch
223         ReservesNeedReturns
224         SuspendHoldsIntranet
225         SuspendHoldsOpac
226         TransferWhenCancelAllWaitingHolds
227         AllowAllMessageDeletion
228         PatronAutoComplete
229         CircAutoPrintQuickSlip
230         DisplayClearScreenButton
231         FilterBeforeOverdueReport
232         FineNotifyAtCheckin
233         itemBarcodeFallbackSearch
234         itemBarcodeInputFilter
235         previousIssuesDefaultSortOrder
236         RecordLocalUseOnReturn
237         AudioAlerts
238         SpecifyDueDate
239         todaysIssuesDefaultSortOrder
240         UpdateTotalIssuesOnCirc
241         UseTablesortForCirc
242         WaitingNotifyAtCheckin
243         SCOAllowCheckin
244         AutoSelfCheckAllowed
245         FRBRizeEditions
246         OPACFRBRizeEditions
247         AmazonCoverImages
248         OPACAmazonCoverImages
249         Babeltheque
250         BakerTaylorEnabled
251         GoogleJackets
252         HTML5MediaEnabled
253         LibraryThingForLibrariesEnabled
254         LocalCoverImages
255         OPACLocalCoverImages
256         NovelistSelectEnabled
257         OpenLibraryCovers
258         OpenLibrarySearch
259         SyndeticsEnabled
260         TagsEnabled
261         CalendarFirstDayOfWeek
262         opaclanguagesdisplay
263         AcquisitionLog
264         AuthoritiesLog
265         BorrowersLog
266         CataloguingLog
267         FinesLog
268         IssueLog
269         ClaimsLog
270         ReturnLog
271         SubscriptionLog
272         BiblioDefaultView
273         COinSinOPACResults
274         DisplayOPACiconsXSLT
275         hidelostitems
276         OpacAddMastheadLibraryPulldown
277         OPACDisplay856uAsImage
278         OpacHighlightedWords
279         OpacKohaUrl
280         OpacMaintenance
281         OpacPublic
282         OpacSeparateHoldings
283         OPACShowCheckoutName
284         OpacShowFiltersPulldownMobile
285         OPACShowHoldQueueDetails
286         OpacShowRecentComments
287         OPACShowUnusedAuthorities
288         OpacStarRatings
289         opacthemes
290         OPACURLOpenInNewWindow
291         OpacAuthorities
292         opacbookbag
293         OpacBrowser
294         OpacBrowseResults
295         OpacCloud
296         OPACFinesTab
297         OpacHoldNotes
298         OpacItemLocation
299         OpacPasswordChange
300         OPACPatronDetails
301         OPACpatronimages
302         OPACPopupAuthorsSearch
303         OpacTopissue
304         opacuserlogin
305         QuoteOfTheDay
306         OPACHoldRequests
307         OPACComments
308         ShowReviewer
309         ShowReviewerPhoto
310         SocialNetworks
311         suggestion
312         OpacAllowPublicListCreation
313         OpacAllowSharingPrivateLists
314         OpacRenewalAllowed
315         OpacRenewalBranch
316         OPACViewOthersSuggestions
317         SearchMyLibraryFirst
318         AnonSuggestions
319         EnableOpacSearchHistory
320         OPACPrivacy
321         opacreadinghistory
322         TrackClicks
323         PatronSelfRegistration
324         OPACShelfBrowser
325         AutoEmailNewUser
326         EmailFieldPrimary
327         autoMemberNum
328         BorrowerRenewalPeriodBase
329         EnableBorrowerFiles
330         EnhancedMessagingPreferences
331         ExtendedPatronAttributes
332         intranetreadinghistory
333         patronimages
334         TalkingTechItivaPhoneNotification
335         uppercasesurnames
336         IncludeSeeFromInSearches
337         QueryAutoTruncate
338         QueryFuzzy
339         QueryStemming
340         QueryWeightFields
341         TraceCompleteSubfields
342         TraceSubjectSubdivisions
343         UseICUStyleQuotes
344         defaultSortField
345         displayFacetCount
346         OPACdefaultSortField
347         expandedSearchOption
348         IntranetNumbersPreferPhrase
349         OPACNumbersPreferPhrase
350         opacSerialDefaultTab
351         RenewSerialAddsSuggestion
352         RoutingListAddReserves
353         RoutingSerials
354         SubscriptionHistory
355         Display856uAsImage
356         DisplayIconsXSLT
357         template
358         yuipath
359         HidePatronName
360         intranetbookbag
361         StaffDetailItemSelection
362         viewISBD
363         viewLabeledMARC
364         viewMARC
365         ILS-DI
366         OAI-PMH
367         version
368         /;
369
370     return \@preferences;
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;