Completed
Push — master ( 26776f...d9604e )
by Michael
11:31
created

functions.php (1 issue)

Upgrade to new PHP Analysis Engine

These results are based on our legacy PHP analysis, consider migrating to our new PHP analysis engine instead. Learn more

Code
1
<?php
0 ignored issues
show
Coding Style Compatibility introduced by
For compatibility and reusability of your code, PSR1 recommends that a file should introduce either new symbols (like classes, functions, etc.) or have side-effects (like outputting something, or including other files), but not both at the same time. The first symbol is defined on line 17 and the first side effect is on line 6.

The PSR-1: Basic Coding Standard recommends that a file should either introduce new symbols, that is classes, functions, constants or similar, or have side effects. Side effects are anything that executes logic, like for example printing output, changing ini settings or writing to a file.

The idea behind this recommendation is that merely auto-loading a class should not change the state of an application. It also promotes a cleaner style of programming and makes your code less prone to errors, because the logic is not spread out all over the place.

To learn more about the PSR-1, please see the PHP-FIG site on the PSR-1.

Loading history...
2
//$Id: functions.php,v 1.97 2006/01/31 16:34:31 eric_juden Exp $
3
4
//Sanity Check: Ensure that /include/constants.php is included
5
if (!defined('XHELP_CONSTANTS_INCLUDED')) {
6
    exit();
7
}
8
9
/**
10
 * Format a time as 'x' years, 'x' weeks, 'x' days, 'x' hours, 'x' minutes, 'x' seconds
11
 *
12
 * @param int $time UNIX timestamp
13
 * @return string formatted time
14
 *
15
 * @access public
16
 */
17
function xhelpFormatTime($time)
18
{
19
    $values = xhelpGetElapsedTime($time);
20
21
    foreach($values as $key=>$value) {
22
        $$key = $value;
23
    }
24
25
    $ret = array();
26
    if ($years) {
27
        $ret[] = $years . ' ' . ($years == 1 ? _XHELP_TIME_YEAR : _XHELP_TIME_YEARS);
28
    }
29
30
    if ($weeks) {
31
        $ret[] = $weeks . ' ' . ($weeks == 1 ? _XHELP_TIME_WEEK : _XHELP_TIME_WEEKS);
32
    }
33
34
    if ($days) {
35
        $ret[] = $days . ' ' . ($days == 1 ? _XHELP_TIME_DAY : _XHELP_TIME_DAYS);
36
    }
37
38
    if ($hours) {
39
        $ret[] = $hours . ' ' . ($hours == 1 ? _XHELP_TIME_HOUR : _XHELP_TIME_HOURS);
40
    }
41
42
    if ($minutes) {
43
        $ret[] = $minutes . ' ' . ($minutes == 1 ? _XHELP_TIME_MIN : _XHELP_TIME_MINS);
44
    }
45
46
    $ret[] = $seconds . ' ' . ($seconds == 1 ? _XHELP_TIME_SEC : _XHELP_TIME_SECS);
47
48
    return implode(', ', $ret);
49
}
50
51
/**
52
 * Changes UNIX timestamp into array of time units of measure
53
 *
54
 * @param int $time UNIX timestamp
55
 * @return array $elapsed_time
56
 *
57
 * @access public
58
 */
59
function xhelpGetElapsedTime($time)
60
{
61
    //Define the units of measure
62
    $units = array('years' => (365*60*60*24) /*Value of Unit expressed in seconds*/,
63
        'weeks' => (7*60*60*24),
64
        'days' => (60*60*24),
65
        'hours' => (60*60),
66
        'minutes' => 60,
67
        'seconds' => 1);
68
69
    $local_time   = $time;
70
    $elapsed_time = array();
71
72
    //Calculate the total for each unit measure
73
    foreach($units as $key=>$single_unit) {
74
        $elapsed_time[$key] = floor($local_time / $single_unit);
75
        $local_time -= ($elapsed_time[$key] * $single_unit);
76
    }
77
78
    return $elapsed_time;
79
}
80
81
/**
82
 * Generate xhelp URL
83
 *
84
 * @param string $page
85
 * @param array $vars
86
 * @return
87
 *
88
 * @access public
89
 */
90
function xhelpMakeURI($page, $vars = array(), $encodeAmp = true)
91
{
92
    $joinStr = '';
93
94
    $amp = ($encodeAmp ? '&amp;': '&');
95
96
    if (! count($vars)) {
97
        return $page;
98
    }
99
    $qs = '';
100
    foreach($vars as $key=>$value) {
101
        $qs .= $joinStr . $key . '=' . $value;
102
        $joinStr = $amp;
103
    }
104
105
    return $page . '?'. $qs;
106
}
107
108
/**
109
 * Changes a ticket priority (int) into its string equivalent
110
 *
111
 * @param int $priority
112
 * @return string $priority
113
 *
114
 * @access public
115
 */
116
function xhelpGetPriority($priority)
117
{
118
    $priorities = array(
119
    1 => _XHELP_TEXT_PRIORITY1,
120
    2 => _XHELP_TEXT_PRIORITY2,
121
    3 => _XHELP_TEXT_PRIORITY3,
122
    4 => _XHELP_TEXT_PRIORITY4,
123
    5 => _XHELP_TEXT_PRIORITY5);
124
125
    $priority = intval($priority);
126
127
    return (isset($priorities[$priority]) ? $priorities[$priority] : $priority);
128
129
}
130
131
/**
132
 * Gets a tickets state (unresolved/resolved)
133
 *
134
 * @param int $state
135
 * @return string $state
136
 *
137
 * @access public
138
 */
139
function xhelpGetState($state)
140
{
141
    $state = intval($state);
142
    $stateValues = array(
143
    1 => _XHELP_STATE1,
144
    2 => _XHELP_STATE2);
145
146
    return (isset($stateValues[$state]) ? $stateValues[$state] : $state);
147
}
148
149
/**
150
 * Changes a ticket status (int) into its string equivalent
151
 * Do not use this function in loops
152
 *
153
 * @param int $status
154
 * @return string Status Description
155
 *
156
 * @access public
157
 */
