-
Notifications
You must be signed in to change notification settings - Fork 3
/
functions.php
1590 lines (1322 loc) · 47.3 KB
/
functions.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
* Set cURL options
*
* @param $ch cURL handle
* @param $target 'users', 'groups', 'groupfolders' or 'capabilities'
* @param $user_id User ID of the target user
* OPTIONAL DEFAULT: null
*
*/
function set_curl_options($ch, $target, $id = null) {
switch ($target) {
case 'users':
$path = '/ocs/v1.php/cloud/users';
break;
case 'groups':
$path = '/ocs/v1.php/cloud/groups';
break;
case 'groupfolders':
$path = '/index.php/apps/groupfolders/folders';
break;
case 'capabilities':
$path = '/ocs/v1.php/cloud/capabilities';
break;
}
$id = $id === null ? null : '/' . rawurlencode($id);
curl_setopt($ch, CURLOPT_URL, $_SESSION['target_url'] . $path . $id);
curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
curl_setopt($ch, CURLOPT_TCP_FASTOPEN, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Expect:'));
curl_setopt($ch, CURLOPT_USERPWD, $_SESSION['user_name'] . ':'
. $_SESSION['user_pass']);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'OCS-APIRequest: true',
'Accept: application/json'
]);
}
/**
* Populate session array 'data_options' with all data options that can be selected
*
* @return $_SESSION['data_options']
*/
function set_data_options() {
$_SESSION['data_options'] = [
'id' => L10N_USER_ID, 'displayname' => L10N_DISPLAYNAME,
'email' => L10N_EMAIL, 'lastLogin' => L10N_LAST_LOGIN,
'backend' => L10N_BACKEND, 'enabled' => L10N_ENABLED,
'quota' => L10N_QUOTA, 'used' => L10N_QUOTA_USED,
'percentage_used' => L10N_PERCENTAGE_USED, 'free' => L10N_QUOTA_FREE,
'groups' => L10N_GROUPS, 'subadmin' => L10N_SUBADMIN,
'language' => L10N_LANGUAGE, 'locale' => L10N_LOCALE];
}
/**
* Check secure outgoing connection
*
* Depending on the first five chars of the supplied URL:
* - In case 'https' -> return unchanged URL
* - In case '!http' -> remove '!' and return trimmed URL
* - In case 'http:' -> exit with insecure connection warning
* - In case 'none of the above' -> prepend input with https:// and return it
*
* @param $input_url URL to be processed
*
* @return $output_url URL after processing
*
*/
function check_https($input_url) {
require 'config.php';
// Prepare error message, depending on https_strict config option
$error_msg = "<font color='red' face='Helvetica'>
<hr>
<b>".L10N_HTTP_IS_BLOCKED."</b>
<br>".L10N_HTTPS_RECOMMENDATION."
<hr><font color='black'>";
if (!$https_strict)
$error_msg .= "<br>".L10N_HTTPS_OVERRIDE_HINT."
<br>".L10N_EG."!http://cloud.example.com</font>";
else
$error_msg .= "<br>".L10N_HTTPS_STRICT_MODE."</font>";
// Save the first five chars of the URL to a new variable '$trim_url'
$trimmed_url = substr($input_url,0,5);
switch($trimmed_url) {
// Leave URL untouched if https:// protocol is already set
case 'https':
$output_url = $input_url;
break;
// Check if plain HTTP is used without override command and exit if not
case 'http:':
header('Content-Type: text/html; charset=utf-8');
exit($error_msg);
break;
// Remove '!' if HTTPS check override is selected by use of '!http'
case '!http':
if($https_strict) {
header('Content-Type: text/html; charset=utf-8');
exit($error_msg);
}
$output_url = ltrim($input_url,'!');
break;
default:
$output_url = "https://".$input_url;
break;
}
return $output_url;
}
/**
* Remove httpx:// from given URL and return the trimmed version
*
* @param $url URL to be trimmed
*
* @return $trim_url URL without http:// or https://
*
*/
function removehttpx($input_url) {
$trimmed_url = preg_replace('(^https?://)', '', $input_url);
return $trimmed_url;
}
/**
* Error handling for cURL requests
*
* Checks cURL error codes and statuscodes in the API response
*
* @param $ch cURL handle to be checked
* @param $data variable containing the API data fetched by cURL exec
*
*/
function check_curl_response($ch, $data) {
// check if cURL returns an error != 0
if (curl_errno($ch)) {
// Iterate through common cURL error codes, exit and return custom error messages or default message
switch (curl_errno($ch)) {
case 6:
header('Content-Type: text/html; charset=utf-8');
exit('
<font color="red">
<hr>
<b>'.L10N_ERROR.'cURL ('.L10N_STATUSCODE.curl_errno($ch).')</b>
<br>'.curl_error($ch).
'<font color="black">
<hr>'.L10N_ERROR_CURL_CONNECTION.'
</font>');
case 51:
header('Content-Type: text/html; charset=utf-8');
exit('
<font color="red">
<hr>
<b>'.L10N_ERROR.'cURL ('.L10N_STATUSCODE.curl_errno($ch).')</b>
<br>'.curl_error($ch).
'<font color="black">
<hr>
'.L10N_ERROR_URL.'
</font>');
default:
header('Content-Type: text/html; charset=utf-8');
exit('
<font color="red">
<hr>
<b>'.L10N_ERROR.'cURL ('.L10N_STATUSCODE.curl_errno($ch).')</b>
<br>'.curl_error($ch).'
<hr>
</font>');
}
}
if ($data === null) {
header('Content-Type: text/html; charset=utf-8');
exit('
<font color="red">
<hr>
<b>'.L10N_ERROR . L10N_ERROR_EMPTY_API_RESPONSE.'</b>
<hr>
</font>');
}
// Read statuscode from API response
$status = $data['ocs']['meta']['statuscode'];
// Iterate through possible statuscode responses
switch ($status) {
case 100:
case 200:
// 100 or 200 mean OK -> break switch case and continue normal script execution
break;
case 404:
header('Content-Type: text/html; charset=utf-8');
exit('
<font color="red">
<hr>
<b>'.L10N_ERROR . L10N_USER_DOES_NOT_EXIST
.' ('.L10N_STATUSCODE.$status.')</b>
<hr>
</font>');
break;
case 997:
header('Content-Type: text/html; charset=utf-8');
exit('
<font color="red">
<hr><b>'.L10N_ERROR . L10N_AUTHENTICATION.' ('.L10N_STATUSCODE.$status.')</b>
<br>'.L10N_CHECK_USER_PASS.'
<font color="black">
<hr>'.L10N_HINT_ADMIN_OR_GROUP_ADMIN.'
</font>');
default:
header('Content-Type: text/html; charset=utf-8');
exit('
<font color="red">
<hr>
<b>'.L10N_ERROR . L10N_UNKNOWN.' ('.L10N_STATUSCODE.$status.')</b>
<hr>
</font>');
}
}
/**
* Fetch the list containing all user IDs from the server
*
*/
function fetch_userlist() {
// Log start timestamp
$timestamp_start = microtime(true);
// Initialize cURL handle to fetch user ID list and set options
$ch = curl_init();
set_curl_options($ch, 'users');
// Fetch raw userlist and store user_ids in $users
$users_raw = json_decode(curl_exec($ch), true);
// Check for errors in cURL request
check_curl_response($ch, $users_raw);
// Drop cURL handle
curl_close($ch);
// Check if the userlist has been received and save user IDs to $users
if (isset($users_raw['ocs']['data']['users'])) {
$users = $users_raw['ocs']['data']['users'];
// Set the session variable 'authenticated' to true to access other pages
$_SESSION['authenticated'] = true;
}
$_SESSION['userlist'] = $users;
// Calculate time for function execution and save as $_SESSION variable
$_SESSION['time_fetch_userlist'] = round(microtime(true) - $timestamp_start,1);
}
/**
* Fetch the list containing all group IDs from the server
*
* @return $groups
*
*/
function fetch_grouplist() {
// Log start timestamp
$timestamp_start = microtime(true);
// Initialize cURL handle to fetch user id list and set options
$ch = curl_init();
set_curl_options($ch, 'groups');
// Fetch raw userlist and store user_ids in $users
$groups_raw = json_decode(curl_exec($ch), true);
// Check for errors in cURL request
check_curl_response($ch, $groups_raw);
// Drop cURL handle
curl_close($ch);
// Check if the userlist has been received and save user IDs to $users
$groups = $groups_raw['ocs']['data']['groups'] ?? null;
$_SESSION['grouplist'] = $groups;
// Calculate time for function execution and save as $_SESSION variable
$_SESSION['time_fetch_grouplist'] = round(microtime(true) - $timestamp_start,1);
}
/**
* Initialize individual cURL handles, set options and append them to multi handle list
*
* @return $raw_user_data
*
*/
function fetch_raw_user_data() {
// Log start timestamp
$timestamp_start = microtime(true);
// Initialize cURL multi handle for parallel requests
$mh = curl_multi_init();
// Iterate through userlist
foreach($_SESSION['userlist'] as $key => $user_id) {
// Initialize cURL handle
$curl_requests[$key] = curl_init();
// Set cURL options for this handle
set_curl_options($curl_requests[$key], 'users', $user_id);
// Add created handle to multi handle list
curl_multi_add_handle($mh, $curl_requests[$key]);
}
/**
* Fetch user data via cURL using parallel connections (curl_multi_*)
*/
do {
$status = curl_multi_exec($mh, $active);
if ($active) {
curl_multi_select($mh);
}
} while ($active && $status == CURLM_OK);
/**
* Save content to $selected_user_data
*/
//Iterate through $curl_requests (the cURL handle list)
foreach ($curl_requests as $key => $request) {
// Get content of one user data request, store in $single_user_data
$raw_user_data[] =
json_decode(curl_multi_getcontent($curl_requests[$key]),true);
// Remove processed cURL handle
curl_multi_remove_handle($mh, $curl_requests[$key]);
}
// Drop cURL multi handle
curl_multi_close($mh);
// Calculate time for function execution and save as $_SESSION variable
$_SESSION['time_fetch_userdata'] = round(microtime(true) - $timestamp_start,1);
// Calculate total script runtime
$_SESSION['time_total'] = number_format(round(
microtime(true) - $_SESSION['timestamp_script_start'], 1),1);
// Save timestamp when data transfer was finished to $_SESSION variable
$_SESSION['timestamp_data'] = date(DATE_ATOM);
return $raw_user_data;
}
/**
* Download groupfolder data if enabled on the server
*
*/
function fetch_raw_groupfolders_data() {
// Log start timestamp
$timestamp_start = microtime(true);
// Initialize cURL handle to fetch user id list and set options
$ch = curl_init();
set_curl_options($ch, 'groupfolders');
// Fetch raw userlist and store user_ids in $users
$_SESSION['raw_groupfolders_data'] = json_decode(curl_exec($ch), true);
// Set session variable telling if groupfolders is active on connected server
$_SESSION['groupfolders_active'] = isset($_SESSION['raw_groupfolders_data']);
// Drop cURL handle
curl_close($ch);
// Calculate time for function execution and save as $_SESSION variable
$_SESSION['time_fetch_groupfolders'] = round(microtime(true) - $timestamp_start,1);
}
/**
* Download groupfolder data
*
*/
function fetch_server_capabilities() {
// Initialize cURL handle to fetch user id list and set options
$ch = curl_init();
set_curl_options($ch, 'capabilities');
// Fetch raw userlist and store user_ids in $users
$_SESSION['raw_server_capabilities'] = json_decode(curl_exec($ch), true);
// Check for errors in cURL request
check_curl_response($ch, $_SESSION['raw_server_capabilities']);
// Drop cURL handle
curl_close($ch);
}
/**
* Iterate through userlist and call select_data_single_user each time
*
* @param $data_choices Array containing a list of data columns to be taken into account
* OPTIONAL DEFAULT: null
* @param $format decode UTF8?
* OPTIONAL DEFAULT: null (decode UTF8)
*
* @return $selected_user_data
* ARRAY
*/
function select_data_all_users($data_choices = null, $userlist = null, $format = null,
$csv_delimiter = ', ') {
$data_choices = $data_choices ?? $_SESSION['data_choices'];
$userlist = $userlist ?? $_SESSION['userlist'];
foreach($userlist as $key => $user_id) {
// Call select_data function to filter/format request data
$selected_user_data[] = select_data_single_user(
$_SESSION['raw_user_data'][$key], $user_id, $data_choices, $format,
$csv_delimiter);
}
return $selected_user_data;
}
/**
* Select elements from array "$data" and format for csv download
* or browser display depending on parameters
*
* @param $data Single user record data array
* @param $user_id ID of the user to be processed
* @param $data_choices Array containing a list of data columns to be taken into account
* @param $format If not 'csv', data will be prepared for browser display
* OPTIONAL DEFAULT: null
*
* @return $selected_data Result of $data filtering
* ARRAY
*/
function select_data_single_user(
$data, $user_id, $data_choices, $format = null, $csv_delimiter = ', ') {
// If data is not returned due to missing permissions (group admins) set 'N/A' instead
if($data['ocs']['meta']['statuscode'] == 997) {
$selected_data[] = $user_id;
for($i = 1; $i < count($data_choices); $i++)
$selected_data[] = 'N/A';
}
// Prepare data for CSV file export if $format = 'csv'
else {
// Iterate through chosen data sets
foreach($data_choices as $key => $item) {
$quota = $data['ocs']['data']['quota']['quota'];
$used = $data['ocs']['data']['quota']['used'];
$backend = $data['ocs']['data']['backend'];
$item_data = $item !== 'percentage_used'
? $data['ocs']['data'][$item]
: ((in_array($quota, [-3, 0, 'none']) || $backend === 'Guests')
? 'N/A'
: round($used / $quota * 100));
// Filter/format different data sets
switch($item) {
// Convert email data set to lowercase
case 'email':
$selected_data[] = $item_data == null ? '-' : strtolower($item_data);
break;
case 'lastLogin':
// If user has never logged in set $last_login to '-'
$selected_data[] = $item_data == 0
? ($format == 'csv'
? '-'
: '<span style="color: red;">✘</span>')
// Format unix timestamp to YYYY-MM-DD after trimming last 3 chars
: date("Y-m-d", substr($item_data, 0, 10));
break;
// Make the display of 'enabled' bool pretty in the browser
case 'enabled':
$selected_data[] = $format == 'csv'
? $item_data
: ($item_data == true
? '<span style="color: green">✔</span>'
: '<span style="color: red">✘</span>');
break;
case 'quota':
case 'free':
if($backend === 'Guests') {
$selected_data[] = 'N/A';
break;
}
$item_data = $data['ocs']['data']['quota'][$item];
$selected_data[] = in_array($item_data, [-3, 'none'], true)
? '∞'
: ($format != 'csv'
? format_size($item_data, 'no_filter')
: $item_data);
break;
case 'used':
if($backend === 'Guests') {
$selected_data[] = 'N/A';
break;
}
$item_data = $data['ocs']['data']['quota'][$item];
$selected_data[] = $format != 'csv'
? format_size($item_data)
: $item_data;
break;
// Convert arrays 'subadmin' and 'groups' to comma separated values and wrap them in parentheses if not null
case 'subadmin':
case 'groups':
$selected_data[] = empty($item_data)
? '-'
: ($format != 'csv'
? build_csv_line($item_data, false, $csv_delimiter)
: build_csv_line($item_data));
break;
case 'locale':
// If user has not set a locale use '-'
$selected_data[] = $item_data == '' ? '-' : $item_data;
break;
// If none of the above apply
default:
$selected_data[] = $item_data;
}
}
}
return $selected_data;
}
/**
* TODO
*/
function select_data_all_users_filter($filter_by, $conditions,
$filter_option = null) {
foreach($_SESSION['userlist'] as $key => $user_id) {
if($filter_by == 'quota' || $filter_by == 'used' || $filter_by == 'free') {
$item_data = $_SESSION['raw_user_data'][$key]['ocs']['data']['quota'][$filter_by];
$limit_to_check = $conditions * 1073741824; // Gibibytes not Gigabytes (1024³)
}
else
$item_data = $_SESSION['raw_user_data'][$key]['ocs']['data'][$filter_by];
switch($filter_by) {
case 'quota':
case 'used':
case 'free':
require 'config.php';
switch ($filter_option) {
case 'gt':
if($item_data > $limit_to_check)
$selected_user_ids[] = $user_id;
break;
case 'lt':
if($item_data < $limit_to_check)
$selected_user_ids[] = $user_id;
break;
case 'asymp':
if($item_data > $limit_to_check * (1 - $filter_tolerance)
&& $item_data < $limit_to_check * (1 + $filter_tolerance))
$selected_user_ids[] = $user_id;
break;
case 'equals':
if($item_data == $limit_to_check)
$selected_user_ids[] = $user_id;
break;
}
break;
case 'lastLogin':
$lastLogin = substr($item_data, 0, 10);
if($lastLogin >= strtotime($conditions[0])
&& $lastLogin <= strtotime($conditions[1].' +1 day'))
$selected_user_ids[] = $user_id;
break;
case 'groups':
case 'subadmin':
if(in_array($conditions, $item_data))
$selected_user_ids[] = $user_id;
break;
}
}
if(!$selected_user_ids)
$selected_user_ids = [''];
return $selected_user_ids;
}
function filter_users() {
if($_SESSION['filters_set']) {
$filter_conditions_ll = [$_SESSION['filter_ll_since'], $_SESSION['filter_ll_before']];
$uids_g = in_array('filter_group_choice', $_SESSION['filters_set'])
? select_data_all_users_filter('groups', $_SESSION['filter_group'])
: $_SESSION['userlist'];
$uids_l = in_array('filter_lastLogin_choice', $_SESSION['filters_set'])
? select_data_all_users_filter('lastLogin', $filter_conditions_ll)
: $_SESSION['userlist'];
$uids_q = in_array('filter_quota_choice', $_SESSION['filters_set'])
? select_data_all_users_filter($_SESSION['type_quota'],
$_SESSION['filter_quota'], $_SESSION['compare_quota'])
: $_SESSION['userlist'];
$user_ids = array_intersect($_SESSION['userlist'], $uids_g, $uids_l, $uids_q);
}
if(!$user_ids)
exit('No users found matching filter settings');
return $user_ids;
}
/**
* Find all users belonging to a given group an return an array containing userID and displayname
*
* @param $group The name of the group to search for
* @param $format If not 'csv', data will be prepared for browser display
* OPTIONAL DEFAULT: null
*
* @return $group_members
*
*/
function select_group_members($group, $format = null) {
// Iterate through userlist
foreach($_SESSION['userlist'] as $key => $user_id) {
// Call select_data function to filter/format request data
$data = $_SESSION['raw_user_data'][$key];
if(in_array($group, $data['ocs']['data']['groups']))
$group_members[] = [$user_id, $data['ocs']['data']['displayname']];
}
return $group_members;
}
/**
* Calculate how much disk space is assigned, used and available in total
* (user and groupfolder quota)
*
*/
function calculate_quota() {
// Reset values
$_SESSION['quota_total_assigned'] = 0;
$_SESSION['quota_total_free'] = 0;
$_SESSION['quota_total_used'] = 0;
// Loop through raw user data and add quota item values to $_SESSION variables
foreach($_SESSION['raw_user_data'] as $user_data) {
$_SESSION['quota_total_used'] += $user_data['ocs']['data']['quota']['used'];
$_SESSION['quota_total_free'] +=
$user_data['ocs']['data']['quota']['free'];
$quota_assigned = $user_data['ocs']['data']['quota']['quota'];
$_SESSION['quota_total_assigned'] += $quota_assigned > 0
? $quota_assigned
: 0;
$_SESSION['quota_total_assigned_infin'] = ($quota_assigned == -3);
}
if($_SESSION['groupfolders_active'])
// Reset values
$_SESSION['quota_groupfolders_used'] = 0;
$_SESSION['quota_groupfolders_assigned'] = 0;
foreach($_SESSION['raw_groupfolders_data']['ocs']['data'] as $groupfolder) {
$_SESSION['quota_groupfolders_used'] += $groupfolder['size'];
$_SESSION['quota_groupfolders_assigned'] += $groupfolder['quota'];
}
}
/**
* Print status message on successful server connection
*
* Status message contains user count, target instance, timestamp and runtime in seconds
*
* Change the standard in 'date(DATE_ATOM)' used to display the timestamp to your needs
*
*/
function print_status_success() {
// Output status message after receiving user and group data
echo '
<hr>'.L10N_CONNECTED_TO_SERVER.removehttpx($_SESSION['target_url'])
.' <span style="color: green">✔</span>'
.'<br>'.L10N_DOWNLOADED.' '.count($_SESSION['raw_user_data']).' '
.L10N_USERS_AND.' '.count($_SESSION['grouplist']).' '
.L10N_GROUPS_IN.' '.$_SESSION['time_total'].' '.L10N_SECONDS
.'<br>Timestamp: '.$_SESSION['timestamp_data'].
'<hr><span style="color: darkgreen;">'
.L10N_ACCESS_TO_ALL_MENU_OPTIONS.'</span>';
}
/**
* Status printed on each page, showing the active server and user/group count
*
*/
function print_status_overview($scope = "quick") {
$infinite = $_SESSION['quota_total_assigned_infin']
? " (+ ∞)"
: "";
if($scope == "quick") {
echo "<hr>
<a class='no_show_link' href='{$_SESSION['target_url']}' target='_blank'>"
.removehttpx($_SESSION['target_url'])."</a>
<hr>";
} else {
fetch_server_capabilities();
$_SESSION['server_version_string'] =
$_SESSION['raw_server_capabilities']['ocs']['data']['version']['string'];
echo "<hr>
<a class='no_show_link' href='{$_SESSION['target_url']}' target='_blank'>"
.removehttpx($_SESSION['target_url'])."</a>
(".L10N_NEXTCLOUD." v{$_SESSION['server_version_string']})
<hr>
<table class='status'>
<tr>
<td colspan=2 style='min-width: 15em;'><b>Overall count</b></td>
</tr>
<tr>
<td>".L10N_USERS."</td>
<td class='align_r'>{$_SESSION['user_count']}</td>
</tr>
<tr>
<td>".L10N_GROUPS."</td>
<td>{$_SESSION['group_count']}</td>
</tr>";
if($_SESSION['groupfolders_active'])
echo "<tr>
<td>".L10N_GROUPFOLDERS."</td>
<td>{$_SESSION['groupfolders_count']}</td>
</tr>";
echo "
</table>
<hr>
<table class='status'>
<tr>
<td colspan=2 style='min-width: 15em;'><b>".L10N_USERS."</b></td>
</tr>
<tr>
<td>".L10N_QUOTA_USED."</td>
<td>".format_size($_SESSION['quota_total_used'])."</td>
</tr>
<tr>
<td>".L10N_QUOTA."</td>
<td>".format_size($_SESSION['quota_total_assigned'])."</td>
<td>$infinite</td>
</tr>
<tr>
<td>".L10N_QUOTA_FREE."</td>
<td>".format_size($_SESSION['quota_total_free'])."</td>
</tr>";
if($_SESSION['groupfolders_active'])
echo "<tr style='height: 10px'>
<td></td>
</tr>
<tr>
<td colspan=2 style='min-width: 15em;'><b>".L10N_GROUPFOLDERS."</b></td>
</tr>
<tr>
<td>".L10N_QUOTA_USED."</td>
<td>".format_size($_SESSION['quota_groupfolders_used'])."</td>
</tr>
<tr>
<td>".L10N_QUOTA."</td>
<td>".format_size($_SESSION['quota_groupfolders_assigned'])."</td>
</tr>
</table>";
echo "<hr><table class='status'>
<tr>
<td colspan=2 style='min-width: 15em;'><b>".L10N_EXECUTION_TIMES."</b></td>
</tr>
<tr>
<td>".L10N_FETCH_USERLIST."</td>
<td>{$_SESSION['time_fetch_userlist']} s</td>
</tr>
<tr>
<td>".L10N_FETCH_GROUPLIST."</td>
<td>{$_SESSION['time_fetch_grouplist']} s</td>
</tr>
<tr>
<td>".L10N_FETCH_GROUPFOLDERS."</td>
<td>{$_SESSION['time_fetch_groupfolders']} s</td>
</tr>
<tr>
<td>".L10N_FETCH_USERDATA."</td>
<td>{$_SESSION['time_fetch_userdata']} s</td>
</tr>
</table><hr>"
.L10N_DATA_RETRIEVED." {$_SESSION['timestamp_data']}";
}
}
/**
* Build CSV file
*
* Creates a file containing provided array data as comma separated values
*
* @param $list Data array containing user data
* @param $headers CSV line containing the column headers, set null if none
* OPTIONAL DEFAULT: List from $data_choices variable
*
* @return $csv_filename Filename of the newly created file
*
*/
function build_csv_file($list, $headers = 'default') {
if(!$_SESSION['temp_folder'])
$_SESSION['temp_folder'] = 'export_temp-'.bin2hex(random_bytes(16));
// Delete temporary folder and contents
delete_temp_folder();
// Create headers from session variable 'data_choices' if not supplied
if($headers == 'default')
$headers = build_csv_line();
// Set random filename
$csv_filename = bin2hex(random_bytes(8)).'.csv';
// Check if temporary folder already exists, else make directory
if(!file_exists($_SESSION['temp_folder']))
mkdir($_SESSION['temp_folder'], 0755, true);
// Create/open file with write access and return file handle
$csv_file = fopen($_SESSION['temp_folder'].'/'.$csv_filename, "w");
// Set file permissions (rw-r-----)
chmod($_SESSION['temp_folder'].'/'.$csv_filename, 0640);
// Write selected headers as first line to file
if($headers != 'no_headers')
fwrite($csv_file, $headers."\n");
// Iterate through provided data array and append each line to the file
foreach($list as $line)
fputcsv($csv_file, $line);
// Close active file handle
fclose($csv_file);
return $csv_filename;
}
/**
* Initiate file download
*
* The selected file (by filename) will be downloaded and deleted afterwards
* It can be downloaded using an alternative filename, if supplied
*
* @param $filename Filename on the server
* @param $mime_type MIME type to be sent in the header
* OPTIONAL DEFAULT: 'text/csv'
* @param $filename_download Filename for download
* OPTIONAL DEFAULT: 'download'
* @param $folder Folder to prepend in front of the server filename
* OPTIONAL DEFAULT: '.'
*
*/
function download_file($filename, $mime_type = 'text/csv',
$filename_download = 'download', $folder = '.') {
// make sure file is deleted even if user cancels download
ignore_user_abort(true);
header('Content-Type: '.$mime_type);
header("Content-Transfer-Encoding: Binary");
header("Content-disposition: attachment; filename=\"".$filename_download."\"");
readfile($folder.'/'.$filename);
// delete file
unlink($folder.'/'.$filename);
// delete folder
if($folder != "." && $folder != "..")
rmdir($folder);
}
/**
* Delete content of specified folder
*
* Do nothing if no foldername or the script base folder is provided
*
* @param $folder Foldername to delete content in
*
*/
function delete_temp_folder() {
// Get filelist from target folder
$files = glob('export_temp-*/*');
// Iterate through filelist and delete all (except hidden files e.g. .htaccess)
foreach($files as $file)
if(is_file($file))
unlink($file);
// Delete folder(s)
foreach(glob('export_temp-*') as $temp_dir)
rmdir($temp_dir);
}
/**
* Build and format userlist
*
* Creates and returns a formatted HTML table containing the userlist
*
* @param $user_data Array containing selected and formatted user data
*
* @return $table_user_data_headers concatenated with $table_user_data
*
*/
function build_table_user_data($user_data) {
require 'config.php';
$data_choices = $_SESSION['data_choices'];
if($_SESSION['filters_set']) {
echo count($user_data)." ".L10N_USERS." ".L10N_FILTERED_BY.
"<table id='info_filters'>";
$quota = $_SESSION['filter_quota'];
foreach($_SESSION['filters_set'] as $filter)
switch($filter) {
case 'filter_group_choice':
echo "<tr>
<td class='pad_b'>• ".L10N_GROUP.":</td>
<td class='pad_b pad_l red'>{$_SESSION['filter_group']}</td>
</tr>";
break;
case 'filter_lastLogin_choice':
if($_SESSION['filter_ll_since'] == '1970-01-01') {
$since = '';
$delimiter = '<= ';
}
else {
$since = $_SESSION['filter_ll_since'];
$delimiter = ' <--> ';
}
$before = $_SESSION['filter_ll_before'] != date('Y-m-d')
? $_SESSION['filter_ll_before']
: L10N_TODAY;
echo "<tr>
<td class='pad_b'>• ".L10N_LAST_LOGIN.":</td>
<td class='pad_b pad_l red'>$since$delimiter$before</td>
</tr>";
break;
case 'filter_quota_choice':