Bug 11926: Package updates
[koha.git] / C4 / UsageStats.pm
1 package UsageStats;
2
3 # Copyright 2000-2003 Katipo Communications
4 # Copyright 2010 BibLibre
5 # Parts Copyright 2010 Catalyst IT
6 #
7 # This file is part of Koha.
8 #
9 # Koha is free software; you can redistribute it and/or modify it under the
10 # terms of the GNU General Public License as published by the Free Software
11 # Foundation; either version 2 of the License, or (at your option) any later
12 # version.
13 #
14 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
15 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
16 # A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
17 #
18 # You should have received a copy of the GNU General Public License along
19 # with Koha; if not, write to the Free Software Foundation, Inc.,
20 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
21
22 use strict;
23 use C4::Context;
24 use POSIX qw(strftime);
25 use LWP::UserAgent;
26 use JSON;
27
28 =head1 NAME 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 This package is normally only called by a cronjob, like
38 0 3 1 * * export KOHA_CONF=/home/koha/etc/koha-conf.xml; export PERL5LIB=/home/koha/src; perl /home/koha/src/C4/UsageStats.pm
39
40 IMPORTANT : please do NOT run the cron on the 1st, but on another day. The idea is to avoid all
41 Koha libraries sending their data at the same time ! So choose any day between 1 and 28 !
42
43
44 =head2 NeedUpdate
45
46   $needUpdateYN = C4::UsageStats::NeedUpdate;
47
48 Returns Y (1) if the last update is more than 1 month old
49 This way, even if the cronjob is run every minute, the webservice will be called
50 only once a month !
51
52 =cut
53
54 sub NeedUpdate {
55     my $lastupdated = C4::Context->preference('UsageStatsLastUpdateTime') || 0;
56     my $now = strftime("%s", localtime);
57
58     # Need to launch cron.
59     return 1 if $now - $lastupdated >= 2592000;
60
61     # Cron no need to be launched.
62     return 0;
63 }
64
65 =head2 LaunchCron
66
67   LaunchCron();
68
69 Compute results and send them to the centralized server
70
71 =cut
72
73 sub LaunchCron {
74     if (!C4::Context->preference('UsageStatsShare')) {
75       die ("UsageStats is not configured");
76     }
77     if (NeedUpdate) {
78         C4::Context->set_preference('UsageStatsLastUpdateTime', strftime("%s", localtime));
79         my $data = BuildReport();
80         ReportToCommunity($data);
81     }
82 }
83
84 =head2 Builreport
85
86   BuildReport();
87
88 retrieve some database volumety and systempreferences that will be sent to hea server
89
90 =cut
91
92 sub BuildReport {
93     my $report = {
94         'library' => {
95             'name' => C4::Context->preference('UsageStatsLibraryName'),
96             'id' => C4::Context->preference('UsageStatsID') || 0,
97         },
98     };
99
100     # Get database volumetry.
101     foreach (qw/biblio auth_header old_issues old_reserves borrowers aqorders subscription/) {
102         $report->{volumetry}{$_} = _count($_);
103     }
104
105     # Get systempreferences.
106     foreach (qw/ AcqCreateItem
107  AcqWarnOnDuplicateInvoice
108  AcqViewBaskets
109  BasketConfirmations
110  OrderPdfFormat
111  casAuthentication
112  casLogout
113  AllowPkiAuth
114  DebugLevel
115  delimiter
116  noItemTypeImages
117  virtualshelves
118  AutoLocation
119  IndependentBranches
120  SessionStorage
121  Persona
122  AuthDisplayHierarchy
123  AutoCreateAuthorities
124  BiblioAddsAuthorities
125  dontmerge
126  UseAuthoritiesForTracings
127  CatalogModuleRelink
128  hide_marc
129  IntranetBiblioDefaultView
130  LabelMARCView
131  OpacSuppression
132  SeparateHoldings
133  UseControlNumber
134  advancedMARCeditor
135  DefaultClassificationSource
136  EasyAnalyticalRecords
137  autoBarcode
138  item-level_itypes
139  marcflavour
140  PrefillItem
141  z3950NormalizeAuthor
142  SpineLabelAutoPrint
143  SpineLabelShowPrintOnBibDetails
144  BlockReturnOfWithdrawnItems
145  CalculateFinesOnReturn
146  AgeRestrictionOverride
147  AllFinesNeedOverride
148  AllowFineOverride
149  AllowItemsOnHoldCheckout
150  AllowNotForLoanOverride
151  AllowRenewalLimitOverride
152  AllowReturnToBranch
153  AllowTooManyOverride
154  AutomaticItemReturn
155  AutoRemoveOverduesRestrictions
156  CircControl
157  HomeOrHoldingBranch
158  HomeOrHoldingBranchReturn
159  InProcessingToShelvingCart
160  IssueLostItem
161  IssuingInProcess
162  ManInvInNoissuesCharge
163  OverduesBlockCirc
164  RenewalPeriodBase
165  RenewalSendNotice
166  RentalsInNoissuesCharge
167  ReturnBeforeExpiry
168  ReturnToShelvingCart
169  TransfersMaxDaysWarning
170  UseBranchTransferLimits
171  useDaysMode
172  UseTransportCostMatrix
173  UseCourseReserves
174  finesCalendar
175  FinesIncludeGracePeriod
176  finesMode
177  RefundLostItemFeeOnReturn
178  WhenLostChargeReplacementFee
179  WhenLostForgiveFine
180  AllowHoldDateInFuture
181  AllowHoldPolicyOverride
182  AllowHoldsOnDamagedItems
183  AllowHoldsOnPatronsPossessions
184  AllowOnShelfHolds
185  AutoResumeSuspendedHolds
186  canreservefromotherbranches
187  decreaseLoanHighHolds
188  DisplayMultiPlaceHold
189  emailLibrarianWhenHoldIsPlaced
190  ExpireReservesMaxPickUpDelay
191  OPACAllowHoldDateInFuture
192  OPACAllowUserToChooseBranch
193  ReservesControlBranch
194  ReservesNeedReturns
195  SuspendHoldsIntranet
196  SuspendHoldsOpac
197  TransferWhenCancelAllWaitingHolds
198  AllowAllMessageDeletion
199  AllowOfflineCirculation
200  CircAutocompl
201  CircAutoPrintQuickSlip
202  DisplayClearScreenButton
203  FilterBeforeOverdueReport
204  FineNotifyAtCheckin
205  itemBarcodeFallbackSearch
206  itemBarcodeInputFilter
207  previousIssuesDefaultSortOrder
208  RecordLocalUseOnReturn
209  soundon
210  SpecifyDueDate
211  todaysIssuesDefaultSortOrder
212  UpdateTotalIssuesOnCirc
213  UseTablesortForCirc
214  WaitingNotifyAtCheckin
215  AllowSelfCheckReturns
216  AutoSelfCheckAllowed
217  FRBRizeEditions
218  OPACFRBRizeEditions
219  AmazonCoverImages
220  OPACAmazonCoverImages
221  Babeltheque
222  BakerTaylorEnabled
223  GoogleJackets
224  HTML5MediaEnabled
225  IDreamBooksReadometer
226  IDreamBooksResults
227  IDreamBooksReviews
228  LibraryThingForLibrariesEnabled
229  LocalCoverImages
230  OPACLocalCoverImages
231  NovelistSelectEnabled
232  XISBN
233  OpenLibraryCovers
234  UseKohaPlugins
235  SyndeticsEnabled
236   TagsEnabled
237  CalendarFirstDayOfWeek
238  opaclanguagesdisplay
239  AuthoritiesLog
240  BorrowersLog
241  CataloguingLog
242  FinesLog
243  IssueLog
244  LetterLog
245  ReturnLog
246  SubscriptionLog
247  AuthorisedValueImages
248  BiblioDefaultView
249  COinSinOPACResults
250  DisplayOPACiconsXSLT
251  hidelostitems
252  HighlightOwnItemsOnOPAC
253  OpacAddMastheadLibraryPulldown
254  OPACDisplay856uAsImage
255  OpacHighlightedWords
256  OpacKohaUrl
257  OpacMaintenance
258  OpacPublic
259  OpacSeparateHoldings
260  OPACShowBarcode
261  OPACShowCheckoutName
262  OpacShowFiltersPulldownMobile
263  OPACShowHoldQueueDetails
264  OpacShowLibrariesPulldownMobile
265  OpacShowRecentComments
266  OPACShowUnusedAuthorities
267  OpacStarRatings
268  opacthemes
269  OPACURLOpenInNewWindow
270  OpacAuthorities
271  opacbookbag
272  OpacBrowser
273  OpacBrowseResults
274  OpacCloud
275  OPACFinesTab
276  OpacHoldNotes
277  OpacItemLocation
278  OpacPasswordChange
279  OPACPatronDetails
280  OPACpatronimages
281  OPACPopupAuthorsSearch
282  OpacTopissue
283  opacuserlogin
284  QuoteOfTheDay
285  RequestOnOpac
286  reviewson
287  ShowReviewer
288  ShowReviewerPhoto
289  SocialNetworks
290  suggestion
291  AllowPurchaseSuggestionBranchChoice
292  OpacAllowPublicListCreation
293  OpacAllowSharingPrivateLists
294  OPACItemHolds
295  OpacRenewalAllowed
296  OpacRenewalBranch
297  OPACViewOthersSuggestions
298  SearchMyLibraryFirst
299  singleBranchMode
300  AnonSuggestions
301  EnableOpacSearchHistory
302  OPACPrivacy
303  opacreadinghistory
304  TrackClicks
305  PatronSelfRegistration
306  OPACShelfBrowser
307  AddPatronLists
308  AutoEmailOpacUser
309  AutoEmailPrimaryAddress
310  autoMemberNum
311  BorrowerRenewalPeriodBase
312  checkdigit
313  EnableBorrowerFiles
314  EnhancedMessagingPreferences
315  ExtendedPatronAttributes
316  intranetreadinghistory
317  memberofinstitution
318  patronimages
319  TalkingTechItivaPhoneNotification
320  uppercasesurnames
321  IncludeSeeFromInSearches
322  OpacGroupResults
323  QueryAutoTruncate
324  QueryFuzzy
325  QueryStemming
326  QueryWeightFields
327  TraceCompleteSubfields
328  TraceSubjectSubdivisions
329  UseICU
330  UseQueryParser
331  defaultSortField
332  displayFacetCount
333  OPACdefaultSortField
334  OPACItemsResultsDisplay
335  expandedSearchOption
336  IntranetNumbersPreferPhrase
337  OPACNumbersPreferPhrase
338  opacSerialDefaultTab
339  RenewSerialAddsSuggestion
340  RoutingListAddReserves
341  RoutingSerials
342  SubscriptionHistory
343  Display856uAsImage
344  DisplayIconsXSLT
345  StaffAuthorisedValueImages
346  template
347  yuipath
348  HidePatronName
349  intranetbookbag
350  StaffDetailItemSelection
351  viewISBD
352  viewLabeledMARC
353  viewMARC
354  ILS-DI
355  OAI-PMH
356  version/) {
357         $report->{systempreferences}{$_} = C4::Context->preference($_);
358     }
359     return $report;
360 }
361
362 =head2 ReportToCommunity
363
364   ReportToCommunity;
365
366 Send to hea.koha-community.org database informations
367
368 =cut
369
370 sub ReportToCommunity {
371     my $data = shift;
372     my $json = to_json($data);
373
374     my $ua = LWP::UserAgent->new;
375     my $req = HTTP::Request->new(POST => "http://hea.koha-community.org/upload.pl");
376     $req->content_type('application/x-www-form-urlencoded');
377     $req->content("data=$json");
378     my $res = $ua->request($req);
379     my $content = from_json($res->decoded_content);
380     C4::Context->set_preference('UsageStatsID', $content->{library}{library_id});
381 }
382
383 =head2 _count
384
385   $data = _count($table);
386
387 Count the number of records in $table tables
388
389 =cut
390
391 sub _count {
392     my $table = shift;
393
394     my $dbh = C4::Context->dbh;
395     my $sth = $dbh->prepare("SELECT count(*) from $table");
396     $sth->execute;
397     return $sth->fetchrow_array;
398 }
399
400 &LaunchCron;
401 1;