-
Notifications
You must be signed in to change notification settings - Fork 171
/
class.flyspray.php
1355 lines (1207 loc) · 45.1 KB
/
class.flyspray.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
/**
* Flyspray
*
* Flyspray class
*
* This script contains all the functions we use often in
* Flyspray to do miscellaneous things.
*
* @license http://opensource.org/licenses/lgpl-license.php Lesser GNU Public License
* @package flyspray
* @author Tony Collins
* @author Florian Schmitz
* @author Cristian Rodriguez
*/
class Flyspray
{
/**
* Current Flyspray version. Change this for each release. Don't forget!
* @access public
* @var string
* For github development use e.g. '1.0-beta dev' ; Flyspray::base_version() currently splits on the ' ' ...
* For making github release use e.g. '1.0-beta' here.
* For online version check www.flyspray.org/version.txt use e.g. '1.0-beta'
* For making releases on github use github's recommended versioning e.g. 'v1.0-beta' --> release files are then named v1.0-beta.zip and v1.0-beta.tar.gz and unzips to a flyspray-1.0-beta/ directory.
* Well, looks like a mess but hopefully consolidate this in future. Maybe use version_compare() everywhere in future instead of an own invented Flyspray::base_version()
*/
public $version = '1.0-rc6';
/**
* Flyspray preferences
* @access public
* @var array
*/
public $prefs = array();
/**
* Max. file size for file uploads. 0 = no uploads allowed
* @access public
* @var integer
*/
public $max_file_size = 0;
/**
* List of projects the user is allowed to view
* @access public
* @var array
*/
public $projects = array();
/**
* List of severities. Loaded in i18n.inc.php
* @access public
* @var array
*/
public $severities = array();
/**
* List of priorities. Loaded in i18n.inc.php
* @access public
* @var array
*/
public $priorities = array();
// Application-wide preferences {{{
/**
* Constructor, starts session, loads settings
* @access private
* @return void
* @version 1.0
*/
public function __construct()
{
global $db;
$this->startSession();
$res = $db->Query('SELECT pref_name, pref_value FROM {prefs}');
while ($row = $db->FetchRow($res)) {
$this->prefs[$row['pref_name']] = $row['pref_value'];
}
$this->setDefaultTimezone();
$sizes = array();
foreach (array(ini_get('memory_limit'), ini_get('post_max_size'), ini_get('upload_max_filesize')) as $val) {
if($val === '-1'){
// unlimited value in php configuration
$val = PHP_INT_MAX;
}
if (!$val || $val < 0) {
continue;
}
$last = strtolower($val{strlen($val)-1});
$val = trim($val, 'gGmMkK');
switch ($last) {
// The 'G' modifier is available since PHP 5.1.0
case 'g':
$val *= 1024;
case 'm':
$val *= 1024;
case 'k':
$val *= 1024;
}
$sizes[] = $val;
}
clearstatcache();
$func = create_function('$x', 'return @is_file($x . "/index.html") && is_writable($x);');
$this->max_file_size = ((bool) ini_get('file_uploads') && $func(BASEDIR . '/attachments')) ? round((min($sizes)/1024/1024), 1) : 0;
} // }}}
protected function setDefaultTimezone()
{
$default_timezone = isset($this->prefs['default_timezone']) && !empty($this->prefs['default_timezone']) ? $this->prefs['default_timezone'] : 'UTC';
// set the default time zone - this will be redefined as we go
define('DEFAULT_TIMEZONE',$default_timezone);
date_default_timezone_set(DEFAULT_TIMEZONE);
}
public static function base_version($version)
{
if (strpos($version, ' ') === false) {
return $version;
}
return substr($version, 0, strpos($version, ' '));
}
public static function get_config_path($basedir = BASEDIR)
{
$cfile = $basedir . '/flyspray.conf.php';
if (is_readable($hostconfig = sprintf('%s/%s.conf.php', $basedir, $_SERVER['SERVER_NAME']))) {
$cfile = $hostconfig;
}
return $cfile;
}
// {{{ Redirect to $url
/**
* Redirects the browser to the page in $url
* This function is based on PEAR HTTP class
* @param string $url
* @param bool $exit
* @param bool $rfc2616
* @license BSD
* @access public static
* @return bool
* @version 1.0
*/
public static function Redirect($url, $exit = true, $rfc2616 = true)
{
@ob_clean();
if (isset($_SESSION) && count($_SESSION)) {
session_write_close();
}
if (headers_sent()) {
die('Headers are already sent, this should not have happened. Please inform Flyspray developers.');
}
$url = FlySpray::absoluteURI($url);
if($_SERVER['REQUEST_METHOD']=='POST' && version_compare(PHP_VERSION, '5.4.0')>=0 ) {
http_response_code(303);
}
header('Location: '. $url);
if ($rfc2616 && isset($_SERVER['REQUEST_METHOD']) &&
$_SERVER['REQUEST_METHOD'] != 'HEAD') {
$url = htmlspecialchars($url, ENT_QUOTES, 'utf-8');
printf('%s to: <a href="%s">%s</a>.', eL('Redirect'), $url, $url);
}
if ($exit) {
exit;
}
return true;
} // }}}
/**
* Absolute URI (This function is part of PEAR::HTTP licensed under the BSD) {{{
*
* This function returns the absolute URI for the partial URL passed.
* The current scheme (HTTP/HTTPS), host server, port, current script
* location are used if necessary to resolve any relative URLs.
*
* Offsets potentially created by PATH_INFO are taken care of to resolve
* relative URLs to the current script.
*
* You can choose a new protocol while resolving the URI. This is
* particularly useful when redirecting a web browser using relative URIs
* and to switch from HTTP to HTTPS, or vice-versa, at the same time.
*
* @author Philippe Jausions <Philippe.Jausions@11abacus.com>
* @static
* @access public
* @return string The absolute URI.
* @param string $url Absolute or relative URI the redirect should go to.
* @param string $protocol Protocol to use when redirecting URIs.
* @param integer $port A new port number.
*/
public static function absoluteURI($url = null, $protocol = null, $port = null)
{
// filter CR/LF
$url = str_replace(array("\r", "\n"), ' ', $url);
// Mess around with already absolute URIs
if (preg_match('!^([a-z0-9]+)://!i', $url)) {
if (empty($protocol) && empty($port)) {
return $url;
}
if (!empty($protocol)) {
$url = $protocol .':'. end($array = explode(':', $url, 2));
}
if (!empty($port)) {
$url = preg_replace('!^(([a-z0-9]+)://[^/:]+)(:[\d]+)?!i',
'\1:'. $port, $url);
}
return $url;
}
$host = 'localhost';
if (!empty($_SERVER['HTTP_HOST'])) {
list($host) = explode(':', $_SERVER['HTTP_HOST']);
if (strpos($_SERVER['HTTP_HOST'], ':') !== false && !isset($port)) {
$port = explode(':', $_SERVER['HTTP_HOST']);
}
} elseif (!empty($_SERVER['SERVER_NAME'])) {
list($host) = explode(':', $_SERVER['SERVER_NAME']);
}
if (empty($protocol)) {
if (isset($_SERVER['HTTPS']) && !strcasecmp($_SERVER['HTTPS'], 'on')) {
$protocol = 'https';
} else {
$protocol = 'http';
}
if (!isset($port) || $port != intval($port)) {
$port = isset($_SERVER['SERVER_PORT']) ? $_SERVER['SERVER_PORT'] : 80;
}
}
if ($protocol == 'http' && $port == 80) {
unset($port);
}
if ($protocol == 'https' && $port == 443) {
unset($port);
}
$server = $protocol .'://'. $host . (isset($port) ? ':'. $port : '');
if (!strlen($url) || $url{0} == '?' || $url{0} == '#') {
$uri = isset($_SERVER['REQUEST_URI']) ?
$_SERVER['REQUEST_URI'] : $_SERVER['PHP_SELF'];
if ($url && $url{0} == '?' && false !== ($q = strpos($uri, '?'))) {
$url = substr($uri, 0, $q) . $url;
} else {
$url = $uri . $url;
}
}
if ($url{0} == '/') {
return $server . $url;
}
// Check for PATH_INFO
if (isset($_SERVER['PATH_INFO']) && strlen($_SERVER['PATH_INFO']) &&
$_SERVER['PHP_SELF'] != $_SERVER['PATH_INFO']) {
$path = dirname(substr($_SERVER['PHP_SELF'], 0, -strlen($_SERVER['PATH_INFO'])));
} else {
$path = dirname($_SERVER['PHP_SELF']);
}
if (substr($path = strtr($path, '\\', '/'), -1) != '/') {
$path .= '/';
}
return $server . $path . $url;
} // }}}
// Duplicate submission check {{{
/**
* Test to see if user resubmitted a form.
* Checks only newtask and addcomment actions.
* @return bool true if user has submitted the same action within less than 6 hours, false otherwise
* @access public static
* @version 1.0
*/
public static function requestDuplicated()
{
// garbage collection -- clean entries older than 6 hrs
$now = isset($_SERVER['REQUEST_TIME']) ? $_SERVER['REQUEST_TIME'] : time();
if (!empty($_SESSION['requests_hash'])) {
foreach ($_SESSION['requests_hash'] as $key => $val) {
if ($val < $now-6*60*60) {
unset($_SESSION['requests_hash'][$key]);
}
}
}
if (count($_POST)) {
if (preg_match('/^newtask.newtask|details.addcomment$/', Post::val('action', '')))
{
$currentrequest = md5(serialize($_POST));
if (!empty($_SESSION['requests_hash'][$currentrequest])) {
return true;
}
$_SESSION['requests_hash'][$currentrequest] = time();
}
}
return false;
} // }}}
// Retrieve task details {{{
/**
* Gets all information about a task (and caches information if wanted)
* @param integer $task_id
* @param bool $cache_enabled
* @access public static
* @return mixed an array with all taskdetails or false on failure
* @version 1.0
*/
public static function GetTaskDetails($task_id, $cache_enabled = false)
{
global $db, $fs;
static $cache = array();
if (isset($cache[$task_id]) && $cache_enabled) {
return $cache[$task_id];
}
//for some reason, task_id is not here
// run away inmediately..
if(!is_numeric($task_id)) {
return false;
}
$get_details = $db->Query('SELECT t.*, p.*,
c.category_name, c.category_owner, c.lft, c.rgt, c.project_id as cproj,
o.os_name,
r.resolution_name,
tt.tasktype_name,
vr.version_name AS reported_version_name,
vd.version_name AS due_in_version_name,
uo.real_name AS opened_by_name,
ue.real_name AS last_edited_by_name,
uc.real_name AS closed_by_name,
lst.status_name AS status_name
FROM {tasks} t
LEFT JOIN {projects} p ON t.project_id = p.project_id
LEFT JOIN {list_category} c ON t.product_category = c.category_id
LEFT JOIN {list_os} o ON t.operating_system = o.os_id
LEFT JOIN {list_resolution} r ON t.resolution_reason = r.resolution_id
LEFT JOIN {list_tasktype} tt ON t.task_type = tt.tasktype_id
LEFT JOIN {list_version} vr ON t.product_version = vr.version_id
LEFT JOIN {list_version} vd ON t.closedby_version = vd.version_id
LEFT JOIN {list_status} lst ON t.item_status = lst.status_id
LEFT JOIN {users} uo ON t.opened_by = uo.user_id
LEFT JOIN {users} ue ON t.last_edited_by = ue.user_id
LEFT JOIN {users} uc ON t.closed_by = uc.user_id
WHERE t.task_id = ?', array($task_id));
if (!$db->CountRows($get_details)) {
return false;
}
if ($get_details = $db->FetchRow($get_details)) {
$get_details += array('severity_name' => $get_details['task_severity']==0 ? '' : $fs->severities[$get_details['task_severity']]);
$get_details += array('priority_name' => $get_details['task_priority']==0 ? '' : $fs->priorities[$get_details['task_priority']]);
}
$get_details['tags'] = Flyspray::getTags($task_id);
$get_details['assigned_to'] = $get_details['assigned_to_name'] = array();
if ($assignees = Flyspray::GetAssignees($task_id, true)) {
$get_details['assigned_to'] = $assignees[0];
$get_details['assigned_to_name'] = $assignees[1];
}
$cache[$task_id] = $get_details;
return $get_details;
} // }}}
// List projects {{{
/**
* Returns a list of all projects
* @param bool $active_only show only active projects
* @access public static
* @return array
* @version 1.0
*/
// FIXME: $active_only would not work since the templates are accessing the returned array implying to be sortyed by project id, which is aparently wrong and error prone ! Same applies to the case when a project was deleted, causing a shift in the project id sequence, hence -> severe bug!
# comment by peterdd 20151012: reenabled param active_only with false as default. I do not see a problem within current Flyspray version. But consider using $fs->projects when possible, saves this extra sql request.
public static function listProjects($active_only = false)
{
global $db;
$query = 'SELECT project_id, project_title, project_is_active FROM {projects}';
if ($active_only) {
$query .= ' WHERE project_is_active = 1';
}
$query .= ' ORDER BY project_is_active DESC, project_id DESC'; # active first, latest projects first for option groups and new projects are probably the most used.
$sql = $db->Query($query);
return $db->fetchAllArray($sql);
} // }}}
// List themes {{{
/**
* Returns a list of all themes
* @access public static
* @return array
* @version 1.0
*/
public static function listThemes()
{
$themes = array();
$dirname = dirname(dirname(__FILE__));
if ($handle = opendir($dirname . '/themes/')) {
while (false !== ($file = readdir($handle))) {
if (substr($file,0,1) != '.' && is_dir("$dirname/themes/$file")
&& (is_file("$dirname/themes/$file/theme.css") || is_dir("$dirname/themes/$file/templates"))
) {
$themes[] = $file;
}
}
closedir($handle);
}
sort($themes);
# always put the full default Flyspray theme first, [0] works as fallback in class Tpl->setTheme()
array_unshift($themes, 'CleanFS');
$themes = array_unique($themes);
return $themes;
} // }}}
// List a project's group {{{
/**
* Returns a list of global groups or a project's groups
* @param integer $proj_id
* @access public static
* @return array
* @version 1.0
*/
public static function listGroups($proj_id = 0)
{
global $db;
$res = $db->Query('SELECT g.*, COUNT(uig.user_id) AS users
FROM {groups} g
LEFT JOIN {users_in_groups} uig ON uig.group_id=g.group_id
WHERE project_id = ?
GROUP BY g.group_id
ORDER BY g.group_id ASC', array($proj_id));
return $db->FetchAllArray($res);
} // }}}
// Get info on all users {{{
/**
* Returns a list of a all users
* @access public static
* @return array
* @version 1.0
*/
public static function listUsers()
{
global $db;
$res = $db->Query('SELECT account_enabled, user_id, user_name, real_name,
email_address, jabber_id, oauth_provider, oauth_uid,
notify_type, notify_own, notify_online,
tasks_perpage, lang_code, time_zone, dateformat, dateformat_extended,
register_date, login_attempts, lock_until,
profile_image, hide_my_email
FROM {users}
ORDER BY account_enabled DESC, UPPER(user_name) ASC');
return $db->FetchAllArray($res);
}
// }}}
// List languages {{{
/**
* Returns a list of installed languages
* @access public static
* @return array
* @version 1.0
*/
public static function listLangs()
{
return str_replace('.php', '', array_map('basename', glob_compat(BASEDIR ."/lang/[a-zA-Z]*.php")));
} // }}}
// Log events to the history table {{{
/**
* Saves an event to the database
* @param integer $task_id
* @param integer $type
* @param string $newvalue
* @param string $oldvalue
* @param string $field
* @param integer $time for synchronisation with other functions
* @access public static
* @return void
* @version 1.0
*/
public static function logEvent($task_id, $type, $newvalue = '', $oldvalue = '', $field = '', $time = null)
{
global $db, $user;
// This function creates entries in the history table. These are the event types:
// 0: Fields changed in a task
// 1: New task created
// 2: Task closed
// 3: Task edited (for backwards compatibility with events prior to the history system)
// 4: Comment added
// 5: Comment edited
// 6: Comment deleted
// 7: Attachment added
// 8: Attachment deleted
// 9: User added to notification list
// 10: User removed from notification list
// 11: Related task added to this task
// 12: Related task removed from this task
// 13: Task re-opened
// 14: Task assigned to user / re-assigned to different user / Unassigned
// 15: This task was added to another task's related list
// 16: This task was removed from another task's related list
// 17: Reminder added
// 18: Reminder deleted
// 19: User took ownership
// 20: Closure request made
// 21: Re-opening request made
// 22: Adding a new dependency
// 23: This task added as a dependency of another task
// 24: Removing a dependency
// 25: This task removed from another task's dependency list
// 26: Task was made private
// 27: Task was made public
// 28: PM request denied
// 29: User added to the list of assignees
// 30: New user registration
// 31: User deletion
// 32: Add new subtask
// 33: Remove Subtask
// 34: Add new parent
// 35: Remove parent
$query_params = array(intval($task_id), intval($user->id),
((!is_numeric($time)) ? time() : $time),
$type, $field, $oldvalue, $newvalue);
if($db->Query('INSERT INTO {history} (task_id, user_id, event_date, event_type, field_changed,
old_value, new_value) VALUES (?, ?, ?, ?, ?, ?, ?)', $query_params)) {
return true;
}
return false;
} // }}}
// Log a request for an admin/project manager to do something {{{
/**
* Adds an admin request to the database
* @param integer $type 1: Task close, 2: Task re-open, 3: Pending user registration
* @param integer $project_id
* @param integer $task_id
* @param integer $submitter
* @param string $reason
* @access public static
* @return void
* @version 1.0
*/
public static function AdminRequest($type, $project_id, $task_id, $submitter, $reason)
{
global $db;
$db->Query('INSERT INTO {admin_requests} (project_id, task_id, submitted_by, request_type, reason_given, time_submitted, deny_reason)
VALUES (?, ?, ?, ?, ?, ?, ?)',
array($project_id, $task_id, $submitter, $type, $reason, time(), ''));
} // }}}
// Check for an existing admin request for a task and event type {{{;
/**
* Checks whether or not there is an admin request for a task
* @param integer $type 1: Task close, 2: Task re-open, 3: Pending user registration
* @param integer $task_id
* @access public static
* @return bool
* @version 1.0
*/
public static function AdminRequestCheck($type, $task_id)
{
global $db;
$check = $db->Query("SELECT *
FROM {admin_requests}
WHERE request_type = ? AND task_id = ? AND resolved_by = 0",
array($type, $task_id));
return (bool)($db->CountRows($check));
} // }}}
// Get the current user's details {{{
/**
* Gets all user details of a user
* @param integer $user_id
* @access public static
* @return array
* @version 1.0
*/
public static function getUserDetails($user_id)
{
global $db;
// Get current user details. We need this to see if their account is enabled or disabled
$result = $db->Query('SELECT * FROM {users} WHERE user_id = ?', array(intval($user_id)));
return $db->FetchRow($result);
} // }}}
// Get group details {{{
/**
* Gets all information about a group
* @param integer $group_id
* @access public static
* @return array
* @version 1.0
*/
public static function getGroupDetails($group_id)
{
global $db;
$sql = $db->Query('SELECT * FROM {groups} WHERE group_id = ?', array($group_id));
return $db->FetchRow($sql);
} // }}}
// {{{
/**
* Crypt a password with the method set in the configfile
* @param string $password
* @access public static
* @return string
* @version 1.0
*/
public static function cryptPassword($password)
{
global $conf;
$pwcrypt = strtolower($conf['general']['passwdcrypt']);
# sha1, md5, sha512 are unsalted, hashing methods, not suited for storing passwords anymore.
# Use crypt(), that adds random salt, customizable rounds and customizable hashing algorithms.
if ($pwcrypt == 'sha1') {
return sha1($password);
} elseif ($pwcrypt == 'md5') {
return md5($password);
} elseif ($pwcrypt == 'sha512') {
return hash('sha512', $password);
} else {
return crypt($password);
}
} // }}}
// {{{
/**
* Check if a user provided the right credentials
* @param string $username
* @param string $password
* @param string $method '', 'oauth', 'ldap', 'native'
* @access public static
* @return integer user_id on success, 0 if account or user is disabled, -1 if password is wrong
* @version 1.0
*/
public static function checkLogin($username, $password, $method = 'native')
{
global $db;
$email_address = $username; //handle multiple email addresses
$temp = $db->Query("SELECT id FROM {user_emails} WHERE email_address = ?",$email_address);
$user_id = $db->FetchRow($temp);
$user_id = $user_id["id"];
$result = $db->Query("SELECT uig.*, g.group_open, u.account_enabled, u.user_pass,
lock_until, login_attempts
FROM {users_in_groups} uig
LEFT JOIN {groups} g ON uig.group_id = g.group_id
LEFT JOIN {users} u ON uig.user_id = u.user_id
WHERE u.user_id = ? OR u.user_name = ? AND g.project_id = ?
ORDER BY g.group_id ASC", array($user_id, $username, 0));
$auth_details = $db->FetchRow($result);
if($auth_details === false) {
return -2;
}
if(!$result || !count($auth_details)) {
return 0;
}
if( $method != 'ldap' ){
// encrypt the password with the method used in the db
switch (strlen($auth_details['user_pass'])) {
# detecting passwords stored with old unsalted hashing methods: sha1,md5,sha512
case 40:
$pwhash = sha1($password);
break;
case 32:
$pwhash = md5($password);
break;
case 128:
$pwhash = hash('sha512', $password);
break;
default:
$pwhash = crypt($password, $auth_details['user_pass']); // user_pass contains algorithm, rounds, salt
break;
}
}
if ($auth_details['lock_until'] > 0 && $auth_details['lock_until'] < time()) {
$db->Query('UPDATE {users} SET lock_until = 0, account_enabled = 1, login_attempts = 0
WHERE user_id = ?', array($auth_details['user_id']));
$auth_details['account_enabled'] = 1;
$_SESSION['was_locked'] = true;
}
// skip password check if the user is using oauth
if($method == 'oauth'){
$pwOk = true;
} elseif( $method == 'ldap'){
$pwOk = Flyspray::checkForLDAPUser($username, $password);
} else{
// Compare the crypted password to the one in the database
if( function_exists('hash_equals') ){
$pwOk = hash_equals($pwhash, $auth_details['user_pass']);
} else{
$pwOk = ($pwhash == $auth_details['user_pass']);
}
}
// Admin users cannot be disabled
if ($auth_details['group_id'] == 1 /* admin */ && $pwOk) {
return $auth_details['user_id'];
}
if ($pwOk && $auth_details['account_enabled'] == '1' && $auth_details['group_open'] == '1'){
return $auth_details['user_id'];
}
return ($auth_details['account_enabled'] && $auth_details['group_open']) ? 0 : -1;
} // }}}
static public function checkForOauthUser($uid, $provider)
{
global $db;
if(empty($uid) || empty($provider)) {
return false;
}
$sql = $db->Query("SELECT id FROM {user_emails} WHERE oauth_uid = ? AND oauth_provider = ?",array($uid, $provider));
if ($db->fetchOne($sql)) {
return true;
} else {
return false;
}
}
/**
* 20150320 just added from provided patch, untested!
*/
public static function checkForLDAPUser($username, $password)
{
# TODO: add to admin settings area, maybe let user set the config at final installation step
$ldap_host = 'ldaphost';
$ldap_port = '389';
$ldap_version = '3';
$base_dn = 'OU=SBSUsers,OU=Users,OU=MyBusiness,DC=MyDomain,DC=local';
$ldap_search_user = 'ldapuser@mydomain.local';
$ldap_search_pass = "ldapuserpass";
$filter = "SAMAccountName=%USERNAME%"; // this is for AD - may be different with other setups
$username = $username;
if (strlen($password) == 0){ // LDAP will succeed binding with no password on AD (defaults to anon bind)
return false;
}
$rs = ldap_connect($ldap_host, $ldap_port);
@ldap_set_option($rs, LDAP_OPT_PROTOCOL_VERSION, $ldap_version);
@ldap_set_option($rs, LDAP_OPT_REFERRALS, 0);
$ldap_bind_dn = empty($ldap_search_user) ? NULL : $ldap_search_user;
$ldap_bind_pw = empty($ldap_search_pass) ? NULL : $ldap_search_pass;
if (!$bindok = @ldap_bind($rs, $ldap_bind_dn, $ldap_search_pass)){
// Uncomment for LDAP debugging
$error_msg = ldap_error($rs);
die("Couldn't bind using ".$ldap_bind_dn."@".$ldap_host.":".$ldap_port." Because:".$error_msg);
return false;
} else{
$filter_r = str_replace("%USERNAME%", $username, $filter);
$result = @ldap_search($rs, $base_dn, $filter_r);
if (!$result){ // ldap search returned nothing or error
return false;
}
$result_user = ldap_get_entries($rs, $result);
if ($result_user["count"] == 0){ // No users match the filter
return false;
}
$first_user = $result_user[0];
$ldap_user_dn = $first_user["dn"];
// Bind with the dn of the user that matched our filter (only one user should match sAMAccountName or uid etc..)
if (!$bind_user = @ldap_bind($rs, $ldap_user_dn, $password)){
$error_msg = ldap_error($rs);
die("Couldn't bind using ".$ldap_user_dn."@".$ldap_host.":".$ldap_port." Because:".$error_msg);
return false;
} else{
return true;
}
}
}
// Set cookie {{{
/**
* Sets a cookie, automatically setting the URL
* Now same params as PHP's builtin setcookie()
* @param string $name
* @param string $val
* @param integer $time
* @param string $path
* @param string $domain
* @param bool $secure
* @param bool $httponly
* @access public static
* @return bool
* @version 1.1
*/
public static function setCookie($name, $val, $time = null, $path=null, $domain=null, $secure=false, $httponly=false)
{
global $conf;
if (null===$path){
$url = parse_url($GLOBALS['baseurl']);
}else{
$url['path']=$path;
}
if (!is_int($time)) {
$time = time()+60*60*24*30;
}
if(null===$domain){
$domain='';
}
if(null===$secure){
$secure = isset($conf['general']['securecookies']) ? $conf['general']['securecookies'] : false;
}
if((strlen($name) + strlen($val)) > 4096) {
//violation of the protocol
trigger_error("Flyspray sent a too big cookie, browsers will not handle it");
return false;
}
return setcookie($name, $val, $time, $url['path'],$domain,$secure,$httponly);
} // }}}
// Start the session {{{
/**
* Starts the session
* @access public static
* @return void
* @version 1.0
* @notes smile intented
*/
public static function startSession()
{
global $conf;
if (defined('IN_FEED') || php_sapi_name() === 'cli') {
return;
}
/*
# commented out IMHO weired obfuscating session names
$names = array( 'GetFirefox',
'UseLinux',
'NoMicrosoft',
'ThinkB4Replying',
'FreeSoftware',
'ReadTheFAQ',
'RTFM',
'VisitAU',
'SubliminalAdvertising',
);
foreach ($names as $val)
{
session_name($val);
session_start();
if (isset($_SESSION['SESSNAME']))
{
$sessname = $_SESSION['SESSNAME'];
break;
}
$_SESSION = array();
session_destroy();
setcookie(session_name(), '', time()-60, '/');
}
if (empty($sessname))
{
$rand_key = array_rand($names);
$sessname = $names[$rand_key];
session_name($sessname);
session_start();
$_SESSION['SESSNAME'] = $sessname;
}
*/
$url = parse_url($GLOBALS['baseurl']);
session_name('flyspray');
session_set_cookie_params(0,$url['path'],'', (isset($conf['general']['securecookies'])? $conf['general']['securecookies']:false), TRUE);
session_start();
if(!isset($_SESSION['csrftoken'])){
$_SESSION['csrftoken']=rand(); # lets start with one anti csrf token secret for the session and see if it's simplicity is good enough (I hope together with enforced Content Security Policies)
}
} // }}}
// Compare tasks {{{
/**
* Compares two tasks and returns an array of differences
* @param array $old
* @param array $new
* @access public static
* @return array array('field', 'old', 'new')
* @version 1.0
*/
public static function compare_tasks($old, $new)
{
$comp = array('priority_name', 'severity_name', 'status_name', 'assigned_to_name', 'due_in_version_name',
'reported_version_name', 'tasktype_name', 'os_name', 'category_name',
'due_date', 'percent_complete', 'item_summary', 'due_in_version_name',
'detailed_desc', 'project_title', 'mark_private');
$changes = array();
foreach ($old as $key => $value)
{
if (!in_array($key, $comp) || ($key === 'due_date' && intval($old[$key]) === intval($new[$key]))) {
continue;
}
if($old[$key] != $new[$key]) {
switch ($key)
{
case 'due_date':
$new[$key] = formatDate($new[$key]);
$value = formatDate($value);
break;
case 'percent_complete':
$new[$key] .= '%';
$value .= '%';
break;
case 'mark_private':
$new[$key] = $new[$key] ? L('private') : L('public');
$value = $value ? L('private') : L('public');
break;
}
$changes[] = array($key, $value, $new[$key]);
}
}
return $changes;
} // }}}
// {{{
/**
* Get all tags of a task
* @access public static
* @return array
* @version 1.0
*/
public static function getTags($task_id)
{
global $db;
# pre FS1.0beta
#$sql = $db->Query('SELECT * FROM {tags} WHERE task_id = ?', array($task_id));
# since FS1.0beta
$sql = $db->Query('SELECT tg.tag_id, tg.tag_name AS tag, tg.class FROM {task_tag} tt
JOIN {list_tag} tg ON tg.tag_id=tt.tag_id
WHERE task_id = ?
ORDER BY list_position', array($task_id));
return $db->FetchAllArray($sql);
} /// }}}
// {{{
/**
* Get a list of assignees for a task
* @param integer $task_id
* @param bool $name whether or not names of the assignees should be returned as well
* @access public static
* @return array
* @version 1.0
*/
public static function GetAssignees($task_id, $name = false)