Completed
Pull Request — develop (#530)
by
unknown
05:43
created
manager/includes/extenders/dbapi.mysql.class.inc.php 1 patch
Indentation   +496 added lines, -496 removed lines patch added patch discarded remove patch
@@ -7,187 +7,187 @@  discard block
 block discarded – undo
7 7
 
8 8
 class DBAPI {
9 9
 
10
-   var $conn;
11
-   var $config;
12
-   var $lastQuery;
13
-   var $isConnected;
10
+    var $conn;
11
+    var $config;
12
+    var $lastQuery;
13
+    var $isConnected;
14 14
 
15
-   /**
16
-    * @name:  DBAPI
17
-    *
18
-    */
19
-   function __construct($host='',$dbase='', $uid='',$pwd='',$pre=NULL,$charset='',$connection_method='SET CHARACTER SET') {
20
-      $this->config['host'] = $host ? $host : $GLOBALS['database_server'];
21
-      $this->config['dbase'] = $dbase ? $dbase : $GLOBALS['dbase'];
22
-      $this->config['user'] = $uid ? $uid : $GLOBALS['database_user'];
23
-      $this->config['pass'] = $pwd ? $pwd : $GLOBALS['database_password'];
24
-      $this->config['charset'] = $charset ? $charset : $GLOBALS['database_connection_charset'];
25
-      $this->config['connection_method'] =  $this->_dbconnectionmethod = (isset($GLOBALS['database_connection_method']) ? $GLOBALS['database_connection_method'] : $connection_method);
26
-      $this->config['table_prefix'] = ($pre !== NULL) ? $pre : $GLOBALS['table_prefix'];
27
-      $this->initDataTypes();
28
-   }
15
+    /**
16
+     * @name:  DBAPI
17
+     *
18
+     */
19
+    function __construct($host='',$dbase='', $uid='',$pwd='',$pre=NULL,$charset='',$connection_method='SET CHARACTER SET') {
20
+        $this->config['host'] = $host ? $host : $GLOBALS['database_server'];
21
+        $this->config['dbase'] = $dbase ? $dbase : $GLOBALS['dbase'];
22
+        $this->config['user'] = $uid ? $uid : $GLOBALS['database_user'];
23
+        $this->config['pass'] = $pwd ? $pwd : $GLOBALS['database_password'];
24
+        $this->config['charset'] = $charset ? $charset : $GLOBALS['database_connection_charset'];
25
+        $this->config['connection_method'] =  $this->_dbconnectionmethod = (isset($GLOBALS['database_connection_method']) ? $GLOBALS['database_connection_method'] : $connection_method);
26
+        $this->config['table_prefix'] = ($pre !== NULL) ? $pre : $GLOBALS['table_prefix'];
27
+        $this->initDataTypes();
28
+    }
29 29
 
30
-   /**
31
-    * @name:  initDataTypes
32
-    * @desc:  called in the constructor to set up arrays containing the types
33
-    *         of database fields that can be used with specific PHP types
34
-    */
35
-   function initDataTypes() {
36
-      $this->dataTypes['numeric'] = array (
37
-         'INT',
38
-         'INTEGER',
39
-         'TINYINT',
40
-         'BOOLEAN',
41
-         'DECIMAL',
42
-         'DEC',
43
-         'NUMERIC',
44
-         'FLOAT',
45
-         'DOUBLE PRECISION',
46
-         'REAL',
47
-         'SMALLINT',
48
-         'MEDIUMINT',
49
-         'BIGINT',
50
-         'BIT'
51
-      );
52
-      $this->dataTypes['string'] = array (
53
-         'CHAR',
54
-         'VARCHAR',
55
-         'BINARY',
56
-         'VARBINARY',
57
-         'TINYBLOB',
58
-         'BLOB',
59
-         'MEDIUMBLOB',
60
-         'LONGBLOB',
61
-         'TINYTEXT',
62
-         'TEXT',
63
-         'MEDIUMTEXT',
64
-         'LONGTEXT',
65
-         'ENUM',
66
-         'SET'
67
-      );
68
-      $this->dataTypes['date'] = array (
69
-         'DATE',
70
-         'DATETIME',
71
-         'TIMESTAMP',
72
-         'TIME',
73
-         'YEAR'
74
-      );
75
-   }
30
+    /**
31
+     * @name:  initDataTypes
32
+     * @desc:  called in the constructor to set up arrays containing the types
33
+     *         of database fields that can be used with specific PHP types
34
+     */
35
+    function initDataTypes() {
36
+        $this->dataTypes['numeric'] = array (
37
+            'INT',
38
+            'INTEGER',
39
+            'TINYINT',
40
+            'BOOLEAN',
41
+            'DECIMAL',
42
+            'DEC',
43
+            'NUMERIC',
44
+            'FLOAT',
45
+            'DOUBLE PRECISION',
46
+            'REAL',
47
+            'SMALLINT',
48
+            'MEDIUMINT',
49
+            'BIGINT',
50
+            'BIT'
51
+        );
52
+        $this->dataTypes['string'] = array (
53
+            'CHAR',
54
+            'VARCHAR',
55
+            'BINARY',
56
+            'VARBINARY',
57
+            'TINYBLOB',
58
+            'BLOB',
59
+            'MEDIUMBLOB',
60
+            'LONGBLOB',
61
+            'TINYTEXT',
62
+            'TEXT',
63
+            'MEDIUMTEXT',
64
+            'LONGTEXT',
65
+            'ENUM',
66
+            'SET'
67
+        );
68
+        $this->dataTypes['date'] = array (
69
+            'DATE',
70
+            'DATETIME',
71
+            'TIMESTAMP',
72
+            'TIME',
73
+            'YEAR'
74
+        );
75
+    }
76 76
 
77
-   /**
78
-    * @name:  connect
79
-    *
80
-    */
81
-   function connect($host = '', $dbase = '', $uid = '', $pwd = '', $persist = 0) {
82
-      global $modx;
83
-      $uid = $uid ? $uid : $this->config['user'];
84
-      $pwd = $pwd ? $pwd : $this->config['pass'];
85
-      $host = $host ? $host : $this->config['host'];
86
-      $dbase = $dbase ? $dbase : $this->config['dbase'];
87
-      $charset = $this->config['charset'];
88
-      $connection_method = $this->config['connection_method'];
89
-      $tstart = $modx->getMicroTime();
90
-      $safe_count = 0;
91
-      while(!$this->conn && $safe_count<3)
92
-      {
93
-          if($persist!=0) $this->conn = mysql_pconnect($host, $uid, $pwd);
94
-          else            $this->conn = mysql_connect($host, $uid, $pwd, true);
77
+    /**
78
+     * @name:  connect
79
+     *
80
+     */
81
+    function connect($host = '', $dbase = '', $uid = '', $pwd = '', $persist = 0) {
82
+        global $modx;
83
+        $uid = $uid ? $uid : $this->config['user'];
84
+        $pwd = $pwd ? $pwd : $this->config['pass'];
85
+        $host = $host ? $host : $this->config['host'];
86
+        $dbase = $dbase ? $dbase : $this->config['dbase'];
87
+        $charset = $this->config['charset'];
88
+        $connection_method = $this->config['connection_method'];
89
+        $tstart = $modx->getMicroTime();
90
+        $safe_count = 0;
91
+        while(!$this->conn && $safe_count<3)
92
+        {
93
+            if($persist!=0) $this->conn = mysql_pconnect($host, $uid, $pwd);
94
+            else            $this->conn = mysql_connect($host, $uid, $pwd, true);
95 95
           
96
-          if(!$this->conn)
97
-          {
96
+            if(!$this->conn)
97
+            {
98 98
             if(isset($modx->config['send_errormail']) && $modx->config['send_errormail'] !== '0')
99 99
             {
100
-               if($modx->config['send_errormail'] <= 2)
101
-               {
102
-                  $logtitle    = 'Failed to create the database connection!';
103
-                  $request_uri = $modx->htmlspecialchars($_SERVER['REQUEST_URI']);
104
-                  $ua          = $modx->htmlspecialchars($_SERVER['HTTP_USER_AGENT']);
105
-                  $referer     = $modx->htmlspecialchars($_SERVER['HTTP_REFERER']);
100
+                if($modx->config['send_errormail'] <= 2)
101
+                {
102
+                    $logtitle    = 'Failed to create the database connection!';
103
+                    $request_uri = $modx->htmlspecialchars($_SERVER['REQUEST_URI']);
104
+                    $ua          = $modx->htmlspecialchars($_SERVER['HTTP_USER_AGENT']);
105
+                    $referer     = $modx->htmlspecialchars($_SERVER['HTTP_REFERER']);
106 106
 
107
-                  $modx->sendmail(array(
108
-					  'subject' => 'Missing to create the database connection! from ' . $modx->config['site_name'],
109
-					  'body' => "{$logtitle}\n{$request_uri}\n{$ua}\n{$referer}",
110
-					  'type' => 'text')
111
-				  );
112
-               }
107
+                    $modx->sendmail(array(
108
+                        'subject' => 'Missing to create the database connection! from ' . $modx->config['site_name'],
109
+                        'body' => "{$logtitle}\n{$request_uri}\n{$ua}\n{$referer}",
110
+                        'type' => 'text')
111
+                    );
112
+                }
113 113
             }
114 114
             sleep(1);
115 115
             $safe_count++;
116
-          }
117
-      }
118
-      if (!$this->conn) {
119
-         $modx->messageQuit("Failed to create the database connection!");
120
-         exit;
121
-      } else {
122
-         $dbase = trim($dbase,'`'); // remove the `` chars
123
-         if (!@ mysql_select_db($dbase, $this->conn)) {
116
+            }
117
+        }
118
+        if (!$this->conn) {
119
+            $modx->messageQuit("Failed to create the database connection!");
120
+            exit;
121
+        } else {
122
+            $dbase = trim($dbase,'`'); // remove the `` chars
123
+            if (!@ mysql_select_db($dbase, $this->conn)) {
124 124
             $modx->messageQuit("Failed to select the database '" . $dbase . "'!");
125 125
             exit;
126
-         }
127
-         @mysql_query("{$connection_method} {$charset}", $this->conn);
128
-         $tend = $modx->getMicroTime();
129
-         $totaltime = $tend - $tstart;
130
-         if ($modx->dumpSQL) {
126
+            }
127
+            @mysql_query("{$connection_method} {$charset}", $this->conn);
128
+            $tend = $modx->getMicroTime();
129
+            $totaltime = $tend - $tstart;
130
+            if ($modx->dumpSQL) {
131 131
             $modx->queryCode .= "<fieldset style='text-align:left'><legend>Database connection</legend>" . sprintf("Database connection was created in %2.4f s", $totaltime) . "</fieldset><br />";
132
-         }
132
+            }
133 133
             if (function_exists('mysql_set_charset')) {
134 134
                 mysql_set_charset($this->config['charset']);
135 135
             } else {
136 136
                 @mysql_query("SET NAMES {$this->config['charset']}", $this->conn);
137 137
             }
138
-         $this->isConnected = true;
139
-         // FIXME (Fixed by line below):
140
-         // this->queryTime = this->queryTime + $totaltime;
141
-         $modx->queryTime += $totaltime;
142
-      }
143
-   }
138
+            $this->isConnected = true;
139
+            // FIXME (Fixed by line below):
140
+            // this->queryTime = this->queryTime + $totaltime;
141
+            $modx->queryTime += $totaltime;
142
+        }
143
+    }
144 144
 
145
-   /**
146
-    * @name:  disconnect
147
-    *
148
-    */
149
-   function disconnect() {
150
-      @ mysql_close($this->conn);
151
-      $this->conn = null;
152
-      $this->isConnected = false;
153
-   }
145
+    /**
146
+     * @name:  disconnect
147
+     *
148
+     */
149
+    function disconnect() {
150
+        @ mysql_close($this->conn);
151
+        $this->conn = null;
152
+        $this->isConnected = false;
153
+    }
154 154
 
155
-   function escape($s, $safecount=0) {
155
+    function escape($s, $safecount=0) {
156 156
       
157
-      $safecount++;
158
-      if(1000<$safecount) exit("Too many loops '{$safecount}'");
157
+        $safecount++;
158
+        if(1000<$safecount) exit("Too many loops '{$safecount}'");
159 159
       
160
-      if (empty ($this->conn) || !is_resource($this->conn)) {
161
-         $this->connect();
162
-       }
160
+        if (empty ($this->conn) || !is_resource($this->conn)) {
161
+            $this->connect();
162
+        }
163 163
        
164
-      if(is_array($s)) {
165
-          if(count($s) === 0) $s = '';
166
-          else {
167
-              foreach($s as $i=>$v) {
168
-                  $s[$i] = $this->escape($v,$safecount);
169
-              }
170
-          }
171
-      }
172
-      else $s = mysql_real_escape_string($s, $this->conn);
173
-          return $s;
174
-   }
164
+        if(is_array($s)) {
165
+            if(count($s) === 0) $s = '';
166
+            else {
167
+                foreach($s as $i=>$v) {
168
+                    $s[$i] = $this->escape($v,$safecount);
169
+                }
170
+            }
171
+        }
172
+        else $s = mysql_real_escape_string($s, $this->conn);
173
+            return $s;
174
+    }
175 175
 
176
-   /**
177
-    * @name:  query
178
-    * @desc:  Mainly for internal use.
179
-    * Developers should use select, update, insert, delete where possible
180
-    */
181
-   function query($sql,$watchError=true) {
182
-      global $modx;
183
-      if (empty ($this->conn) || !is_resource($this->conn)) {
184
-         $this->connect();
185
-      }
186
-      $tstart = $modx->getMicroTime();
187
-      if(is_array($sql)) $sql = join("\n", $sql);
188
-      $this->lastQuery = $sql;
189
-      if (!$result = @ mysql_query($sql, $this->conn)) {
190
-         if(!$watchError) return;
176
+    /**
177
+     * @name:  query
178
+     * @desc:  Mainly for internal use.
179
+     * Developers should use select, update, insert, delete where possible
180
+     */
181
+    function query($sql,$watchError=true) {
182
+        global $modx;
183
+        if (empty ($this->conn) || !is_resource($this->conn)) {
184
+            $this->connect();
185
+        }
186
+        $tstart = $modx->getMicroTime();
187
+        if(is_array($sql)) $sql = join("\n", $sql);
188
+        $this->lastQuery = $sql;
189
+        if (!$result = @ mysql_query($sql, $this->conn)) {
190
+            if(!$watchError) return;
191 191
             switch(mysql_errno()) {
192 192
                 case 1054:
193 193
                 case 1060:
@@ -198,11 +198,11 @@  discard block
 block discarded – undo
198 198
                 default:
199 199
                     $modx->messageQuit('Execution of a query to the database failed - ' . $this->getLastError(), $sql);
200 200
             }
201
-      } else {
202
-         $tend = $modx->getMicroTime();
203
-         $totaltime = $tend - $tstart;
204
-         $modx->queryTime = $modx->queryTime + $totaltime;
205
-         if ($modx->dumpSQL) {
201
+        } else {
202
+            $tend = $modx->getMicroTime();
203
+            $totaltime = $tend - $tstart;
204
+            $modx->queryTime = $modx->queryTime + $totaltime;
205
+            if ($modx->dumpSQL) {
206 206
             $debug = debug_backtrace();
207 207
             array_shift($debug);	
208 208
             $debug_path = array();
@@ -217,124 +217,124 @@  discard block
 block discarded – undo
217 217
             else $modx->queryCode .= 'Affected Rows => ' . $this->getAffectedRows() . '<br>';
218 218
             $modx->queryCode .= 'Functions Path => ' . $debug_path . '<br>';
219 219
             $modx->queryCode .= "</fieldset><br />";
220
-         }
221
-         $modx->executedQueries = $modx->executedQueries + 1;
222
-         return $result;
223
-      }
224
-   }
220
+            }
221
+            $modx->executedQueries = $modx->executedQueries + 1;
222
+            return $result;
223
+        }
224
+    }
225 225
 
226
-   /**
227
-    * @name:  delete
228
-    *
229
-    */
230
-   function delete($from, $where='', $orderby='', $limit = '') {
231
-      global $modx;
232
-      if (!$from)
233
-         $modx->messageQuit("Empty \$from parameters in DBAPI::delete().");
234
-      else {
235
-         $from = $this->replaceFullTableName($from);
236
-         $where   = trim($where);
237
-         $orderby = trim($orderby);
238
-         $limit   = trim($limit);
239
-         if($where!==''   && stripos($where,   'WHERE')!==0)    $where   = "WHERE {$where}";
240
-         if($orderby!=='' && stripos($orderby, 'ORDER BY')!==0) $orderby = "ORDER BY {$orderby}";
241
-         if($limit!==''   && stripos($limit,   'LIMIT')!==0)    $limit   = "LIMIT {$limit}";
242
-         return $this->query("DELETE FROM {$from} {$where} {$orderby} {$limit}");
243
-      }
244
-   }
226
+    /**
227
+     * @name:  delete
228
+     *
229
+     */
230
+    function delete($from, $where='', $orderby='', $limit = '') {
231
+        global $modx;
232
+        if (!$from)
233
+            $modx->messageQuit("Empty \$from parameters in DBAPI::delete().");
234
+        else {
235
+            $from = $this->replaceFullTableName($from);
236
+            $where   = trim($where);
237
+            $orderby = trim($orderby);
238
+            $limit   = trim($limit);
239
+            if($where!==''   && stripos($where,   'WHERE')!==0)    $where   = "WHERE {$where}";
240
+            if($orderby!=='' && stripos($orderby, 'ORDER BY')!==0) $orderby = "ORDER BY {$orderby}";
241
+            if($limit!==''   && stripos($limit,   'LIMIT')!==0)    $limit   = "LIMIT {$limit}";
242
+            return $this->query("DELETE FROM {$from} {$where} {$orderby} {$limit}");
243
+        }
244
+    }
245 245
 
246
-   /**
247
-    * @name:  select
248
-    *
249
-    */
250
-   function select($fields = "*", $from = "", $where = "", $orderby = "", $limit = "") {
251
-      global $modx;
246
+    /**
247
+     * @name:  select
248
+     *
249
+     */
250
+    function select($fields = "*", $from = "", $where = "", $orderby = "", $limit = "") {
251
+        global $modx;
252 252
       
253
-      if(is_array($fields)) $fields = $this->_getFieldsStringFromArray($fields);
254
-      if(is_array($from))   $from   = $this->_getFromStringFromArray($from);
255
-      if(is_array($where))  $where  = join(' ', $where);
253
+        if(is_array($fields)) $fields = $this->_getFieldsStringFromArray($fields);
254
+        if(is_array($from))   $from   = $this->_getFromStringFromArray($from);
255
+        if(is_array($where))  $where  = join(' ', $where);
256 256
       
257
-      if (!$from) {
258
-         $modx->messageQuit("Empty \$from parameters in DBAPI::select().");
259
-         exit;
260
-      }
257
+        if (!$from) {
258
+            $modx->messageQuit("Empty \$from parameters in DBAPI::select().");
259
+            exit;
260
+        }
261 261
       
262
-      $fields = $this->replaceFullTableName($fields);
263
-      $from = $this->replaceFullTableName($from);
264
-      $where   = trim($where);
265
-      $orderby = trim($orderby);
266
-      $limit   = trim($limit);
267
-      if($where!==''   && stripos($where,'WHERE')!==0)   $where   = "WHERE {$where}";
268
-      if($orderby!=='' && stripos($orderby,'ORDER')!==0) $orderby = "ORDER BY {$orderby}";
269
-      if($limit!==''   && stripos($limit,'LIMIT')!==0)   $limit   = "LIMIT {$limit}";
270
-      return $this->query("SELECT {$fields} FROM {$from} {$where} {$orderby} {$limit}");
271
-   }
262
+        $fields = $this->replaceFullTableName($fields);
263
+        $from = $this->replaceFullTableName($from);
264
+        $where   = trim($where);
265
+        $orderby = trim($orderby);
266
+        $limit   = trim($limit);
267
+        if($where!==''   && stripos($where,'WHERE')!==0)   $where   = "WHERE {$where}";
268
+        if($orderby!=='' && stripos($orderby,'ORDER')!==0) $orderby = "ORDER BY {$orderby}";
269
+        if($limit!==''   && stripos($limit,'LIMIT')!==0)   $limit   = "LIMIT {$limit}";
270
+        return $this->query("SELECT {$fields} FROM {$from} {$where} {$orderby} {$limit}");
271
+    }
272 272
 
273
-   /**
274
-    * @name:  update
275
-    *
276
-    */
277
-   function update($fields, $table, $where = "") {
278
-      global $modx;
279
-      if (!$table)
280
-         $modx->messageQuit("Empty \$table parameter in DBAPI::update().");
281
-      else {
282
-         $table = $this->replaceFullTableName($table);
283
-         if (is_array($fields)) {
284
-			 foreach ($fields as $key => $value) {
285
-				 if(is_null($value) || strtolower($value) === 'null'){
286
-					 $flds = 'NULL';
287
-				 }else{
288
-					 $flds = "'" . $value . "'";
289
-				 }
290
-				 $fields[$key] = "`{$key}` = ".$flds;
291
-			 }
273
+    /**
274
+     * @name:  update
275
+     *
276
+     */
277
+    function update($fields, $table, $where = "") {
278
+        global $modx;
279
+        if (!$table)
280
+            $modx->messageQuit("Empty \$table parameter in DBAPI::update().");
281
+        else {
282
+            $table = $this->replaceFullTableName($table);
283
+            if (is_array($fields)) {
284
+                foreach ($fields as $key => $value) {
285
+                    if(is_null($value) || strtolower($value) === 'null'){
286
+                        $flds = 'NULL';
287
+                    }else{
288
+                        $flds = "'" . $value . "'";
289
+                    }
290
+                    $fields[$key] = "`{$key}` = ".$flds;
291
+                }
292 292
             $fields = implode(",", $fields);
293
-         }
294
-         $where = trim($where);
295
-         if($where!=='' && stripos($where, 'WHERE')!==0) $where = "WHERE {$where}";
296
-         return $this->query("UPDATE {$table} SET {$fields} {$where}");
297
-      }
298
-   }
293
+            }
294
+            $where = trim($where);
295
+            if($where!=='' && stripos($where, 'WHERE')!==0) $where = "WHERE {$where}";
296
+            return $this->query("UPDATE {$table} SET {$fields} {$where}");
297
+        }
298
+    }
299 299
 
300
-   /**
301
-    * @name:  insert
302
-    * @desc:  returns either last id inserted or the result from the query
303
-    */
304
-   function insert($fields, $intotable, $fromfields = "*", $fromtable = "", $where = "", $limit = "") {
305
-      global $modx;
306
-      if (!$intotable)
307
-         $modx->messageQuit("Empty \$intotable parameters in DBAPI::insert().");
308
-      else {
309
-         $intotable = $this->replaceFullTableName($intotable);
310
-         if (!is_array($fields)) {
300
+    /**
301
+     * @name:  insert
302
+     * @desc:  returns either last id inserted or the result from the query
303
+     */
304
+    function insert($fields, $intotable, $fromfields = "*", $fromtable = "", $where = "", $limit = "") {
305
+        global $modx;
306
+        if (!$intotable)
307
+            $modx->messageQuit("Empty \$intotable parameters in DBAPI::insert().");
308
+        else {
309
+            $intotable = $this->replaceFullTableName($intotable);
310
+            if (!is_array($fields)) {
311 311
             $this->query("INSERT INTO {$intotable} {$fields}");
312
-         } else {
312
+            } else {
313 313
             if (empty($fromtable)) {
314
-               $fields = "(`".implode("`, `", array_keys($fields))."`) VALUES('".implode("', '", array_values($fields))."')";
315
-               $rt = $this->query("INSERT INTO {$intotable} {$fields}");
314
+                $fields = "(`".implode("`, `", array_keys($fields))."`) VALUES('".implode("', '", array_values($fields))."')";
315
+                $rt = $this->query("INSERT INTO {$intotable} {$fields}");
316 316
             } else {
317
-               if (version_compare($this->getVersion(),"4.0.14")>=0) {
318
-                  $fromtable = $this->replaceFullTableName($fromtable);
319
-                  $fields = "(".implode(",", array_keys($fields)).")";
320
-                  $where = trim($where);
321
-                  $limit = trim($limit);
322
-                  if($where!=='' && stripos($where, 'WHERE')!==0) $where = "WHERE {$where}";
323
-                  if($limit!=='' && stripos($limit, 'LIMIT')!==0) $limit = "LIMIT {$limit}";
324
-                  $rt = $this->query("INSERT INTO {$intotable} {$fields} SELECT {$fromfields} FROM {$fromtable} {$where} {$limit}");
325
-               } else {
326
-                  $ds = $this->select($fromfields, $fromtable, $where, '', $limit);
327
-                  while ($row = $this->getRow($ds)) {
328
-                     $fields = "(".implode(",", array_keys($fields)).") VALUES('".implode("', '", $row)."')";
329
-                     $rt = $this->query("INSERT INTO {$intotable} {$fields}");
330
-                  }
331
-               }
317
+                if (version_compare($this->getVersion(),"4.0.14")>=0) {
318
+                    $fromtable = $this->replaceFullTableName($fromtable);
319
+                    $fields = "(".implode(",", array_keys($fields)).")";
320
+                    $where = trim($where);
321
+                    $limit = trim($limit);
322
+                    if($where!=='' && stripos($where, 'WHERE')!==0) $where = "WHERE {$where}";
323
+                    if($limit!=='' && stripos($limit, 'LIMIT')!==0) $limit = "LIMIT {$limit}";
324
+                    $rt = $this->query("INSERT INTO {$intotable} {$fields} SELECT {$fromfields} FROM {$fromtable} {$where} {$limit}");
325
+                } else {
326
+                    $ds = $this->select($fromfields, $fromtable, $where, '', $limit);
327
+                    while ($row = $this->getRow($ds)) {
328
+                        $fields = "(".implode(",", array_keys($fields)).") VALUES('".implode("', '", $row)."')";
329
+                        $rt = $this->query("INSERT INTO {$intotable} {$fields}");
330
+                    }
331
+                }
332
+            }
332 333
             }
333
-         }
334
-         if (($lid = $this->getInsertId())===false) $modx->messageQuit("Couldn't get last insert key!");
335
-         return $lid;
336
-      }
337
-   }
334
+            if (($lid = $this->getInsertId())===false) $modx->messageQuit("Couldn't get last insert key!");
335
+            return $lid;
336
+        }
337
+    }
338 338
    
339 339
     function save($fields, $table, $where='') {
340 340
         
@@ -346,277 +346,277 @@  discard block
 block discarded – undo
346 346
         else                 return $this->update($fields, $table, $where);
347 347
     }
348 348
     
349
-   /**
350
-    * @name:  isResult
351
-    *
352
-    */
353
-   function isResult($rs) {
354
-      return is_resource($rs);
355
-   }
349
+    /**
350
+     * @name:  isResult
351
+     *
352
+     */
353
+    function isResult($rs) {
354
+        return is_resource($rs);
355
+    }
356 356
 
357
-   /**
358
-    * @name:  freeResult
359
-    *
360
-    */
361
-   function freeResult($rs) {
362
-      mysql_free_result($rs);
363
-   }
357
+    /**
358
+     * @name:  freeResult
359
+     *
360
+     */
361
+    function freeResult($rs) {
362
+        mysql_free_result($rs);
363
+    }
364 364
    
365
-   /**
366
-    * @name:  numFields
367
-    *
368
-    */
369
-   function numFields($rs) {
370
-      return mysql_num_fields($rs);
371
-   }
365
+    /**
366
+     * @name:  numFields
367
+     *
368
+     */
369
+    function numFields($rs) {
370
+        return mysql_num_fields($rs);
371
+    }
372 372
    
373
-   /**
374
-    * @name:  fieldName
375
-    *
376
-    */
377
-   function fieldName($rs,$col=0) {
378
-      return mysql_field_name($rs,$col);
379
-   }
373
+    /**
374
+     * @name:  fieldName
375
+     *
376
+     */
377
+    function fieldName($rs,$col=0) {
378
+        return mysql_field_name($rs,$col);
379
+    }
380 380
    
381 381
     /**
382
-    * @name:  selectDb
383
-    *
384
-    */
385
-   function selectDb($name) {
386
-      mysql_select_db($name);
387
-   }
382
+     * @name:  selectDb
383
+     *
384
+     */
385
+    function selectDb($name) {
386
+        mysql_select_db($name);
387
+    }
388 388
    
389 389
 
390
-   /**
391
-    * @name:  getInsertId
392
-    *
393
-    */
394
-   function getInsertId($conn=NULL) {
395
-      if( !is_resource($conn)) $conn =& $this->conn;
396
-      return mysql_insert_id($conn);
397
-   }
390
+    /**
391
+     * @name:  getInsertId
392
+     *
393
+     */
394
+    function getInsertId($conn=NULL) {
395
+        if( !is_resource($conn)) $conn =& $this->conn;
396
+        return mysql_insert_id($conn);
397
+    }
398 398
 
399
-   /**
400
-    * @name:  getAffectedRows
401
-    *
402
-    */
403
-   function getAffectedRows($conn=NULL) {
404
-      if (!is_resource($conn)) $conn =& $this->conn;
405
-      return mysql_affected_rows($conn);
406
-   }
399
+    /**
400
+     * @name:  getAffectedRows
401
+     *
402
+     */
403
+    function getAffectedRows($conn=NULL) {
404
+        if (!is_resource($conn)) $conn =& $this->conn;
405
+        return mysql_affected_rows($conn);
406
+    }
407 407
 
408
-   /**
409
-    * @name:  getLastError
410
-    *
411
-    */
412
-   function getLastError($conn=NULL) {
413
-      if (!is_resource($conn)) $conn =& $this->conn;
414
-      return mysql_error($conn);
415
-   }
408
+    /**
409
+     * @name:  getLastError
410
+     *
411
+     */
412
+    function getLastError($conn=NULL) {
413
+        if (!is_resource($conn)) $conn =& $this->conn;
414
+        return mysql_error($conn);
415
+    }
416 416
 
417
-   /**
418
-    * @name:  getRecordCount
419
-    *
420
-    */
421
-   function getRecordCount($ds) {
422
-      return (is_resource($ds)) ? mysql_num_rows($ds) : 0;
423
-   }
417
+    /**
418
+     * @name:  getRecordCount
419
+     *
420
+     */
421
+    function getRecordCount($ds) {
422
+        return (is_resource($ds)) ? mysql_num_rows($ds) : 0;
423
+    }
424 424
 
425
-   /**
426
-    * @name:  getRow
427
-    * @desc:  returns an array of column values
428
-    * @param: $dsq - dataset
429
-    *
430
-    */
431
-   function getRow($ds, $mode = 'assoc') {
432
-      if (is_resource($ds)) {
433
-         if ($mode == 'assoc') {
425
+    /**
426
+     * @name:  getRow
427
+     * @desc:  returns an array of column values
428
+     * @param: $dsq - dataset
429
+     *
430
+     */
431
+    function getRow($ds, $mode = 'assoc') {
432
+        if (is_resource($ds)) {
433
+            if ($mode == 'assoc') {
434 434
             return mysql_fetch_assoc($ds);
435
-         }
436
-         elseif ($mode == 'num') {
435
+            }
436
+            elseif ($mode == 'num') {
437 437
             return mysql_fetch_row($ds);
438
-         }
439
-		 elseif ($mode == 'object') {
438
+            }
439
+            elseif ($mode == 'object') {
440 440
             return mysql_fetch_object($ds);
441
-         }
442
-         elseif ($mode == 'both') {
441
+            }
442
+            elseif ($mode == 'both') {
443 443
             return mysql_fetch_array($ds, MYSQL_BOTH);
444
-         } else {
444
+            } else {
445 445
             global $modx;
446 446
             $modx->messageQuit("Unknown get type ($mode) specified for fetchRow - must be empty, 'assoc', 'num' or 'both'.");
447
-         }
448
-      }
449
-   }
447
+            }
448
+        }
449
+    }
450 450
 
451
-   /**
452
-    * @name:  getColumn
453
-    * @desc:  returns an array of the values found on colun $name
454
-    * @param: $dsq - dataset or query string
455
-    */
456
-   function getColumn($name, $dsq) {
457
-      if (!is_resource($dsq))
458
-         $dsq = $this->query($dsq);
459
-      if ($dsq) {
460
-         $col = array ();
461
-         while ($row = $this->getRow($dsq)) {
451
+    /**
452
+     * @name:  getColumn
453
+     * @desc:  returns an array of the values found on colun $name
454
+     * @param: $dsq - dataset or query string
455
+     */
456
+    function getColumn($name, $dsq) {
457
+        if (!is_resource($dsq))
458
+            $dsq = $this->query($dsq);
459
+        if ($dsq) {
460
+            $col = array ();
461
+            while ($row = $this->getRow($dsq)) {
462 462
             $col[] = $row[$name];
463
-         }
464
-         return $col;
465
-      }
466
-   }
463
+            }
464
+            return $col;
465
+        }
466
+    }
467 467
 
468
-   /**
469
-    * @name:  getColumnNames
470
-    * @desc:  returns an array containing the column $name
471
-    * @param: $dsq - dataset or query string
472
-    */
473
-   function getColumnNames($dsq) {
474
-      if (!is_resource($dsq))
475
-         $dsq = $this->query($dsq);
476
-      if ($dsq) {
477
-         $names = array ();
478
-         $limit = mysql_num_fields($dsq);
479
-         for ($i = 0; $i < $limit; $i++) {
468
+    /**
469
+     * @name:  getColumnNames
470
+     * @desc:  returns an array containing the column $name
471
+     * @param: $dsq - dataset or query string
472
+     */
473
+    function getColumnNames($dsq) {
474
+        if (!is_resource($dsq))
475
+            $dsq = $this->query($dsq);
476
+        if ($dsq) {
477
+            $names = array ();
478
+            $limit = mysql_num_fields($dsq);
479
+            for ($i = 0; $i < $limit; $i++) {
480 480
             $names[] = mysql_field_name($dsq, $i);
481
-         }
482
-         return $names;
483
-      }
484
-   }
481
+            }
482
+            return $names;
483
+        }
484
+    }
485 485
 
486
-   /**
487
-    * @name:  getValue
488
-    * @desc:  returns the value from the first column in the set
489
-    * @param: $dsq - dataset or query string
490
-    */
491
-   function getValue($dsq) {
492
-      if (!is_resource($dsq))
493
-         $dsq = $this->query($dsq);
494
-      if ($dsq) {
495
-         $r = $this->getRow($dsq, "num");
496
-         return $r[0];
497
-      }
498
-   }
486
+    /**
487
+     * @name:  getValue
488
+     * @desc:  returns the value from the first column in the set
489
+     * @param: $dsq - dataset or query string
490
+     */
491
+    function getValue($dsq) {
492
+        if (!is_resource($dsq))
493
+            $dsq = $this->query($dsq);
494
+        if ($dsq) {
495
+            $r = $this->getRow($dsq, "num");
496
+            return $r[0];
497
+        }
498
+    }
499 499
 
500
-   /**
501
-    * @name:  getTableMetaData
502
-    * @desc:  returns an array of MySQL structure detail for each column of a
503
-    *         table
504
-    * @param: $table: the full name of the database table
505
-    */
506
-   function getTableMetaData($table) {
507
-      $metadata = false;
508
-      if (!empty ($table)) {
509
-         $sql = "SHOW FIELDS FROM $table";
510
-         if ($ds = $this->query($sql)) {
500
+    /**
501
+     * @name:  getTableMetaData
502
+     * @desc:  returns an array of MySQL structure detail for each column of a
503
+     *         table
504
+     * @param: $table: the full name of the database table
505
+     */
506
+    function getTableMetaData($table) {
507
+        $metadata = false;
508
+        if (!empty ($table)) {
509
+            $sql = "SHOW FIELDS FROM $table";
510
+            if ($ds = $this->query($sql)) {
511 511
             while ($row = $this->getRow($ds)) {
512
-               $fieldName = $row['Field'];
513
-               $metadata[$fieldName] = $row;
512
+                $fieldName = $row['Field'];
513
+                $metadata[$fieldName] = $row;
514
+            }
514 515
             }
515
-         }
516
-      }
517
-      return $metadata;
518
-   }
516
+        }
517
+        return $metadata;
518
+    }
519 519
 
520
-   /**
521
-    * @name:  prepareDate
522
-    * @desc:  prepares a date in the proper format for specific database types
523
-    *         given a UNIX timestamp
524
-    * @param: $timestamp: a UNIX timestamp
525
-    * @param: $fieldType: the type of field to format the date for
526
-    *         (in MySQL, you have DATE, TIME, YEAR, and DATETIME)
527
-    */
528
-   function prepareDate($timestamp, $fieldType = 'DATETIME') {
529
-      $date = '';
530
-      if (!$timestamp === false && $timestamp > 0) {
531
-         switch ($fieldType) {
520
+    /**
521
+     * @name:  prepareDate
522
+     * @desc:  prepares a date in the proper format for specific database types
523
+     *         given a UNIX timestamp
524
+     * @param: $timestamp: a UNIX timestamp
525
+     * @param: $fieldType: the type of field to format the date for
526
+     *         (in MySQL, you have DATE, TIME, YEAR, and DATETIME)
527
+     */
528
+    function prepareDate($timestamp, $fieldType = 'DATETIME') {
529
+        $date = '';
530
+        if (!$timestamp === false && $timestamp > 0) {
531
+            switch ($fieldType) {
532 532
             case 'DATE' :
533 533
                $date = date('Y-m-d', $timestamp);
534
-               break;
534
+                break;
535 535
             case 'TIME' :
536 536
                $date = date('H:i:s', $timestamp);
537
-               break;
537
+                break;
538 538
             case 'YEAR' :
539 539
                $date = date('Y', $timestamp);
540
-               break;
540
+                break;
541 541
             default :
542 542
                $date = date('Y-m-d H:i:s', $timestamp);
543
-               break;
544
-         }
545
-      }
546
-      return $date;
547
-   }
543
+                break;
544
+            }
545
+        }
546
+        return $date;
547
+    }
548 548
 
549
-   /**
550
-   * @name:  makeArray
551
-   * @desc:  turns a recordset into a multidimensional array
552
-   * @return: an array of row arrays from recordset, or empty array
553
-   *          if the recordset was empty, returns false if no recordset
554
-   *          was passed
555
-   * @param: $rs Recordset to be packaged into an array
556
-   */
557
-	function makeArray($rs='',$index=false){
558
-		if (!$rs) return false;
559
-		$rsArray = array();
560
-		$iterator = 0;
561
-		while ($row = $this->getRow($rs)) {
562
-			$returnIndex = $index !== false && isset($row[$index]) ? $row[$index] : $iterator;
563
-			$rsArray[$returnIndex] = $row;
564
-			$iterator++;
565
-		}
566
-		return $rsArray;
567
-	}
549
+    /**
550
+     * @name:  makeArray
551
+     * @desc:  turns a recordset into a multidimensional array
552
+     * @return: an array of row arrays from recordset, or empty array
553
+     *          if the recordset was empty, returns false if no recordset
554
+     *          was passed
555
+     * @param: $rs Recordset to be packaged into an array
556
+     */
557
+    function makeArray($rs='',$index=false){
558
+        if (!$rs) return false;
559
+        $rsArray = array();
560
+        $iterator = 0;
561
+        while ($row = $this->getRow($rs)) {
562
+            $returnIndex = $index !== false && isset($row[$index]) ? $row[$index] : $iterator;
563
+            $rsArray[$returnIndex] = $row;
564
+            $iterator++;
565
+        }
566
+        return $rsArray;
567
+    }
568 568
    
569
-   /**
570
-    * @name	getVersion
571
-    * @desc	returns a string containing the database server version
572
-    *
573
-    * @return string
574
-    */
575
-   function getVersion() {
576
-       return mysql_get_server_info();
577
-   }
569
+    /**
570
+     * @name	getVersion
571
+     * @desc	returns a string containing the database server version
572
+     *
573
+     * @return string
574
+     */
575
+    function getVersion() {
576
+        return mysql_get_server_info();
577
+    }
578 578
    
579
-   /**
580
-    * @name replaceFullTableName
581
-    * @desc  Get full table name. Append table name and table prefix.
582
-    * 
583
-    * @param string $str
584
-    * @return string 
585
-    */
586
-   function replaceFullTableName($str,$force=null) {
579
+    /**
580
+     * @name replaceFullTableName
581
+     * @desc  Get full table name. Append table name and table prefix.
582
+     * 
583
+     * @param string $str
584
+     * @return string 
585
+     */
586
+    function replaceFullTableName($str,$force=null) {
587 587
        
588
-       $str = trim($str);
589
-       $dbase  = trim($this->config['dbase'],'`');
590
-       $prefix = $this->config['table_prefix'];
591
-       if(!empty($force))
592
-       {
593
-           $result = "`{$dbase}`.`{$prefix}{$str}`";
594
-       }
595
-       elseif(strpos($str,'[+prefix+]')!==false)
596
-       {
597
-           $result = preg_replace('@\[\+prefix\+\]([0-9a-zA-Z_]+)@', "`{$dbase}`.`{$prefix}$1`", $str);
598
-       }
599
-       else $result = $str;
588
+        $str = trim($str);
589
+        $dbase  = trim($this->config['dbase'],'`');
590
+        $prefix = $this->config['table_prefix'];
591
+        if(!empty($force))
592
+        {
593
+            $result = "`{$dbase}`.`{$prefix}{$str}`";
594
+        }
595
+        elseif(strpos($str,'[+prefix+]')!==false)
596
+        {
597
+            $result = preg_replace('@\[\+prefix\+\]([0-9a-zA-Z_]+)@', "`{$dbase}`.`{$prefix}$1`", $str);
598
+        }
599
+        else $result = $str;
600 600
        
601
-       return $result;
602
-   }
601
+        return $result;
602
+    }
603 603
    
604
-   function optimize($table_name)
605
-   {
606
-       $rs = $this->query("OPTIMIZE TABLE {$table_name}");
607
-       if($rs) $rs = $this->query("ALTER TABLE {$table_name}");
608
-       return $rs;
609
-   }
604
+    function optimize($table_name)
605
+    {
606
+        $rs = $this->query("OPTIMIZE TABLE {$table_name}");
607
+        if($rs) $rs = $this->query("ALTER TABLE {$table_name}");
608
+        return $rs;
609
+    }
610 610
    
611
-   function truncate($table_name)
612
-   {
613
-       $rs = $this->query("TRUNCATE {$table_name}");
614
-       return $rs;
615
-   }
611
+    function truncate($table_name)
612
+    {
613
+        $rs = $this->query("TRUNCATE {$table_name}");
614
+        return $rs;
615
+    }
616 616
 
617
-  function dataSeek($result, $row_number) {
617
+    function dataSeek($result, $row_number) {
618 618
     return mysql_data_seek($result, $row_number);
619
-  }
619
+    }
620 620
   
621 621
     function _getFieldsStringFromArray($fields=array()) {
622 622
         
Please login to merge, or discard this patch.
manager/includes/extenders/export.class.inc.php 1 patch
Indentation   +213 added lines, -213 removed lines patch added patch discarded remove patch
@@ -1,258 +1,258 @@  discard block
 block discarded – undo
1 1
 <?php
2 2
 class EXPORT_SITE
3 3
 {
4
-	var $targetDir;
5
-	var $generate_mode;
6
-	var $total;
7
-	var $count;
8
-	var $ignore_ids;
9
-	var $exportstart;
10
-	var $repl_before;
11
-	var $repl_after;
12
-	var $output = array();
4
+    var $targetDir;
5
+    var $generate_mode;
6
+    var $total;
7
+    var $count;
8
+    var $ignore_ids;
9
+    var $exportstart;
10
+    var $repl_before;
11
+    var $repl_after;
12
+    var $output = array();
13 13
 	
14
-	function __construct()
15
-	{
16
-		global $modx;
14
+    function __construct()
15
+    {
16
+        global $modx;
17 17
 		
18
-		if(!defined('MODX_BASE_PATH'))  return false;
19
-		$this->exportstart = $this->get_mtime();
20
-		$this->count = 0;
21
-		$this->setUrlMode();
22
-		$this->dirCheckCount = 0;
23
-		$this->generate_mode = 'crawl';
24
-		$this->targetDir = $modx->config['base_path'] . 'temp/export';
25
-		if(!isset($this->total)) $this->getTotal();
26
-	}
18
+        if(!defined('MODX_BASE_PATH'))  return false;
19
+        $this->exportstart = $this->get_mtime();
20
+        $this->count = 0;
21
+        $this->setUrlMode();
22
+        $this->dirCheckCount = 0;
23
+        $this->generate_mode = 'crawl';
24
+        $this->targetDir = $modx->config['base_path'] . 'temp/export';
25
+        if(!isset($this->total)) $this->getTotal();
26
+    }
27 27
 	
28
-	function setExportDir($dir)
29
-	{
30
-		$dir = str_replace('\\','/',$dir);
31
-		$dir = rtrim($dir, '/');
32
-		$this->targetDir = $dir;
33
-	}
28
+    function setExportDir($dir)
29
+    {
30
+        $dir = str_replace('\\','/',$dir);
31
+        $dir = rtrim($dir, '/');
32
+        $this->targetDir = $dir;
33
+    }
34 34
 	
35
-	function get_mtime()
36
-	{
37
-		$mtime = microtime();
38
-		$mtime = explode(' ', $mtime);
39
-		$mtime = $mtime[1] + $mtime[0];
40
-		return $mtime;
41
-	}
35
+    function get_mtime()
36
+    {
37
+        $mtime = microtime();
38
+        $mtime = explode(' ', $mtime);
39
+        $mtime = $mtime[1] + $mtime[0];
40
+        return $mtime;
41
+    }
42 42
 	
43
-	function setUrlMode()
44
-	{
45
-		global $modx;
43
+    function setUrlMode()
44
+    {
45
+        global $modx;
46 46
 		
47
-		if($modx->config['friendly_urls']==0)
48
-		{
49
-			$modx->config['friendly_urls']  = 1;
50
-			$modx->config['use_alias_path'] = 1;
51
-			$modx->clearCache('full');
52
-		}
53
-		$modx->config['make_folders'] = '1';
54
-	}
47
+        if($modx->config['friendly_urls']==0)
48
+        {
49
+            $modx->config['friendly_urls']  = 1;
50
+            $modx->config['use_alias_path'] = 1;
51
+            $modx->clearCache('full');
52
+        }
53
+        $modx->config['make_folders'] = '1';
54
+    }
55 55
 	
56
-	function getTotal($ignore_ids='', $noncache='0')
57
-	{
58
-		global $modx;
59
-		$tbl_site_content = $modx->getFullTableName('site_content');
56
+    function getTotal($ignore_ids='', $noncache='0')
57
+    {
58
+        global $modx;
59
+        $tbl_site_content = $modx->getFullTableName('site_content');
60 60
 		
61
-		$ignore_ids = array_filter(array_map('intval', explode(',', $ignore_ids)));
62
-		if(count($ignore_ids)>0)
63
-		{
64
-			$ignore_ids = "AND NOT id IN ('".implode("','", $ignore_ids)."')";
65
-		} else {
66
-			$ignore_ids = '';
67
-		}
61
+        $ignore_ids = array_filter(array_map('intval', explode(',', $ignore_ids)));
62
+        if(count($ignore_ids)>0)
63
+        {
64
+            $ignore_ids = "AND NOT id IN ('".implode("','", $ignore_ids)."')";
65
+        } else {
66
+            $ignore_ids = '';
67
+        }
68 68
 		
69
-		$this->ignore_ids = $ignore_ids;
69
+        $this->ignore_ids = $ignore_ids;
70 70
 		
71
-		$noncache = ($noncache == 1) ? '' : 'AND cacheable=1';
72
-		$where = "deleted=0 AND ((published=1 AND type='document') OR (isfolder=1)) {$noncache} {$ignore_ids}";
73
-		$rs  = $modx->db->select('count(id)',$tbl_site_content,$where);
74
-		$this->total = $modx->db->getValue($rs);
75
-		return $this->total;
76
-	}
71
+        $noncache = ($noncache == 1) ? '' : 'AND cacheable=1';
72
+        $where = "deleted=0 AND ((published=1 AND type='document') OR (isfolder=1)) {$noncache} {$ignore_ids}";
73
+        $rs  = $modx->db->select('count(id)',$tbl_site_content,$where);
74
+        $this->total = $modx->db->getValue($rs);
75
+        return $this->total;
76
+    }
77 77
 	
78
-	function removeDirectoryAll($directory='')
79
-	{
80
-		if(empty($directory)) $directory = $this->targetDir;
81
-		$directory = rtrim($directory,'/');
82
-		// if the path is not valid or is not a directory ...
83
-		if(empty($directory)) return false;
84
-		if(strpos($directory,MODX_BASE_PATH)===false) return FALSE;
78
+    function removeDirectoryAll($directory='')
79
+    {
80
+        if(empty($directory)) $directory = $this->targetDir;
81
+        $directory = rtrim($directory,'/');
82
+        // if the path is not valid or is not a directory ...
83
+        if(empty($directory)) return false;
84
+        if(strpos($directory,MODX_BASE_PATH)===false) return FALSE;
85 85
 		
86
-		if(!is_dir($directory))          return FALSE;
87
-		elseif(!is_readable($directory)) return FALSE;
88
-		else
89
-		{
90
-			$files = glob($directory . '/*');
91
-			if(!empty($files))
92
-			{
93
-    			foreach($files as $path)
94
-    			{
95
-    				if(is_dir($path)) $this->removeDirectoryAll($path);
96
-    				else              $rs = unlink($path);
97
-    			}
98
-			}
99
-		}
100
-		if($directory !== $this->targetDir) $rs = rmdir($directory);
86
+        if(!is_dir($directory))          return FALSE;
87
+        elseif(!is_readable($directory)) return FALSE;
88
+        else
89
+        {
90
+            $files = glob($directory . '/*');
91
+            if(!empty($files))
92
+            {
93
+                foreach($files as $path)
94
+                {
95
+                    if(is_dir($path)) $this->removeDirectoryAll($path);
96
+                    else              $rs = unlink($path);
97
+                }
98
+            }
99
+        }
100
+        if($directory !== $this->targetDir) $rs = rmdir($directory);
101 101
 		
102
-		return $rs;
103
-	}
102
+        return $rs;
103
+    }
104 104
 
105
-	function makeFile($docid, $filepath)
106
-	{
107
-		global  $modx,$_lang;
108
-		$file_permission = octdec($modx->config['new_file_permissions']);
109
-		if($this->generate_mode==='direct')
110
-		{
111
-			$back_lang = $_lang;
112
-			$src = $modx->executeParser($docid);
105
+    function makeFile($docid, $filepath)
106
+    {
107
+        global  $modx,$_lang;
108
+        $file_permission = octdec($modx->config['new_file_permissions']);
109
+        if($this->generate_mode==='direct')
110
+        {
111
+            $back_lang = $_lang;
112
+            $src = $modx->executeParser($docid);
113 113
 			
114
-			$_lang = $back_lang;
115
-		}
116
-		else $src = $this->curl_get_contents(MODX_SITE_URL . "index.php?id={$docid}");
114
+            $_lang = $back_lang;
115
+        }
116
+        else $src = $this->curl_get_contents(MODX_SITE_URL . "index.php?id={$docid}");
117 117
 		
118 118
 		
119
-		if($src !== false)
120
-		{
121
-			if($this->repl_before!==$this->repl_after) $src = str_replace($this->repl_before,$this->repl_after,$src);
122
-			$result = file_put_contents($filepath,$src);
123
-			if($result!==false) @chmod($filepath, $file_permission);
119
+        if($src !== false)
120
+        {
121
+            if($this->repl_before!==$this->repl_after) $src = str_replace($this->repl_before,$this->repl_after,$src);
122
+            $result = file_put_contents($filepath,$src);
123
+            if($result!==false) @chmod($filepath, $file_permission);
124 124
 			
125
-			if($result !== false) return 'success';
126
-			else                  return 'failed_no_write';
127
-		}
128
-		else                      return 'failed_no_retrieve';
129
-	}
125
+            if($result !== false) return 'success';
126
+            else                  return 'failed_no_write';
127
+        }
128
+        else                      return 'failed_no_retrieve';
129
+    }
130 130
 
131
-	function getFileName($docid, $alias='', $prefix, $suffix)
132
-	{
133
-		global $modx;
131
+    function getFileName($docid, $alias='', $prefix, $suffix)
132
+    {
133
+        global $modx;
134 134
 		
135
-		if($alias==='') $filename = $prefix.$docid.$suffix;
136
-		else
137
-		{
138
-			if($modx->config['suffix_mode']==='1' && strpos($alias, '.')!==false)
139
-			{
140
-				$suffix = '';
141
-			}
142
-			$filename = $prefix.$alias.$suffix;
143
-		}
144
-		return $filename;
145
-	}
135
+        if($alias==='') $filename = $prefix.$docid.$suffix;
136
+        else
137
+        {
138
+            if($modx->config['suffix_mode']==='1' && strpos($alias, '.')!==false)
139
+            {
140
+                $suffix = '';
141
+            }
142
+            $filename = $prefix.$alias.$suffix;
143
+        }
144
+        return $filename;
145
+    }
146 146
 
147
-	function run($parent=0)
148
-	{
149
-		global $_lang;
150
-		global $modx;
147
+    function run($parent=0)
148
+    {
149
+        global $_lang;
150
+        global $modx;
151 151
 		
152
-		$tbl_site_content = $modx->getFullTableName('site_content');
152
+        $tbl_site_content = $modx->getFullTableName('site_content');
153 153
 		
154
-		$ignore_ids = $this->ignore_ids;
155
-		$dirpath = $this->targetDir . '/';
154
+        $ignore_ids = $this->ignore_ids;
155
+        $dirpath = $this->targetDir . '/';
156 156
 		
157
-		$prefix = $modx->config['friendly_url_prefix'];
158
-		$suffix = $modx->config['friendly_url_suffix'];
157
+        $prefix = $modx->config['friendly_url_prefix'];
158
+        $suffix = $modx->config['friendly_url_suffix'];
159 159
 		
160
-		$tpl = ' <span class="[+status+]">[+msg1+]</span> [+msg2+]</span>';
161
-		$ph = array();
160
+        $tpl = ' <span class="[+status+]">[+msg1+]</span> [+msg2+]</span>';
161
+        $ph = array();
162 162
 		
163
-		$ph['status'] = 'fail';
164
-		$ph['msg1']   = $_lang['export_site_failed'];
165
-		$ph['msg2']   = $_lang["export_site_failed_no_write"] . ' - ' . $dirpath;
166
-		$msg_failed_no_write    = $this->parsePlaceholder($tpl,$ph);
163
+        $ph['status'] = 'fail';
164
+        $ph['msg1']   = $_lang['export_site_failed'];
165
+        $ph['msg2']   = $_lang["export_site_failed_no_write"] . ' - ' . $dirpath;
166
+        $msg_failed_no_write    = $this->parsePlaceholder($tpl,$ph);
167 167
 		
168
-		$ph['msg2']   = $_lang["export_site_failed_no_retrieve"];
169
-		$msg_failed_no_retrieve = $this->parsePlaceholder($tpl,$ph);
168
+        $ph['msg2']   = $_lang["export_site_failed_no_retrieve"];
169
+        $msg_failed_no_retrieve = $this->parsePlaceholder($tpl,$ph);
170 170
 		
171
-		$ph['status'] = 'success';
172
-		$ph['msg1']   = $_lang['export_site_success'];
173
-		$ph['msg2']   = '';
174
-		$msg_success            = $this->parsePlaceholder($tpl,$ph);
171
+        $ph['status'] = 'success';
172
+        $ph['msg1']   = $_lang['export_site_success'];
173
+        $ph['msg2']   = '';
174
+        $msg_success            = $this->parsePlaceholder($tpl,$ph);
175 175
 		
176
-		$ph['msg2']   = $_lang['export_site_success_skip_doc'];
177
-		$msg_success_skip_doc = $this->parsePlaceholder($tpl,$ph);
176
+        $ph['msg2']   = $_lang['export_site_success_skip_doc'];
177
+        $msg_success_skip_doc = $this->parsePlaceholder($tpl,$ph);
178 178
 		
179
-		$ph['msg2']   = $_lang['export_site_success_skip_dir'];
180
-		$msg_success_skip_dir = $this->parsePlaceholder($tpl,$ph);
179
+        $ph['msg2']   = $_lang['export_site_success_skip_dir'];
180
+        $msg_success_skip_dir = $this->parsePlaceholder($tpl,$ph);
181 181
 		
182
-		$fields = "id, alias, pagetitle, isfolder, (content = '' AND template = 0) AS wasNull, published";
183
-		$noncache = $_POST['includenoncache']==1 ? '' : 'AND cacheable=1';
184
-		$where = "parent = '{$parent}' AND deleted=0 AND ((published=1 AND type='document') OR (isfolder=1)) {$noncache} {$ignore_ids}";
185
-		$rs = $modx->db->select($fields,$tbl_site_content,$where);
182
+        $fields = "id, alias, pagetitle, isfolder, (content = '' AND template = 0) AS wasNull, published";
183
+        $noncache = $_POST['includenoncache']==1 ? '' : 'AND cacheable=1';
184
+        $where = "parent = '{$parent}' AND deleted=0 AND ((published=1 AND type='document') OR (isfolder=1)) {$noncache} {$ignore_ids}";
185
+        $rs = $modx->db->select($fields,$tbl_site_content,$where);
186 186
 		
187
-		$ph = array();
188
-		$ph['total']     = $this->total;
189
-		$folder_permission = octdec($modx->config['new_folder_permissions']);
190
-		while($row = $modx->db->getRow($rs))
191
-		{
192
-			$this->count++;
187
+        $ph = array();
188
+        $ph['total']     = $this->total;
189
+        $folder_permission = octdec($modx->config['new_folder_permissions']);
190
+        while($row = $modx->db->getRow($rs))
191
+        {
192
+            $this->count++;
193 193
 			
194
-			$row['count']     = $this->count;
195
-			$row['url'] = $modx->makeUrl($row['id']);
194
+            $row['count']     = $this->count;
195
+            $row['url'] = $modx->makeUrl($row['id']);
196 196
 			
197
-			if (!$row['wasNull'])
198
-			{ // needs writing a document
199
-				$docname = $this->getFileName($row['id'], $row['alias'], $prefix, $suffix);
200
-				$filename = $dirpath.$docname;
201
-				if (!is_file($filename))
202
-				{
203
-					if($row['published']==='1')
204
-					{
205
-						$status = $this->makeFile($row['id'], $filename);
206
-						switch($status)
207
-						{
208
-							case 'failed_no_write'   :
197
+            if (!$row['wasNull'])
198
+            { // needs writing a document
199
+                $docname = $this->getFileName($row['id'], $row['alias'], $prefix, $suffix);
200
+                $filename = $dirpath.$docname;
201
+                if (!is_file($filename))
202
+                {
203
+                    if($row['published']==='1')
204
+                    {
205
+                        $status = $this->makeFile($row['id'], $filename);
206
+                        switch($status)
207
+                        {
208
+                            case 'failed_no_write'   :
209 209
                                                             $row['status'] = $msg_failed_no_write;
210 210
                                                             break;
211
-							case 'failed_no_retrieve':
211
+                            case 'failed_no_retrieve':
212 212
                                                             $row['status'] = $msg_failed_no_retrieve;
213 213
                                                             break;
214
-							default:
214
+                            default:
215 215
                                                             $row['status'] = $msg_success;
216
-						}
217
-					}
218
-					else $row['status'] = $msg_failed_no_retrieve;
219
-				}
220
-				else     $row['status'] = $msg_success_skip_doc;
221
-				$this->output[] = $this->parsePlaceholder($_lang['export_site_exporting_document'], $row);
222
-			}
223
-			else
224
-			{
225
-				$row['status'] = $msg_success_skip_dir;
226
-				$this->output[] = $this->parsePlaceholder($_lang['export_site_exporting_document'], $row);
227
-			}
228
-			if ($row['isfolder']==='1' && ($modx->config['suffix_mode']!=='1' || strpos($row['alias'],'.')===false))
229
-			{ // needs making a folder
230
-				$end_dir = ($row['alias']!=='') ? $row['alias'] : $row['id'];
231
-				$dir_path = $dirpath . $end_dir;
232
-				if(strpos($dir_path,MODX_BASE_PATH)===false) return FALSE;
233
-				if (!is_dir($dir_path))
234
-				{
235
-					if (is_file($dir_path)) @unlink($dir_path);
236
-					mkdir($dir_path);
237
-					@chmod($dir_path, $folder_permission);
216
+                        }
217
+                    }
218
+                    else $row['status'] = $msg_failed_no_retrieve;
219
+                }
220
+                else     $row['status'] = $msg_success_skip_doc;
221
+                $this->output[] = $this->parsePlaceholder($_lang['export_site_exporting_document'], $row);
222
+            }
223
+            else
224
+            {
225
+                $row['status'] = $msg_success_skip_dir;
226
+                $this->output[] = $this->parsePlaceholder($_lang['export_site_exporting_document'], $row);
227
+            }
228
+            if ($row['isfolder']==='1' && ($modx->config['suffix_mode']!=='1' || strpos($row['alias'],'.')===false))
229
+            { // needs making a folder
230
+                $end_dir = ($row['alias']!=='') ? $row['alias'] : $row['id'];
231
+                $dir_path = $dirpath . $end_dir;
232
+                if(strpos($dir_path,MODX_BASE_PATH)===false) return FALSE;
233
+                if (!is_dir($dir_path))
234
+                {
235
+                    if (is_file($dir_path)) @unlink($dir_path);
236
+                    mkdir($dir_path);
237
+                    @chmod($dir_path, $folder_permission);
238 238
 					
239
-				}
239
+                }
240 240
 				
241 241
 				
242
-				if($modx->config['make_folders']==='1' && $row['published']==='1')
243
-				{
244
-					if(is_file($filename)) rename($filename,$dir_path . '/index.html');
245
-				}
246
-				$this->targetDir = $dir_path;
247
-				$this->run($row['id']);
248
-			}
249
-		}
250
-		return implode("\n", $this->output);
251
-	}
242
+                if($modx->config['make_folders']==='1' && $row['published']==='1')
243
+                {
244
+                    if(is_file($filename)) rename($filename,$dir_path . '/index.html');
245
+                }
246
+                $this->targetDir = $dir_path;
247
+                $this->run($row['id']);
248
+            }
249
+        }
250
+        return implode("\n", $this->output);
251
+    }
252 252
 	
253 253
     function curl_get_contents($url, $timeout = 30 )
254 254
     {
255
-    	if(!function_exists('curl_init')) return @file_get_contents($url);
255
+        if(!function_exists('curl_init')) return @file_get_contents($url);
256 256
 
257 257
         $ch = curl_init();
258 258
         curl_setopt($ch, CURLOPT_URL, $url);
@@ -269,12 +269,12 @@  discard block
 block discarded – undo
269 269
 
270 270
     function parsePlaceholder($tpl,$ph=array())
271 271
     {
272
-    	foreach($ph as $k=>$v)
273
-    	{
274
-    		$k = "[+{$k}+]";
275
-    		$tpl = str_replace($k,$v,$tpl);
276
-    	}
277
-    	return $tpl;
272
+        foreach($ph as $k=>$v)
273
+        {
274
+            $k = "[+{$k}+]";
275
+            $tpl = str_replace($k,$v,$tpl);
276
+        }
277
+        return $tpl;
278 278
     }
279 279
 
280 280
 }
Please login to merge, or discard this patch.
manager/includes/extenders/manager.api.class.inc.php 1 patch
Indentation   +183 added lines, -183 removed lines patch added patch discarded remove patch
@@ -10,215 +10,215 @@
 block discarded – undo
10 10
 // Content manager wrapper class
11 11
 class ManagerAPI {
12 12
 	
13
-	var $action; // action directive
13
+    var $action; // action directive
14 14
 
15
-	function __construct(){
16
-		global $action;
17
-		$this->action = $action; // set action directive
18
-	}
15
+    function __construct(){
16
+        global $action;
17
+        $this->action = $action; // set action directive
18
+    }
19 19
 	
20
-	function initPageViewState($id=0){
21
-		global $_PAGE;
22
-		$vsid = isset($_SESSION["mgrPageViewSID"]) ? $_SESSION["mgrPageViewSID"] : '';
23
-		if($vsid!=$this->action) {
24
-			$_SESSION["mgrPageViewSDATA"] = array(); // new view state
25
-			$_SESSION["mgrPageViewSID"] = $id>0 ? $id:$this->action; // set id
26
-		}
27
-		$_PAGE['vs'] = &$_SESSION["mgrPageViewSDATA"]; // restore viewstate
28
-	}
20
+    function initPageViewState($id=0){
21
+        global $_PAGE;
22
+        $vsid = isset($_SESSION["mgrPageViewSID"]) ? $_SESSION["mgrPageViewSID"] : '';
23
+        if($vsid!=$this->action) {
24
+            $_SESSION["mgrPageViewSDATA"] = array(); // new view state
25
+            $_SESSION["mgrPageViewSID"] = $id>0 ? $id:$this->action; // set id
26
+        }
27
+        $_PAGE['vs'] = &$_SESSION["mgrPageViewSDATA"]; // restore viewstate
28
+    }
29 29
 
30
-	// save page view state - not really necessary,
31
-	function savePageViewState($id=0){
32
-		global $_PAGE;
33
-		$_SESSION["mgrPageViewSDATA"] = $_PAGE['vs'];
34
-		$_SESSION["mgrPageViewSID"] = $id>0 ? $id:$this->action;
35
-	}
30
+    // save page view state - not really necessary,
31
+    function savePageViewState($id=0){
32
+        global $_PAGE;
33
+        $_SESSION["mgrPageViewSDATA"] = $_PAGE['vs'];
34
+        $_SESSION["mgrPageViewSID"] = $id>0 ? $id:$this->action;
35
+    }
36 36
 	
37
-	// check for saved form
38
-	function hasFormValues() {
39
-		if(isset($_SESSION["mgrFormValueId"])) {		
40
-			if($this->action==$_SESSION["mgrFormValueId"]) {
41
-				return true;
42
-			}
43
-			else {
44
-				$this->clearSavedFormValues();
45
-			}
46
-		}
47
-		return false;
48
-	}	
49
-	// saved form post from $_POST
50
-	function saveFormValues($id=0){
51
-		$_SESSION["mgrFormValues"] = $_POST;
52
-		$_SESSION["mgrFormValueId"] = $id>0 ? $id:$this->action;
53
-	}		
54
-	// load saved form values into $_POST
55
-	function loadFormValues(){
37
+    // check for saved form
38
+    function hasFormValues() {
39
+        if(isset($_SESSION["mgrFormValueId"])) {		
40
+            if($this->action==$_SESSION["mgrFormValueId"]) {
41
+                return true;
42
+            }
43
+            else {
44
+                $this->clearSavedFormValues();
45
+            }
46
+        }
47
+        return false;
48
+    }	
49
+    // saved form post from $_POST
50
+    function saveFormValues($id=0){
51
+        $_SESSION["mgrFormValues"] = $_POST;
52
+        $_SESSION["mgrFormValueId"] = $id>0 ? $id:$this->action;
53
+    }		
54
+    // load saved form values into $_POST
55
+    function loadFormValues(){
56 56
 		
57
-		if(!$this->hasFormValues()) return false;
57
+        if(!$this->hasFormValues()) return false;
58 58
 		
59
-		$p = $_SESSION["mgrFormValues"];
60
-		$this->clearSavedFormValues();
61
-		foreach($p as $k=>$v) {
62
-			$_POST[$k]=$v;
63
-		}
64
-		return true;
65
-	}
66
-	// clear form post
67
-	function clearSavedFormValues(){
68
-		unset($_SESSION["mgrFormValues"]);
69
-		unset($_SESSION["mgrFormValueId"]);	
70
-	}
59
+        $p = $_SESSION["mgrFormValues"];
60
+        $this->clearSavedFormValues();
61
+        foreach($p as $k=>$v) {
62
+            $_POST[$k]=$v;
63
+        }
64
+        return true;
65
+    }
66
+    // clear form post
67
+    function clearSavedFormValues(){
68
+        unset($_SESSION["mgrFormValues"]);
69
+        unset($_SESSION["mgrFormValueId"]);	
70
+    }
71 71
 	
72
-	function getHashType($db_value='') { // md5 | v1 | phpass
73
-		$c = substr($db_value,0,1);
74
-		if($c==='$')                                      return 'phpass';
75
-		elseif(strlen($db_value)===32)                    return 'md5';
76
-		elseif($c!=='$' && strpos($db_value,'>')!==false) return 'v1';
77
-		else                                              return 'unknown';
78
-	}
72
+    function getHashType($db_value='') { // md5 | v1 | phpass
73
+        $c = substr($db_value,0,1);
74
+        if($c==='$')                                      return 'phpass';
75
+        elseif(strlen($db_value)===32)                    return 'md5';
76
+        elseif($c!=='$' && strpos($db_value,'>')!==false) return 'v1';
77
+        else                                              return 'unknown';
78
+    }
79 79
 	
80
-	function genV1Hash($password, $seed='1')
81
-	{ // $seed is user_id basically
82
-		global $modx;
80
+    function genV1Hash($password, $seed='1')
81
+    { // $seed is user_id basically
82
+        global $modx;
83 83
 		
84
-		if(isset($modx->config['pwd_hash_algo']) && !empty($modx->config['pwd_hash_algo']))
85
-			$algorithm = $modx->config['pwd_hash_algo'];
86
-		else $algorithm = 'UNCRYPT';
84
+        if(isset($modx->config['pwd_hash_algo']) && !empty($modx->config['pwd_hash_algo']))
85
+            $algorithm = $modx->config['pwd_hash_algo'];
86
+        else $algorithm = 'UNCRYPT';
87 87
 		
88
-		$salt = md5($password . $seed);
88
+        $salt = md5($password . $seed);
89 89
 		
90
-		switch($algorithm)
91
-		{
92
-			case 'BLOWFISH_Y':
93
-				$salt = '$2y$07$' . substr($salt,0,22);
94
-				break;
95
-			case 'BLOWFISH_A':
96
-				$salt = '$2a$07$' . substr($salt,0,22);
97
-				break;
98
-			case 'SHA512':
99
-				$salt = '$6$' . substr($salt,0,16);
100
-				break;
101
-			case 'SHA256':
102
-				$salt = '$5$' . substr($salt,0,16);
103
-				break;
104
-			case 'MD5':
105
-				$salt = '$1$' . substr($salt,0,8);
106
-				break;
107
-		}
90
+        switch($algorithm)
91
+        {
92
+            case 'BLOWFISH_Y':
93
+                $salt = '$2y$07$' . substr($salt,0,22);
94
+                break;
95
+            case 'BLOWFISH_A':
96
+                $salt = '$2a$07$' . substr($salt,0,22);
97
+                break;
98
+            case 'SHA512':
99
+                $salt = '$6$' . substr($salt,0,16);
100
+                break;
101
+            case 'SHA256':
102
+                $salt = '$5$' . substr($salt,0,16);
103
+                break;
104
+            case 'MD5':
105
+                $salt = '$1$' . substr($salt,0,8);
106
+                break;
107
+        }
108 108
 		
109
-		if($algorithm!=='UNCRYPT')
110
-		{
111
-			$password = sha1($password) . crypt($password,$salt);
112
-		}
113
-		else $password = sha1($salt.$password);
109
+        if($algorithm!=='UNCRYPT')
110
+        {
111
+            $password = sha1($password) . crypt($password,$salt);
112
+        }
113
+        else $password = sha1($salt.$password);
114 114
 		
115
-		$result = strtolower($algorithm) . '>' . md5($salt.$password) . substr(md5($salt),0,8);
115
+        $result = strtolower($algorithm) . '>' . md5($salt.$password) . substr(md5($salt),0,8);
116 116
 		
117
-		return $result;
118
-	}
117
+        return $result;
118
+    }
119 119
 	
120
-	function getV1UserHashAlgorithm($uid)
121
-	{
122
-		global $modx;
123
-		$tbl_manager_users = $modx->getFullTableName('manager_users');
124
-		$rs = $modx->db->select('password',$tbl_manager_users,"id='{$uid}'");
125
-		$password = $modx->db->getValue($rs);
120
+    function getV1UserHashAlgorithm($uid)
121
+    {
122
+        global $modx;
123
+        $tbl_manager_users = $modx->getFullTableName('manager_users');
124
+        $rs = $modx->db->select('password',$tbl_manager_users,"id='{$uid}'");
125
+        $password = $modx->db->getValue($rs);
126 126
 		
127
-		if(strpos($password,'>')===false) $algo = 'NOSALT';
128
-		else
129
-		{
130
-			$algo = substr($password,0,strpos($password,'>'));
131
-		}
132
-		return strtoupper($algo);
133
-	}
127
+        if(strpos($password,'>')===false) $algo = 'NOSALT';
128
+        else
129
+        {
130
+            $algo = substr($password,0,strpos($password,'>'));
131
+        }
132
+        return strtoupper($algo);
133
+    }
134 134
 	
135
-	function checkHashAlgorithm($algorithm='')
136
-	{
137
-		$result = false;
138
-		if (!empty($algorithm))
139
-		{
140
-			switch ($algorithm)
141
-			{
142
-				case 'BLOWFISH_Y':
143
-					if (defined('CRYPT_BLOWFISH') && CRYPT_BLOWFISH == 1)
144
-					{
145
-						if (version_compare('5.3.7', PHP_VERSION) <= 0) $result = true;
146
-					}
147
-					break;
148
-				case 'BLOWFISH_A':
149
-					if (defined('CRYPT_BLOWFISH') && CRYPT_BLOWFISH == 1) $result = true;
150
-					break;
151
-				case 'SHA512':
152
-					if (defined('CRYPT_SHA512') && CRYPT_SHA512 == 1) $result = true;
153
-					break;
154
-				case 'SHA256':
155
-					if (defined('CRYPT_SHA256') && CRYPT_SHA256 == 1) $result = true;
156
-					break;
157
-				case 'MD5':
158
-					if (defined('CRYPT_MD5') && CRYPT_MD5 == 1 && PHP_VERSION != '5.3.7') $result = true;
159
-					break;
160
-				case 'UNCRYPT':
161
-					$result = true;
162
-					break;
163
-			}
164
-		}
165
-		return $result;
166
-	}
135
+    function checkHashAlgorithm($algorithm='')
136
+    {
137
+        $result = false;
138
+        if (!empty($algorithm))
139
+        {
140
+            switch ($algorithm)
141
+            {
142
+                case 'BLOWFISH_Y':
143
+                    if (defined('CRYPT_BLOWFISH') && CRYPT_BLOWFISH == 1)
144
+                    {
145
+                        if (version_compare('5.3.7', PHP_VERSION) <= 0) $result = true;
146
+                    }
147
+                    break;
148
+                case 'BLOWFISH_A':
149
+                    if (defined('CRYPT_BLOWFISH') && CRYPT_BLOWFISH == 1) $result = true;
150
+                    break;
151
+                case 'SHA512':
152
+                    if (defined('CRYPT_SHA512') && CRYPT_SHA512 == 1) $result = true;
153
+                    break;
154
+                case 'SHA256':
155
+                    if (defined('CRYPT_SHA256') && CRYPT_SHA256 == 1) $result = true;
156
+                    break;
157
+                case 'MD5':
158
+                    if (defined('CRYPT_MD5') && CRYPT_MD5 == 1 && PHP_VERSION != '5.3.7') $result = true;
159
+                    break;
160
+                case 'UNCRYPT':
161
+                    $result = true;
162
+                    break;
163
+            }
164
+        }
165
+        return $result;
166
+    }
167 167
 
168
-	function getSystemChecksum($check_files) {
169
-		$_ = array();
170
-		$check_files = trim($check_files);
171
-		$check_files = explode("\n", $check_files);
172
-		foreach($check_files as $file) {
173
-			$file = trim($file);
174
-			$file = MODX_BASE_PATH . $file;
175
-			if(!is_file($file)) continue;
176
-			$_[$file]= md5_file($file);
177
-		}
178
-		return serialize($_);
179
-	}
168
+    function getSystemChecksum($check_files) {
169
+        $_ = array();
170
+        $check_files = trim($check_files);
171
+        $check_files = explode("\n", $check_files);
172
+        foreach($check_files as $file) {
173
+            $file = trim($file);
174
+            $file = MODX_BASE_PATH . $file;
175
+            if(!is_file($file)) continue;
176
+            $_[$file]= md5_file($file);
177
+        }
178
+        return serialize($_);
179
+    }
180 180
 
181
-	function getModifiedSystemFilesList($check_files, $checksum) {
182
-		$_ = array();
183
-		$check_files = trim($check_files);
184
-		$check_files = explode("\n", $check_files);
185
-		$checksum = unserialize($checksum);
186
-		foreach($check_files as $file) {
187
-			$file = trim($file);
188
-			$filePath = MODX_BASE_PATH . $file;
189
-			if(!is_file($filePath)) continue;
190
-			if(md5_file($filePath) != $checksum[$filePath]) $_[] = $file;
191
-		}
192
-		return $_;
193
-	}
181
+    function getModifiedSystemFilesList($check_files, $checksum) {
182
+        $_ = array();
183
+        $check_files = trim($check_files);
184
+        $check_files = explode("\n", $check_files);
185
+        $checksum = unserialize($checksum);
186
+        foreach($check_files as $file) {
187
+            $file = trim($file);
188
+            $filePath = MODX_BASE_PATH . $file;
189
+            if(!is_file($filePath)) continue;
190
+            if(md5_file($filePath) != $checksum[$filePath]) $_[] = $file;
191
+        }
192
+        return $_;
193
+    }
194 194
 
195
-	function setSystemChecksum($checksum) {
196
-		global $modx;
197
-		$tbl_system_settings = $modx->getFullTableName('system_settings');
198
-		$sql = "REPLACE INTO {$tbl_system_settings} (setting_name, setting_value) VALUES ('sys_files_checksum','" . $modx->db->escape($checksum) . "')";
195
+    function setSystemChecksum($checksum) {
196
+        global $modx;
197
+        $tbl_system_settings = $modx->getFullTableName('system_settings');
198
+        $sql = "REPLACE INTO {$tbl_system_settings} (setting_name, setting_value) VALUES ('sys_files_checksum','" . $modx->db->escape($checksum) . "')";
199 199
         $modx->db->query($sql);
200
-	}
200
+    }
201 201
 	
202
-	function checkSystemChecksum() {
203
-		global $modx;
202
+    function checkSystemChecksum() {
203
+        global $modx;
204 204
 
205
-		if(!isset($modx->config['check_files_onlogin']) || empty($modx->config['check_files_onlogin'])) return '0';
205
+        if(!isset($modx->config['check_files_onlogin']) || empty($modx->config['check_files_onlogin'])) return '0';
206 206
 		
207
-		$current = $this->getSystemChecksum($modx->config['check_files_onlogin']);
208
-		if(empty($current)) return '0';
207
+        $current = $this->getSystemChecksum($modx->config['check_files_onlogin']);
208
+        if(empty($current)) return '0';
209 209
 		
210
-		if(!isset($modx->config['sys_files_checksum']) || empty($modx->config['sys_files_checksum']))
211
-		{
212
-			$this->setSystemChecksum($current);
213
-			return '0';
214
-		}
215
-		if($current===$modx->config['sys_files_checksum']) $result = '0';
216
-		else {
217
-			$result = $this->getModifiedSystemFilesList($modx->config['check_files_onlogin'], $modx->config['sys_files_checksum']);
218
-		} 
210
+        if(!isset($modx->config['sys_files_checksum']) || empty($modx->config['sys_files_checksum']))
211
+        {
212
+            $this->setSystemChecksum($current);
213
+            return '0';
214
+        }
215
+        if($current===$modx->config['sys_files_checksum']) $result = '0';
216
+        else {
217
+            $result = $this->getModifiedSystemFilesList($modx->config['check_files_onlogin'], $modx->config['sys_files_checksum']);
218
+        } 
219 219
 
220
-		return $result;
221
-	}
220
+        return $result;
221
+    }
222 222
 
223 223
     function getLastUserSetting($key=false) {
224 224
         global $modx;
Please login to merge, or discard this patch.
manager/includes/extenders/phpcompat.class.inc.php 1 patch
Indentation   +16 added lines, -16 removed lines patch added patch discarded remove patch
@@ -2,26 +2,26 @@
 block discarded – undo
2 2
 // todo file_put_contents(), strftime(), mb_*()
3 3
 class PHPCOMPAT
4 4
 {
5
-	function __construct()
6
-	{
7
-	}
5
+    function __construct()
6
+    {
7
+    }
8 8
 	
9
-	function htmlspecialchars($str='', $flags = ENT_COMPAT, $encode='')
10
-	{
11
-		global $modx;
9
+    function htmlspecialchars($str='', $flags = ENT_COMPAT, $encode='')
10
+    {
11
+        global $modx;
12 12
 		
13
-		if($str=='') return '';
13
+        if($str=='') return '';
14 14
 		
15
-		if($encode=='') $encode = $modx->config['modx_charset'];
15
+        if($encode=='') $encode = $modx->config['modx_charset'];
16 16
 		
17
-		$ent_str = htmlspecialchars($str, $flags, $encode);
17
+        $ent_str = htmlspecialchars($str, $flags, $encode);
18 18
 		
19
-		if(!empty($str) && empty($ent_str))
20
-		{
21
-			$detect_order = implode(',', mb_detect_order());
22
-			$ent_str = mb_convert_encoding($str, $encode, $detect_order); 
23
-		}
19
+        if(!empty($str) && empty($ent_str))
20
+        {
21
+            $detect_order = implode(',', mb_detect_order());
22
+            $ent_str = mb_convert_encoding($str, $encode, $detect_order); 
23
+        }
24 24
 		
25
-		return $ent_str;
26
-	}
25
+        return $ent_str;
26
+    }
27 27
 }
Please login to merge, or discard this patch.
manager/includes/extenders/modifiers.class.inc.php 1 patch
Indentation   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -598,7 +598,7 @@  discard block
 block discarded – undo
598 598
                     else               $opt = true;
599 599
                 }
600 600
                 elseif(isset($modx->config['mce_element_format'])&&$modx->config['mce_element_format']==='html')
601
-                                       $opt = false;
601
+                                        $opt = false;
602 602
                 else                   $opt = true;
603 603
                 return nl2br($value,$opt);
604 604
             case 'ltrim':
@@ -1022,7 +1022,7 @@  discard block
 block discarded – undo
1022 1022
         {
1023 1023
             $bt = $content;
1024 1024
             if(strpos($content,'[*')!==false && $modx->documentIdentifier)
1025
-                                              $content = $modx->mergeDocumentContent($content);
1025
+                                                $content = $modx->mergeDocumentContent($content);
1026 1026
             if(strpos($content,'[(')!==false) $content = $modx->mergeSettingsContent($content);
1027 1027
             if(strpos($content,'{{')!==false) $content = $modx->mergeChunkContent($content);
1028 1028
             if(strpos($content,'[!')!==false) $content = str_replace(array('[!','!]'),array('[[',']]'),$content);
Please login to merge, or discard this patch.
install/actions/action_summary.php 1 patch
Indentation   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -248,9 +248,9 @@
 block discarded – undo
248 248
         echo '<span class="notok">' . $_lang['failed'] . '</span></b>' . $_lang['table_prefix_not_exist'] . '</p>';
249 249
         $errors++;
250 250
         echo '<p>' . $_lang['table_prefix_not_exist_note'] . '</p>';
251
-  } else {
251
+    } else {
252 252
         echo '<span class="ok">' . $_lang['ok'] . '</span></p>';
253
-  }
253
+    }
254 254
 }
255 255
 
256 256
 // check mysql version
Please login to merge, or discard this patch.
manager/includes/user_settings.inc.php 1 patch
Indentation   +13 added lines, -13 removed lines patch added patch discarded remove patch
@@ -3,23 +3,23 @@
 block discarded – undo
3 3
 
4 4
 // START HACK
5 5
 if (isset ($modx)) {
6
-	$user_id = $modx->getLoginUserID();
6
+    $user_id = $modx->getLoginUserID();
7 7
 } else {
8
-	$user_id = $_SESSION['mgrInternalKey'];
8
+    $user_id = $_SESSION['mgrInternalKey'];
9 9
 }
10 10
 // END HACK
11 11
 
12 12
 if (!empty($user_id)) {
13
-	// Raymond: grab the user settings from the database.
14
-	$rs = $modx->db->select('setting_name, setting_value', $modx->getFullTableName('user_settings'), "user=".$modx->getLoginUserID());
13
+    // Raymond: grab the user settings from the database.
14
+    $rs = $modx->db->select('setting_name, setting_value', $modx->getFullTableName('user_settings'), "user=".$modx->getLoginUserID());
15 15
 
16
-	$which_browser_default = $which_browser;
17
-	while ($row = $modx->db->getRow($rs)) {
18
-		if($row['setting_name'] == 'which_browser' && $row['setting_value'] == 'default') $row['setting_value'] = $which_browser_default;
19
-		$settings[$row['setting_name']] = $row['setting_value'];
20
-		if (isset($modx->config)) {
21
-			$modx->config[$row['setting_name']] = $row['setting_value'];
22
-		}
23
-	}
24
-	extract($settings, EXTR_OVERWRITE);
16
+    $which_browser_default = $which_browser;
17
+    while ($row = $modx->db->getRow($rs)) {
18
+        if($row['setting_name'] == 'which_browser' && $row['setting_value'] == 'default') $row['setting_value'] = $which_browser_default;
19
+        $settings[$row['setting_name']] = $row['setting_value'];
20
+        if (isset($modx->config)) {
21
+            $modx->config[$row['setting_name']] = $row['setting_value'];
22
+        }
23
+    }
24
+    extract($settings, EXTR_OVERWRITE);
25 25
 }
Please login to merge, or discard this patch.
manager/includes/rss.inc.php 1 patch
Indentation   +32 added lines, -32 removed lines patch added patch discarded remove patch
@@ -1,5 +1,5 @@  discard block
 block discarded – undo
1 1
 <?php
2
- /*
2
+    /*
3 3
  *  MODX Manager Home Page Implmentation by pixelchutes (www.pixelchutes.com)
4 4
  *  Based on kudo's kRSS Module v1.0.72
5 5
  *
@@ -30,43 +30,43 @@  discard block
 block discarded – undo
30 30
 require_once(MODX_MANAGER_PATH.'media/rss/rss_fetch.inc');
31 31
 // Convert relative path into absolute url
32 32
 function rel2abs( $rel, $base ) {
33
-	// parse base URL  and convert to local variables: $scheme, $host,  $path
34
-	extract( parse_url( $base ) );
35
-	if ( strpos( $rel,"//" ) === 0 ) {
36
-		return $scheme . ':' . $rel;
37
-	}
38
-	// return if already absolute URL
39
-	if ( parse_url( $rel, PHP_URL_SCHEME ) != '' ) {
40
-		return $rel;
41
-	}
42
-	// queries and anchors
43
-	if ( $rel[0] == '#' || $rel[0] == '?' ) {
44
-		return $base . $rel;
45
-	}
46
-	// remove non-directory element from path
47
-	$path = preg_replace( '#/[^/]*$#', '', $path );
48
-	// destroy path if relative url points to root
49
-	if ( $rel[0] ==  '/' ) {
50
-		$path = '';
51
-	}
52
-	// dirty absolute URL
53
-	$abs = $host . $path . "/" . $rel;
54
-	// replace '//' or  '/./' or '/foo/../' with '/'
55
-	$abs = preg_replace( "/(\/\.?\/)/", "/", $abs );
56
-	$abs = preg_replace( "/\/(?!\.\.)[^\/]+\/\.\.\//", "/", $abs );
57
-	// absolute URL is ready!
58
-	return $scheme . '://' . $abs;
33
+    // parse base URL  and convert to local variables: $scheme, $host,  $path
34
+    extract( parse_url( $base ) );
35
+    if ( strpos( $rel,"//" ) === 0 ) {
36
+        return $scheme . ':' . $rel;
37
+    }
38
+    // return if already absolute URL
39
+    if ( parse_url( $rel, PHP_URL_SCHEME ) != '' ) {
40
+        return $rel;
41
+    }
42
+    // queries and anchors
43
+    if ( $rel[0] == '#' || $rel[0] == '?' ) {
44
+        return $base . $rel;
45
+    }
46
+    // remove non-directory element from path
47
+    $path = preg_replace( '#/[^/]*$#', '', $path );
48
+    // destroy path if relative url points to root
49
+    if ( $rel[0] ==  '/' ) {
50
+        $path = '';
51
+    }
52
+    // dirty absolute URL
53
+    $abs = $host . $path . "/" . $rel;
54
+    // replace '//' or  '/./' or '/foo/../' with '/'
55
+    $abs = preg_replace( "/(\/\.?\/)/", "/", $abs );
56
+    $abs = preg_replace( "/\/(?!\.\.)[^\/]+\/\.\.\//", "/", $abs );
57
+    // absolute URL is ready!
58
+    return $scheme . '://' . $abs;
59 59
 }
60 60
 $feedData = array();
61 61
 
62 62
 // create Feed
63 63
 foreach ($urls as $section=>$url) {
64
-	$output = '';
64
+    $output = '';
65 65
     $rss = @fetch_rss($url);
66 66
     if( !$rss ){
67
-    	$feedData[$section] = 'Failed to retrieve ' . $url;
68
-    	continue;
69
-	}
67
+        $feedData[$section] = 'Failed to retrieve ' . $url;
68
+        continue;
69
+    }
70 70
     $output .= '<ul>';
71 71
 
72 72
     $items = array_slice($rss->items, 0, $itemsNumber);
@@ -84,5 +84,5 @@  discard block
 block discarded – undo
84 84
     }
85 85
 
86 86
     $output .= '</ul>';
87
-	$feedData[$section] = $output;
87
+    $feedData[$section] = $output;
88 88
 }
Please login to merge, or discard this patch.
manager/includes/extenders/maketable.class.php 1 patch
Indentation   +494 added lines, -494 removed lines patch added patch discarded remove patch
@@ -9,366 +9,366 @@  discard block
 block discarded – undo
9 9
  * @author Jason Coward <[email protected]> (MODX)
10 10
  */
11 11
 class MakeTable {
12
-	var $actionField;
13
-	var $cellAction;
14
-	var $linkAction;
15
-	var $tableWidth;
16
-	var $tableClass;
17
-	var $tableID;
18
-	var $thClass;
19
-	var $rowHeaderClass;
20
-	var $columnHeaderClass;
21
-	var $rowRegularClass;
22
-	var $rowAlternateClass;
23
-	var $formName;
24
-	var $formAction;
25
-	var $formElementType;
26
-	var $formElementName;
27
-	var $rowAlternatingScheme;
28
-	var $excludeFields;
29
-	var $allOption;
30
-	var $pageNav;
31
-	var $columnWidths;
32
-	var $selectedValues;
33
-
34
-	function __construct() {
35
-		$this->fieldHeaders= array();
36
-		$this->excludeFields= array();
37
-		$this->actionField= '';
38
-		$this->cellAction= '';
39
-		$this->linkAction= '';
40
-		$this->tableWidth= '';
41
-		$this->tableClass= '';
42
-		$this->rowHeaderClass= '';
43
-		$this->columnHeaderClass= '';
44
-		$this->rowRegularClass= '';
45
-		$this->rowAlternateClass= 'alt';
46
-		$this->formName= 'tableForm';
47
-		$this->formAction= '[~[*id*]~]';
48
-		$this->formElementName= '';
49
-		$this->formElementType= '';
50
-		$this->rowAlternatingScheme= 'EVEN';
51
-		$this->allOption= 0;
52
-		$this->selectedValues= array();
53
-		$this->extra= '';
54
-	}
55
-
56
-	/**
57
-	 * Sets the default link href for all cells in the table.
58
-	 *
59
-	 * @param $value A URL to execute when table cells are clicked.
60
-	 */
61
-	function setCellAction($value) {
62
-		$this->cellAction= $this->prepareLink($value);
63
-	}
64
-
65
-	/**
66
-	 * Sets the default link href for the text presented in a cell.
67
-	 *
68
-	 * @param $value A URL to execute when text within table cells are clicked.
69
-	 */
70
-	function setLinkAction($value) {
71
-		$this->linkAction= $this->prepareLink($value);
72
-	}
73
-
74
-	/**
75
-	 * Sets the width attribute of the main HTML TABLE.
76
-	 *
77
-	 * @param $value A valid width attribute for the HTML TABLE tag
78
-	 */
79
-	function setTableWidth($value) {
80
-		$this->tableWidth= $value;
81
-	}
82
-
83
-	/**
84
-	 * Sets the class attribute of the main HTML TABLE.
85
-	 *
86
-	 * @param $value A class for the main HTML TABLE.
87
-	 */
88
-	function setTableClass($value) {
89
-		$this->tableClass= $value;
90
-	}
91
-
92
-	/**
93
-	 * Sets the id attribute of the main HTML TABLE.
94
-	 *
95
-	 * @param $value A class for the main HTML TABLE.
96
-	 */
97
-	function setTableID($value) {
98
-		$this->tableID= $value;
99
-	}
100
-
101
-	/**
102
-	 * Sets the class attribute of the table header row.
103
-	 *
104
-	 * @param $value A class for the table header row.
105
-	 */
106
-	function setRowHeaderClass($value) {
107
-		$this->rowHeaderClass= $value;
108
-	}
109
-
110
-		/**
111
-	 * Sets the class attribute of the table header row.
112
-	 *
113
-	 * @param $value A class for the table header row.
114
-	 */
115
-	function setThHeaderClass($value) {
116
-		$this->thClass= $value;
117
-	}
118
-
119
-	/**
120
-	 * Sets the class attribute of the column header row.
121
-	 *
122
-	 * @param $value A class for the column header row.
123
-	 */
124
-	function setColumnHeaderClass($value) {
125
-		$this->columnHeaderClass= $value;
126
-	}
127
-
128
-	/**
129
-	 * Sets the class attribute of regular table rows.
130
-	 *
131
-	 * @param $value A class for regular table rows.
132
-	 */
133
-	function setRowRegularClass($value) {
134
-		$this->rowRegularClass= $value;
135
-	}
136
-
137
-	/**
138
-	 * Sets the class attribute of alternate table rows.
139
-	 *
140
-	 * @param $value A class for alternate table rows.
141
-	 */
142
-	function setRowAlternateClass($value) {
143
-		$this->rowAlternateClass= $value;
144
-	}
145
-
146
-	/**
147
-	 * Sets the type of INPUT form element to be presented as the first column.
148
-	 *
149
-	 * @param $value Indicates the INPUT form element type attribute.
150
-	 */
151
-	function setFormElementType($value) {
152
-		$this->formElementType= $value;
153
-	}
154
-
155
-	/**
156
-	 * Sets the name of the INPUT form element to be presented as the first column.
157
-	 *
158
-	 * @param $value Indicates the INPUT form element name attribute.
159
-	 */
160
-	function setFormElementName($value) {
161
-		$this->formElementName= $value;
162
-	}
163
-
164
-	/**
165
-	 * Sets the name of the FORM to wrap the table in when a form element has
166
-	 * been indicated.
167
-	 *
168
-	 * @param $value Indicates the FORM name attribute.
169
-	 */
170
-	function setFormName($value) {
171
-		$this->formName= $value;
172
-	}
173
-
174
-	/**
175
-	 * Sets the action of the FORM element.
176
-	 *
177
-	 * @param $value Indicates the FORM action attribute.
178
-	 */
179
-	function setFormAction($value) {
180
-		$this->formAction= $value;
181
-	}
182
-
183
-	/**
184
-	 * Excludes fields from the table by array key.
185
-	 *
186
-	 * @param $value An Array of field keys to exclude from the table.
187
-	 */
188
-	function setExcludeFields($value) {
189
-		$this->excludeFields= $value;
190
-	}
191
-
192
-	/**
193
-	 * Sets the table to provide alternate row colors using ODD or EVEN rows
194
-	 *
195
-	 * @param $value 'ODD' or 'EVEN' to indicate the alternate row scheme.
196
-	 */
197
-	function setRowAlternatingScheme($value) {
198
-		$this->rowAlternatingScheme= $value;
199
-	}
200
-
201
-	/**
202
-	 * Sets the default field value to be used when appending query parameters
203
-	 * to link actions.
204
-	 *
205
-	 * @param $value The key of the field to add as a query string parameter.
206
-	 */
207
-	function setActionFieldName($value) {
208
-		$this->actionField= $value;
209
-	}
210
-
211
-	/**
212
-	 * Sets the width attribute of each column in the array.
213
-	 *
214
-	 * @param $value An Array of column widths in the order of the keys in the
215
-	 * 			source table array.
216
-	 */
217
-	function setColumnWidths($widthArray) {
218
-		$this->columnWidths= $widthArray;
219
-	}
220
-
221
-	/**
222
-	 * An optional array of values that can be preselected when using
223
-	 *
224
-	 * @param $value Indicates the INPUT form element type attribute.
225
-	 */
226
-	function setSelectedValues($valueArray) {
227
-		$this->selectedValues= $valueArray;
228
-	}
229
-
230
-	/**
231
-	 * Sets extra content to be presented following the table (but within
232
-	 * the form, if a form is being rendered with the table).
233
-	 *
234
-	 * @param $value A string of additional content.
235
-	 */
236
-	function setExtra($value) {
237
-		$this->extra= $value;
238
-	}
239
-
240
-	/**
241
-	 * Retrieves the width of a specific table column by index position.
242
-	 *
243
-	 * @param $columnPosition The index of the column to get the width for.
244
-	 */
245
-	function getColumnWidth($columnPosition) {
246
-		$currentWidth= '';
247
-		if (is_array($this->columnWidths)) {
248
-			$currentWidth= $this->columnWidths[$columnPosition] ? ' width="'.$this->columnWidths[$columnPosition].'" ' : '';
249
-		}
250
-		return $currentWidth;
251
-	}
252
-
253
-	/**
254
-	 * Determines what class the current row should have applied.
255
-	 *
256
-	 * @param $value The position of the current row being rendered.
257
-	 */
258
-	function determineRowClass($position) {
259
-		switch ($this->rowAlternatingScheme) {
260
-			case 'ODD' :
261
-				$modRemainder= 1;
262
-				break;
263
-			case 'EVEN' :
264
-				$modRemainder= 0;
265
-				break;
266
-		}
267
-		if ($position % 2 == $modRemainder) {
268
-			$currentClass= $this->rowRegularClass;
269
-		} else {
270
-			$currentClass= $this->rowAlternateClass;
271
-		}
272
-		return ' class="'.$currentClass.'"';
273
-	}
274
-
275
-	/**
276
-	 * Generates an onclick action applied to the current cell, to execute
277
-	 * any specified cell actions.
278
-	 *
279
-	 * @param $value Indicates the INPUT form element type attribute.
280
-	 */
281
-	function getCellAction($currentActionFieldValue) {
282
-		if ($this->cellAction) {
283
-			$cellAction= ' onClick="javascript:window.location=\''.$this->cellAction.$this->actionField.'='.urlencode($currentActionFieldValue).'\'" ';
284
-		}
285
-		return $cellAction;
286
-	}
287
-
288
-	/**
289
-	 * Generates the cell content, including any specified action fields values.
290
-	 *
291
-	 * @param $currentActionFieldValue The value to be applied to the link action.
292
-	 * @param $value The value of the cell.
293
-	 */
294
-	function createCellText($currentActionFieldValue, $value) {
295
-		$cell .= $value;
296
-		if ($this->linkAction) {
297
-			$cell= '<a href="'.$this->linkAction.$this->actionField.'='.urlencode($currentActionFieldValue).'">'.$cell.'</a>';
298
-		}
299
-		return $cell;
300
-	}
301
-
302
-	/**
303
-	 * Sets an option to generate a check all link when checkbox is indicated
304
-	 * as the table formElementType.
305
-	 */
306
-	function setAllOption() {
307
-		$this->allOption= 1;
308
-	}
309
-
310
-	/**
311
-	 * Function to prepare a link generated in the table cell/link actions.
312
-	 *
313
-	 * @param $value Indicates the INPUT form element type attribute.
314
-	 */
315
-	function prepareLink($link) {
316
-		if (strstr($link, '?')) {
317
-			$end= '&';
318
-		} else {
319
-			$end= '?';
320
-		}
321
-		return $link.$end;
322
-	}
323
-
324
-	/**
325
-	 * Generates the table content.
326
-	 *
327
-	 * @param $fieldsArray The associative array representing the table rows
328
-	 * and columns.
329
-	 * @param $fieldHeadersArray An optional array of values for providing
330
-	 * alternative field headers; this is an associative arrays of keys from
331
-	 * the $fieldsArray where the values represent the alt heading content
332
-	 * for each column.
333
-	 */
334
-	function create($fieldsArray, $fieldHeadersArray=array(),$linkpage="") {
335
-	global $_lang;
336
-		if (is_array($fieldsArray)) {
337
-			$i= 0;
338
-			foreach ($fieldsArray as $fieldName => $fieldValue) {
339
-				$table .= "\t<tr".$this->determineRowClass($i).">\n";
340
-				$currentActionFieldValue= $fieldValue[$this->actionField];
341
-				if (is_array($this->selectedValues)) {
342
-					$isChecked= array_search($currentActionFieldValue, $this->selectedValues)===false? 0 : 1;
343
-				} else {
344
-					$isChecked= false;
345
-				}
346
-				$table .= $this->addFormField($currentActionFieldValue, $isChecked);
347
-				$colPosition= 0;
348
-				foreach ($fieldValue as $key => $value) {
349
-					if (!in_array($key, $this->excludeFields)) {
350
-						$table .= "\t\t<td".$this->getCellAction($currentActionFieldValue).">";
351
-						$table .= $this->createCellText($currentActionFieldValue, $value);
352
-						$table .= "</td>\n";
353
-						if ($i == 0) {
354
-							if (empty ($header) && $this->formElementType) {
355
-								$header .= "\t\t<th style=\"width:32px\" ".($this->thClass ? 'class="'.$this->thClass.'"' : '').">". ($this->allOption ? '<a href="javascript:clickAll()">all</a>' : '')."</th>\n";
356
-							}
357
-							$headerText= array_key_exists($key, $fieldHeadersArray)? $fieldHeadersArray[$key]: $key;
358
-							$header .= "\t\t<th".$this->getColumnWidth($colPosition).($this->thClass ? ' class="'.$this->thClass.'" ' : '').">".$headerText."</th>\n";
359
-						}
360
-						$colPosition ++;
361
-					}
362
-				}
363
-				$i ++;
364
-				$table .= "\t</tr>\n";
365
-			}
366
-			$table= "\n".'<table'. ($this->tableWidth ? ' width="'.$this->tableWidth.'"' : ''). ($this->tableClass ? ' class="'.$this->tableClass.'"' : ''). ($this->tableID ? ' id="'.$this->tableID.'"' : '').">\n". ($header ? "\t<thead>\n\t<tr class=\"".$this->rowHeaderClass."\">\n".$header."\t</tr>\n\t</thead>\n" : '').$table."</table>\n";
367
-			if ($this->formElementType) {
368
-				$table= "\n".'<form id="'.$this->formName.'" name="'.$this->formName.'" action="'.$this->formAction.'" method="POST">'.$table;
369
-			}
370
-			if (strlen($this->pageNav) > 1) {//changed to display the pagination if exists.
371
-				/* commented this part because of cookie
12
+    var $actionField;
13
+    var $cellAction;
14
+    var $linkAction;
15
+    var $tableWidth;
16
+    var $tableClass;
17
+    var $tableID;
18
+    var $thClass;
19
+    var $rowHeaderClass;
20
+    var $columnHeaderClass;
21
+    var $rowRegularClass;
22
+    var $rowAlternateClass;
23
+    var $formName;
24
+    var $formAction;
25
+    var $formElementType;
26
+    var $formElementName;
27
+    var $rowAlternatingScheme;
28
+    var $excludeFields;
29
+    var $allOption;
30
+    var $pageNav;
31
+    var $columnWidths;
32
+    var $selectedValues;
33
+
34
+    function __construct() {
35
+        $this->fieldHeaders= array();
36
+        $this->excludeFields= array();
37
+        $this->actionField= '';
38
+        $this->cellAction= '';
39
+        $this->linkAction= '';
40
+        $this->tableWidth= '';
41
+        $this->tableClass= '';
42
+        $this->rowHeaderClass= '';
43
+        $this->columnHeaderClass= '';
44
+        $this->rowRegularClass= '';
45
+        $this->rowAlternateClass= 'alt';
46
+        $this->formName= 'tableForm';
47
+        $this->formAction= '[~[*id*]~]';
48
+        $this->formElementName= '';
49
+        $this->formElementType= '';
50
+        $this->rowAlternatingScheme= 'EVEN';
51
+        $this->allOption= 0;
52
+        $this->selectedValues= array();
53
+        $this->extra= '';
54
+    }
55
+
56
+    /**
57
+     * Sets the default link href for all cells in the table.
58
+     *
59
+     * @param $value A URL to execute when table cells are clicked.
60
+     */
61
+    function setCellAction($value) {
62
+        $this->cellAction= $this->prepareLink($value);
63
+    }
64
+
65
+    /**
66
+     * Sets the default link href for the text presented in a cell.
67
+     *
68
+     * @param $value A URL to execute when text within table cells are clicked.
69
+     */
70
+    function setLinkAction($value) {
71
+        $this->linkAction= $this->prepareLink($value);
72
+    }
73
+
74
+    /**
75
+     * Sets the width attribute of the main HTML TABLE.
76
+     *
77
+     * @param $value A valid width attribute for the HTML TABLE tag
78
+     */
79
+    function setTableWidth($value) {
80
+        $this->tableWidth= $value;
81
+    }
82
+
83
+    /**
84
+     * Sets the class attribute of the main HTML TABLE.
85
+     *
86
+     * @param $value A class for the main HTML TABLE.
87
+     */
88
+    function setTableClass($value) {
89
+        $this->tableClass= $value;
90
+    }
91
+
92
+    /**
93
+     * Sets the id attribute of the main HTML TABLE.
94
+     *
95
+     * @param $value A class for the main HTML TABLE.
96
+     */
97
+    function setTableID($value) {
98
+        $this->tableID= $value;
99
+    }
100
+
101
+    /**
102
+     * Sets the class attribute of the table header row.
103
+     *
104
+     * @param $value A class for the table header row.
105
+     */
106
+    function setRowHeaderClass($value) {
107
+        $this->rowHeaderClass= $value;
108
+    }
109
+
110
+        /**
111
+         * Sets the class attribute of the table header row.
112
+         *
113
+         * @param $value A class for the table header row.
114
+         */
115
+    function setThHeaderClass($value) {
116
+        $this->thClass= $value;
117
+    }
118
+
119
+    /**
120
+     * Sets the class attribute of the column header row.
121
+     *
122
+     * @param $value A class for the column header row.
123
+     */
124
+    function setColumnHeaderClass($value) {
125
+        $this->columnHeaderClass= $value;
126
+    }
127
+
128
+    /**
129
+     * Sets the class attribute of regular table rows.
130
+     *
131
+     * @param $value A class for regular table rows.
132
+     */
133
+    function setRowRegularClass($value) {
134
+        $this->rowRegularClass= $value;
135
+    }
136
+
137
+    /**
138
+     * Sets the class attribute of alternate table rows.
139
+     *
140
+     * @param $value A class for alternate table rows.
141
+     */
142
+    function setRowAlternateClass($value) {
143
+        $this->rowAlternateClass= $value;
144
+    }
145
+
146
+    /**
147
+     * Sets the type of INPUT form element to be presented as the first column.
148
+     *
149
+     * @param $value Indicates the INPUT form element type attribute.
150
+     */
151
+    function setFormElementType($value) {
152
+        $this->formElementType= $value;
153
+    }
154
+
155
+    /**
156
+     * Sets the name of the INPUT form element to be presented as the first column.
157
+     *
158
+     * @param $value Indicates the INPUT form element name attribute.
159
+     */
160
+    function setFormElementName($value) {
161
+        $this->formElementName= $value;
162
+    }
163
+
164
+    /**
165
+     * Sets the name of the FORM to wrap the table in when a form element has
166
+     * been indicated.
167
+     *
168
+     * @param $value Indicates the FORM name attribute.
169
+     */
170
+    function setFormName($value) {
171
+        $this->formName= $value;
172
+    }
173
+
174
+    /**
175
+     * Sets the action of the FORM element.
176
+     *
177
+     * @param $value Indicates the FORM action attribute.
178
+     */
179
+    function setFormAction($value) {
180
+        $this->formAction= $value;
181
+    }
182
+
183
+    /**
184
+     * Excludes fields from the table by array key.
185
+     *
186
+     * @param $value An Array of field keys to exclude from the table.
187
+     */
188
+    function setExcludeFields($value) {
189
+        $this->excludeFields= $value;
190
+    }
191
+
192
+    /**
193
+     * Sets the table to provide alternate row colors using ODD or EVEN rows
194
+     *
195
+     * @param $value 'ODD' or 'EVEN' to indicate the alternate row scheme.
196
+     */
197
+    function setRowAlternatingScheme($value) {
198
+        $this->rowAlternatingScheme= $value;
199
+    }
200
+
201
+    /**
202
+     * Sets the default field value to be used when appending query parameters
203
+     * to link actions.
204
+     *
205
+     * @param $value The key of the field to add as a query string parameter.
206
+     */
207
+    function setActionFieldName($value) {
208
+        $this->actionField= $value;
209
+    }
210
+
211
+    /**
212
+     * Sets the width attribute of each column in the array.
213
+     *
214
+     * @param $value An Array of column widths in the order of the keys in the
215
+     * 			source table array.
216
+     */
217
+    function setColumnWidths($widthArray) {
218
+        $this->columnWidths= $widthArray;
219
+    }
220
+
221
+    /**
222
+     * An optional array of values that can be preselected when using
223
+     *
224
+     * @param $value Indicates the INPUT form element type attribute.
225
+     */
226
+    function setSelectedValues($valueArray) {
227
+        $this->selectedValues= $valueArray;
228
+    }
229
+
230
+    /**
231
+     * Sets extra content to be presented following the table (but within
232
+     * the form, if a form is being rendered with the table).
233
+     *
234
+     * @param $value A string of additional content.
235
+     */
236
+    function setExtra($value) {
237
+        $this->extra= $value;
238
+    }
239
+
240
+    /**
241
+     * Retrieves the width of a specific table column by index position.
242
+     *
243
+     * @param $columnPosition The index of the column to get the width for.
244
+     */
245
+    function getColumnWidth($columnPosition) {
246
+        $currentWidth= '';
247
+        if (is_array($this->columnWidths)) {
248
+            $currentWidth= $this->columnWidths[$columnPosition] ? ' width="'.$this->columnWidths[$columnPosition].'" ' : '';
249
+        }
250
+        return $currentWidth;
251
+    }
252
+
253
+    /**
254
+     * Determines what class the current row should have applied.
255
+     *
256
+     * @param $value The position of the current row being rendered.
257
+     */
258
+    function determineRowClass($position) {
259
+        switch ($this->rowAlternatingScheme) {
260
+            case 'ODD' :
261
+                $modRemainder= 1;
262
+                break;
263
+            case 'EVEN' :
264
+                $modRemainder= 0;
265
+                break;
266
+        }
267
+        if ($position % 2 == $modRemainder) {
268
+            $currentClass= $this->rowRegularClass;
269
+        } else {
270
+            $currentClass= $this->rowAlternateClass;
271
+        }
272
+        return ' class="'.$currentClass.'"';
273
+    }
274
+
275
+    /**
276
+     * Generates an onclick action applied to the current cell, to execute
277
+     * any specified cell actions.
278
+     *
279
+     * @param $value Indicates the INPUT form element type attribute.
280
+     */
281
+    function getCellAction($currentActionFieldValue) {
282
+        if ($this->cellAction) {
283
+            $cellAction= ' onClick="javascript:window.location=\''.$this->cellAction.$this->actionField.'='.urlencode($currentActionFieldValue).'\'" ';
284
+        }
285
+        return $cellAction;
286
+    }
287
+
288
+    /**
289
+     * Generates the cell content, including any specified action fields values.
290
+     *
291
+     * @param $currentActionFieldValue The value to be applied to the link action.
292
+     * @param $value The value of the cell.
293
+     */
294
+    function createCellText($currentActionFieldValue, $value) {
295
+        $cell .= $value;
296
+        if ($this->linkAction) {
297
+            $cell= '<a href="'.$this->linkAction.$this->actionField.'='.urlencode($currentActionFieldValue).'">'.$cell.'</a>';
298
+        }
299
+        return $cell;
300
+    }
301
+
302
+    /**
303
+     * Sets an option to generate a check all link when checkbox is indicated
304
+     * as the table formElementType.
305
+     */
306
+    function setAllOption() {
307
+        $this->allOption= 1;
308
+    }
309
+
310
+    /**
311
+     * Function to prepare a link generated in the table cell/link actions.
312
+     *
313
+     * @param $value Indicates the INPUT form element type attribute.
314
+     */
315
+    function prepareLink($link) {
316
+        if (strstr($link, '?')) {
317
+            $end= '&';
318
+        } else {
319
+            $end= '?';
320
+        }
321
+        return $link.$end;
322
+    }
323
+
324
+    /**
325
+     * Generates the table content.
326
+     *
327
+     * @param $fieldsArray The associative array representing the table rows
328
+     * and columns.
329
+     * @param $fieldHeadersArray An optional array of values for providing
330
+     * alternative field headers; this is an associative arrays of keys from
331
+     * the $fieldsArray where the values represent the alt heading content
332
+     * for each column.
333
+     */
334
+    function create($fieldsArray, $fieldHeadersArray=array(),$linkpage="") {
335
+    global $_lang;
336
+        if (is_array($fieldsArray)) {
337
+            $i= 0;
338
+            foreach ($fieldsArray as $fieldName => $fieldValue) {
339
+                $table .= "\t<tr".$this->determineRowClass($i).">\n";
340
+                $currentActionFieldValue= $fieldValue[$this->actionField];
341
+                if (is_array($this->selectedValues)) {
342
+                    $isChecked= array_search($currentActionFieldValue, $this->selectedValues)===false? 0 : 1;
343
+                } else {
344
+                    $isChecked= false;
345
+                }
346
+                $table .= $this->addFormField($currentActionFieldValue, $isChecked);
347
+                $colPosition= 0;
348
+                foreach ($fieldValue as $key => $value) {
349
+                    if (!in_array($key, $this->excludeFields)) {
350
+                        $table .= "\t\t<td".$this->getCellAction($currentActionFieldValue).">";
351
+                        $table .= $this->createCellText($currentActionFieldValue, $value);
352
+                        $table .= "</td>\n";
353
+                        if ($i == 0) {
354
+                            if (empty ($header) && $this->formElementType) {
355
+                                $header .= "\t\t<th style=\"width:32px\" ".($this->thClass ? 'class="'.$this->thClass.'"' : '').">". ($this->allOption ? '<a href="javascript:clickAll()">all</a>' : '')."</th>\n";
356
+                            }
357
+                            $headerText= array_key_exists($key, $fieldHeadersArray)? $fieldHeadersArray[$key]: $key;
358
+                            $header .= "\t\t<th".$this->getColumnWidth($colPosition).($this->thClass ? ' class="'.$this->thClass.'" ' : '').">".$headerText."</th>\n";
359
+                        }
360
+                        $colPosition ++;
361
+                    }
362
+                }
363
+                $i ++;
364
+                $table .= "\t</tr>\n";
365
+            }
366
+            $table= "\n".'<table'. ($this->tableWidth ? ' width="'.$this->tableWidth.'"' : ''). ($this->tableClass ? ' class="'.$this->tableClass.'"' : ''). ($this->tableID ? ' id="'.$this->tableID.'"' : '').">\n". ($header ? "\t<thead>\n\t<tr class=\"".$this->rowHeaderClass."\">\n".$header."\t</tr>\n\t</thead>\n" : '').$table."</table>\n";
367
+            if ($this->formElementType) {
368
+                $table= "\n".'<form id="'.$this->formName.'" name="'.$this->formName.'" action="'.$this->formAction.'" method="POST">'.$table;
369
+            }
370
+            if (strlen($this->pageNav) > 1) {//changed to display the pagination if exists.
371
+                /* commented this part because of cookie
372 372
 				$table .= '<div id="max-display-records" ><select style="display:inline" onchange="javascript:updatePageSize(this[this.selectedIndex].value);">';
373 373
 				$pageSizes= array (10, 25, 50, 100, 250);
374 374
 				for ($i= 0; $i < count($pageSizes); $i ++) {
@@ -379,12 +379,12 @@  discard block
 block discarded – undo
379 379
 
380 380
 				$table .= '</select>'.$_lang["pagination_table_perpage"].'</div>';
381 381
 				*/
382
-				$table .= '<div id="pagination" class="paginate">'.$_lang["pagination_table_gotopage"].'<ul>'.$this->pageNav.'</ul></div>';
383
-				//$table .= '<script language="javascript">function updatePageSize(size){window.location = \''.$this->prepareLink($linkpage).'pageSize=\'+size;}</script>';
382
+                $table .= '<div id="pagination" class="paginate">'.$_lang["pagination_table_gotopage"].'<ul>'.$this->pageNav.'</ul></div>';
383
+                //$table .= '<script language="javascript">function updatePageSize(size){window.location = \''.$this->prepareLink($linkpage).'pageSize=\'+size;}</script>';
384 384
 
385
-			}
386
-			if ($this->allOption) {
387
-				$table .= '
385
+            }
386
+            if ($this->allOption) {
387
+                $table .= '
388 388
 <script language="javascript">
389 389
 	toggled = 0;
390 390
 	function clickAll() {
@@ -397,134 +397,134 @@  discard block
 block discarded – undo
397 397
 		toggled = (toggled?0:1);
398 398
 	}
399 399
 </script>';
400
-			}
401
-			if ($this->formElementType) {
402
-				if ($this->extra) {
403
-					$table.= "\n".$this->extra."\n";
404
-				}
405
-				$table.= "\n".'</form>'."\n";
406
-			}
407
-			return $table;
408
-		}
409
-	}
410
-
411
-	/**
412
-	 * Generates optional paging navigation controls for the table.
413
-	 *
414
-	 * @param $numRecords The number of records to show per page.
415
-	 * @param $qs An optional query string to be appended to the paging links
416
-	 */
417
-	function createPagingNavigation($numRecords, $qs='') {
418
-		global $_lang;
419
-		$currentPage= (is_numeric($_GET['page']) ? $_GET['page'] : 1);
420
-		$numPages= ceil($numRecords / MAX_DISPLAY_RECORDS_NUM);
421
-		if ($numPages > 1) {
422
-			$currentURL= empty($qs)? '': '?'.$qs;
423
-			if ($currentPage > 6) {
424
-				$nav .= $this->createPageLink($currentURL, 1, $_lang["pagination_table_first"]);
425
-			}
426
-			if ($currentPage != 1) {
427
-				$nav .= $this->createPageLink($currentURL, $currentPage -1, '&lt;&lt;');
428
-			}
429
-			$offset= -4 + ($currentPage < 5 ? (5 - $currentPage) : 0);
430
-			$i= 1;
431
-			while ($i < 10 && ($currentPage + $offset <= $numPages)) {
432
-				if ($currentPage == $currentPage + $offset)
433
-					$nav .= $this->createPageLink($currentURL, $currentPage + $offset, $currentPage + $offset, true);
434
-				else
435
-					$nav .= $this->createPageLink($currentURL, $currentPage + $offset, $currentPage + $offset);
436
-				$i ++;
437
-				$offset ++;
438
-			}
439
-			if ($currentPage < $numPages) {
440
-				$nav .= $this->createPageLink($currentURL, $currentPage +1, '&gt;&gt;');
441
-			}
442
-			if ($currentPage != $numPages) {
443
-				$nav .= $this->createPageLink($currentURL, $numPages, $_lang["pagination_table_last"]);
444
-			}
445
-		}
446
-		$this->pageNav= ' '.$nav;
447
-	}
448
-
449
-	/**
450
-	 * Creates an individual page link for the paging navigation.
451
-	 *
452
-	 * @param $link The link for the page, defaulted to the current document.
453
-	 * @param $pageNum The page number of the link.
454
-	 * @param $displayText The text of the link.
455
-	 * @param $currentPage Indicates if the link is to the current page.
456
-	 * @param $qs And optional query string to be appended to the link.
457
-	 */
458
-	function createPageLink($link='', $pageNum, $displayText, $currentPage=false, $qs='') {
459
-		global $modx;
460
-		$orderBy= !empty($_GET['orderby'])? '&orderby=' . $_GET['orderby']: '';
461
-		$orderDir= !empty($_GET['orderdir'])? '&orderdir=' . $_GET['orderdir']: '';
462
-		if (!empty($qs)) $qs= "?$qs";
463
-		$link= empty($link)? $modx->makeUrl($modx->documentIdentifier, $modx->documentObject['alias'], $qs . "page=$pageNum$orderBy$orderDir"): $this->prepareLink($link) . "page=$pageNum";
464
-		$nav .= '<li'.($currentPage? ' class="currentPage"': '').'><a'.($currentPage? ' class="currentPage"': '').' href="'.$link.'">'.$displayText.'</a></li>'."\n";
465
-		return $nav;
466
-	}
467
-
468
-	/**
469
-	 * Adds an INPUT form element column to the table.
470
-	 *
471
-	 * @param $value The value attribute of the element.
472
-	 * @param $isChecked Indicates if the checked attribute should apply to the
473
-	 * element.
474
-	 */
475
-	function addFormField($value, $isChecked) {
476
-		if ($this->formElementType) {
477
-			$checked= $isChecked? "checked ": "";
478
-			$field= "\t\t".'<td><input type="'.$this->formElementType.'" name="'. ($this->formElementName ? $this->formElementName : $value).'"  value="'.$value.'" '.$checked.'/></td>'."\n";
479
-		}
480
-		return $field;
481
-	}
482
-
483
-	/**
484
-	 * Generates the proper LIMIT clause for queries to retrieve paged results in
485
-	 * a MakeTable $fieldsArray.
486
-	 */
487
-	function handlePaging() {
488
-		$offset= (is_numeric($_GET['page']) && $_GET['page'] > 0) ? $_GET['page'] - 1 : 0;
489
-		$limitClause= ' LIMIT '. ($offset * MAX_DISPLAY_RECORDS_NUM).', '.MAX_DISPLAY_RECORDS_NUM;
490
-		return $limitClause;
491
-	}
492
-
493
-	/**
494
-	 * Generates the SORT BY clause for queries used to retrieve a MakeTable
495
-	 * $fieldsArray
496
-	 *
497
-	 * @param $natural_order If true, the results are returned in natural order.
498
-	 */
499
-	function handleSorting($natural_order=false) {
500
-		$orderByClause= '';
501
-		if (!$natural_order) {
502
-			$orderby= !empty($_GET['orderby'])? $_GET['orderby']: "id";
503
-			$orderdir= !empty($_GET['orderdir'])? $_GET['orderdir']: "DESC";
504
-			$orderbyClause= !empty($orderby)? ' ORDER BY ' . $orderby . ' ' . $orderdir . ' ': "";
505
-		}
506
-		return $orderbyClause;
507
-	}
508
-
509
-	/**
510
-	 * Generates a link to order by a specific $fieldsArray key; use to generate
511
-	 * sort by links in the MakeTable $fieldHeadingsArray values.
512
-	 *
513
-	 * @param $key The $fieldsArray key for the column to sort by.
514
-	 * @param $text The text for the link (e.g. table column header).
515
-	 * @param $qs An optional query string to append to the order by link.
516
-	 */
517
-	function prepareOrderByLink($key, $text, $qs='') {
518
-		global $modx;
519
-		if (!empty($_GET['orderdir'])) {
520
-			$orderDir= strtolower($_GET['orderdir'])=='desc'? '&orderdir=asc': '&orderdir=desc';
521
-		} else {
522
-			$orderDir= '&orderdir=asc';
523
-		}
524
-		if (!empty($qs)) {
525
-			if (!strrpos($qs, '&')==strlen($qs)-1) $qs.= '&';
526
-		}
527
-		return '<a href="[~'.$modx->documentIdentifier.'~]?'.$qs.'orderby='.$key.$orderDir.'">'.$text.'</a>';
528
-	}
400
+            }
401
+            if ($this->formElementType) {
402
+                if ($this->extra) {
403
+                    $table.= "\n".$this->extra."\n";
404
+                }
405
+                $table.= "\n".'</form>'."\n";
406
+            }
407
+            return $table;
408
+        }
409
+    }
410
+
411
+    /**
412
+     * Generates optional paging navigation controls for the table.
413
+     *
414
+     * @param $numRecords The number of records to show per page.
415
+     * @param $qs An optional query string to be appended to the paging links
416
+     */
417
+    function createPagingNavigation($numRecords, $qs='') {
418
+        global $_lang;
419
+        $currentPage= (is_numeric($_GET['page']) ? $_GET['page'] : 1);
420
+        $numPages= ceil($numRecords / MAX_DISPLAY_RECORDS_NUM);
421
+        if ($numPages > 1) {
422
+            $currentURL= empty($qs)? '': '?'.$qs;
423
+            if ($currentPage > 6) {
424
+                $nav .= $this->createPageLink($currentURL, 1, $_lang["pagination_table_first"]);
425
+            }
426
+            if ($currentPage != 1) {
427
+                $nav .= $this->createPageLink($currentURL, $currentPage -1, '&lt;&lt;');
428
+            }
429
+            $offset= -4 + ($currentPage < 5 ? (5 - $currentPage) : 0);
430
+            $i= 1;
431
+            while ($i < 10 && ($currentPage + $offset <= $numPages)) {
432
+                if ($currentPage == $currentPage + $offset)
433
+                    $nav .= $this->createPageLink($currentURL, $currentPage + $offset, $currentPage + $offset, true);
434
+                else
435
+                    $nav .= $this->createPageLink($currentURL, $currentPage + $offset, $currentPage + $offset);
436
+                $i ++;
437
+                $offset ++;
438
+            }
439
+            if ($currentPage < $numPages) {
440
+                $nav .= $this->createPageLink($currentURL, $currentPage +1, '&gt;&gt;');
441
+            }
442
+            if ($currentPage != $numPages) {
443
+                $nav .= $this->createPageLink($currentURL, $numPages, $_lang["pagination_table_last"]);
444
+            }
445
+        }
446
+        $this->pageNav= ' '.$nav;
447
+    }
448
+
449
+    /**
450
+     * Creates an individual page link for the paging navigation.
451
+     *
452
+     * @param $link The link for the page, defaulted to the current document.
453
+     * @param $pageNum The page number of the link.
454
+     * @param $displayText The text of the link.
455
+     * @param $currentPage Indicates if the link is to the current page.
456
+     * @param $qs And optional query string to be appended to the link.
457
+     */
458
+    function createPageLink($link='', $pageNum, $displayText, $currentPage=false, $qs='') {
459
+        global $modx;
460
+        $orderBy= !empty($_GET['orderby'])? '&orderby=' . $_GET['orderby']: '';
461
+        $orderDir= !empty($_GET['orderdir'])? '&orderdir=' . $_GET['orderdir']: '';
462
+        if (!empty($qs)) $qs= "?$qs";
463
+        $link= empty($link)? $modx->makeUrl($modx->documentIdentifier, $modx->documentObject['alias'], $qs . "page=$pageNum$orderBy$orderDir"): $this->prepareLink($link) . "page=$pageNum";
464
+        $nav .= '<li'.($currentPage? ' class="currentPage"': '').'><a'.($currentPage? ' class="currentPage"': '').' href="'.$link.'">'.$displayText.'</a></li>'."\n";
465
+        return $nav;
466
+    }
467
+
468
+    /**
469
+     * Adds an INPUT form element column to the table.
470
+     *
471
+     * @param $value The value attribute of the element.
472
+     * @param $isChecked Indicates if the checked attribute should apply to the
473
+     * element.
474
+     */
475
+    function addFormField($value, $isChecked) {
476
+        if ($this->formElementType) {
477
+            $checked= $isChecked? "checked ": "";
478
+            $field= "\t\t".'<td><input type="'.$this->formElementType.'" name="'. ($this->formElementName ? $this->formElementName : $value).'"  value="'.$value.'" '.$checked.'/></td>'."\n";
479
+        }
480
+        return $field;
481
+    }
482
+
483
+    /**
484
+     * Generates the proper LIMIT clause for queries to retrieve paged results in
485
+     * a MakeTable $fieldsArray.
486
+     */
487
+    function handlePaging() {
488
+        $offset= (is_numeric($_GET['page']) && $_GET['page'] > 0) ? $_GET['page'] - 1 : 0;
489
+        $limitClause= ' LIMIT '. ($offset * MAX_DISPLAY_RECORDS_NUM).', '.MAX_DISPLAY_RECORDS_NUM;
490
+        return $limitClause;
491
+    }
492
+
493
+    /**
494
+     * Generates the SORT BY clause for queries used to retrieve a MakeTable
495
+     * $fieldsArray
496
+     *
497
+     * @param $natural_order If true, the results are returned in natural order.
498
+     */
499
+    function handleSorting($natural_order=false) {
500
+        $orderByClause= '';
501
+        if (!$natural_order) {
502
+            $orderby= !empty($_GET['orderby'])? $_GET['orderby']: "id";
503
+            $orderdir= !empty($_GET['orderdir'])? $_GET['orderdir']: "DESC";
504
+            $orderbyClause= !empty($orderby)? ' ORDER BY ' . $orderby . ' ' . $orderdir . ' ': "";
505
+        }
506
+        return $orderbyClause;
507
+    }
508
+
509
+    /**
510
+     * Generates a link to order by a specific $fieldsArray key; use to generate
511
+     * sort by links in the MakeTable $fieldHeadingsArray values.
512
+     *
513
+     * @param $key The $fieldsArray key for the column to sort by.
514
+     * @param $text The text for the link (e.g. table column header).
515
+     * @param $qs An optional query string to append to the order by link.
516
+     */
517
+    function prepareOrderByLink($key, $text, $qs='') {
518
+        global $modx;
519
+        if (!empty($_GET['orderdir'])) {
520
+            $orderDir= strtolower($_GET['orderdir'])=='desc'? '&orderdir=asc': '&orderdir=desc';
521
+        } else {
522
+            $orderDir= '&orderdir=asc';
523
+        }
524
+        if (!empty($qs)) {
525
+            if (!strrpos($qs, '&')==strlen($qs)-1) $qs.= '&';
526
+        }
527
+        return '<a href="[~'.$modx->documentIdentifier.'~]?'.$qs.'orderby='.$key.$orderDir.'">'.$text.'</a>';
528
+    }
529 529
 
530 530
 }
Please login to merge, or discard this patch.