Bug 28727: Show edit item link when user has edit items permission
[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         BiblioAddsAuthorities
156         AuthorityMergeLimit
157         AuthorityMergeMode
158         UseAuthoritiesForTracings
159         CatalogModuleRelink
160         hide_marc
161         IntranetBiblioDefaultView
162         LabelMARCView
163         OpacSuppression
164         SeparateHoldings
165         UseControlNumber
166         advancedMARCeditor
167         DefaultClassificationSource
168         EasyAnalyticalRecords
169         autoBarcode
170         item-level_itypes
171         marcflavour
172         PrefillItem
173         z3950NormalizeAuthor
174         SpineLabelAutoPrint
175         SpineLabelShowPrintOnBibDetails
176         BlockReturnOfLostItems
177         BlockReturnOfWithdrawnItems
178         CalculateFinesOnReturn
179         AgeRestrictionOverride
180         AllFinesNeedOverride
181         AllowFineOverride
182         AllowItemsOnHoldCheckoutSIP
183         AllowItemsOnHoldCheckoutSCO
184         AllowNotForLoanOverride
185         AllowRenewalLimitOverride
186         AllowReturnToBranch
187         AllowTooManyOverride
188         AutomaticItemReturn
189         AutoRemoveOverduesRestrictions
190         CircControl
191         HomeOrHoldingBranch
192         IssueLostItem
193         IssuingInProcess
194         ManInvInNoissuesCharge
195         OverduesBlockCirc
196         RenewalPeriodBase
197         RenewalSendNotice
198         RentalsInNoissuesCharge
199         ReturnBeforeExpiry
200         TransfersMaxDaysWarning
201         UseBranchTransferLimits
202         UseTransportCostMatrix
203         UseCourseReserves
204         finesCalendar
205         FinesIncludeGracePeriod
206         finesMode
207         RefundLostOnReturnControl
208         WhenLostChargeReplacementFee
209         WhenLostForgiveFine
210         AllowHoldDateInFuture
211         AllowHoldItemTypeSelection
212         AllowHoldPolicyOverride
213         AllowHoldsOnDamagedItems
214         AllowHoldsOnPatronsPossessions
215         AutoResumeSuspendedHolds
216         canreservefromotherbranches
217         decreaseLoanHighHolds
218         DisplayMultiPlaceHold
219         emailLibrarianWhenHoldIsPlaced
220         ExpireReservesMaxPickUpDelay
221         OPACAllowHoldDateInFuture
222         OPACAllowUserToChooseBranch
223         ReservesControlBranch
224         ReservesNeedReturns
225         SuspendHoldsIntranet
226         SuspendHoldsOpac
227         TransferWhenCancelAllWaitingHolds
228         AllowAllMessageDeletion
229         AllowOfflineCirculation
230         PatronAutoComplete
231         CircAutoPrintQuickSlip
232         DisplayClearScreenButton
233         FilterBeforeOverdueReport
234         FineNotifyAtCheckin
235         itemBarcodeFallbackSearch
236         itemBarcodeInputFilter
237         previousIssuesDefaultSortOrder
238         RecordLocalUseOnReturn
239         AudioAlerts
240         SpecifyDueDate
241         todaysIssuesDefaultSortOrder
242         UpdateTotalIssuesOnCirc
243         UseTablesortForCirc
244         WaitingNotifyAtCheckin
245         SCOAllowCheckin
246         AutoSelfCheckAllowed
247         FRBRizeEditions
248         OPACFRBRizeEditions
249         AmazonCoverImages
250         OPACAmazonCoverImages
251         Babeltheque
252         BakerTaylorEnabled
253         GoogleJackets
254         HTML5MediaEnabled
255         LibraryThingForLibrariesEnabled
256         LocalCoverImages
257         OPACLocalCoverImages
258         NovelistSelectEnabled
259         OpenLibraryCovers
260         OpenLibrarySearch
261         SyndeticsEnabled
262         TagsEnabled
263         CalendarFirstDayOfWeek
264         opaclanguagesdisplay
265         AcquisitionLog
266         AuthoritiesLog
267         BorrowersLog
268         CataloguingLog
269         FinesLog
270         IssueLog
271         ClaimsLog
272         ReturnLog
273         SubscriptionLog
274         BiblioDefaultView
275         COinSinOPACResults
276         DisplayOPACiconsXSLT
277         hidelostitems
278         HighlightOwnItemsOnOPAC
279         OpacAddMastheadLibraryPulldown
280         OPACDisplay856uAsImage
281         OpacHighlightedWords
282         OpacKohaUrl
283         OpacMaintenance
284         OpacPublic
285         OpacSeparateHoldings
286         OPACShowCheckoutName
287         OpacShowFiltersPulldownMobile
288         OPACShowHoldQueueDetails
289         OpacShowRecentComments
290         OPACShowUnusedAuthorities
291         OpacStarRatings
292         opacthemes
293         OPACURLOpenInNewWindow
294         OpacAuthorities
295         opacbookbag
296         OpacBrowser
297         OpacBrowseResults
298         OpacCloud
299         OPACFinesTab
300         OpacHoldNotes
301         OpacItemLocation
302         OpacPasswordChange
303         OPACPatronDetails
304         OPACpatronimages
305         OPACPopupAuthorsSearch
306         OpacTopissue
307         opacuserlogin
308         QuoteOfTheDay
309         RequestOnOpac
310         OPACComments
311         ShowReviewer
312         ShowReviewerPhoto
313         SocialNetworks
314         suggestion
315         OpacAllowPublicListCreation
316         OpacAllowSharingPrivateLists
317         OpacRenewalAllowed
318         OpacRenewalBranch
319         OPACViewOthersSuggestions
320         SearchMyLibraryFirst
321         AnonSuggestions
322         EnableOpacSearchHistory
323         OPACPrivacy
324         opacreadinghistory
325         TrackClicks
326         PatronSelfRegistration
327         OPACShelfBrowser
328         AutoEmailOpacUser
329         AutoEmailPrimaryAddress
330         autoMemberNum
331         BorrowerRenewalPeriodBase
332         EnableBorrowerFiles
333         EnhancedMessagingPreferences
334         ExtendedPatronAttributes
335         intranetreadinghistory
336         patronimages
337         TalkingTechItivaPhoneNotification
338         uppercasesurnames
339         IncludeSeeFromInSearches
340         QueryAutoTruncate
341         QueryFuzzy
342         QueryStemming
343         QueryWeightFields
344         TraceCompleteSubfields
345         TraceSubjectSubdivisions
346         UseICUStyleQuotes
347         defaultSortField
348         displayFacetCount
349         OPACdefaultSortField
350         OPACItemsResultsDisplay
351         expandedSearchOption
352         IntranetNumbersPreferPhrase
353         OPACNumbersPreferPhrase
354         opacSerialDefaultTab
355         RenewSerialAddsSuggestion
356         RoutingListAddReserves
357         RoutingSerials
358         SubscriptionHistory
359         Display856uAsImage
360         DisplayIconsXSLT
361         template
362         yuipath
363         HidePatronName
364         intranetbookbag
365         StaffDetailItemSelection
366         viewISBD
367         viewLabeledMARC
368         viewMARC
369         ILS-DI
370         OAI-PMH
371         version
372         /;
373
374     return \@preferences;
375 }
376
377 =head2 _count
378
379   $data = _count($table);
380
381 Count the number of records in $table tables
382
383 =cut
384
385 sub _count {
386     my $table = shift;
387
388     my $dbh = C4::Context->dbh;
389     my $sth = $dbh->prepare("SELECT count(*) from $table");
390     $sth->execute;
391     return $sth->fetchrow_array;
392 }
393
394 1;