Bug 33815: Do not explode if logged in user modify their own userid
[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         AllowOfflineCirculation
229         PatronAutoComplete
230         CircAutoPrintQuickSlip
231         DisplayClearScreenButton
232         FilterBeforeOverdueReport
233         FineNotifyAtCheckin
234         itemBarcodeFallbackSearch
235         itemBarcodeInputFilter
236         previousIssuesDefaultSortOrder
237         RecordLocalUseOnReturn
238         AudioAlerts
239         SpecifyDueDate
240         todaysIssuesDefaultSortOrder
241         UpdateTotalIssuesOnCirc
242         UseTablesortForCirc
243         WaitingNotifyAtCheckin
244         SCOAllowCheckin
245         AutoSelfCheckAllowed
246         FRBRizeEditions
247         OPACFRBRizeEditions
248         AmazonCoverImages
249         OPACAmazonCoverImages
250         Babeltheque
251         BakerTaylorEnabled
252         GoogleJackets
253         HTML5MediaEnabled
254         LibraryThingForLibrariesEnabled
255         LocalCoverImages
256         OPACLocalCoverImages
257         NovelistSelectEnabled
258         OpenLibraryCovers
259         OpenLibrarySearch
260         SyndeticsEnabled
261         TagsEnabled
262         CalendarFirstDayOfWeek
263         opaclanguagesdisplay
264         AcquisitionLog
265         AuthoritiesLog
266         BorrowersLog
267         CataloguingLog
268         FinesLog
269         IssueLog
270         ClaimsLog
271         ReturnLog
272         SubscriptionLog
273         BiblioDefaultView
274         COinSinOPACResults
275         DisplayOPACiconsXSLT
276         hidelostitems
277         OpacAddMastheadLibraryPulldown
278         OPACDisplay856uAsImage
279         OpacHighlightedWords
280         OpacKohaUrl
281         OpacMaintenance
282         OpacPublic
283         OpacSeparateHoldings
284         OPACShowCheckoutName
285         OpacShowFiltersPulldownMobile
286         OPACShowHoldQueueDetails
287         OpacShowRecentComments
288         OPACShowUnusedAuthorities
289         OpacStarRatings
290         opacthemes
291         OPACURLOpenInNewWindow
292         OpacAuthorities
293         opacbookbag
294         OpacBrowser
295         OpacBrowseResults
296         OpacCloud
297         OPACFinesTab
298         OpacHoldNotes
299         OpacItemLocation
300         OpacPasswordChange
301         OPACPatronDetails
302         OPACpatronimages
303         OPACPopupAuthorsSearch
304         OpacTopissue
305         opacuserlogin
306         QuoteOfTheDay
307         OPACHoldRequests
308         OPACComments
309         ShowReviewer
310         ShowReviewerPhoto
311         SocialNetworks
312         suggestion
313         OpacAllowPublicListCreation
314         OpacAllowSharingPrivateLists
315         OpacRenewalAllowed
316         OpacRenewalBranch
317         OPACViewOthersSuggestions
318         SearchMyLibraryFirst
319         AnonSuggestions
320         EnableOpacSearchHistory
321         OPACPrivacy
322         opacreadinghistory
323         TrackClicks
324         PatronSelfRegistration
325         OPACShelfBrowser
326         AutoEmailNewUser
327         EmailFieldPrimary
328         autoMemberNum
329         BorrowerRenewalPeriodBase
330         EnableBorrowerFiles
331         EnhancedMessagingPreferences
332         ExtendedPatronAttributes
333         intranetreadinghistory
334         patronimages
335         TalkingTechItivaPhoneNotification
336         uppercasesurnames
337         IncludeSeeFromInSearches
338         QueryAutoTruncate
339         QueryFuzzy
340         QueryStemming
341         QueryWeightFields
342         TraceCompleteSubfields
343         TraceSubjectSubdivisions
344         UseICUStyleQuotes
345         defaultSortField
346         displayFacetCount
347         OPACdefaultSortField
348         expandedSearchOption
349         IntranetNumbersPreferPhrase
350         OPACNumbersPreferPhrase
351         opacSerialDefaultTab
352         RenewSerialAddsSuggestion
353         RoutingListAddReserves
354         RoutingSerials
355         SubscriptionHistory
356         Display856uAsImage
357         DisplayIconsXSLT
358         template
359         yuipath
360         HidePatronName
361         intranetbookbag
362         StaffDetailItemSelection
363         viewISBD
364         viewLabeledMARC
365         viewMARC
366         ILS-DI
367         OAI-PMH
368         version
369         /;
370
371     return \@preferences;
372 }
373
374 =head2 _count
375
376   $data = _count($table);
377
378 Count the number of records in $table tables
379
380 =cut
381
382 sub _count {
383     my $table = shift;
384
385     my $dbh = C4::Context->dbh;
386     my $sth = $dbh->prepare("SELECT count(*) from $table");
387     $sth->execute;
388     return $sth->fetchrow_array;
389 }
390
391 1;