158
function xhelpGetStatus($status)
159
{
160
    static $statuses;
161
162
    $status = intval($status);
163
    $hStatus =& xhelpGetHandler('status');
164
165
    //Get Statuses from database if first request
166
    if (!$statuses) {
167
        $statuses = $hStatus->getObjects(null, true);
168
    }
169
170
    return (isset($statuses[$status]) ? $statuses[$status]->getVar('description') : $status);
171
}
172
173
/**
174
 * Changes a response rating (int) into its string equivalent
175
 *
176
 * @param int $rating
177
 * @return string $rating
178
 *
179
 * @access public
180
 */
181
function xhelpGetRating($rating)
182
{
183
    $ratings = array(
184
    0 => _XHELP_RATING0,
185
    1 => _XHELP_RATING1,
186
    2 => _XHELP_RATING2,
187
    3 => _XHELP_RATING3,
188
    4 => _XHELP_RATING4,
189
    5 => _XHELP_RATING5);
190
    $rating = intval($rating);
191
192
    return (isset($ratings[$rating]) ? $ratings[$rating] : $rating);
193
}
194
195
function xhelpGetEventClass($class)
196
{
197
    $classes = array(
198
    0 => _XHELP_MAIL_CLASS0,
199
    1 => _XHELP_MAIL_CLASS1,
200
    2 => _XHELP_MAIL_CLASS2,
201
    3 => _XHELP_MAIL_CLASS3);
202
    $class = intval($class);
203
204
    return (isset($classes[$class]) ? $classes[$class] : $class);
205
}
206
207
/**
208
 * Move specified tickets into department
209
 *
210
 * @param array $tickets  array of ticket ids (int)
211
 * @param int $dept  department ID
212
 * @return bool True on success, False on error
213
 *
214
 * @access public
215
 */
216 View Code Duplication
function xhelpSetDept($tickets, $dept)
217
{
218
    $hTicket =& xhelpGetHandler('ticket');
219
    $crit    = new Criteria('id', "(". implode($tickets, ',') .")", "IN");
220
221
    return $hTicket->updateAll('department', intval($dept), $crit);
222
}
223
224
/**
225
 * Set specified tickets to a priority
226
 *
227
 * @param array $tickets  array of ticket ids (int)
228
 * @param int $priority  priority value
229
 * @return bool True on success, False on error
230
 *
231
 * @access public
232
 */
233 View Code Duplication
function xhelpSetPriority($tickets, $priority)
234
{
235
    $hTicket =& xhelpGetHandler('ticket');
236
    $crit    = new Criteria('id', "(". implode($tickets, ',') .")", 'IN');
237
238
    return $hTicket->updateAll('priority', intval($priority), $crit);
239
}
240
241
/**
242
 * Set specified tickets to a status
243
 *
244
 * @param array $tickets  array of ticket ids (int)
245
 * @param int $status  status value
246
 * @return bool True on success, False on error
247
 *
248
 * @access public
249
 */
250 View Code Duplication
function xhelpSetStatus($tickets, $status)
251
{
252
    $hTicket =& xhelpGetHandler('ticket');
253
    $crit    = new Criteria('id', "(". implode($tickets, ',') .")", 'IN');
254
255
    return $hTicket->updateAll('status', intval($status), $crit);
256
}
257
258
/**
259
 * Assign specified tickets to a staff member
260
 *
261
 * Assumes that owner is a member of all departments in specified tickets
262
 *
263
 * @param array $tickets  array of ticket ids (int)
264
 * @param int $owner  uid of new owner
265
 * @return bool True on success, False on error
266
 *
267
 * @access public
268
 */
269 View Code Duplication
function xhelpSetOwner($tickets, $owner)
270
{
271
    $hTicket =& xhelpGetHandler('ticket');
272
    $crit    = new Criteria('id', "(". implode($tickets, ',') .")", 'IN');
273
274
    return $hTicket->updateAll('ownership', intval($owner), $crit);
275
}
276
277
/**
278
 * Add the response to each ticket
279
 *
280
 *
281
 * @param array $tickets array of ticket ids (int)
282
 * @param string $response response text to add
283
 * @param int $timespent Number of minutes spent on ticket
284
 * @param bool $private Should this be a private message?
285
 * @return xhelpResponses Response information
286
 *
287
 * @access public
288
 */
289
function &xhelpAddResponse($tickets, $sresponse, $timespent = 0, $private = false)
290
{
291
    global $xoopsUser;
292
    $hResponse  =& xhelpGetHandler('responses');
293
    $hTicket    =& xhelpGetHandler('ticket');
294
    $updateTime = time();
295
    $uid        = $xoopsUser->getVar('uid');
296
    $ret        = true;
297
    $userIP     = getenv("REMOTE_ADDR");
298
    $ticket_count = count($tickets);
299
    $i = 1;
300
    foreach ($tickets as $ticketid) {
301
        $response =& $hResponse->create();
302
        $response->setVar('uid', $uid);
303
        $response->setVar('ticketid', $ticketid);
304
        $response->setVar('message', $sresponse);
305
        $response->setVar('timeSpent', $timespent);
306
        $response->setVar('updateTime', $updateTime);
307
        $response->setVar('userIP', $userIP);
308
        $response->setVar('private', $private);
309
        $ret = $ret && $hResponse->insert($response);
310
        if($ticket_count != $i){
311
            unset($response);
312
        }
313
        $i++;
314
    }
315
    if ($ret) {
316
        $crit = new Criteria('id', "(". implode($tickets, ',') .")", 'IN');
317
        $ret  = $hTicket->incrementAll('totalTimeSpent', $timespent, $crit);
318
        $ret  = $hTicket->updateAll('lastUpdated', $updateTime, $crit);
319
        $response->setVar('ticketid', 0);
320
        $response->setVar('id', 0);
321
322
        return $response;
323
    }
324
325
    return false;
326
}
327
328
/**
329
 * Remove the specified tickets
330
 *
331
 * @param array $tickets array of ticket ids (int)
332
 * @return bool True on success, False on error
333
 *
334
 * @access public
335
 */
