Browse Source

Upload files to 'classes'

Stortebeker 6 years ago
parent
commit
64deceafce
5 changed files with 1235 additions and 1205 deletions
  1. 98
    97
      classes/userrank.class.php
  2. 605
    584
      classes/users.class.php
  3. 127
    115
      classes/util.php
  4. 266
    279
      classes/validate.class.php
  5. 139
    130
      classes/view.class.php

+ 98
- 97
classes/userrank.class.php View File

1
-<?
2
-class UserRank {
3
-  const PREFIX = 'percentiles_'; // Prefix for memcache keys, to make life easier
4
-
5
-  // Returns a 101 row array (101 percentiles - 0 - 100), with the minimum value for that percentile as the value for each row
6
-  // BTW - ingenious
7
-  private static function build_table($MemKey, $Query) {
8
-    $QueryID = G::$DB->get_query_id();
9
-
10
-    G::$DB->query("
1
+<?php
2
+class UserRank
3
+{
4
+    const PREFIX = 'percentiles_'; // Prefix for memcache keys, to make life easier
5
+
6
+    // Returns a 101 row array (101 percentiles - 0 - 100), with the minimum value for that percentile as the value for each row
7
+    // BTW - ingenious
8
+    private static function build_table($MemKey, $Query)
9
+    {
10
+        $QueryID = G::$DB->get_query_id();
11
+
12
+        G::$DB->query("
11
       DROP TEMPORARY TABLE IF EXISTS temp_stats");
13
       DROP TEMPORARY TABLE IF EXISTS temp_stats");
12
 
14
 
13
-    G::$DB->query("
15
+        G::$DB->query("
14
       CREATE TEMPORARY TABLE temp_stats (
16
       CREATE TEMPORARY TABLE temp_stats (
15
         ID int(10) NOT NULL PRIMARY KEY AUTO_INCREMENT,
17
         ID int(10) NOT NULL PRIMARY KEY AUTO_INCREMENT,
16
         Val bigint(20) NOT NULL
18
         Val bigint(20) NOT NULL
17
       );");
19
       );");
18
 
20
 
19
-    G::$DB->query("
21
+        G::$DB->query("
20
       INSERT INTO temp_stats (Val) ".
22
       INSERT INTO temp_stats (Val) ".
21
-      $Query);
23
+        $Query);
22
 
24
 
23
-    G::$DB->query("
25
+        G::$DB->query("
24
       SELECT COUNT(ID)
26
       SELECT COUNT(ID)
25
       FROM temp_stats");
27
       FROM temp_stats");
26
-    list($UserCount) = G::$DB->next_record();
28
+        list($UserCount) = G::$DB->next_record();
27
 
29
 
28
-    G::$DB->query("
30
+        G::$DB->query("
29
       SELECT MIN(Val)
31
       SELECT MIN(Val)
30
       FROM temp_stats
32
       FROM temp_stats
31
       GROUP BY CEIL(ID / (".(int)$UserCount." / 100));");
33
       GROUP BY CEIL(ID / (".(int)$UserCount." / 100));");
32
 
34
 
33
-    $Table = G::$DB->to_array();
35
+        $Table = G::$DB->to_array();
34
 
36
 
35
-    G::$DB->set_query_id($QueryID);
37
+        G::$DB->set_query_id($QueryID);
36
 
38
 
37
-    // Give a little variation to the cache length, so all the tables don't expire at the same time
38
-    G::$Cache->cache_value($MemKey, $Table, 3600 * 24 * rand(800, 1000) * 0.001);
39
+        // Give a little variation to the cache length, so all the tables don't expire at the same time
40
+        G::$Cache->cache_value($MemKey, $Table, 3600 * 24 * rand(800, 1000) * 0.001);
39
 
41
 
40
-    return $Table;
41
-  }
42
+        return $Table;
43
+    }
42
 
44
 
43
-  private static function table_query($TableName) {
44
-    switch ($TableName) {
45
-      case 'uploaded':
46
-        $Query =  "
45
+    private static function table_query($TableName)
46
+    {
47
+        switch ($TableName) {
48
+            case 'uploaded':
49
+                $Query =  "
47
           SELECT Uploaded
50
           SELECT Uploaded
48
           FROM users_main
51
           FROM users_main
49
           WHERE Enabled = '1'
52
           WHERE Enabled = '1'
50
             AND Uploaded > 0
53
             AND Uploaded > 0
51
           ORDER BY Uploaded;";
54
           ORDER BY Uploaded;";
52
-        break;
53
-      case 'downloaded':
54
-        $Query =  "
55
+                break;
56
+            case 'downloaded':
57
+                $Query =  "
55
           SELECT Downloaded
58
           SELECT Downloaded
56
           FROM users_main
59
           FROM users_main
57
           WHERE Enabled = '1'
60
           WHERE Enabled = '1'
58
             AND Downloaded > 0
61
             AND Downloaded > 0
59
           ORDER BY Downloaded;";
62
           ORDER BY Downloaded;";
60
-        break;
61
-      case 'uploads':
62
-        $Query = "
63
+                break;
64
+            case 'uploads':
65
+                $Query = "
63
           SELECT COUNT(t.ID) AS Uploads
66
           SELECT COUNT(t.ID) AS Uploads
64
           FROM users_main AS um
67
           FROM users_main AS um
65
             JOIN torrents AS t ON t.UserID = um.ID
68
             JOIN torrents AS t ON t.UserID = um.ID
66
           WHERE um.Enabled = '1'
69
           WHERE um.Enabled = '1'
67
           GROUP BY um.ID
70
           GROUP BY um.ID
68
           ORDER BY Uploads;";
71
           ORDER BY Uploads;";
69
-        break;
70
-      case 'requests':
71
-        $Query = "
72
+                break;
73
+            case 'requests':
74
+                $Query = "
72
           SELECT COUNT(r.ID) AS Requests
75
           SELECT COUNT(r.ID) AS Requests
73
           FROM users_main AS um
76
           FROM users_main AS um
74
             JOIN requests AS r ON r.FillerID = um.ID
77
             JOIN requests AS r ON r.FillerID = um.ID
75
           WHERE um.Enabled = '1'
78
           WHERE um.Enabled = '1'
76
           GROUP BY um.ID
79
           GROUP BY um.ID
77
           ORDER BY Requests;";
80
           ORDER BY Requests;";
78
-        break;
79
-      case 'posts':
80
-        $Query = "
81
+                break;
82
+            case 'posts':
83
+                $Query = "
81
           SELECT COUNT(p.ID) AS Posts
84
           SELECT COUNT(p.ID) AS Posts
82
           FROM users_main AS um
85
           FROM users_main AS um
83
             JOIN forums_posts AS p ON p.AuthorID = um.ID
86
             JOIN forums_posts AS p ON p.AuthorID = um.ID
84
           WHERE um.Enabled = '1'
87
           WHERE um.Enabled = '1'
85
           GROUP BY um.ID
88
           GROUP BY um.ID
86
           ORDER BY Posts;";
89
           ORDER BY Posts;";
87
-        break;
88
-      case 'bounty':
89
-        $Query = "
90
+                break;
91
+            case 'bounty':
92
+                $Query = "
90
           SELECT SUM(rv.Bounty) AS Bounty
93
           SELECT SUM(rv.Bounty) AS Bounty
91
           FROM users_main AS um
94
           FROM users_main AS um
92
             JOIN requests_votes AS rv ON rv.UserID = um.ID
95
             JOIN requests_votes AS rv ON rv.UserID = um.ID
93
           WHERE um.Enabled = '1' " .
96
           WHERE um.Enabled = '1' " .
94
-          "GROUP BY um.ID
97
+                "GROUP BY um.ID
95
           ORDER BY Bounty;";
98
           ORDER BY Bounty;";
96
-        break;
97
-      case 'artists':
98
-        $Query = "
99
+                break;
100
+            case 'artists':
101
+                $Query = "
99
           SELECT COUNT(ta.ArtistID) AS Artists
102
           SELECT COUNT(ta.ArtistID) AS Artists
100
           FROM torrents_artists AS ta
103
           FROM torrents_artists AS ta
101
             JOIN torrents_group AS tg ON tg.ID = ta.GroupID
104
             JOIN torrents_group AS tg ON tg.ID = ta.GroupID
103
           WHERE t.UserID != ta.UserID
106
           WHERE t.UserID != ta.UserID
104
           GROUP BY tg.ID
107
           GROUP BY tg.ID
105
           ORDER BY Artists ASC";
108
           ORDER BY Artists ASC";
106
-        break;
107
-    }
108
-    return $Query;
109
-  }
110
-
111
-  public static function get_rank($TableName, $Value) {
112
-    if ($Value == 0) {
113
-      return 0;
109
+                break;
110
+        }
111
+        return $Query;
114
     }
112
     }
115
 
113
 
116
-    $Table = G::$Cache->get_value(self::PREFIX.$TableName);
117
-    if (!$Table) {
118
-      //Cache lock!
119
-      $Lock = G::$Cache->get_value(self::PREFIX.$TableName.'_lock');
120
-      if ($Lock) {
121
-        return false;
122
-      } else {
123
-        G::$Cache->cache_value(self::PREFIX.$TableName.'_lock', '1', 300);
124
-        $Table = self::build_table(self::PREFIX.$TableName, self::table_query($TableName));
125
-        G::$Cache->delete_value(self::PREFIX.$TableName.'_lock');
126
-      }
114
+    public static function get_rank($TableName, $Value)
115
+    {
116
+        if ($Value == 0) {
117
+            return 0;
118
+        }
119
+
120
+        $Table = G::$Cache->get_value(self::PREFIX.$TableName);
121
+        if (!$Table) {
122
+            //Cache lock!
123
+            $Lock = G::$Cache->get_value(self::PREFIX.$TableName.'_lock');
124
+            if ($Lock) {
125
+                return false;
126
+            } else {
127
+                G::$Cache->cache_value(self::PREFIX.$TableName.'_lock', '1', 300);
128
+                $Table = self::build_table(self::PREFIX.$TableName, self::table_query($TableName));
129
+                G::$Cache->delete_value(self::PREFIX.$TableName.'_lock');
130
+            }
131
+        }
132
+        $LastPercentile = 0;
133
+        foreach ($Table as $Row) {
134
+            list($CurValue) = $Row;
135
+            if ($CurValue >= $Value) {
136
+                return $LastPercentile;
137
+            }
138
+            $LastPercentile++;
139
+        }
140
+        return 100; // 100th percentile
127
     }
141
     }
128
-    $LastPercentile = 0;
129
-    foreach ($Table as $Row) {
130
-      list($CurValue) = $Row;
131
-      if ($CurValue >= $Value) {
132
-        return $LastPercentile;
133
-      }
134
-      $LastPercentile++;
135
-    }
136
-    return 100; // 100th percentile
137
-  }
138
 
142
 
139
-  public static function overall_score($Uploaded, $Downloaded, $Uploads, $Requests, $Posts, $Bounty, $Artists, $Ratio) {
140
-    // We can do this all in 1 line, but it's easier to read this way
141
-    if ($Ratio > 1) {
142
-      $Ratio = 1;
143
-    }
144
-    $TotalScore = 0;
145
-    if (in_array(false, func_get_args(), true)) {
146
-      return false;
143
+    public static function overall_score($Uploaded, $Downloaded, $Uploads, $Requests, $Posts, $Bounty, $Artists, $Ratio)
144
+    {
145
+        // We can do this all in 1 line, but it's easier to read this way
146
+        if ($Ratio > 1) {
147
+            $Ratio = 1;
148
+        }
149
+        $TotalScore = 0;
150
+        if (in_array(false, func_get_args(), true)) {
151
+            return false;
152
+        }
153
+        $TotalScore += $Uploaded * 15;
154
+        $TotalScore += $Downloaded * 8;
155
+        $TotalScore += $Uploads * 25;
156
+        $TotalScore += $Requests * 2;
157
+        $TotalScore += $Posts;
158
+        $TotalScore += $Bounty;
159
+        $TotalScore += $Artists;
160
+        $TotalScore /= (15 + 8 + 25 + 2 + 1 + 1 + 1);
161
+        $TotalScore *= $Ratio;
162
+        return $TotalScore;
147
     }
163
     }
148
-    $TotalScore += $Uploaded * 15;
149
-    $TotalScore += $Downloaded * 8;
150
-    $TotalScore += $Uploads * 25;
151
-    $TotalScore += $Requests * 2;
152
-    $TotalScore += $Posts;
153
-    $TotalScore += $Bounty;
154
-    $TotalScore += $Artists;
155
-    $TotalScore /= (15 + 8 + 25 + 2 + 1 + 1 + 1);
156
-    $TotalScore *= $Ratio;
157
-    return $TotalScore;
158
-  }
159
-
160
 }
164
 }
161
-
162
-
163
-?>

+ 605
- 584
classes/users.class.php
File diff suppressed because it is too large
View File


+ 127
- 115
classes/util.php View File

1
-<?
1
+<?php
2
 // This is a file of miscellaneous functions that are called so damn often
2
 // This is a file of miscellaneous functions that are called so damn often
3
 // that it'd just be annoying to stick them in namespaces.
3
 // that it'd just be annoying to stick them in namespaces.
4
 
4
 
9
  * @return bool
9
  * @return bool
10
  */
10
  */
11
 if (PHP_INT_SIZE === 4) {
11
 if (PHP_INT_SIZE === 4) {
12
-  function is_number($Str) {
13
-    if ($Str === null || $Str === '') {
14
-      return false;
12
+    function is_number($Str)
13
+    {
14
+        if ($Str === null || $Str === '') {
15
+            return false;
16
+        }
17
+        if (is_int($Str)) {
18
+            return true;
19
+        }
20
+        if ($Str[0] == '-' || $Str[0] == '+') { // Leading plus/minus signs are ok
21
+            $Str[0] = 0;
22
+        }
23
+        return ltrim($Str, "0..9") === '';
15
     }
24
     }
16
-    if (is_int($Str)) {
17
-      return true;
18
-    }
19
-    if ($Str[0] == '-' || $Str[0] == '+') { // Leading plus/minus signs are ok
20
-      $Str[0] = 0;
21
-    }
22
-    return ltrim($Str, "0..9") === '';
23
-  }
24
 } else {
25
 } else {
25
-  function is_number($Str) {
26
-    return $Str == strval(intval($Str));
27
-  }
26
+    function is_number($Str)
27
+    {
28
+        return $Str == strval(intval($Str));
29
+    }
28
 }
30
 }
29
 
31
 
30
-function is_date($Date) {
31
-  list($Y, $M, $D) = explode('-', $Date);
32
-  if (checkdate($M, $D, $Y)) {
33
-    return true;
34
-  }
35
-  return false;
32
+function is_date($Date)
33
+{
34
+    list($Y, $M, $D) = explode('-', $Date);
35
+    if (checkdate($M, $D, $Y)) {
36
+        return true;
37
+    }
38
+    return false;
36
 }
39
 }
37
 
40
 
38
 /**
41
 /**
42
  * @param array $Keys list of keys to check
45
  * @param array $Keys list of keys to check
43
  * @param mixed $Error error code or string to pass to the error() function if a key isn't numeric
46
  * @param mixed $Error error code or string to pass to the error() function if a key isn't numeric
44
  */
47
  */
45
-function assert_numbers(&$Base, $Keys, $Error = 0) {
46
-  // make sure both arguments are arrays
47
-  if (!is_array($Base) || !is_array($Keys)) {
48
-    return;
49
-  }
50
-  foreach ($Keys as $Key) {
51
-    if (!isset($Base[$Key]) || !is_number($Base[$Key])) {
52
-      error($Error);
48
+function assert_numbers(&$Base, $Keys, $Error = 0)
49
+{
50
+    // make sure both arguments are arrays
51
+    if (!is_array($Base) || !is_array($Keys)) {
52
+        return;
53
+    }
54
+    foreach ($Keys as $Key) {
55
+        if (!isset($Base[$Key]) || !is_number($Base[$Key])) {
56
+            error($Error);
57
+        }
53
     }
58
     }
54
-  }
55
 }
59
 }
56
 
60
 
57
 /**
61
 /**
61
  * @return true if $Value is "truthy", false if it is "non-truthy" or null if $Value was not
65
  * @return true if $Value is "truthy", false if it is "non-truthy" or null if $Value was not
62
  *         a bool-like value
66
  *         a bool-like value
63
  */
67
  */
64
-function is_bool_value($Value) {
65
-  if (is_bool($Value)) {
66
-    return $Value;
67
-  }
68
-  if (is_string($Value)) {
69
-    switch (strtolower($Value)) {
70
-      case 'true':
71
-      case 'yes':
72
-      case 'on':
73
-      case '1':
74
-        return true;
75
-      case 'false':
76
-      case 'no':
77
-      case 'off':
78
-      case '0':
79
-        return false;
68
+function is_bool_value($Value)
69
+{
70
+    if (is_bool($Value)) {
71
+        return $Value;
80
     }
72
     }
81
-  }
82
-  if (is_numeric($Value)) {
83
-    if ($Value == 1) {
84
-      return true;
85
-    } elseif ($Value == 0) {
86
-      return false;
73
+    if (is_string($Value)) {
74
+        switch (strtolower($Value)) {
75
+            case 'true':
76
+            case 'yes':
77
+            case 'on':
78
+            case '1':
79
+                return true;
80
+            case 'false':
81
+            case 'no':
82
+            case 'off':
83
+            case '0':
84
+                return false;
85
+        }
87
     }
86
     }
88
-  }
89
-  return null;
87
+    if (is_numeric($Value)) {
88
+        if ($Value == 1) {
89
+            return true;
90
+        } elseif ($Value == 0) {
91
+            return false;
92
+        }
93
+    }
94
+    return null;
90
 }
95
 }
91
 
96
 
92
 /**
97
 /**
96
  * @param string $Str
101
  * @param string $Str
97
  * @return string escaped string.
102
  * @return string escaped string.
98
  */
103
  */
99
-function display_str($Str) {
100
-  if ($Str === null || $Str === false || is_array($Str)) {
101
-    return '';
102
-  }
103
-  if ($Str != '' && !is_number($Str)) {
104
-    $Str = Format::make_utf8($Str);
105
-    $Str = mb_convert_encoding($Str, 'HTML-ENTITIES', 'UTF-8');
106
-    $Str = preg_replace("/&(?![A-Za-z]{0,4}\w{2,3};|#[0-9]{2,6};)/m", '&amp;', $Str);
107
-
108
-    $Replace = array(
109
-      "'",'"',"<",">",
110
-      '&#128;','&#130;','&#131;','&#132;','&#133;','&#134;','&#135;','&#136;',
111
-      '&#137;','&#138;','&#139;','&#140;','&#142;','&#145;','&#146;','&#147;',
112
-      '&#148;','&#149;','&#150;','&#151;','&#152;','&#153;','&#154;','&#155;',
113
-      '&#156;','&#158;','&#159;'
114
-    );
115
-
116
-    $With = array(
117
-      '&#39;','&quot;','&lt;','&gt;',
118
-      '&#8364;','&#8218;','&#402;','&#8222;','&#8230;','&#8224;','&#8225;','&#710;',
119
-      '&#8240;','&#352;','&#8249;','&#338;','&#381;','&#8216;','&#8217;','&#8220;',
120
-      '&#8221;','&#8226;','&#8211;','&#8212;','&#732;','&#8482;','&#353;','&#8250;',
121
-      '&#339;','&#382;','&#376;'
122
-    );
123
-
124
-    $Str = str_replace($Replace, $With, $Str);
125
-  }
126
-  return $Str;
104
+function display_str($Str)
105
+{
106
+    if ($Str === null || $Str === false || is_array($Str)) {
107
+        return '';
108
+    }
109
+    if ($Str != '' && !is_number($Str)) {
110
+        $Str = Format::make_utf8($Str);
111
+        $Str = mb_convert_encoding($Str, 'HTML-ENTITIES', 'UTF-8');
112
+        $Str = preg_replace("/&(?![A-Za-z]{0,4}\w{2,3};|#[0-9]{2,6};)/m", '&amp;', $Str);
113
+
114
+        $Replace = array(
115
+        "'",'"',"<",">",
116
+        '&#128;','&#130;','&#131;','&#132;','&#133;','&#134;','&#135;','&#136;',
117
+        '&#137;','&#138;','&#139;','&#140;','&#142;','&#145;','&#146;','&#147;',
118
+        '&#148;','&#149;','&#150;','&#151;','&#152;','&#153;','&#154;','&#155;',
119
+        '&#156;','&#158;','&#159;'
120
+        );
121
+
122
+        $With = array(
123
+        '&#39;','&quot;','&lt;','&gt;',
124
+        '&#8364;','&#8218;','&#402;','&#8222;','&#8230;','&#8224;','&#8225;','&#710;',
125
+        '&#8240;','&#352;','&#8249;','&#338;','&#381;','&#8216;','&#8217;','&#8220;',
126
+        '&#8221;','&#8226;','&#8211;','&#8212;','&#732;','&#8482;','&#353;','&#8250;',
127
+        '&#339;','&#382;','&#376;'
128
+        );
129
+
130
+        $Str = str_replace($Replace, $With, $Str);
131
+    }
132
+    return $Str;
127
 }
133
 }
128
 
134
 
129
 
135
 
132
  *
138
  *
133
  * @param string $Raw An IRC protocol snippet to send.
139
  * @param string $Raw An IRC protocol snippet to send.
134
  */
140
  */
135
-function send_irc($Raw) {
136
-  // check if IRC is enabled
137
-  if (!FEATURE_IRC) {
138
-    return;
139
-  }
140
-
141
-  $IRCSocket = fsockopen(SOCKET_LISTEN_ADDRESS, SOCKET_LISTEN_PORT);
142
-  $Raw = str_replace(array("\n", "\r"), '', $Raw);
143
-  fwrite($IRCSocket, $Raw);
144
-  fclose($IRCSocket);
141
+function send_irc($Raw)
142
+{
143
+    // check if IRC is enabled
144
+    if (!FEATURE_IRC) {
145
+        return;
146
+    }
147
+
148
+    $IRCSocket = fsockopen(SOCKET_LISTEN_ADDRESS, SOCKET_LISTEN_PORT);
149
+    $Raw = str_replace(array("\n", "\r"), '', $Raw);
150
+    fwrite($IRCSocket, $Raw);
151
+    fclose($IRCSocket);
145
 }
152
 }
146
 
153
 
147
 
154
 
154
  * @param boolean $NoHTML If true, the header/footer won't be shown, just the description.
161
  * @param boolean $NoHTML If true, the header/footer won't be shown, just the description.
155
  * @param string $Log If true, the user is given a link to search $Log in the site log.
162
  * @param string $Log If true, the user is given a link to search $Log in the site log.
156
  */
163
  */
157
-function error($Error, $NoHTML = false, $Log = false) {
158
-  global $Debug;
159
-  require(SERVER_ROOT.'/sections/error/index.php');
160
-  $Debug->profile();
161
-  die();
164
+function error($Error, $NoHTML = false, $Log = false)
165
+{
166
+    global $Debug;
167
+    require(SERVER_ROOT.'/sections/error/index.php');
168
+    $Debug->profile();
169
+    die();
162
 }
170
 }
163
 
171
 
164
 
172
 
165
 /**
173
 /**
166
  * Convenience function. See doc in permissions.class.php
174
  * Convenience function. See doc in permissions.class.php
167
  */
175
  */
168
-function check_perms($PermissionName, $MinClass = 0) {
169
-  return Permissions::check_perms($PermissionName, $MinClass);
176
+function check_perms($PermissionName, $MinClass = 0)
177
+{
178
+    return Permissions::check_perms($PermissionName, $MinClass);
170
 }
179
 }
171
 
180
 
172
-function get_permissions_for_user($UserID, $CustomPermissions = false) {
173
-  return Permissions::get_permissions_for_user($UserID, $CustomPermissions = false);
181
+function get_permissions_for_user($UserID, $CustomPermissions = false)
182
+{
183
+    return Permissions::get_permissions_for_user($UserID, $CustomPermissions = false);
174
 }
184
 }
175
 
185
 
176
 /**
186
 /**
177
  * Print JSON status result with an optional message and die.
187
  * Print JSON status result with an optional message and die.
178
  * DO NOT USE THIS FUNCTION!
188
  * DO NOT USE THIS FUNCTION!
179
  */
189
  */
180
-function json_die($Status, $Message) {
181
-  json_print($Status, $Message);
182
-  die();
190
+function json_die($Status, $Message)
191
+{
192
+    json_print($Status, $Message);
193
+    die();
183
 }
194
 }
184
 
195
 
185
 /**
196
 /**
186
  * Print JSON status result with an optional message.
197
  * Print JSON status result with an optional message.
187
  */
198
  */
188
-function json_print($Status, $Message) {
189
-  if ($Status == 'success' && $Message) {
190
-    print json_encode(array('status' => $Status, 'response' => $Message));
191
-  } elseif ($Message) {
192
-    print json_encode(array('status' => $Status, 'error' => $Message));
193
-  } else {
194
-    print json_encode(array('status' => $Status, 'response' => []));
195
-  }
199
+function json_print($Status, $Message)
200
+{
201
+    if ($Status == 'success' && $Message) {
202
+        print json_encode(array('status' => $Status, 'response' => $Message));
203
+    } elseif ($Message) {
204
+        print json_encode(array('status' => $Status, 'error' => $Message));
205
+    } else {
206
+        print json_encode(array('status' => $Status, 'response' => []));
207
+    }
196
 }
208
 }
197
 
209
 
198
 /**
210
 /**
199
  * Print the site's URL including the appropriate URI scheme, including the trailing slash
211
  * Print the site's URL including the appropriate URI scheme, including the trailing slash
200
  */
212
  */
201
-function site_url() {
202
-  return 'https://' . SITE_DOMAIN . '/';
213
+function site_url()
214
+{
215
+    return 'https://' . SITE_DOMAIN . '/';
203
 }
216
 }
204
-?>

+ 266
- 279
classes/validate.class.php View File

1
-<?
1
+<?php
2
 /*-- TODO ---------------------------//
2
 /*-- TODO ---------------------------//
3
 Writeup how to use the VALIDATE class, add in support for form id checks
3
 Writeup how to use the VALIDATE class, add in support for form id checks
4
 Complete the number and date validation
4
 Complete the number and date validation
5
 Remove the GenerateJS stuff
5
 Remove the GenerateJS stuff
6
 //-----------------------------------*/
6
 //-----------------------------------*/
7
 
7
 
8
-class VALIDATE {
9
-  var $Fields = [];
10
-
11
-  function SetFields($FieldName, $Required, $FieldType, $ErrorMessage, $Options = []) {
12
-    $this->Fields[$FieldName]['Type'] = strtolower($FieldType);
13
-    $this->Fields[$FieldName]['Required'] = $Required;
14
-    $this->Fields[$FieldName]['ErrorMessage'] = $ErrorMessage;
15
-    if (!empty($Options['maxlength'])) {
16
-      $this->Fields[$FieldName]['MaxLength'] = $Options['maxlength'];
17
-    }
18
-    if (!empty($Options['minlength'])) {
19
-      $this->Fields[$FieldName]['MinLength'] = $Options['minlength'];
20
-    }
21
-    if (!empty($Options['comparefield'])) {
22
-      $this->Fields[$FieldName]['CompareField'] = $Options['comparefield'];
23
-    }
24
-    if (!empty($Options['allowperiod'])) {
25
-      $this->Fields[$FieldName]['AllowPeriod'] = $Options['allowperiod'];
26
-    }
27
-    if (!empty($Options['allowcomma'])) {
28
-      $this->Fields[$FieldName]['AllowComma'] = $Options['allowcomma'];
29
-    }
30
-    if (!empty($Options['inarray'])) {
31
-      $this->Fields[$FieldName]['InArray'] = $Options['inarray'];
32
-    }
33
-    if (!empty($Options['regex'])) {
34
-      $this->Fields[$FieldName]['Regex'] = $Options['regex'];
35
-    }
36
-  }
37
-
38
-  function ValidateForm($ValidateArray) {
39
-    reset($this->Fields);
40
-    foreach ($this->Fields as $FieldKey => $Field) {
41
-      $ValidateVar = $ValidateArray[$FieldKey];
42
-
43
-      if ($ValidateVar != '' || !empty($Field['Required']) || $Field['Type'] == 'date') {
44
-        if ($Field['Type'] == 'string') {
45
-          if (isset($Field['MaxLength'])) {
46
-            $MaxLength = $Field['MaxLength'];
47
-          } else {
48
-            $MaxLength = 255;
49
-          }
50
-          if (isset($Field['MinLength'])) {
51
-            $MinLength = $Field['MinLength'];
52
-          } else {
53
-            $MinLength = 1;
54
-          }
55
-
56
-          if (strlen($ValidateVar) > $MaxLength) {
57
-            return $Field['ErrorMessage'];
58
-          } elseif (strlen($ValidateVar) < $MinLength) {
59
-            return $Field['ErrorMessage'];
60
-          }
61
-
62
-        } elseif ($Field['Type'] == 'number') {
63
-          if (isset($Field['MaxLength'])) {
64
-            $MaxLength = $Field['MaxLength'];
65
-          } else {
66
-            $MaxLength = '';
67
-          }
68
-          if (isset($Field['MinLength'])) {
69
-            $MinLength = $Field['MinLength'];
70
-          } else {
71
-            $MinLength = 0;
72
-          }
73
-
74
-          $Match = '0-9';
75
-          if (isset($Field['AllowPeriod'])) {
76
-            $Match .= '.';
77
-          }
78
-          if (isset($Field['AllowComma'])) {
79
-            $Match .= ',';
80
-          }
81
-
82
-          if (preg_match('/[^'.$Match.']/', $ValidateVar) || strlen($ValidateVar) < 1) {
83
-            return $Field['ErrorMessage'];
84
-          } elseif ($MaxLength != '' && $ValidateVar > $MaxLength) {
85
-            return $Field['ErrorMessage'].'!!';
86
-          } elseif ($ValidateVar < $MinLength) {
87
-            return $Field['ErrorMessage']."$MinLength";
88
-          }
89
-
90
-        } elseif ($Field['Type'] == 'email') {
91
-          if (isset($Field['MaxLength'])) {
92
-            $MaxLength = $Field['MaxLength'];
93
-          } else {
94
-            $MaxLength = 255;
95
-          }
96
-          if (isset($Field['MinLength'])) {
97
-            $MinLength = $Field['MinLength'];
98
-          } else {
99
-            $MinLength = 6;
100
-          }
101
-
102
-          if (!preg_match("/^".EMAIL_REGEX."$/i", $ValidateVar)) {
103
-            return $Field['ErrorMessage'];
104
-          } elseif (strlen($ValidateVar) > $MaxLength) {
105
-            return $Field['ErrorMessage'];
106
-          } elseif (strlen($ValidateVar) < $MinLength) {
107
-            return $Field['ErrorMessage'];
108
-          }
109
-
110
-        } elseif ($Field['Type'] == 'link') {
111
-          if (isset($Field['MaxLength'])) {
112
-            $MaxLength = $Field['MaxLength'];
113
-          } else {
114
-            $MaxLength = 255;
115
-          }
116
-          if (isset($Field['MinLength'])) {
117
-            $MinLength = $Field['MinLength'];
118
-          } else {
119
-            $MinLength = 10;
120
-          }
121
-
122
-          if (!preg_match('/^'.URL_REGEX.'$/i', $ValidateVar)) {
123
-            return $Field['ErrorMessage'];
124
-          } elseif (strlen($ValidateVar) > $MaxLength) {
125
-            return $Field['ErrorMessage'];
126
-          } elseif (strlen($ValidateVar) < $MinLength) {
127
-            return $Field['ErrorMessage'];
128
-          }
129
-
130
-        } elseif ($Field['Type'] == 'username') {
131
-          if (isset($Field['MaxLength'])) {
132
-            $MaxLength = $Field['MaxLength'];
133
-          } else {
134
-            $MaxLength = 20;
135
-          }
136
-          if (isset($Field['MinLength'])) {
137
-            $MinLength = $Field['MinLength'];
138
-          } else {
139
-            $MinLength = 1;
140
-          }
141
-
142
-          if (!preg_match(USERNAME_REGEX, $ValidateVar)) {
143
-            return $Field['ErrorMessage'];
144
-          } elseif (strlen($ValidateVar) > $MaxLength) {
145
-            return $Field['ErrorMessage'];
146
-          } elseif (strlen($ValidateVar) < $MinLength) {
147
-            return $Field['ErrorMessage'];
148
-          }
149
-
150
-        } elseif ($Field['Type'] == 'checkbox') {
151
-          if (!isset($ValidateArray[$FieldKey])) {
152
-            return $Field['ErrorMessage'];
153
-          }
154
-
155
-        } elseif ($Field['Type'] == 'compare') {
156
-          if ($ValidateArray[$Field['CompareField']] != $ValidateVar) {
157
-            return $Field['ErrorMessage'];
158
-          }
159
-
160
-        } elseif ($Field['Type'] == 'inarray') {
161
-          if (array_search($ValidateVar, $Field['InArray']) === false) {
162
-            return $Field['ErrorMessage'];
163
-          }
164
-
165
-        } elseif ($Field['Type'] == 'regex') {
166
-          if (!preg_match($Field['Regex'], $ValidateVar)) {
167
-            return $Field['ErrorMessage'];
168
-          }
169
-        }
170
-      }
171
-    } // while
172
-  } // function
173
-
174
-  function GenerateJS($FormID) {
175
-    $ReturnJS = "<script type=\"text/javascript\" language=\"javascript\">\r\n";
176
-    $ReturnJS .= "function formVal() {\r\n";
177
-    $ReturnJS .= "  clearErrors('$FormID');\r\n";
178
-
179
-    reset($this->Fields);
180
-    foreach ($this->Fields as $FieldKey => $Field) {
181
-      if ($Field['Type'] == 'string') {
182
-        $ValItem = '  if ($(\'#'.$FieldKey.'\').raw().value == ""';
183
-        if (!empty($Field['MaxLength'])) {
184
-          $ValItem .= ' || $(\'#'.$FieldKey.'\').raw().value.length > '.$Field['MaxLength'];
185
-        } else {
186
-          $ValItem .= ' || $(\'#'.$FieldKey.'\').raw().value.length > 255';
187
-        }
188
-        if (!empty($Field['MinLength'])) {
189
-          $ValItem .= ' || $(\'#'.$FieldKey.'\').raw().value.length < '.$Field['MinLength'];
190
-        }
191
-        $ValItem .= ') { return showError(\''.$FieldKey.'\',\''.$Field['ErrorMessage'].'\'); }'."\r\n";
192
-
193
-      } elseif ($Field['Type'] == 'number') {
194
-        $Match = '0-9';
195
-        if (!empty($Field['AllowPeriod'])) {
196
-          $Match .= '.';
197
-        }
198
-        if (!empty($Field['AllowComma'])) {
199
-          $Match .= ',';
200
-        }
201
-
202
-        $ValItem = '  if ($(\'#'.$FieldKey.'\').raw().value.match(/[^'.$Match.']/) || $(\'#'.$FieldKey.'\').raw().value.length < 1';
203
-        if (!empty($Field['MaxLength'])) {
204
-          $ValItem .= ' || $(\'#'.$FieldKey.'\').raw().value/1 > '.$Field['MaxLength'];
8
+class VALIDATE
9
+{
10
+    public $Fields = [];
11
+
12
+    public function SetFields($FieldName, $Required, $FieldType, $ErrorMessage, $Options = [])
13
+    {
14
+        $this->Fields[$FieldName]['Type'] = strtolower($FieldType);
15
+        $this->Fields[$FieldName]['Required'] = $Required;
16
+        $this->Fields[$FieldName]['ErrorMessage'] = $ErrorMessage;
17
+        if (!empty($Options['maxlength'])) {
18
+            $this->Fields[$FieldName]['MaxLength'] = $Options['maxlength'];
205
         }
19
         }
206
-        if (!empty($Field['MinLength'])) {
207
-          $ValItem .= ' || $(\'#'.$FieldKey.'\').raw().value/1 < '.$Field['MinLength'];
20
+        if (!empty($Options['minlength'])) {
21
+            $this->Fields[$FieldName]['MinLength'] = $Options['minlength'];
208
         }
22
         }
209
-        $ValItem .= ') { return showError(\''.$FieldKey.'\',\''.$Field['ErrorMessage'].'\'); }'."\r\n";
210
-
211
-      } elseif ($Field['Type'] == 'email') {
212
-        $ValItem = '  if (!validEmail($(\'#'.$FieldKey.'\').raw().value)';
213
-        if (!empty($Field['MaxLength'])) {
214
-          $ValItem .= ' || $(\'#'.$FieldKey.'\').raw().value.length > '.$Field['MaxLength'];
215
-        } else {
216
-          $ValItem .= ' || $(\'#'.$FieldKey.'\').raw().value.length > 255';
217
-        }
218
-        if (!empty($Field['MinLength'])) {
219
-          $ValItem .= ' || $(\'#'.$FieldKey.'\').raw().value.length < '.$Field['MinLength'];
220
-        } else {
221
-          $ValItem .= ' || $(\'#'.$FieldKey.'\').raw().value.length < 6';
23
+        if (!empty($Options['comparefield'])) {
24
+            $this->Fields[$FieldName]['CompareField'] = $Options['comparefield'];
222
         }
25
         }
223
-        $ValItem .= ') { return showError(\''.$FieldKey.'\',\''.$Field['ErrorMessage'].'\'); }'."\r\n";
224
-
225
-      } elseif ($Field['Type'] == 'link') {
226
-        $ValItem = '  if (!validLink($(\'#'.$FieldKey.'\').raw().value)';
227
-        if (!empty($Field['MaxLength'])) {
228
-          $ValItem .= ' || $(\'#'.$FieldKey.'\').raw().value.length > '.$Field['MaxLength'];
229
-        } else {
230
-          $ValItem .= ' || $(\'#'.$FieldKey.'\').raw().value.length > 255';
26
+        if (!empty($Options['allowperiod'])) {
27
+            $this->Fields[$FieldName]['AllowPeriod'] = $Options['allowperiod'];
231
         }
28
         }
232
-        if (!empty($Field['MinLength'])) {
233
-          $ValItem .= ' || $(\'#'.$FieldKey.'\').raw().value.length < '.$Field['MinLength'];
234
-        } else {
235
-          $ValItem .= ' || $(\'#'.$FieldKey.'\').raw().value.length < 10';
29
+        if (!empty($Options['allowcomma'])) {
30
+            $this->Fields[$FieldName]['AllowComma'] = $Options['allowcomma'];
236
         }
31
         }
237
-        $ValItem .= ') { return showError(\''.$FieldKey.'\',\''.$Field['ErrorMessage'].'\'); }'."\r\n";
238
-
239
-      } elseif ($Field['Type'] == 'username') {
240
-        $ValItem = '  if ($(\'#'.$FieldKey.'\').raw().value.match(/[^a-zA-Z0-9_\-]/)';
241
-        if (!empty($Field['MaxLength'])) {
242
-          $ValItem .= ' || $(\'#'.$FieldKey.'\').raw().value.length > '.$Field['MaxLength'];
32
+        if (!empty($Options['inarray'])) {
33
+            $this->Fields[$FieldName]['InArray'] = $Options['inarray'];
243
         }
34
         }
244
-        if (!empty($Field['MinLength'])) {
245
-          $ValItem .= ' || $(\'#'.$FieldKey.'\').raw().value.length < '.$Field['MinLength'];
35
+        if (!empty($Options['regex'])) {
36
+            $this->Fields[$FieldName]['Regex'] = $Options['regex'];
246
         }
37
         }
247
-        $ValItem .= ') { return showError(\''.$FieldKey.'\',\''.$Field['ErrorMessage'].'\'); }'."\r\n";
248
-
249
-      } elseif ($Field['Type'] == 'regex') {
250
-        $ValItem = '  if (!$(\'#'.$FieldKey.'\').raw().value.match('.$Field['Regex'].')) { return showError(\''.$FieldKey.'\',\''.$Field['ErrorMessage'].'\'); }'."\r\n";
251
-
252
-      } elseif ($Field['Type'] == 'date') {
253
-        $DisplayError = $FieldKey.'month';
254
-        if (isset($Field['MinLength']) && $Field['MinLength'] == 3) {
255
-          $Day = '$(\'#'.$FieldKey.'day\').raw().value';
256
-          $DisplayError .= ",{$FieldKey}day";
257
-        } else {
258
-          $Day = '1';
259
-        }
260
-        $DisplayError .= ",{$FieldKey}year";
261
-        $ValItemHold = '  if (!validDate($(\'#'.$FieldKey.'month\').raw().value+\'/\'+'.$Day.'+\'/\'+$(\'#'.$FieldKey.'year\').raw().value)) { return showError(\''.$DisplayError.'\',\''.$Field['ErrorMessage'].'\'); }'."\r\n";
38
+    }
262
 
39
 
263
-        if (empty($Field['Required'])) {
264
-          $ValItem = '  if ($(\'#'.$FieldKey.'month\').raw().value != ""';
265
-          if (isset($Field['MinLength']) && $Field['MinLength'] == 3) {
266
-            $ValItem .= ' || $(\'#'.$FieldKey.'day\').raw().value != ""';
267
-          }
268
-          $ValItem .= ' || $(\'#'.$FieldKey.'year\').raw().value != "") {'."\r\n";
269
-          $ValItem .= $ValItemHold;
270
-          $ValItem .= " }\r\n";
271
-        } else {
272
-          $ValItem .= $ValItemHold;
40
+    public function ValidateForm($ValidateArray)
41
+    {
42
+        reset($this->Fields);
43
+        foreach ($this->Fields as $FieldKey => $Field) {
44
+            $ValidateVar = $ValidateArray[$FieldKey];
45
+
46
+            if ($ValidateVar != '' || !empty($Field['Required']) || $Field['Type'] == 'date') {
47
+                if ($Field['Type'] == 'string') {
48
+                    if (isset($Field['MaxLength'])) {
49
+                        $MaxLength = $Field['MaxLength'];
50
+                    } else {
51
+                        $MaxLength = 255;
52
+                    }
53
+                    if (isset($Field['MinLength'])) {
54
+                        $MinLength = $Field['MinLength'];
55
+                    } else {
56
+                        $MinLength = 1;
57
+                    }
58
+
59
+                    if (strlen($ValidateVar) > $MaxLength) {
60
+                        return $Field['ErrorMessage'];
61
+                    } elseif (strlen($ValidateVar) < $MinLength) {
62
+                        return $Field['ErrorMessage'];
63
+                    }
64
+                } elseif ($Field['Type'] == 'number') {
65
+                    if (isset($Field['MaxLength'])) {
66
+                        $MaxLength = $Field['MaxLength'];
67
+                    } else {
68
+                        $MaxLength = '';
69
+                    }
70
+                    if (isset($Field['MinLength'])) {
71
+                        $MinLength = $Field['MinLength'];
72
+                    } else {
73
+                        $MinLength = 0;
74
+                    }
75
+
76
+                    $Match = '0-9';
77
+                    if (isset($Field['AllowPeriod'])) {
78
+                        $Match .= '.';
79
+                    }
80
+                    if (isset($Field['AllowComma'])) {
81
+                        $Match .= ',';
82
+                    }
83
+
84
+                    if (preg_match('/[^'.$Match.']/', $ValidateVar) || strlen($ValidateVar) < 1) {
85
+                        return $Field['ErrorMessage'];
86
+                    } elseif ($MaxLength != '' && $ValidateVar > $MaxLength) {
87
+                        return $Field['ErrorMessage'].'!!';
88
+                    } elseif ($ValidateVar < $MinLength) {
89
+                        return $Field['ErrorMessage']."$MinLength";
90
+                    }
91
+                } elseif ($Field['Type'] == 'email') {
92
+                    if (isset($Field['MaxLength'])) {
93
+                        $MaxLength = $Field['MaxLength'];
94
+                    } else {
95
+                        $MaxLength = 255;
96
+                    }
97
+                    if (isset($Field['MinLength'])) {
98
+                        $MinLength = $Field['MinLength'];
99
+                    } else {
100
+                        $MinLength = 6;
101
+                    }
102
+
103
+                    if (!preg_match("/^".EMAIL_REGEX."$/i", $ValidateVar)) {
104
+                        return $Field['ErrorMessage'];
105
+                    } elseif (strlen($ValidateVar) > $MaxLength) {
106
+                        return $Field['ErrorMessage'];
107
+                    } elseif (strlen($ValidateVar) < $MinLength) {
108
+                        return $Field['ErrorMessage'];
109
+                    }
110
+                } elseif ($Field['Type'] == 'link') {
111
+                    if (isset($Field['MaxLength'])) {
112
+                        $MaxLength = $Field['MaxLength'];
113
+                    } else {
114
+                        $MaxLength = 255;
115
+                    }
116
+                    if (isset($Field['MinLength'])) {
117
+                        $MinLength = $Field['MinLength'];
118
+                    } else {
119
+                        $MinLength = 10;
120
+                    }
121
+
122
+                    if (!preg_match('/^'.URL_REGEX.'$/i', $ValidateVar)) {
123
+                        return $Field['ErrorMessage'];
124
+                    } elseif (strlen($ValidateVar) > $MaxLength) {
125
+                        return $Field['ErrorMessage'];
126
+                    } elseif (strlen($ValidateVar) < $MinLength) {
127
+                        return $Field['ErrorMessage'];
128
+                    }
129
+                } elseif ($Field['Type'] == 'username') {
130
+                    if (isset($Field['MaxLength'])) {
131
+                        $MaxLength = $Field['MaxLength'];
132
+                    } else {
133
+                        $MaxLength = 20;
134
+                    }
135
+                    if (isset($Field['MinLength'])) {
136
+                        $MinLength = $Field['MinLength'];
137
+                    } else {
138
+                        $MinLength = 1;
139
+                    }
140
+
141
+                    if (!preg_match(USERNAME_REGEX, $ValidateVar)) {
142
+                        return $Field['ErrorMessage'];
143
+                    } elseif (strlen($ValidateVar) > $MaxLength) {
144
+                        return $Field['ErrorMessage'];
145
+                    } elseif (strlen($ValidateVar) < $MinLength) {
146
+                        return $Field['ErrorMessage'];
147
+                    }
148
+                } elseif ($Field['Type'] == 'checkbox') {
149
+                    if (!isset($ValidateArray[$FieldKey])) {
150
+                        return $Field['ErrorMessage'];
151
+                    }
152
+                } elseif ($Field['Type'] == 'compare') {
153
+                    if ($ValidateArray[$Field['CompareField']] != $ValidateVar) {
154
+                        return $Field['ErrorMessage'];
155
+                    }
156
+                } elseif ($Field['Type'] == 'inarray') {
157
+                    if (array_search($ValidateVar, $Field['InArray']) === false) {
158
+                        return $Field['ErrorMessage'];
159
+                    }
160
+                } elseif ($Field['Type'] == 'regex') {
161
+                    if (!preg_match($Field['Regex'], $ValidateVar)) {
162
+                        return $Field['ErrorMessage'];
163
+                    }
164
+                }
165
+            }
166
+        } // while
167
+    } // function
168
+
169
+    public function GenerateJS($FormID)
170
+    {
171
+        $ReturnJS = "<script type=\"text/javascript\" language=\"javascript\">\r\n";
172
+        $ReturnJS .= "function formVal() {\r\n";
173
+        $ReturnJS .= "  clearErrors('$FormID');\r\n";
174
+
175
+        reset($this->Fields);
176
+        foreach ($this->Fields as $FieldKey => $Field) {
177
+            if ($Field['Type'] == 'string') {
178
+                $ValItem = '  if ($(\'#'.$FieldKey.'\').raw().value == ""';
179
+                if (!empty($Field['MaxLength'])) {
180
+                    $ValItem .= ' || $(\'#'.$FieldKey.'\').raw().value.length > '.$Field['MaxLength'];
181
+                } else {
182
+                    $ValItem .= ' || $(\'#'.$FieldKey.'\').raw().value.length > 255';
183
+                }
184
+                if (!empty($Field['MinLength'])) {
185
+                    $ValItem .= ' || $(\'#'.$FieldKey.'\').raw().value.length < '.$Field['MinLength'];
186
+                }
187
+                $ValItem .= ') { return showError(\''.$FieldKey.'\',\''.$Field['ErrorMessage'].'\'); }'."\r\n";
188
+            } elseif ($Field['Type'] == 'number') {
189
+                $Match = '0-9';
190
+                if (!empty($Field['AllowPeriod'])) {
191
+                    $Match .= '.';
192
+                }
193
+                if (!empty($Field['AllowComma'])) {
194
+                    $Match .= ',';
195
+                }
196
+
197
+                $ValItem = '  if ($(\'#'.$FieldKey.'\').raw().value.match(/[^'.$Match.']/) || $(\'#'.$FieldKey.'\').raw().value.length < 1';
198
+                if (!empty($Field['MaxLength'])) {
199
+                    $ValItem .= ' || $(\'#'.$FieldKey.'\').raw().value/1 > '.$Field['MaxLength'];
200
+                }
201
+                if (!empty($Field['MinLength'])) {
202
+                    $ValItem .= ' || $(\'#'.$FieldKey.'\').raw().value/1 < '.$Field['MinLength'];
203
+                }
204
+                $ValItem .= ') { return showError(\''.$FieldKey.'\',\''.$Field['ErrorMessage'].'\'); }'."\r\n";
205
+            } elseif ($Field['Type'] == 'email') {
206
+                $ValItem = '  if (!validEmail($(\'#'.$FieldKey.'\').raw().value)';
207
+                if (!empty($Field['MaxLength'])) {
208
+                    $ValItem .= ' || $(\'#'.$FieldKey.'\').raw().value.length > '.$Field['MaxLength'];
209
+                } else {
210
+                    $ValItem .= ' || $(\'#'.$FieldKey.'\').raw().value.length > 255';
211
+                }
212
+                if (!empty($Field['MinLength'])) {
213
+                    $ValItem .= ' || $(\'#'.$FieldKey.'\').raw().value.length < '.$Field['MinLength'];
214
+                } else {
215
+                    $ValItem .= ' || $(\'#'.$FieldKey.'\').raw().value.length < 6';
216
+                }
217
+                $ValItem .= ') { return showError(\''.$FieldKey.'\',\''.$Field['ErrorMessage'].'\'); }'."\r\n";
218
+            } elseif ($Field['Type'] == 'link') {
219
+                $ValItem = '  if (!validLink($(\'#'.$FieldKey.'\').raw().value)';
220
+                if (!empty($Field['MaxLength'])) {
221
+                    $ValItem .= ' || $(\'#'.$FieldKey.'\').raw().value.length > '.$Field['MaxLength'];
222
+                } else {
223
+                    $ValItem .= ' || $(\'#'.$FieldKey.'\').raw().value.length > 255';
224
+                }
225
+                if (!empty($Field['MinLength'])) {
226
+                    $ValItem .= ' || $(\'#'.$FieldKey.'\').raw().value.length < '.$Field['MinLength'];
227
+                } else {
228
+                    $ValItem .= ' || $(\'#'.$FieldKey.'\').raw().value.length < 10';
229
+                }
230
+                $ValItem .= ') { return showError(\''.$FieldKey.'\',\''.$Field['ErrorMessage'].'\'); }'."\r\n";
231
+            } elseif ($Field['Type'] == 'username') {
232
+                $ValItem = '  if ($(\'#'.$FieldKey.'\').raw().value.match(/[^a-zA-Z0-9_\-]/)';
233
+                if (!empty($Field['MaxLength'])) {
234
+                    $ValItem .= ' || $(\'#'.$FieldKey.'\').raw().value.length > '.$Field['MaxLength'];
235
+                }
236
+                if (!empty($Field['MinLength'])) {
237
+                    $ValItem .= ' || $(\'#'.$FieldKey.'\').raw().value.length < '.$Field['MinLength'];
238
+                }
239
+                $ValItem .= ') { return showError(\''.$FieldKey.'\',\''.$Field['ErrorMessage'].'\'); }'."\r\n";
240
+            } elseif ($Field['Type'] == 'regex') {
241
+                $ValItem = '  if (!$(\'#'.$FieldKey.'\').raw().value.match('.$Field['Regex'].')) { return showError(\''.$FieldKey.'\',\''.$Field['ErrorMessage'].'\'); }'."\r\n";
242
+            } elseif ($Field['Type'] == 'date') {
243
+                $DisplayError = $FieldKey.'month';
244
+                if (isset($Field['MinLength']) && $Field['MinLength'] == 3) {
245
+                    $Day = '$(\'#'.$FieldKey.'day\').raw().value';
246
+                    $DisplayError .= ",{$FieldKey}day";
247
+                } else {
248
+                    $Day = '1';
249
+                }
250
+                $DisplayError .= ",{$FieldKey}year";
251
+                $ValItemHold = '  if (!validDate($(\'#'.$FieldKey.'month\').raw().value+\'/\'+'.$Day.'+\'/\'+$(\'#'.$FieldKey.'year\').raw().value)) { return showError(\''.$DisplayError.'\',\''.$Field['ErrorMessage'].'\'); }'."\r\n";
252
+
253
+                if (empty($Field['Required'])) {
254
+                    $ValItem = '  if ($(\'#'.$FieldKey.'month\').raw().value != ""';
255
+                    if (isset($Field['MinLength']) && $Field['MinLength'] == 3) {
256
+                        $ValItem .= ' || $(\'#'.$FieldKey.'day\').raw().value != ""';
257
+                    }
258
+                    $ValItem .= ' || $(\'#'.$FieldKey.'year\').raw().value != "") {'."\r\n";
259
+                    $ValItem .= $ValItemHold;
260
+                    $ValItem .= " }\r\n";
261
+                } else {
262
+                    $ValItem .= $ValItemHold;
263
+                }
264
+            } elseif ($Field['Type'] == 'checkbox') {
265
+                $ValItem = '  if (!$(\'#'.$FieldKey.'\').checked) { return showError(\''.$FieldKey.'\',\''.$Field['ErrorMessage'].'\'); }'."\r\n";
266
+            } elseif ($Field['Type'] == 'compare') {
267
+                $ValItem = '  if ($(\'#'.$FieldKey.'\').raw().value!=$(\'#'.$Field['CompareField'].'\').raw().value) { return showError(\''.$FieldKey.','.$Field['CompareField'].'\',\''.$Field['ErrorMessage'].'\'); }'."\r\n";
268
+            }
269
+
270
+            if (empty($Field['Required']) && $Field['Type'] != 'date') {
271
+                $ReturnJS .= '  if ($(\'#'.$FieldKey.'\').raw().value!="") {'."\r\n ";
272
+                $ReturnJS .= $ValItem;
273
+                $ReturnJS .= "  }\r\n";
274
+            } else {
275
+                $ReturnJS .= $ValItem;
276
+            }
277
+            $ValItem = '';
273
         }
278
         }
274
 
279
 
275
-      } elseif ($Field['Type'] == 'checkbox') {
276
-        $ValItem = '  if (!$(\'#'.$FieldKey.'\').checked) { return showError(\''.$FieldKey.'\',\''.$Field['ErrorMessage'].'\'); }'."\r\n";
277
-
278
-      } elseif ($Field['Type'] == 'compare') {
279
-        $ValItem = '  if ($(\'#'.$FieldKey.'\').raw().value!=$(\'#'.$Field['CompareField'].'\').raw().value) { return showError(\''.$FieldKey.','.$Field['CompareField'].'\',\''.$Field['ErrorMessage'].'\'); }'."\r\n";
280
-      }
281
-
282
-      if (empty($Field['Required']) && $Field['Type'] != 'date') {
283
-        $ReturnJS .= '  if ($(\'#'.$FieldKey.'\').raw().value!="") {'."\r\n ";
284
-        $ReturnJS .= $ValItem;
285
-        $ReturnJS .= "  }\r\n";
286
-      } else {
287
-        $ReturnJS .= $ValItem;
288
-      }
289
-      $ValItem = '';
280
+        $ReturnJS .= "}\r\n";
281
+        $ReturnJS .= "</script>\r\n";
282
+        return $ReturnJS;
290
     }
283
     }
291
-
292
-    $ReturnJS .= "}\r\n";
293
-    $ReturnJS .= "</script>\r\n";
294
-    return $ReturnJS;
295
-  }
296
 }
284
 }
297
-?>

+ 139
- 130
classes/view.class.php View File

1
-<?
2
-class View {
3
-  /**
4
-   * @var string Path relative to where (P)HTML templates reside
5
-   */
6
-  const IncludePath = './design/views/';
1
+<?php
2
+class View
3
+{
4
+    /**
5
+     * @var string Path relative to where (P)HTML templates reside
6
+     */
7
+    const IncludePath = './design/views/';
7
 
8
 
8
-  /**
9
-   * This function is to include the header file on a page.
10
-   *
11
-   * @param $PageTitle the title of the page
12
-   * @param $JSIncludes is a comma-separated list of JS files to be included on
13
-   *                    the page. ONLY PUT THE RELATIVE LOCATION WITHOUT '.js'
14
-   *                    example: 'somefile,somedir/somefile'
15
-   */
16
-  public static function show_header($PageTitle = '', $JSIncludes = '', $CSSIncludes = '') {
17
-    global $Document, $Mobile, $Classes;
9
+    /**
10
+     * This function is to include the header file on a page.
11
+     *
12
+     * @param $PageTitle the title of the page
13
+     * @param $JSIncludes is a comma-separated list of JS files to be included on
14
+     *                    the page. ONLY PUT THE RELATIVE LOCATION WITHOUT '.js'
15
+     *                    example: 'somefile,somedir/somefile'
16
+     */
17
+    public static function show_header($PageTitle = '', $JSIncludes = '', $CSSIncludes = '')
18
+    {
19
+        global $Document, $Mobile, $Classes;
18
 
20
 
19
-    if ($PageTitle != '') {
20
-      $PageTitle .= ' :: ';
21
-    }
22
-    $PageTitle .= SITE_NAME;
23
-    $PageID = array(
24
-      $Document, // Document
25
-      empty($_REQUEST['action']) ? false : $_REQUEST['action'], // Action
26
-      empty($_REQUEST['type']) ? false : $_REQUEST['type'] // Type
27
-    );
21
+        if ($PageTitle != '') {
22
+            $PageTitle .= ' :: ';
23
+        }
24
+        $PageTitle .= SITE_NAME;
25
+        $PageID = array(
26
+        $Document, // Document
27
+        empty($_REQUEST['action']) ? false : $_REQUEST['action'], // Action
28
+        empty($_REQUEST['type']) ? false : $_REQUEST['type'] // Type
29
+        );
28
 
30
 
29
-    if (!is_array(G::$LoggedUser) || empty(G::$LoggedUser['ID']) || $PageTitle == 'Recover Password :: ' . SITE_NAME) {
30
-      require(SERVER_ROOT.'/design/publicheader.php');
31
-    } else {
32
-      // HTTP/2 Server Push headers for cloudflare
33
-      $Scripts = array_merge(['jquery', 'global', 'ajax.class', 'jquery.autocomplete', 'autocomplete', 'tooltipster'], explode(',', $JSIncludes));
34
-      $Styles = array_merge(['tooltipster'], explode(',', $CSSIncludes));
35
-      foreach ($Scripts as $Script) {
36
-        if (trim($Script) == '') { continue; }
37
-        header('Link: <'.STATIC_SERVER.'functions/'.$Script.'.js?v='.filemtime(SERVER_ROOT.STATIC_SERVER.'functions/'.$Script.'.js').'>; rel=preload; as=script;', false);
38
-      }
39
-      header('Link: <'.STATIC_SERVER.'styles/global.css?v='.filemtime(SERVER_ROOT.STATIC_SERVER.'styles/global.css').'>; rel=preload; as=style', false);
40
-      foreach ($Styles as $Style) {
41
-        if (trim($Style) == '') { continue; }
42
-        header('Link: <'.STATIC_SERVER.'styles/'.$Style.'/style.css?v='.filemtime(SERVER_ROOT.STATIC_SERVER.'styles/'.$Style.'/style.css').'>; rel=preload; as=style;', false);
43
-      }
44
-      require(SERVER_ROOT.'/design/privateheader.php');
31
+        if (!is_array(G::$LoggedUser) || empty(G::$LoggedUser['ID']) || $PageTitle == 'Recover Password :: ' . SITE_NAME) {
32
+            require(SERVER_ROOT.'/design/publicheader.php');
33
+        } else {
34
+            // HTTP/2 Server Push headers for cloudflare
35
+            $Scripts = array_merge(['jquery', 'global', 'ajax.class', 'jquery.autocomplete', 'autocomplete', 'tooltipster'], explode(',', $JSIncludes));
36
+            $Styles = array_merge(['tooltipster'], explode(',', $CSSIncludes));
37
+            foreach ($Scripts as $Script) {
38
+                if (trim($Script) == '') {
39
+                    continue;
40
+                }
41
+                header('Link: <'.STATIC_SERVER.'functions/'.$Script.'.js?v='.filemtime(SERVER_ROOT.STATIC_SERVER.'functions/'.$Script.'.js').'>; rel=preload; as=script;', false);
42
+            }
43
+            header('Link: <'.STATIC_SERVER.'styles/global.css?v='.filemtime(SERVER_ROOT.STATIC_SERVER.'styles/global.css').'>; rel=preload; as=style', false);
44
+            foreach ($Styles as $Style) {
45
+                if (trim($Style) == '') {
46
+                    continue;
47
+                }
48
+                header('Link: <'.STATIC_SERVER.'styles/'.$Style.'/style.css?v='.filemtime(SERVER_ROOT.STATIC_SERVER.'styles/'.$Style.'/style.css').'>; rel=preload; as=style;', false);
49
+            }
50
+            require(SERVER_ROOT.'/design/privateheader.php');
51
+        }
45
     }
52
     }
46
-  }
47
 
53
 
48
-  /**
49
-   * This function is to include the footer file on a page.
50
-   *
51
-   * @param $Options an optional array that you can pass information to the
52
-   *                 header through as well as setup certain limitations
53
-   *                 Here is a list of parameters that work in the $Options array:
54
-   *                 ['disclaimer'] = [boolean] (False) Displays the disclaimer in the footer
55
-   */
56
-  public static function show_footer($Options = []) {
57
-    global $ScriptStartTime, $SessionID, $UserSessions, $Debug, $Time, $Mobile;
58
-    if (!is_array(G::$LoggedUser) || (isset($Options['recover']) && $Options['recover'] === true)) {
59
-      require(SERVER_ROOT.'/design/publicfooter.php');
60
-    } else {
61
-      require(SERVER_ROOT.'/design/privatefooter.php');
54
+    /**
55
+     * This function is to include the footer file on a page.
56
+     *
57
+     * @param $Options an optional array that you can pass information to the
58
+     *                 header through as well as setup certain limitations
59
+     *                 Here is a list of parameters that work in the $Options array:
60
+     *                 ['disclaimer'] = [boolean] (False) Displays the disclaimer in the footer
61
+     */
62
+    public static function show_footer($Options = [])
63
+    {
64
+        global $ScriptStartTime, $SessionID, $UserSessions, $Debug, $Time, $Mobile;
65
+        if (!is_array(G::$LoggedUser) || (isset($Options['recover']) && $Options['recover'] === true)) {
66
+            require(SERVER_ROOT.'/design/publicfooter.php');
67
+        } else {
68
+            require(SERVER_ROOT.'/design/privatefooter.php');
69
+        }
62
     }
70
     }
63
-  }
64
 
71
 
65
-  /**
66
-   * This is a generic function to load a template fromm /design and render it.
67
-   * The template should be in /design/my_template_name.php, and have a class
68
-   * in it called MyTemplateNameTemplate (my_template_name transformed to
69
-   * MixedCase, with the word 'Template' appended).
70
-   * This class should have a public static function render($Args), where
71
-   * $Args is an associative array of the template variables.
72
-   * You should note that by "Template", we mean "php file that outputs stuff".
73
-   *
74
-   * This function loads /design/$TemplateName.php, and then calls
75
-   * render($Args) on the class.
76
-   *
77
-   * @param string $TemplateName The name of the template, in underscore_format
78
-   * @param array $Args the arguments passed to the template.
79
-   */
80
-  public static function render_template($TemplateName, $Args) {
81
-    static $LoadedTemplates; // Keep track of templates we've already loaded.
82
-    $ClassName = '';
83
-    if (isset($LoadedTemplates[$TemplateName])) {
84
-      $ClassName = $LoadedTemplates[$TemplateName];
85
-    } else {
86
-      include(SERVER_ROOT.'/design/' . $TemplateName . '.php');
72
+    /**
73
+     * This is a generic function to load a template fromm /design and render it.
74
+     * The template should be in /design/my_template_name.php, and have a class
75
+     * in it called MyTemplateNameTemplate (my_template_name transformed to
76
+     * MixedCase, with the word 'Template' appended).
77
+     * This class should have a public static function render($Args), where
78
+     * $Args is an associative array of the template variables.
79
+     * You should note that by "Template", we mean "php file that outputs stuff".
80
+     *
81
+     * This function loads /design/$TemplateName.php, and then calls
82
+     * render($Args) on the class.
83
+     *
84
+     * @param string $TemplateName The name of the template, in underscore_format
85
+     * @param array $Args the arguments passed to the template.
86
+     */
87
+    public static function render_template($TemplateName, $Args)
88
+    {
89
+        static $LoadedTemplates; // Keep track of templates we've already loaded.
90
+        $ClassName = '';
91
+        if (isset($LoadedTemplates[$TemplateName])) {
92
+            $ClassName = $LoadedTemplates[$TemplateName];
93
+        } else {
94
+            include(SERVER_ROOT.'/design/' . $TemplateName . '.php');
87
 
95
 
88
-      // Turn template_name into TemplateName
89
-      $ClassNameParts = explode('_', $TemplateName);
90
-      foreach ($ClassNameParts as $Index => $Part) {
91
-        $ClassNameParts[$Index] = ucfirst($Part);
92
-      }
93
-      $ClassName = implode($ClassNameParts). 'Template';
94
-      $LoadedTemplates[$TemplateName] = $ClassName;
96
+            // Turn template_name into TemplateName
97
+            $ClassNameParts = explode('_', $TemplateName);
98
+            foreach ($ClassNameParts as $Index => $Part) {
99
+                $ClassNameParts[$Index] = ucfirst($Part);
100
+            }
101
+            $ClassName = implode($ClassNameParts). 'Template';
102
+            $LoadedTemplates[$TemplateName] = $ClassName;
103
+        }
104
+        $ClassName::render($Args);
95
     }
105
     }
96
-    $ClassName::render($Args);
97
-  }
98
 
106
 
99
-  /**
100
-   * This method is similar to render_template, but does not require a
101
-   * template class.
102
-   *
103
-   * Instead, this method simply renders a PHP file (PHTML) with the supplied
104
-   * variables.
105
-   *
106
-   * All files must be placed within {self::IncludePath}. Create and organize
107
-   * new paths and files. (e.g.: /design/views/artist/, design/view/forums/, etc.)
108
-   *
109
-   * @static
110
-   * @param string  $TemplateFile A relative path to a PHTML file
111
-   * @param array   $Variables Assoc. array of variables to extract for the template
112
-   * @param boolean $Buffer enables Output Buffer
113
-   * @return boolean|string
114
-   *
115
-   * @example <pre><?php
116
-   *  // box.phtml
117
-   *  <p id="<?=$id?>">Data</p>
118
-   *
119
-   *  // The variable $id within box.phtml will be filled by $some_id
120
-   *  View::parse('section/box.phtml', array('id' => $some_id));
121
-   *
122
-   *  // Parse a template without outputing it
123
-   *  $SavedTemplate = View::parse('sec/tion/eg.php', $DataArray, true);
124
-   *  // later . . .
125
-   *  echo $SavedTemplate; // Output the buffer
126
-   * </pre>
127
-   */
128
-  public static function parse($TemplateFile, array $Variables = [], $Buffer = false) {
129
-    $Template = self::IncludePath . $TemplateFile;
130
-    if (file_exists($Template)) {
131
-      extract($Variables);
132
-      if ($Buffer) {
133
-        ob_start();
134
-        include $Template;
135
-        $Content = ob_get_contents();
136
-        ob_end_clean();
137
-        return $Content;
138
-      }
139
-      return include $Template;
107
+    /**
108
+     * This method is similar to render_template, but does not require a
109
+     * template class.
110
+     *
111
+     * Instead, this method simply renders a PHP file (PHTML) with the supplied
112
+     * variables.
113
+     *
114
+     * All files must be placed within {self::IncludePath}. Create and organize
115
+     * new paths and files. (e.g.: /design/views/artist/, design/view/forums/, etc.)
116
+     *
117
+     * @static
118
+     * @param string  $TemplateFile A relative path to a PHTML file
119
+     * @param array   $Variables Assoc. array of variables to extract for the template
120
+     * @param boolean $Buffer enables Output Buffer
121
+     * @return boolean|string
122
+     *
123
+     * @example <pre><?php
124
+     *  // box.phtml
125
+     *  <p id="<?=$id?>">Data</p>
126
+     *
127
+     *  // The variable $id within box.phtml will be filled by $some_id
128
+     *  View::parse('section/box.phtml', array('id' => $some_id));
129
+     *
130
+     *  // Parse a template without outputing it
131
+     *  $SavedTemplate = View::parse('sec/tion/eg.php', $DataArray, true);
132
+     *  // later . . .
133
+     *  echo $SavedTemplate; // Output the buffer
134
+     * </pre>
135
+     */
136
+    public static function parse($TemplateFile, array $Variables = [], $Buffer = false)
137
+    {
138
+        $Template = self::IncludePath . $TemplateFile;
139
+        if (file_exists($Template)) {
140
+            extract($Variables);
141
+            if ($Buffer) {
142
+                ob_start();
143
+                include $Template;
144
+                $Content = ob_get_contents();
145
+                ob_end_clean();
146
+                return $Content;
147
+            }
148
+            return include $Template;
149
+        }
140
     }
150
     }
141
-  }
142
 }
151
 }

Loading…
Cancel
Save