forked from highfidelity-worklist/worklist
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfunctions.php
More file actions
1700 lines (1491 loc) · 60.4 KB
/
Copy pathfunctions.php
File metadata and controls
1700 lines (1491 loc) · 60.4 KB
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
function worklist_autoloader($class) {
if ($class != 'View' && substr($class, -4) == 'View') {
$fileName = substr($class, 0, -4);
$file = VIEWS_DIR . DIRECTORY_SEPARATOR . $fileName . '.php';
} elseif ($class != 'Layout' && substr($class, -6) == 'Layout') {
$fileName = substr($class, 0, -6);
$file = VIEWS_DIR . DIRECTORY_SEPARATOR . 'layout' . DIRECTORY_SEPARATOR . $fileName . '.php';
} else if ($class != 'Controller' && substr($class, -10) == 'Controller') {
$fileName = substr($class, 0, -10);
$file = CONTROLLERS_DIR . DIRECTORY_SEPARATOR . $fileName . '.php';
} else if ($class != 'Model' && substr($class, -5) == 'Model') {
$fileName = substr($class, 0, -5);
$file = MODELS_DIR . DIRECTORY_SEPARATOR . $fileName . '.php';
} else {
$file = realpath(dirname(__FILE__) . DIRECTORY_SEPARATOR . 'classes') .
DIRECTORY_SEPARATOR . "$class.class.php";
}
if (file_exists($file)) {
require_once($file);
}
}
spl_autoload_register('worklist_autoloader');
/**
* Timezones functions
*/
function getTimeZoneDateTime($GMT) {
$timezones = array(
'-1200'=>'Pacific/Kwajalein',
'-1100'=>'Pacific/Samoa',
'-1000'=>'Pacific/Honolulu',
'-0900'=>'America/Juneau',
'-0800'=>'America/Los_Angeles',
'-0700'=>'America/Denver',
'-0600'=>'America/Mexico_City',
'-0500'=>'America/New_York',
'-0400'=>'America/Caracas',
'-0330'=>'America/St_Johns',
'-0300'=>'America/Argentina/Buenos_Aires',
'-0200'=>'Atlantic/Azores',// no cities here so just picking an hour ahead
'-0100'=>'Atlantic/Azores',
'+0000'=>'Europe/London',
'+0100'=>'Europe/Paris',
'+0200'=>'Europe/Helsinki',
'+0300'=>'Europe/Moscow',
'+0330'=>'Asia/Tehran',
'+0400'=>'Asia/Baku',
'+0430'=>'Asia/Kabul',
'+0500'=>'Asia/Karachi',
'+0530'=>'Asia/Calcutta',
'+0600'=>'Asia/Colombo',
'+0700'=>'Asia/Bangkok',
'+0800'=>'Asia/Singapore',
'+0900'=>'Asia/Tokyo',
'+0930'=>'Australia/Darwin',
'+1000'=>'Pacific/Guam',
'+1100'=>'Asia/Magadan',
'+1200'=>'Asia/Kamchatka'
);
if(isset($timezones[$GMT])){
return $timezones[$GMT];
} else {
return date_default_timezone_get();
}
}
// @param $short == 1 -> return date format as 4:31 AM
// else return date format as 04:31:22 AM
function convertTimeZoneToLocalTime($timeoffset, $short) {
$DefZone = getTimeZoneDateTime($timeoffset);
date_default_timezone_set($DefZone);
if (strlen($timeoffset) == 5) {
$formatedTime = str_split($timeoffset);
$Symbol = $formatedTime[0];
$First = $formatedTime[1];
$Second = $formatedTime[2];
$Third = $formatedTime[3];
$Fourth = $formatedTime[4];
if ($Third=="3") {
$Third =5;
}
$timezone_local = $Symbol.$First.$Second.".".$Third.$Fourth;
} else {
$timezone_local = 0;
}
$time = time();
$timezone_offset = date("Z");
$timezone_add = round($timezone_local*60*60);
$ar = localtime($time,true);
if ($ar['tm_isdst']) { $time += 3600; }
$time = round($time-$timezone_offset+$timezone_add);
if (isset($short) && $short == 1)
$LocalTime = date("g:i A", $time);
else
$LocalTime = date("h:i:s A", $time);
return $LocalTime;
}
function checkReferer() {
$len = strlen(SERVER_NAME);
if ( empty($_SERVER['HTTP_REFERER'])
|| ( substr($_SERVER['HTTP_REFERER'], 0, $len + 8) != 'https://'.SERVER_NAME )) {
return false;
} else {
return true;
}
}
function enforceRateLimit($class, $id, $test=false) {
$classMap = array('love'=>array('cost'=>15, 'maximum'=>20));
if (!isset($classMap[$class])) return 0;
$cost = $classMap[$class]['cost'];
$maximum = $classMap[$class]['maximum'];
$qry = "select TIMESTAMPDIFF(SECOND,NOW(),expires) as expires from ".LIMITS." where class='$class' and id='$id'";
$res = mysql_query($qry);
if ($res && ($row = mysql_fetch_assoc($res))) {
$expires = max(0, $row['expires']);
if ($expires > $maximum) {
return $expires - $maximum;
}
} else {
$expires = 0;
}
if (!$test) {
$expires += $cost;
$res = mysql_query("update ".LIMITS." set expires=TIMESTAMPADD(SECOND,$expires,NOW()) where class='$class' and id='$id'");
if (!$res) {
$res = mysql_query("insert into ".LIMITS." set class='$class', id='$id', expires=TIMESTAMPADD(SECOND,$expires,NOW())");
}
}
return 0;
}
// Get the userId from the session, or set it to 0 for Guests.
function getSessionUserId() {
return isset($_SESSION['userid']) ? (int)$_SESSION['userid'] : 0;
}
function getNickName($username) {
static $map = array();
if (!isset($map[$username])) {
$strSQL = "select nickname from ".USERS." where username='".$username."'";
$result = mysql_query($strSQL);
$row = mysql_fetch_array($result);
$map[$username] = $row['nickname'];
}
return $map[$username];
}
function getWorkItemSummary($itemid) {
$query = "select summary from ".WORKLIST." where id='$itemid'";
$rt = mysql_query($query);
if ($rt) {
$row = mysql_fetch_assoc($rt);
$summary = $row['summary'];
}
return $summary;
}
/* initSessionData
*
* Initializes the session data for a user. Takes as input either a username or a an array containing
* data from a row in the users table.
*
* NOTE: keep this function in sync with the same function in journal!!!
*/
function initSessionData($user) {
if (!is_array($user)) {
$res = mysql_query("select * from ".USERS." where username='".mysql_real_escape_string($user)."'");
$user_row = (($res) ? mysql_fetch_assoc($res) : null);
if (empty($user_row)) return;
} else {
$user_row = $user;
}
$_SESSION['username'] = $user_row['username'];
$_SESSION['userid'] = $user_row['id'];
$_SESSION['confirm_string'] = $user_row['confirm_string'];
$_SESSION['nickname'] = $user_row['nickname'];
$_SESSION['timezone'] = $user_row['timezone'];
$_SESSION['is_admin'] = intval($user_row['is_admin']);
$_SESSION['is_runner'] = intval($user_row['is_runner']);
$_SESSION['is_payer'] = intval($user_row['is_payer']);
}
//joanne - TODO - wl uses function initUserById($userid)journal uses $uid {
//let's see if we can take this out and replace any calls with function initUserById($userid) {
function initSessionDataByUserId($uid) {
$res = mysql_query("select * from ".USERS." where id='".mysql_real_escape_string($uid)."'");
$user_row = (($res) ? mysql_fetch_assoc($res) : null);
if (empty($user_row)) return;
$_SESSION['username'] = $user_row['username'];
$_SESSION['confirm_string'] = isset($user_row['confirm_string']) ? $user_row['confirm_string'] : 0;
$_SESSION['nickname'] = $user_row['nickname'];
$_SESSION['timezone'] = isset($user_row['timezone']) ? $user_row['timezone'] : 0;
$_SESSION['is_admin'] = $user_row['is_admin'];
$_SESSION['is_runner'] = $user_row['is_runner'];
$_SESSION['is_payer'] = isset($user_row['is_payer']) ? intval($user_row['is_payer']) : 0;
}
function initUserById($userid) {
$res = mysql_query("select * from ".USERS." where id='".mysql_real_escape_string($userid)."'");
$user_row = (($res) ? mysql_fetch_assoc($res) : null);
if (empty($user_row)) return;
$_SESSION['username'] = $user_row['username'];
$_SESSION['userid'] = $user_row['id'];
$_SESSION['confirm_string'] = $user_row['confirm_string'];
$_SESSION['nickname'] = $user_row['nickname'];
$_SESSION['timezone'] = $user_row['timezone'];
$_SESSION['is_runner'] = intval($user_row['is_runner']);
$_SESSION['is_payer'] = intval($user_row['is_payer']);
// set the session variable for the inline message for new users before last seen is updated
if ($user_row['last_seen'] === null) {
$_SESSION['inlineHide'] = 0;
} else {
$_SESSION['inlineHide'] = 1;
}
$last_seen_db = substr($user_row['last_seen'], 0, 10);
$today = date('Y-m-d');
if ($last_seen_db != $today) {
$res = mysql_query("UPDATE ".USERS." SET last_seen = NOW() WHERE id={$userid}");
}
$_SESSION['last_seen'] = $today;
}
function isEnabled($features) {
if (empty($_SESSION['features']) || ($_SESSION['features'] & $features) != $features) {
return false;
} else {
return true;
}
}
function isSuperAdmin() {
if (empty($_SESSION['features']) || ($_SESSION['features'] & FEATURE_SUPER_ADMIN) != FEATURE_SUPER_ADMIN) {
return false;
} else {
return true;
}
}
/* Function: countLoveToUser
*
* Purpose: Gets the count of love sent to a user.
*
* Parameters: username - The username of the desired user.
* fromUser - If set will get the love sent by this user.
*/
function countLove($username, $fromUsername="") {
defineSendLoveAPI();
//Wires off countLove to 0, ignores API (api working 5/24)
//return array('status'=>SL_OK,'error'=>SL_NO_ERROR,array('count'=>0));
if($fromUsername != "") {
$params = array (
'action' => 'getcount',
'api_key' => SENDLOVE_API_KEY,
'username' => $username,
'fromUsername' => $fromUsername);
} else {
$params = array (
'action' => 'getcount',
'api_key' => SENDLOVE_API_KEY,
'username' => $username);
}
$referer = (empty($_SERVER['HTTPS'])?'http://':'https://').$_SERVER['SERVER_NAME'].$_SERVER['PHP_SELF'];
$retval = json_decode(postRequest (SENDLOVE_API_URL, $params, array(CURLOPT_REFERER => $referer)), true);
if ($retval['status'] == "ok") {
return $retval['data']['count'];
} else {
return -1;
}
}
/* Function: getUserLove
*
* Purpose: Get Love sent to the user
*
* Parameters: username - The username of the user to get love from.
* fromUsername - If set it will filter to the love sent by this username.
*/
function getUserLove($username, $fromUsername="") {
defineSendLoveAPI();
//Wires off getUserLove to 0, ignores API (api working 5/24)
//return array('status'=>SL_OK,'error'=>SL_NO_ERROR,array('count'=>0));
if($fromUsername != "") {
$params = array (
'action' => 'getlove',
'api_key' => SENDLOVE_API_KEY,
'username' => $username,
'fromUsername' => $fromUsername,
'pagination' => 0);
} else {
$params = array (
'action' => 'getlove',
'api_key' => SENDLOVE_API_KEY,
'username' => $username,
'pagination' => 0);
}
$referer = (empty($_SERVER['HTTPS'])?'http://':'https://').$_SERVER['SERVER_NAME'].$_SERVER['PHP_SELF'];
$retval = json_decode(postRequest (SENDLOVE_API_URL, $params, array(CURLOPT_REFERER => $referer)), true);
if ($retval['status'] == "ok") {
return $retval['data'];
} else {
return -1;
}
}
function defineSendLoveAPI() {
// Sendlove API status and error codes. Keep in sync with .../sendlove/api.php
// only define constants once
if (!defined('SL_OK')){
define ('SL_OK', 'ok');
define ('SL_ERROR', 'error');
define ('SL_WARNING', 'warning');
define ('SL_NO_ERROR', '');
define ('SL_NO_RESPONSE', 'no response');
define ('SL_BAD_CALL', 'bad call');
define ('SL_DB_FAILURE', 'db failure');
define ('SL_UNKNOWN_USER', 'unknown user');
define ('SL_NOT_COWORKER', 'receiver not co-worker');
define ('SL_RATE_LIMIT', 'rate limit');
define ('SL_SEND_FAILED', 'send failed');
define ('SL_JOURNAL_FAILED', 'journal failed');
define ('SL_NO_SSL', 'no ssl call');
define ('SL_WRONG_KEY', 'wrong api key');
define ('SL_LOVE_DISABLED', 'sendlove disabled');
}
}
// This will be handled by Rewarder API
/*
* Populate the rewarder team automatically. It's based on who added a fee to a task you worked on in the last 30 days.
*
*
*/
function PopulateRewarderTeam($user_id, $worklist_id = '') {
//Wire off rewarder interface for the time being - gj 5/21/10
// returns results of mysql update operation (success=true)
return true;
$where = !empty($worklist_id) ? " f.worklist_id = $worklist_id " : " f.worklist_id IN (SELECT DISTINCT f1.worklist_id FROM " . FEES . " f1 WHERE f1.user_id = $user_id and f1.rewarder = 0) ";
$rewarder_limit_day = GetPopulateRewarderLimit($user_id);
$rewarder_limit_day = $rewarder_limit_day == 0 ? 30 : $rewarder_limit_day;
$where .= " AND f.paid_date BETWEEN (NOW() - INTERVAL $rewarder_limit_day day) AND NOW() " ;
// This will be replaced with an API call
// $sql = "INSERT INTO " . REWARDER . " (giver_id,receiver_id,rewarder_points) SELECT DISTINCT $user_id, u.id, 0 FROM " . USERS . " u INNER JOIN " . FEES . " f ON (f.user_id = u.id) WHERE $where AND NOT EXISTS (SELECT 1 FROM " . REWARDER . " rd WHERE rd.giver_id = $user_id) AND u.id <> $user_id ";
// mysql_query($sql);
}
function GetPopulateRewarderLimit($user_id) {
//Wire off rewarder, will use API - gj 5/24/10
//Rewarder limit/day just return 0
return 0;
$sql = "SELECT rewarder_limit_day FROM ". USERS . " WHERE id= $user_id ";
$rt = mysql_query($sql);
if($row = mysql_fetch_assoc($rt)) {
return $row['rewarder_limit_day'];
}
return 0;
}
/* postRequest
*
* Function for performing a CURL request given an url and post data.
* Returns the results.
*/
function postRequest($url, $post_data, $options = array(), $curlopt_timeout = 30) {
if (!function_exists('curl_init')) {
error_log('Curl is not enabled.');
return 'error: curl is not enabled.';
}
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, $curlopt_timeout);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
if (count($options)) {
curl_setopt_array($ch, $options);
}
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
//converts unix timestamp to user's time according to his timezone settings
function getUserTime($timestamp){
//need a default to not spew errors when browser is not logged in
//We should probably change logic to always has a SESSION defined (from default)
//Determine login status by SESSION['userid'] etc
if (!empty($_SESSION['timezone'])) {
$tz_correction = $_SESSION['timezone'];
if(strpos($_SESSION['timezone'], "+") === 0){
$tz_correction = "-".substr($_SESSION['timezone'],1);
}elseif(strpos($_SESSION['timezone'], "-") === 0){
$tz_correction = "+".substr($_SESSION['timezone'],1);
}
} else { $tz_correction=0; }
$server_tz = date_default_timezone_get();
date_default_timezone_set ("Europe/London");
$userTime = date("m/d/Y h:i a", strtotime(date("Y-m-d H:i", $timestamp)." ".$tz_correction));
date_default_timezone_set ($server_tz);
return $userTime;
}
// converts server time to users timzone time
function convertTimezone($timestamp){
if (isset($_SESSION['timezone']) && !empty($_SESSION['timezone'])) {
$time_zone_date_time = getTimeZoneDateTime($_SESSION['timezone']);
if ($time_zone_date_time) {
$oTz = date_default_timezone_get();
date_default_timezone_set($time_zone_date_time);
$new_time = date('m/d/Y h:i a', $timestamp);
date_default_timezone_set($oTz);
return $new_time;
}
}
return date('m/d/Y h:i a', $timestamp);
}
/* Function: AddFee
*
* Purpose: This function inserts
*
* Parameters: itemid - id of the worklist entry
* fee_amount - amount of the fee
* fee_category - accounting category for the fee (Refer to below list)
* fee_desc - description of the fee entry
* mechanic_id - userid of the mechanic
*
* Fee Categories: Bid, Code Review, Design Spec, Misc Expense, Management Fee
*
*/
function AddFee($itemid, $fee_amount, $fee_category, $fee_desc, $mechanic_id, $is_expense, $is_rewarder=0)
{
if ($is_rewarder) $is_expense = 0;
// Get work item summary
$query = "select summary from ".WORKLIST." where id='$itemid'";
$rt = mysql_query($query);
if ($rt) {
$row = mysql_fetch_assoc($rt);
$summary = $row['summary'];
}
$query = "INSERT INTO `".FEES."` (`id`, `worklist_id`, `amount`, `category`, `user_id`, `desc`, `date`, `paid`, `expense`) ".
"VALUES (NULL, '".(int)$itemid."', '".(float)$fee_amount."', '".(int)$fee_category."', '".(int)$mechanic_id."', '".mysql_real_escape_string($fee_desc)."', NOW(), '0', '".mysql_real_escape_string($is_expense)."' )";
$result = mysql_unbuffered_query($query);
// Journal notification
if($mechanic_id == $_SESSION['userid'])
{
$journal_message = '@' . $_SESSION['nickname'] . ' added a fee of $' . $fee_amount . ' to #' . $itemid;
}
else
{
// Get the mechanic's nickname
$rt = mysql_query("select nickname from ".USERS." where id='".(int)$mechanic_id."'");
if ($rt) {
$row = mysql_fetch_assoc($rt);
$nickname = $row['nickname'];
}
else
{
$nickname = "unknown-{$mechanic_id}";
}
$journal_message = '@' . $_SESSION['nickname'] . ' on behalf of @' . $nickname . ' added a fee of $' . $fee_amount . ' to #' . $itemid;
}
return $journal_message;
}
function payBonusToUser($user_id, $amount, $notes, $budget_id) {
$query = "INSERT INTO `".FEES."` (`id`, `worklist_id`, `budget_id`, `payer_id`, `user_id`, `amount`, `notes`, `desc`, `date`, `bonus`,`paid`,`category`)".
"VALUES ".
"(NULL, 0, '" . (int)$budget_id . "', '" . (int)$_SESSION['userid'] . "', '" . (int)$user_id . "', '" . (float)$amount . "', 'BONUS','" . mysql_real_escape_string($notes) . "', NOW(), 1, 0,0)";
$result = mysql_unbuffered_query($query);
if (mysql_insert_id()) {
return true;
} else {
return false;
}
}
function formatableRelativeTime($timestamp, $detailLevel = 1) {
$periods = array("sec", "min", "hr", "day", "week", "mnth", "yr", "decade");
$lengths = array("60", "60", "24", "7", "4.357", "12", "10");
$now = time();
if(empty($timestamp)) {
return "Unknown time";
}
if($now > $timestamp) {
$difference = $now - $timestamp;
$tense = "";
} else {
$difference = $timestamp - $now;
$tense = "from now";
}
if ($difference == 0) {
return "1 second ago";
}
$remainders = array();
for($j = 0; $j < count($lengths); $j++) {
$remainders[$j] = floor(fmod($difference, $lengths[$j]));
$difference = floor($difference / $lengths[$j]);
}
$difference = round($difference);
$remainders[] = $difference;
$string = "";
for ($i = count($remainders) - 1; $i >= 0; $i--) {
if ($remainders[$i]) {
$string .= $remainders[$i] . " " . $periods[$i];
if($remainders[$i] != 1) {
$string .= "s";
}
$string .= " ";
$detailLevel--;
if ($detailLevel <= 0) {
break;
}
}
}
return $string . $tense;
}
function relativeTime($time, $withIn = true, $justNow = true, $withAgo = true, $specific = true) {
$secs = abs($time);
$mins = 60;
$hour = $mins * 60;
$day = $hour * 24;
$week = $day * 7;
$month = $day * 30;
$year = $day * 365;
// years
$segments = array();
$segments['yr'] = intval($secs / $year);
$secs %= $year;
// month
$segments['mnth'] = intval($secs / $month);
$secs %= $month;
if (!$segments['yr']) {
$segments['day'] = intval($secs / $day);
$secs %= $day;
if (!$segments['mnth']) {
$segments['hr'] = intval($secs / $hour);
$secs %= $hour;
if (!$segments['day']) {
$segments['min'] = intval($secs / $mins);
$secs %= $mins;
if (!$segments['hr'] && !$segments['min']) {
$segments['sec'] = $secs;
}
}
}
}
$relTime = '';
foreach ($segments as $unit=>$cnt) {
if ($segments[$unit]) {
if (strlen($relTime)) {
$relTime .= ', ';
}
$relTime .= "$cnt $unit";
if ($cnt > 1) {
$relTime .= 's';
}
if (!$specific) {
break;
}
}
}
if (!empty($relTime)) {
return ($time < 0) ? ($withAgo ? '' : '-') . ("$relTime " . ($withAgo ? 'ago' : '')) : ($withIn ? "in $relTime" : $relTime);
} else {
return $justNow ? 'just now' : '';
}
}
function is_runner() {
return !empty($_SESSION['is_runner']) ? true : false;
}
function sendJournalNotification($message) {
$entry = new EntryModel();
return $entry->notify($message);
global $chat;
$username = mysql_real_escape_string(JOURNAL_API_USER);
$password = mysql_real_escape_string(sha1(JOURNAL_API_PWD));
$sql = "select id, nickname from ".USERS." where username='$username' and password='$password' and confirm='1'";
if (! $res = mysql_query($sql)) {
error_log("jadd.mysql: ".mysql_error());
}
if($res && mysql_num_rows($res) > 0) {
$row = mysql_fetch_assoc($res);
$data = $chat->sendEntry($row['nickname'], $message, array('userid' => $row['id']), false, false);
if($data['status'] == 'ok') {
return "ok";
} else {
return "error: failed while writing entry with status: {$data['status']}.";
}
} else {
return "error: invalid user.";
}
}
function withdrawBid($bid_id, $withdraw_reason) {
$res = mysql_query('SELECT * FROM `' . BIDS . '` WHERE `id`='.$bid_id);
$bid = mysql_fetch_object($res);
// checking if is bidder or runner
if (is_runner() || ($bid->bidder_id == $_SESSION['userid'])) {
// getting the job
$res = mysql_query('SELECT * FROM `' . WORKLIST . '` WHERE `id` = ' . $bid->worklist_id);
$job = mysql_fetch_assoc($res);
if (! in_array($job['status'], array(
'Draft',
'Suggestion',
'Bidding',
'Done'
))) {
$creator_fee_desc = 'Creator';
$runner_fee_desc = 'Runner';
$WorkItem = new WorkItem($bid->worklist_id);
$fees = $WorkItem->getFees($WorkItem->getId());
foreach ($fees as $fee) {
if ($fee['desc'] == $creator_fee_desc) {
deleteFee($fee['id']);
}
if ($fee['desc'] == $runner_fee_desc) {
deleteFee($fee['id']);
}
}
}
// additional changes if status is WORKING, SVNHOLD, FUNCTIONAL or REVIEW
if (($job['status'] == 'In Progress' || $job['status'] == 'Review' || $job['status'] == 'QA Ready')
&& ($bid->accepted == 1) && (is_runner() || ($bid->bidder_id == $_SESSION['userid']))) {
// change status of worklist item
mysql_unbuffered_query("UPDATE `" . WORKLIST . "`
SET `mechanic_id` = '0',
`status` = 'Bidding'
WHERE `id` = $bid->worklist_id
LIMIT 1 ;");
}
// set back to suggested if swb and is only bid
$res = mysql_query('SELECT count(*) AS count_bids FROM `' . BIDS . '` WHERE `worklist_id` = ' . $job['id'] . ' AND `withdrawn` = 0');
$bidCount = mysql_fetch_assoc($res);
if ($bidCount['count_bids'] == 1 && $job['status'] == 'Bidding' && ($bid->bidder_id == $_SESSION['userid']) && $job['runner_id'] = 0) {
mysql_unbuffered_query("UPDATE `" . WORKLIST . "` SET `status` = 'Suggestion' WHERE `id` = $bid->worklist_id LIMIT 1 ;");
}
// change bid to withdrawn and set bids.accepted to 0
mysql_unbuffered_query('UPDATE `' . BIDS . '`
SET `withdrawn` = 1 , `accepted` = 0
WHERE `id` = ' . $bid->id);
// delete the fee entry for this bid
mysql_unbuffered_query('UPDATE `' . FEES . '`
SET `withdrawn` = 1
WHERE `worklist_id` = ' . $bid->worklist_id . '
AND `user_id` = ' . $bid->bidder_id . '
AND `bid_id` = ' . $bid->id);
// Get user
$user = getUserById($bid->bidder_id);
// Journal message
$message = 'A bid was deleted from #' . $job['id'];
// Journal notification
sendJournalNotification($message);
// Sending email to the bidder or runner
$subject = "Bid: " . $job['id'] . " (" . $job['summary']. ")";
if(is_runner()){
// Send to bidder
$recipient=$user;
$body = "<p>Your bid has been deleted from item #" . $job['id'] . " by: ".$_SESSION['nickname']."</p>";
} else {
// Send to runner
$recipient=getUserById($job['runner_id']);
$body = "<p>A bid has been deleted from item #" . $job['id'] . " by: ".$_SESSION['nickname']."</p>";
}
if(strlen($withdraw_reason)>0) {
// nl2br is added for proper formatting in email alert 12-MAR-2011 <webdev>
$body .= "<p>Reason: " .nl2br($withdraw_reason)."</p>";
}
// Continue adding text to email body
$item_link = SERVER_URL . $bid->worklist_id;
$body .= "<p><a href='${item_link}'>View Item</a></p>";
$body .= "<p>If you think this has been done in error, please contact the job Runner.</p>";
if (!send_email($recipient->username, $subject, $body)) { error_log("withdrawBid: send_email failed"); }
// Check if there are any active bids remaining
$res = mysql_query("SELECT count(*) AS active_bids FROM `" . BIDS . "` WHERE `worklist_id` = " . $job['id'] . " AND `withdrawn` = 0 AND (NOW() < `bid_expires` OR `bid_expires`='0000-00-00 00:00:00')");
$bids = mysql_fetch_assoc($res);
if ($bids['active_bids'] < 1) {
// There are no active bids, so resend notifications
$workitem = new WorkItem();
$workitem->loadById($job['id']);
Notification::massStatusNotify($workitem);
}
}
}
function deleteFee($fee_id) {
$res = mysql_query('SELECT * FROM `' . FEES . '` WHERE `id`='.$fee_id);
$fee = mysql_fetch_object($res);
// checking if is bidder or runner
if (is_runner() || ($fee->user_id == $_SESSION['userid'])) {
mysql_unbuffered_query('UPDATE `' . FEES . '`
SET `withdrawn` = 1
WHERE `id` = ' . $fee_id);
// Get worklist item summary
$summary = getWorkItemSummary($fee->worklist_id);
// Get user
$user = getUserById($fee->user_id);
if ($user !== false) {
// Journal message
$message = '@' . $_SESSION['nickname'] . ' deleted a fee from @';
$message .= $user->nickname . ' on #' . $fee->worklist_id;
// Journal notification
sendJournalNotification($message);
//sending email to the bidder
$options = array();
$options['emails'] = array($user->username);
$options['workitem'] = new WorkItem();
$options['workitem']->loadById($fee->worklist_id);
$options['type'] = "fee_deleted";
Notification::workitemNotify($options);
$data = array(
'nick' => $_SESSION['nickname'],
'fee_nick' => $user->nickname
);
Notification::workitemNotifyHipchat($options, $data);
}
}
}
function getUserById($id) {
$res = mysql_query('SELECT * FROM `' . USERS . '` WHERE `id` = ' . $id . ' AND `is_active` = 1');
if ($res && (mysql_num_rows($res) == 1)) {
return mysql_fetch_object($res);
}
return false;
}
function getUserByNickname($nickname) {
$res = mysql_query('SELECT * FROM `' . USERS . '` WHERE `nickname` = "' . $nickname . '" AND `is_active` = 1;');
if ($res && (mysql_num_rows($res) == 1)) {
return mysql_fetch_object($res);
}
return false;
}
function getWorklistById($id) {
$query = "select * from ".WORKLIST." where id='$id'";
$rt = mysql_query($query);
if ($rt && (mysql_num_rows($rt) == 1)) {
return mysql_fetch_assoc($rt);
}
return false;
}
/**
Validate an email address.
Provide email address (raw input)
Returns true if the email address has the email
address format and the domain exists.
*/
function validEmail($email) {
$isValid = true;
$atIndex = strrpos($email, "@");
if (is_bool($atIndex) && !$atIndex) {
$isValid = false;
} else {
$domain = substr($email, $atIndex+1);
$local = substr($email, 0, $atIndex);
$localLen = strlen($local);
$domainLen = strlen($domain);
if ($localLen < 1 || $localLen > 64) {
// local part length exceeded
$isValid = false;
} else if ($domainLen < 1 || $domainLen > 255) {
// domain part length exceeded
$isValid = false;
} else if ($local[0] == '.' || $local[$localLen-1] == '.') {
// local part starts or ends with '.'
$isValid = false;
} else if (preg_match('/\\.\\./', $local)) {
// local part has two consecutive dots
$isValid = false;
} else if (!preg_match('/^[A-Za-z0-9\\-\\.]+$/', $domain)) {
// character not valid in domain part
$isValid = false;
} else if (preg_match('/\\.\\./', $domain)) {
// domain part has two consecutive dots
$isValid = false;
} else if (!preg_match('/^(\\\\.|[A-Za-z0-9!#%&`_=\\/$\'*+?^{}|~.-])+$/', str_replace("\\\\","",$local))) {
// character not valid in local part unless
// local part is quoted
if (!preg_match('/^"(\\\\"|[^"])+"$/', str_replace("\\\\","",$local))) {
$isValid = false;
}
}
if ($isValid && !(checkdnsrr($domain,"MX") || checkdnsrr($domain,"A"))) {
// domain not found in DNS
$isValid = false;
}
}
return $isValid;
}
function GetTimeStamp($MySqlDate, $i='')
{
if (empty($MySqlDate)) $MySqlDate = date('Y/m/d');
$date_array = explode("/",$MySqlDate); // split the array
$var_year = $date_array[0];
$var_month = $date_array[1];
$var_day = $date_array[2];
$var_timestamp=$date_array[2]."-".$date_array[0]."-".$date_array[1];
//$var_timestamp=$var_month ."/".$var_day ."-".$var_year;
return($var_timestamp); // return it to the user
}
// is user posting data without being logged in
function handleUnloggedPost() {
// get the IP address
$request_ip = $_SERVER['REMOTE_ADDR'];
$request_uri = $_SERVER['REQUEST_URI'];
error_log('Possible hack attempt from ' . $request_ip . ' on: ' . $request_uri);
error_log(json_encode($_REQUEST));
die('You are not authorized to post to this URL. Click ' .
'<a href="' . SERVER_URL . '">here</a> to go to the main page. ' . "\n");
}
function checkLogin() {
if (! getSessionUserId()) {
$_SESSION = array();
session_destroy();
if (!empty($_POST)) {
handleUnloggedPost();
}
Utils::redirect('./github/login?expired=1&redir=' . urlencode($_SERVER['REQUEST_URI']));
exit;
}
}
function validateAPIKey() {
if(! isset($_REQUEST["api_key"])) {
error_log("No api key defined.");
header('HTTP/1.1 401 Unauthorized', true, 401);
die("No api key defined.");
} else if(strcmp($_REQUEST["api_key"],API_KEY) != 0 ) {
error_log("Wrong api key provided.");
header('HTTP/1.1 401 Unauthorized', true, 401);
die("Wrong api key provided.");
} else {
return true;
}
}
/* linkify function
*
* this takes some input and makes links where it thinks they should go
*
*/
function linkify($url, $author = null, $bot = false, $process = true)
{
$original = $url;
if(!$process) {
if (mb_detect_encoding($url, 'UTF-8', true) === FALSE) {
$url = utf8_encode($url);
}
return '<a href="http://' . htmlentities($url, ENT_QUOTES, "UTF-8") . '">' . htmlspecialchars($url) . '</a>';
}
$class = '';
if(strpos($url, "helper/get_attachment.php") > 0)
{
$bot = true;
$class=' class="attachment noicon"';
} else {
$class='';
}
$url = html_entity_decode($url, ENT_QUOTES);
if (preg_match("/\<a href=\"([^\"]*)\"/i", $url) == 0) {
// modified this so that it will exclude certain characters from the end of the url
// add to this as you see fit as I assume the list is not exhaustive
$regexp="/((?:(?:ht|f)tps?\:\/\/|www\.)\S+[^\s\.\)\"\'])/i";
$url= preg_replace($regexp, DELIMITER . '<a href="$0"' . $class . '>$0</a>' . DELIMITER, $url);
$regexp="/href=\"(www\.\S+?)\"/i";
$url = preg_replace($regexp,'href="http://$1"', $url);
}
$regexp="/(href=)(.)?((www\.)\S+(\.)\S+)/i";
$url = preg_replace($regexp,'href="http://$3"', $url);
// Replace '#<number>' with a link to the worklist item with the same number
$regexp = "/\#([1-9][0-9]{4})(\s|[^0-9a-z]|$)/i";
if (!function_exists('workitemLinkPregReplaceCallback')) {
/**
* Checks whether a #<number> string should be taken as a workitem link or not.
* This function is used as a callback with preg_replace_callback (see below lines)
*/
function workitemLinkPregReplaceCallback($matches) {
$job_id = (int) $matches[1];
if ($job_id < 99999 && WorkItem::idExists($job_id)) {
return
DELIMITER .
'<a href="' . WORKLIST_URL . $job_id . '"' .
' class="worklist-item" id="worklist-' . $job_id . '" >#' . $job_id . '</a>' .
DELIMITER . $matches[2];
} else {
return $matches[0];
}
}
}
$url = preg_replace_callback($regexp, 'workitemLinkPregReplaceCallback', $url);
// Replace '##<projectName>##' with a link to the worklist project with the same name
// This is used in situations where the project name has a space or spaces or no space
$regexp = "/\#\#([A-Za-z0-9_ ]+)\#\#/";
$link = DELIMITER . '<a href="' . WORKLIST_URL . '$1">$1</a>' . DELIMITER;
$url = preg_replace($regexp, $link, $url);
// Replace '##<projectName>' with a link to the worklist project with the same name
// This is used in situations where the first space encountered is assumed to
// be the end of the project name. Left mainly for backward compatibility.
$regexp = "/\#\#([A-Za-z0-9_]+)/";
$link = DELIMITER . '<a href="' . WORKLIST_URL . '$1">$1</a>' . DELIMITER;
$url = preg_replace($regexp, $link, $url);
// Replace '#<nick>/<url>' with a link to the author sandbox
$regexp="/\#([A-Za-z]+)\/(\S*)/i";
$url = preg_replace(
$regexp, DELIMITER .
'<a href="https://' . SANDBOX_SERVER . '/~$1/$2" class="sandbox-item" id="sandbox-$1">$1 : $2</a>' . DELIMITER,
$url
);