336 View Code Duplication
function xhelpDeleteTickets($tickets)
337
{
338
    $hTicket =& xhelpGetHandler('ticket');
339
    $crit    = new Criteria('id', "(". implode($tickets, ',') .")", 'IN');
340
341
    return $hTicket->deleteAll($crit);
342
}
343
344
/**
345
 * Retrieves an array of tickets in one query
346
 *
347
 * @param array $tickets array of ticket ids (int)
348
 * @return array Array of ticket objects
349
 *
350
 * @access public
351
 */
352 View Code Duplication
function &xhelpGetTickets(&$tickets)
353
{
354
    $hTicket =& xhelpGetHandler('ticket');
355
    $crit    = new Criteria('t.id', "(". implode($tickets, ',') .")", 'IN');
356
357
    return $hTicket->getObjects($crit);
358
}
359
360
/**
361
 * Check if all supplied rules pass, and return any errors
362
 *
363
 * @param array $rules array of {@link Validator} classes
364
 * @param array $errors array of errors found (if any)
365
 * @return bool True if all rules pass, false if any fail
366
 *
367
 * @access public
368
 */
369
function xhelpCheckRules(&$rules, &$errors)
370
{
371
    $ret = true;
372
    if (is_array($rules)) {
373
        foreach($rules as $rule) {
374
            $ret = $ret && xhelpCheckRules($rule, $error);
375
            $errors = array_merge($errors, $error);
376
        }
377
    } else {
378
        if (!$rules->isValid()) {
379
            $ret = false;
380
            $errors = $rules->getErrors();
381
        } else {
382
            $ret = true;
383
            $errors = array();
384
        }
385
    }
386
387
    return $ret;
388
389
}
390
391
/**
392
 * Output the specified variable (for debugging)
393
 *
394
 * @param mixed $var Variable to output
395
 * @return void
396
 *
397
 * @access public
398
 */
399
function xhelpDebug(&$var)
400
{
401
    echo "<pre>";
402
    print_r($var);
403
    echo "</pre>";
404
}
405
406
/**
407
 * Detemines if a table exists in the current db
408
 *
409
 * @param string $table the table name (without XOOPS prefix)
410
 * @return bool True if table exists, false if not
411
 *
412
 * @access public
413
 */
414
function xhelpTableExists($table)
415
{
416
417
    $bRetVal = false;
418
    //Verifies that a MySQL table exists
419
    $xoopsDB =& XoopsDatabaseFactory::getDatabaseConnection();
420
    $realname = $xoopsDB->prefix($table);
421
    $dbname = XOOPS_DB_NAME;
422
    $sql = "SHOW TABLES FROM $dbname";
423
    $ret = $xoopsDB->queryF($sql);
424
    while (list($m_table)=$xoopsDB->fetchRow($ret)) {
425
        if ($m_table ==  $realname) {
426
            $bRetVal = true;
427
            break;
428
        }
429
    }
430
    $xoopsDB->freeRecordSet($ret);
431
432
    return ($bRetVal);
433
}
434
435
/**
436
 * Gets a value from a key in the xhelp_meta table
437
 *
438
 * @param string $key
439
 * @return string $value
440
 *
441
 * @access public
442
 */
443
function xhelpGetMeta($key)
444
{
445
    $xoopsDB =& XoopsDatabaseFactory::getDatabaseConnection();
446
    $sql = sprintf("SELECT metavalue FROM %s WHERE metakey=%s", $xoopsDB->prefix('xhelp_meta'), $xoopsDB->quoteString($key));
447
    $ret = $xoopsDB->query($sql);
448
    if (!$ret) {
449
        $value = false;
450
    } else {
451
        list($value) = $xoopsDB->fetchRow($ret);
452
453
    }
454
455
    return $value;
456
}
457
458
/**
459
 * Sets a value for a key in the xhelp_meta table
460
 *
461
 * @param string $key
462
 * @param string $value
463
 * @return bool TRUE if success, FALSE if failure
464
 *
465
 * @access public
466
 */
467
function xhelpSetMeta($key, $value)
468
{
469
    $xoopsDB =& XoopsDatabaseFactory::getDatabaseConnection();
470
    $ret = xhelpGetMeta($key);
471
    if($ret != false){
472
        $sql = sprintf("UPDATE %s SET metavalue = %s WHERE metakey = %s", $xoopsDB->prefix('xhelp_meta'), $xoopsDB->quoteString($value), $xoopsDB->quoteString($key));
473
    } else {
474
        $sql = sprintf("INSERT INTO %s (metakey, metavalue) VALUES (%s, %s)", $xoopsDB->prefix('xhelp_meta'), $xoopsDB->quoteString($key), $xoopsDB->quoteString($value));
475
    }
476
    $ret = $xoopsDB->queryF($sql);
477
    if (!$ret) {
478
        return false;
479
    }
480
481
    return true;
482
}
483
484
/**
485
 * Deletes a record from the xhelp_meta table
486
 *
487
 * @param string $key
488
 * @return bool TRUE if success, FALSE if failure
489
 *
490
 * @access public
491
 */
492 View Code Duplication
function xhelpDeleteMeta($key)
493
{
494
    $xoopsDB =& XoopsDatabaseFactory::getDatabaseConnection();
495
    $sql = sprintf("DELETE FROM %s WHERE metakey=%s", $xoopsDB->prefix('xhelp_meta'), $xoopsDB->quoteString($key));
496
    $ret = $xoopsDB->query($sql);
497
    if(!$ret) {
498
        return false;
499
    } else {
500
        return $ret;
501
    }
502
}
503
504
/**
505
 * Does the supplied email belong to an existing xoops user
506
 *
507
 * @param string $email
508
 * @return {@link xoopsUser} object if success, FALSE if failure
509
 *
510
 * @access public
511
 */
512
function &xhelpEmailIsXoopsUser($email)
513
{
514
    $hXoopsMember =& xoops_gethandler('member');
515
    $crit = new Criteria('email', $email);
516
    $crit->setLimit(1);
517
518
    $users =& $hXoopsMember->getUsers($crit);
519
    if (count($users) > 0) {
520
        return $users[0];
521
    } else {
522
        return false;
523
    }
524
}
525
526
/**
527
 * Detemines if a field exists in the current db
528
 *
529
 * @param string $table the table name (without XOOPS prefix)
530
 * @param string $field the field name
531
 * @return mixed false if field does not exist, array containing field info if does
532
 *
533
 * @access public
534
 */
535
function xhelpFieldExists($table, $field)
536
{
537
    $xoopsDB =& XoopsDatabaseFactory::getDatabaseConnection();
538
    $tblname = $xoopsDB->prefix($table);
539
    $ret     = $xoopsDB->query("DESCRIBE $tblname");
540
541
    if (!$ret) {
542
        return false;
543
    }
544
545
    while ($row = $xoopsDB->fetchRow($ret)) {
546
        if(strcasecmp($row['Field'], $field) == 0) {
547
            return $row;
548
        }
549
    }
550
551
    return false;
552
}
553
554
/**
555
 * Creates a xoops account from an email address and password
556
 *
557
 * @param string $email
558
 * @param string $password
559
 * @return {@link xoopsUser} object if success, FALSE if failure
560
 *
561
 * @access public
562
 */
563
function &xhelpXoopsAccountFromEmail($email, $name, &$password, $level)
564
{
565
    $member_handler =& xoops_gethandler('member');
566
567
    $unamecount = 10;
568
    if (strlen($password) == 0) {
569
        $password = substr(md5(uniqid(mt_rand(), 1)), 0, 6);
570
    }
571
572
    $usernames = xhelpGenUserNames($email, $name, $unamecount);
573
    $newuser = false;
574
    $i = 0;
575
    while ($newuser == false) {
576
        $crit = new Criteria('uname', $usernames[$i]);
577
        $count = $member_handler->getUserCount($crit);
578
        if ($count == 0) {
579
            $newuser = true;
580
        } else {
581
            //Move to next username
582
            $i++;
583
            if ($i == $unamecount) {
584
                //Get next batch of usernames to try, reset counter
585
                $usernames = xhelpGenUserNames($email->getEmail(), $email->getName(), $unamecount);
586
                $i = 0;
587
            }
588
        }
589
590
    }
591
592
    $xuser =& $member_handler->createUser();
593
    $xuser->setVar("uname",$usernames[$i]);
594
    $xuser->setVar("loginname", $usernames[$i]);
595
    $xuser->setVar("user_avatar","blank.gif");
596
    $xuser->setVar('user_regdate', time());
597
    $xuser->setVar('timezone_offset', 0);
598
    $xuser->setVar('actkey',substr(md5(uniqid(mt_rand(), 1)), 0, 8));
599
    $xuser->setVar("email",$email);
600
    $xuser->setVar("name", $name);
601
    $xuser->setVar("pass", md5($password));
602
    $xuser->setVar('notify_method', 2);
603
    $xuser->setVar("level",$level);
604
605
    if ($member_handler->insertUser($xuser)){
606
        //Add the user to Registered Users group
607
        $member_handler->addUserToGroup(XOOPS_GROUP_USERS, $xuser->getVar('uid'));
608
    } else {
609
        return false;
610
    }
611
612
    return $xuser;
613
}
614
615
/**
616
 * Generates an array of usernames
617
 *
618
 * @param string $email email of user
619
 * @param string $name name of user
620
 * @param int $count number of names to generate
621
 * @return array $names
622
 *
623
 * @access public
624
 */
625
function xhelpGenUserNames($email, $name, $count=20)
626
{
627
    $names = array();
628
    $userid   = explode('@',$email);
629
630
    $basename = '';
631
    $hasbasename = false;
632
    $emailname = $userid[0];
633
634
    $names[] = $emailname;
635
636
    if (strlen($name) > 0) {
637
        $name = explode(' ', trim($name));
638
        if (count($name) > 1) {
639
            $basename = strtolower(substr($name[0], 0, 1) . $name[count($name) - 1]);
640
        } else {
641
            $basename = strtolower($name[0]);
642
        }
643
        $basename = xoops_substr($basename, 0, 60, '');
644
        //Prevent Duplication of Email Username and Name
645
        if (!in_array($basename, $names)) {
646
            $names[] = $basename;
647
            $hasbasename = true;
648
        }
649
    }
650
651
    $i = count($names);
652
    $onbasename = 1;
653
    while ($i < $count) {
654
        $num = xhelpGenRandNumber();
655
        if ($onbasename < 0 && $hasbasename) {
656
            $names[] = xoops_substr($basename, 0, 58, '').$num;
657
658
        } else {
659
            $names[] = xoops_substr($emailname, 0, 58, ''). $num;
660
        }
661
        $i = count($names);
662
        $onbasename = ~ $onbasename;
663
        $num = '';
664
    }
665
666
    return $names;
667
668
}
669
670
/**
671
 * Gives the random number generator a seed to start from
672
 *
673
 * @return void
674
 *
675
 * @access public
676
 */
677
function xhelpInitRand()
678
{
679
    static $randCalled = FALSE;
680
    if (!$randCalled)
681
    {
682
        srand((double) microtime() * 1000000);
683
        $randCalled = TRUE;
684
    }
685
}
686
687
/**
688
 * Creates a random number with a specified number of $digits
689
 *
690
 * @param int $digits number of digits
691
 * @return return int random number
692
 *
693
 * @access public
694
 */
695
function xhelpGenRandNumber($digits = 2)
696
{
697
    xhelpInitRand();
698
    $tmp = array();
699
700
    for ($i = 0; $i < $digits; $i++) {
701
        $tmp[$i] = (rand()%9);
702
    }
703
704
    return implode('', $tmp);
705
}
706
707
/**
708
 * Converts int $type into its string equivalent
709
 *
710
 * @param int $type
711
 * @return string $type
712
 *
713
 * @access public
714
 */
715
function xhelpGetMBoxType($type)
716
{
717
    $mboxTypes = array(
718
    _XHELP_MAILBOXTYPE_POP3 => 'POP3',
719
    _XHELP_MAILBOXTYPE_IMAP => 'IMAP');
720
721
    return (isset($mboxTypes[$type]) ? $mboxTypes[$type] : 'NA');
722
}
723
724
/**
725
 * Retrieve list of all staff members
726
 *
727
 * @return array {@link xhelpStaff} objects
728
 *
729
 * @access public
730
 */
731
function &xhelpGetStaff($displayName)
732
{
733
    $xoopsDB =& XoopsDatabaseFactory::getDatabaseConnection();
734
735
    $sql = sprintf("SELECT u.uid, u.uname, u.name FROM %s u INNER JOIN %s s ON u.uid = s.uid ORDER BY u.uname",
736
    $xoopsDB->prefix('users'), $xoopsDB->prefix('xhelp_staff'));
737
    $ret = $xoopsDB->query($sql);
738
739
    $staff[-1] = _XHELP_TEXT_SELECT_ALL;
740
    $staff[0]  = _XHELP_NO_OWNER;
741
    while($member = $xoopsDB->fetchArray($ret)){
742
        $staff[$member['uid']] = xhelpGetDisplayName($displayName, $member['name'],$member['uname']);
743
    }
744
745
    return $staff;
746
}
747
748
/**
749
 * Create default staff roles for a new installation
750
 *
751
 * @return TRUE if success, FALSE if failure
752
 *
753
 * @access public
754
 */
755
function xhelpCreateRoles()
756
{
757
    if(!defined('_XHELP_ROLE_NAME1')){
758
        xhelpIncludeLang('main', 'english');
759
    }
760
761
    $defaultRolePermissions = array(
762
    1 => array('name' => _XHELP_ROLE_NAME1, 'desc' => _XHELP_ROLE_DSC1, 'value' => XHELP_ROLE_PERM_1),
763
    2 => array('name' => _XHELP_ROLE_NAME2, 'desc' => _XHELP_ROLE_DSC2, 'value' => XHELP_ROLE_PERM_2),
764
    3 => array('name' => _XHELP_ROLE_NAME3, 'desc' => _XHELP_ROLE_DSC3, 'value' => XHELP_ROLE_PERM_3));
765
766
    $hRole =& xhelpGetHandler('role');
767
768
    foreach ($defaultRolePermissions as $key => $aRole)
769
    {
770
        $role =& $hRole->create();
771
        $role->setVar('id', $key);
772
        $role->setVar('name', $aRole['name']);
773
        $role->setVar('description', $aRole['desc']);
774
        $role->setVar('tasks', $aRole['value']);
775
        if (!$hRole->insert($role)) {
776
            return false;
777
        }
778
    }
779
780
    return true;
781
}
782
783
/**
784
 * Create ticket statuses for a new installation
785
 *
786
 * @return TRUE if success, FALSE if failure
787
 * @access public
788
 */
789
function xhelpCreateStatuses()
790
{
791
    if(!defined('_XHELP_STATUS0')){
792
        xhelpIncludeLang('main', 'english');
793
    }
794
795
    $statuses = array(
796
    1 => array('description' => _XHELP_STATUS0, 'state' => XHELP_STATE_UNRESOLVED),
797
    2 => array('description' => _XHELP_STATUS1, 'state' => XHELP_STATE_UNRESOLVED),
798
    3 => array('description' => _XHELP_STATUS2, 'state' => XHELP_STATE_RESOLVED));
799
800
    $hStatus =& xhelpGetHandler('status');
801
    foreach($statuses as $id => $status){
802
        $newStatus =& $hStatus->create();
803
        $newStatus->setVar('id', $id);
804
        $newStatus->setVar('description', $status['description']);
805
        $newStatus->setVar('state', $status['state']);
806
807
        if(!$hStatus->insert($newStatus)){
808
            return false;
809
        }
810
    }
811
812
    return true;
813
}
814
815
/**
816
 * Convert Bytes to a human readable size (GB, MB, KB, etc)
817
 *
818
 * @return string Human readable size
819
 * @access public
820
 */
821
function xhelpPrettyBytes($bytes)
822
{
823
    $bytes = intval($bytes);
824
825
    if ($bytes >= 1099511627776) {
826
        $return = number_format($bytes / 1024 / 1024 / 1024 / 1024, 2);
827
        $suffix = _XHELP_SIZE_TB;
828 View Code Duplication
    } elseif ($bytes >= 1073741824) {
829
        $return = number_format($bytes / 1024 / 1024 / 1024, 2);
830
        $suffix = _XHELP_SIZE_GB;
831
    } elseif ($bytes >= 1048576) {
832
        $return = number_format($bytes / 1024 / 1024, 2);
833
        $suffix = _XHELP_SIZE_MB;
834 View Code Duplication
    } elseif ($bytes >= 1024) {
835
        $return = number_format($bytes / 1024, 2);
836
        $suffix = _XHELP_SIZE_KB;
837
    } else {
838
        $return = $bytes;
839
        $suffix = _XHELP_SIZE_BYTES;
840
    }
841
842
    return $return . " " . $suffix;
843
}
844
845
/**
846
 * Add a new database field to an existing table
847
 * MySQL Only!
848
 *
849
 * @return RESOURCE SQL query resource
850
 * @access public
851
 */
852
function xhelpAddDBField($table, $fieldname, $fieldtype='VARCHAR', $size=0, $attr=null)
853
{
854
    $xoopsDB =& XoopsDatabaseFactory::getDatabaseConnection();
855
856
    $column_def = $fieldname;
857
    if ($size) {
858
        $column_def .= sprintf(' %s(%s)', $fieldtype, $size);
859
    } else {
860
        $column_def .= " $fieldtype";
861
    }
862
    if (is_array($attr)) {
863
        if (isset($attr['nullable']) && $attr['nullable'] == true) {
864
            $column_def .= ' NULL';
865
        } else {
866
            $column_def .= ' NOT NULL';
867
        }
868
869
        if (isset($attr['default'])) {
870
            $column_def .= ' DEFAULT '. $xoopsDB->quoteString($attr['default']);
871
        }
872
873
        if (isset($attr['increment'])) {
874
            $column_def .= ' AUTO_INCREMENT';
875
        }
876
877
        if (isset($attr['key'])) {
878
            $column_def .= ' KEY';
879
        }
880
881
        if (isset($attr['comment'])) {
882
            $column_def .= 'COMMENT '. $xoopsDB->quoteString($attr['comment']);
883
        }
884
    }
885
886
    $sql = sprintf('ALTER TABLE %s ADD COLUMN %s', $xoopsDB->prefix($table), $column_def);
887
    $ret = $xoopsDB->query($sql);
888
889
    return $ret;
890
}
891
892
/**
893
 * Rename an existing database field
894
 * MySQL Only!
895
 *
896
 * @return RESOURCE SQL query resource
897
 * @access public
898
 */
899
function xhelpRenameDBField($table, $oldcol, $newcol, $fieldtype='VARCHAR', $size=0)
900
{
901
    $xoopsDB =& XoopsDatabaseFactory::getDatabaseConnection();
902
    $column_def = $newcol;
903
    $column_def .= ($size ? sprintf(' %s(%s)', $fieldtype, $size) : " $fieldtype");
904
    $sql = sprintf('ALTER TABLE %s CHANGE %s %s', $xoopsDB->prefix($table), $oldcol, $column_def);
905
    $ret = $xoopsDB->query($sql);
906
907
    return $ret;
908
}
909
910
/**
911
 * Remove an existing database field
912
 * MySQL Only!
913
 *
914
 * @return RESOURCE SQL query resource
915
 * @access public
916
 */
917 View Code Duplication
function xhelpRemoveDBField($table, $column)
918
{
919
    $xoopsDB =& XoopsDatabaseFactory::getDatabaseConnection();
920
    $sql = sprintf('ALTER TABLE %s DROP COLUMN `%s`', $xoopsDB->prefix($table), $column);
921
    $ret = $xoopsDB->query($sql);
922
923
    return $ret;
924
}
925
926
/**
927
 * Mark all staff accounts as being updated
928
 *
929
 * @return BOOL True on success, False on Error
930
 * @access public
931
 */
932
function xhelpResetStaffUpdatedTime()
933
{
934
    $hStaff =& xhelpGetHandler('staff');
935
936
    return $hStaff->updateAll('permTimestamp', time());
937
}
938
939
/**
940
 * Retrieve the XoopsModule object representing this application
941
 *
942
 * @return XoopsModule object representing this application
943
 * @access public
944
 */
945
function &xhelpGetModule()
946
{
947
    global $xoopsModule;
948
    static $_module;
949
950
    if (isset($_module)) {
951
        return $_module;
952
    }
953
954
    if (isset($xoopsModule) && is_object($xoopsModule) && $xoopsModule->getVar('dirname') == XHELP_DIR_NAME) {
955
        $_module =& $xoopsModule;
956
    } else {
957
        $hModule =& xoops_gethandler('module');
958
        $_module =& $hModule->getByDirname('xhelp');
959
    }
960
961
    return $_module;
962
}
963
964
/**
965
 * Retrieve this modules configuration variables
966
 *
967
 * @return ARRAY Key = config variable name, Value = current value
968
 * @access public
969
 */
970
971
function &xhelpGetModuleConfig()
972
{
973
    static $_config;
974
975
    if (!isset($_config)) {
976
        $hModConfig =& xoops_gethandler('config');
977
        $_module    =& xhelpGetModule();
978
979
        $_config    =& $hModConfig->getConfigsByCat(0, $_module->getVar('mid'));
980
    }
981
982
    return $_config;
983
}
984
985
/**
986
 * Wrapper for the xoops_getmodulehandler function
987
 *
988
 * @param string $handler Name of the handler to return
989
 * @return XoopsObjectHandler The object handler requested
990
 * @access public
991
 */
992
function &xhelpGetHandler($handler)
993
{
994
    $handler =& xoops_getmodulehandler($handler, XHELP_DIR_NAME);
995
996
    return $handler;
997
}
998
999
/**
1000
 * Retrieve all saved searches for the specified user(s)
1001
 *
1002
 * @param mixed $users Either an integer (UID) or an array of UIDs
1003
 * @return array xhelpSavedSearch objects
1004
 * @access public
1005
 */
1006
function xhelpGetSavedSearches($users)
1007
{
1008
    $hSavedSearch =& xhelpGetHandler('savedSearch');
1009
1010 View Code Duplication
    if (is_array($users)) {
1011
        $crit = new Criteria('uid', "(". implode($users, ',') .")", 'IN');
1012
    } else {
1013
        $crit = new Criteria('uid', intval($users));
1014
    }
1015
1016
    $savedSearches = $hSavedSearch->getObjects($crit);
1017
1018
    $ret = array();
1019
    foreach($savedSearches as $obj)
1020
    {
1021
        $ret[$obj->getVar('id')] = array('id' => $obj->getVar('id'),
1022
                                  'uid' => $obj->getVar('uid'),
1023
                                  'name' => $obj->getVar('name'),
1024
                                  'search' => unserialize($obj->getVar('search')),
1025
                                  'pagenav_vars' => $obj->getVar('pagenav_vars'),
1026
                                  'hasCustFields' => $obj->getVar('hasCustFields'));
1027
    }
1028
1029
    return (count($ret) > 0 ? $ret : false);
1030
}
1031
1032
/**
1033
 * Set default notification settings for all xhelp events
1034
 *
1035
 * @return BOOL True on success, False on failure
1036
 * @access public
1037
 */
1038
function xhelpCreateNotifications()
1039
{
1040
    $hRole =& xhelpGetHandler('role');
1041
    $hNotification =& xhelpGetHandler('notification');
1042
1043
    // Get list of all roles
1044
    $roles =& $hRole->getObjects();
1045
1046
    $allRoles = array();
1047
    foreach($roles as $role){
1048
        $allRoles[$role->getVar('id')] = $role->getVar('id');
1049
    }
1050
1051
    $notifications = array(
1052
    array('id' => 1, 'staff' => XHELP_NOTIF_STAFF_DEPT, 'user' => XHELP_NOTIF_USER_YES),
1053
    array('id' => 2, 'staff' => XHELP_NOTIF_STAFF_DEPT, 'user' => XHELP_NOTIF_USER_YES),
1054
    array('id' => 3, 'staff' => XHELP_NOTIF_STAFF_DEPT, 'user' => XHELP_NOTIF_USER_YES),
1055
    array('id' => 4, 'staff' => XHELP_NOTIF_STAFF_OWNER, 'user'=>XHELP_NOTIF_USER_YES),
1056
    array('id' => 5, 'staff' => XHELP_NOTIF_STAFF_OWNER, 'user'=>XHELP_NOTIF_USER_YES),
1057
    array('id' => 6, 'staff' => XHELP_NOTIF_STAFF_DEPT, 'user'=>XHELP_NOTIF_USER_YES),
1058
    array('id' => 7, 'staff' => XHELP_NOTIF_STAFF_DEPT, 'user'=>XHELP_NOTIF_USER_YES),
1059
    array('id' => 8, 'staff' => XHELP_NOTIF_STAFF_OWNER, 'user'=>XHELP_NOTIF_USER_NO),
1060
    array('id' => 9, 'staff' => XHELP_NOTIF_STAFF_DEPT, 'user'=>XHELP_NOTIF_USER_YES),
1061
    array('id' => 10, 'staff' => XHELP_NOTIF_STAFF_DEPT, 'user' => XHELP_NOTIF_USER_YES));
1062
1063
    foreach($notifications as $notif){
1064
        $template =& $hNotification->create();
1065
        $template->setVar('notif_id', $notif['id']);
1066
        $template->setVar('staff_setting', $notif['staff']);
1067
        $template->setVar('user_setting', $notif['user']);
1068
        //Set the notification for all staff roles (if necessary)
1069
        if($notif['staff'] == XHELP_NOTIF_STAFF_DEPT){
1070
            $template->setVar('staff_options', $allRoles);
1071
        } else {
1072
            $template->setVar('staff_options', array());
1073
        }
1074
        $hNotification->insert($template, true);
1075
    }
1076
1077
    return true;
1078
}
1079
1080
/**
1081
 * Get the XOOPS username or realname for the specified users
1082
 *
1083
 * @param CriteriaElement $criteria Which users to retrieve
1084
 * @param INTEGER $displayName XHELP_DISPLAYNAME_UNAME for username XHELP_DISPLAYNAME_REALNAME for realname
1085
 * @return BOOL True on success, False on failure
1086
 * @access public
1087
 */
1088
function &xhelpGetUsers($criteria = null, $displayName = XHELP_DISPLAYNAME_UNAME)
1089
{
1090
    $hUser =& xoops_gethandler('user');
1091
    $users =& $hUser->getObjects($criteria, true);
1092
    $ret = array();
1093
    foreach ($users as $i => $user) {
1094
        $ret[$i] = xhelpGetDisplayName($displayName, $user->getVar('name'), $user->getVar('uname'));
1095
    }
1096
1097
    return $ret;
1098
}
1099
1100
/**
1101
 * Retrieve a user's name or username depending on value of xhelp_displayName preference
1102
 *
1103
 * @param mixed $xUser {@link $xoopsUser object) or int {userid}
1104
 * @param int $displayName {xhelp_displayName preference value}
1105
 *
1106
 * @return string username or real name
1107
 *
1108
 * @access public
1109
 */
1110
function xhelpGetUsername($xUser, $displayName = XHELP_DISPLAYNAME_UNAME)
1111
{
1112
    global $xoopsUser, $xoopsConfig;
1113
    $user = false;
1114
    $hMember =& xoops_getHandler('member');
1115
1116
    if(is_numeric($xUser)){
1117
        if($xUser <> $xoopsUser->getVar('uid')){
1118
            if($xUser == 0){
1119
                return $xoopsConfig['anonymous'];
1120
            }
1121
            $user =& $hMember->getUser($xUser);
1122
        } else {
1123
            $user = $xoopsUser;
1124
        }
1125
    } elseif(is_object($xUser)){
1126
        $user = $xUser;
1127
    } else {
1128
        return $xoopsConfig['anonymous'];
1129
    }
1130
1131
    $ret = xhelpGetDisplayName($displayName, $user->getVar('name'), $user->getVar('uname'));
1132
1133
    return $ret;
1134
}
1135
1136
/**
1137
 * Retrieve the Displayname for the user
1138
 *
1139
 * @param int $displayName {xhelp_displayName preference value}
1140
 * @param string $name {user's real name}
1141
 * @param string $uname {user's username}
1142
 * @return string {username or real name}
1143
 * @access public
1144
 */
1145
function xhelpGetDisplayName($displayName, $name = '', $uname = '')
1146
{
1147
    return (($displayName == XHELP_DISPLAYNAME_REALNAME && $name <> '') ? $name : $uname);
1148
}
1149
1150
/**
1151
 * Retrieve the site's active language
1152
 *
1153
 * @return string Name of language
1154
 * @access public
1155
 */
1156
function xhelpGetSiteLanguage()
1157
{
1158
    global $xoopsConfig;
1159
    if (isset($xoopsConfig) && isset($xoopsConfig['language'])) {
1160
        $language = $xoopsConfig['language'];
1161
    } else {
1162
        $config_handler =& xoops_gethandler('config');
1163
        $xoopsConfig =& $config_handler->getConfigsByCat(XOOPS_CONF);
1164
        $language = $xoopsConfig['language'];
1165
    }
1166
1167
    return $language;
1168
}
1169
1170
/**
1171
 * Include the specified language translation
1172
 *
1173
 * @param string $filename file to include
1174
 * @param string $language translation to use
1175
 * @return null
1176
 * @access public
1177
 */
1178
function xhelpIncludeLang($filename, $language = null)
1179
{
1180
    $langFiles = array('admin', 'blocks', 'main', 'modinfo', 'noise_words');
1181
1182
    if (!in_array($filename, $langFiles)) {
1183
        trigger_error("Invalid language file inclusion attempt", E_USER_ERROR);
1184
    }
1185
1186
    if (is_null($language)) {
1187
        $language = xhelpGetSiteLanguage();
1188
    }
1189
1190 View Code Duplication
    if (file_exists(XHELP_BASE_PATH . "/language/$language/$filename.php")) {
1191
        include_once(XHELP_BASE_PATH ."/language/$language/$filename.php");
1192
    } else {
1193
        if (file_exists(XHELP_BASE_PATH ."/language/english/$filename.php")) {
1194
            include_once(XHELP_BASE_PATH ."/language/english/$filename.php");
1195
        } else {
1196
            trigger_error("Unable to load language file $filename", E_USER_NOTICE);
1197
        }
1198
    }
1199
}
1200
1201
function xhelpIncludeReportLangFile($reportName)
1202
{
1203
    $language = xhelpGetSiteLanguage();
1204
1205 View Code Duplication
    if (file_exists(XHELP_BASE_PATH . "/language/$language/reports/$reportName.php")) {
1206
        include_once(XHELP_BASE_PATH ."/language/$language/reports/$reportName.php");
1207
    } else {
1208
        if (file_exists(XHELP_BASE_PATH ."/language/english/reports/$reportName.php")) {
1209
            include_once(XHELP_BASE_PATH ."/language/english/reports/$reportName.php");
1210
        }
1211
    }
1212
}
1213
1214
/**
1215
 * Retrieve the Displayname for the user
1216
 *
1217
 * @param int $displayName {xhelp_displayName preference value}
1218
 * @param string $name {user's real name}
1219
 * @param string $uname {user's username}
1220
 * @return string {username or real name}
1221
 * @access public
1222
 */
1223
function xhelpCreateDefaultTicketLists()
1224
{
1225
    $hSavedSearch =& xhelpGetHandler('savedSearch');
1226
    $hTicketList =& xhelpGetHandler('ticketList');
1227
    $hStaff =& xhelpGetHandler('staff');
1228
1229
    $ticketLists = array(XHELP_QRY_STAFF_HIGHPRIORITY, XHELP_QRY_STAFF_NEW, XHELP_QRY_STAFF_MINE, XHELP_QRY_STAFF_ALL);
1230
    $i = 1;
1231
    foreach($ticketLists as $ticketList){
1232
        $newSearch =& $hSavedSearch->create();
1233
        $crit = new CriteriaCompo();
1234
        switch($ticketList){
1235 View Code Duplication
            case XHELP_QRY_STAFF_HIGHPRIORITY:
1236
                $crit->add(new Criteria('uid', XHELP_GLOBAL_UID, '=', 'j'));
1237
                $crit->add(new Criteria('state', 1, '=', 's'));
1238
                $crit->add(new Criteria('ownership', 0, '=', 't'));
1239
                $crit->setSort('t.priority, t.posted');
1240
                $newSearch->setVar('name', _XHELP_TEXT_HIGH_PRIORITY);
1241
                $newSearch->setVar('pagenav_vars', 'limit=50&state=1');
1242
                break;
1243
1244 View Code Duplication
            case XHELP_QRY_STAFF_NEW:
1245
                $crit->add(new Criteria('uid', XHELP_GLOBAL_UID, '=', 'j'));
1246
                $crit->add(new Criteria('ownership', 0, '=', 't'));
1247
                $crit->add(new Criteria('state', 1, '=', 's'));
1248
                $crit->setSort('t.posted');
1249
                $crit->setOrder('DESC');
1250
                $newSearch->setVar('name', _XHELP_TEXT_NEW_TICKETS);
1251
                $newSearch->setVar('pagenav_vars', 'limit=50&state=1');
1252
                break;
1253
1254 View Code Duplication
            case XHELP_QRY_STAFF_MINE:
1255
                $crit->add(new Criteria('uid', XHELP_GLOBAL_UID, '=', 'j'));
1256
                $crit->add(new Criteria('ownership', XHELP_GLOBAL_UID, '=', 't'));
1257
                $crit->add(new Criteria('state', 1, '=', 's'));
1258
                $crit->setSort('t.posted');
1259
                $newSearch->setVar('name', _XHELP_TEXT_MY_TICKETS);
1260
                $newSearch->setVar('pagenav_vars', 'limit=50&state=1&ownership='.XHELP_GLOBAL_UID);
1261
                break;
1262
1263 View Code Duplication
            case XHELP_QRY_STAFF_ALL:
1264
                $crit->add(new Criteria('uid', XHELP_GLOBAL_UID, '=', 'j'));
1265
                $crit->add(new Criteria('state', 1, '=', 's'));
1266
                $crit->add(new Criteria('uid', XHELP_GLOBAL_UID, '=', 't'));
1267
                $newSearch->setVar('name', _XHELP_TEXT_SUBMITTED_TICKETS);
1268
                $newSearch->setVar('pagenav_vars', 'limit=50&state=1&submittedBy='.XHELP_GLOBAL_UID);
1269
                break;
1270
1271
            default:
1272
                return false;
1273
                break;
1274
        }
1275
1276
        $newSearch->setVar('uid', XHELP_GLOBAL_UID);
1277
        $newSearch->setVar('search', serialize($crit));
1278
        $newSearch->setVar('hasCustFields', 0);
1279
        $ret = $hSavedSearch->insert($newSearch, true);
1280
1281
        $staff =& $hStaff->getObjects(null, true);
1282 View Code Duplication
        foreach($staff as $stf){
1283
            $list =& $hTicketList->create();
1284
            $list->setVar('uid', $stf->getVar('uid'));
1285
            $list->setVar('searchid', $newSearch->getVar('id'));
1286
            $list->setVar('weight', $i);
1287
            $ret = $hTicketList->insert($list, true);
1288
        }
1289
        $i++;
1290
    }
1291
1292
    return true;
1293
}
1294
1295
function &xhelpNewEventService()
1296
{
1297
    static $instance;
1298
1299
    if (!isset($instance)) {
1300
        $instance = new xhelpEventService();
1301
    }
1302
1303
    return $instance;
1304
}
1305