Project

General

Profile

plugin.foundation.php

krileon, 14 September 2011 08:05 PM

 
1
<?php
2
/**
3
* Joomla/Mambo Community Builder
4
* @version $Id: plugin.foundation.php 1549 2011-07-30 15:31:34Z beat $
5
* @package Community Builder
6
* @subpackage plugin.foundation.php
7
* @author JoomlaJoe and Beat
8
* @copyright (C) JoomlaJoe and Beat, www.joomlapolis.com
9
* @license http://www.gnu.org/licenses/old-licenses/gpl-2.0.html GNU/GPL version 2
10
*/
11

    
12
// ensure this file is being included by a parent file
13
if ( ! ( defined( '_VALID_CB' ) || defined( '_JEXEC' ) || defined( '_VALID_MOS' ) ) ) { die( 'Direct Access to this location is not allowed.' ); }
14

    
15
global $ueConfig;
16
include_once( dirname( __FILE__ ) . '/ue_config.php' );
17
$ueConfig['version']                =        '1.7';
18
define( '_CB_JQUERY_VERSION', '1.5.2' );                // IMPORTANT: when changing version here also change in the 2 XML installation files
19
define( '_CB_SPOOFCHECKS', ( isset( $ueConfig['enableSpoofCheck'] ) && $ueConfig['enableSpoofCheck'] ) ? 1 : 0 );
20
define( '_CB_VALIDATE_NEW', 1 );                // Comment line with // at begin for old-way mosReq way
21

    
22
/**
23
 * CB 1.2 Stable Release
24
 */
25

    
26
/**
27
 * CB Functions
28
 */
29

    
30
/**
31
 * gets Itemid of CB profile, or by default of homepage
32
 * @deprecated  CB 1.2.3  (use $_CB_framework->userProfiler...Url and ->viewUrl from CB 1.2.3 on)
33
 *
34
 * @param  boolean $htmlspecialchars  TRUE if should return "&amp:Itemid...." instead of "&Itemid..." (with FALSE as default), === 0 if return only int
35
 * @param  string $task               task/view  e.g. 'userslist'   (since CB 1.2.3)
36
 * @return string                     "&Itemid=xxx"
37
 */
38
function getCBprofileItemid( $htmlspecialchars = false, $task = 'userprofile' ) {
39
        global $_CB_database, $_CB_framework;
40
        static $cacheItemids                =        array();
41

    
42
        if ( ! isset( $cacheItemids[$task] ) ) {
43
                if ( $task !== 'userprofile' && is_string( $task ) ) {
44
                        $_CB_database->setQuery( 'SELECT id FROM #__menu WHERE link LIKE '
45
                                                                        . $_CB_database->Quote( 'index.php?option=com_comprofiler&task=' . $_CB_database->getEscaped( $task, true ) . '%', false )
46
                                                                        . ' AND published=1 AND access ' . ( $_CB_framework->myCmsGid() == 0 ? '= ' : '<= ' ) . (int) $_CB_framework->myCmsGid() );
47
                        $Itemid                                =        (int) $_CB_database->loadResult();
48
                } else {
49
                        $Itemid                                =        null;
50
                }
51
                if ( ( $task === 'userprofile' ) || ( ( ! $Itemid ) && ! in_array( $task, array( 'login', 'logout', 'registers', 'lostpassword' ) ) ) ) {
52
                        // $task used to be a boolean before CB 1.2.3 but with no effect:
53
                        $task                                =        'userprofile';
54
                        $_CB_database->setQuery("SELECT id FROM #__menu WHERE link = 'index.php?option=com_comprofiler' AND published=1 AND access " . ( $_CB_framework->myCmsGid() == 0 ? "= " : "<= " ) . (int) $_CB_framework->myCmsGid() );
55
                        $Itemid = (int) $_CB_database->loadResult();
56
                        if ( ! $Itemid ) {                // if no user profile, try getting itemid of the default list:
57
                                $_CB_database->setQuery("SELECT id FROM #__menu WHERE link = 'index.php?option=com_comprofiler&task=usersList' AND published=1 AND access " . ( $_CB_framework->myCmsGid() == 0 ? "= " : "<= " ) . (int) $_CB_framework->myCmsGid() );
58
                                $Itemid = (int) $_CB_database->loadResult();
59
                        }
60
                }
61
                $cacheItemids[$task]        =        $Itemid;
62
        }
63
        if ( $cacheItemids[$task] ) {
64
                if ( is_bool( $htmlspecialchars ) ) {
65
                        return ( $htmlspecialchars ? "&amp;" : "&") . "Itemid=" . $cacheItemids[$task];
66
                } else {
67
                        return $cacheItemids[$task];
68
                }
69
        } else {
70
                return null;
71
        }
72
}
73

    
74
/**
75
 * Includes CB library
76
 * --- usage: cbimport('cb.xml.simplexml');
77
 *
78
 * @param string $path
79
 */
80
function cbimport( $lib ) {
81
        global $_CB_framework;
82
        static $imported                        =        array();
83
        static $tmpClasses                        =        array( 'cb.html', 'cb.tabs', 'cb.field', 'cb.calendar', 'cb.connection', 'cb.notification' );
84

    
85
        if ( ! isset( $imported[$lib] ) ) {
86
                $imported[$lib]                        =        true;
87

    
88
                $liblow                                        =        strtolower( $lib );
89
                $pathAr                                        =        explode( '.', $liblow );
90
                if ( $pathAr[0] == 'language' ) {
91
                        $langPath                        =        $_CB_framework->getCfg( 'absolute_path' ) . '/components/com_comprofiler/plugin/language';
92
                        $lang                                =        $_CB_framework->getCfg( 'lang' );
93
                        if ( in_array( $pathAr[1], array( 'front', 'all' ) ) ) {
94
                                $filename                =        $lang . '.php';
95
                        } else {
96
                                $filename                =        $pathAr[1] . '_language.php';
97
                        }
98
                        if ( ! file_exists( $langPath . '/' . $lang . '/' . $filename ) ) {
99
                                $lang                        =        strtolower( $_CB_framework->getCfg( 'lang_tag' ) );
100
                                if ( in_array( $pathAr[1], array( 'front', 'all' ) ) ) {
101
                                        $filename        =        'language.php';
102
                                }
103
                        }
104
                        if ( ! file_exists( $langPath . '/' . $lang . '/' . $filename ) ) {
105
                                $lang                        =        'default_language';
106
                                if ( in_array( $pathAr[1], array( 'front', 'all' ) ) ) {
107
                                        $filename        =        $lang . '.php';
108
                                }
109
                        }
110
                        if ( file_exists( $langPath . '/' . $lang . '/' . $filename ) ) {
111
                                include_once( $langPath . '/' . $lang . '/' . $filename );
112
                        }
113
                } elseif ( $lib == 'cb.plugins' ) {
114
                        // this part is temporary until we refactor those 2 files into the corresponding CB libraries:
115
                        require_once( $_CB_framework->getCfg('absolute_path') . '/administrator/components/com_comprofiler/plugin.class.php' );
116
                } elseif ( in_array( $lib, $tmpClasses ) ) {
117
                        // this part is temporary until we refactor those 2 files into the corresponding CB libraries:
118
                        if ( ! isset( $imported['cb.plugins'] ) ) {
119
                                $imported['cb.plugins']        =        true;
120
                                require_once( $_CB_framework->getCfg('absolute_path') . '/administrator/components/com_comprofiler/plugin.class.php' );
121
                        }
122
                        if ( ! isset( $imported['class'] ) ) {
123
                                $imported['class']        =        true;
124
                                require_once( $_CB_framework->getCfg('absolute_path') . '/administrator/components/com_comprofiler/comprofiler.class.php' );
125
                        }
126
                } elseif ( $lib == 'cb.imgtoolbox' ) {
127
                        // this part is temporary until we refactor those 2 files into the corresponding CB libraries:
128
                        require_once( $_CB_framework->getCfg('absolute_path') . '/administrator/components/com_comprofiler/imgToolbox.class.php' );
129
                } elseif ( $lib == 'cb.snoopy' ) {
130
                        require_once( $_CB_framework->getCfg('absolute_path') . '/administrator/components/com_comprofiler/Snoopy.class.php' );
131
                } else {
132
                        array_pop( $pathAr );
133
                        $filepath                =        implode( '/', $pathAr ) . (count( $pathAr ) ? '/' : '' ) . $liblow . '.php';
134

    
135
                        require_once( $_CB_framework->getCfg('absolute_path') . '/administrator/components/com_comprofiler/library/' . $filepath );
136
                }
137
        }
138
}
139
/**
140
 * Sanitizes an array of (int)
141
 * 
142
 * @param  array $array  in/out
143
 * @return array
144
 */
145
function & cbArrayToInts( &$array ) {
146
        foreach ( $array as $k => $v ) {
147
                $array[$k]        =        (int) $v;
148
        }
149
        return $array;
150
}
151
/**
152
 * Does the opposite of htmlspecialchars()
153
 *
154
 * @param  string  $text
155
 * @return string
156
 */
157
function cbUnHtmlspecialchars( $text ) {
158
        return str_replace( array( "&amp;", "&quot;", "&#039;", "&lt;", "&gt;" ), array( "&", "\"", "'", "<", ">" ), $text );
159
}
160
/**
161
* String based find and replace that is case insensitive and works on php4 too
162
* same as PHP5 str_ireplace()
163
*
164
* @param  string  $search   value to look for
165
* @param  string  $replace  value to replace with
166
* @param  string  $subject  text to be searched
167
* @return string            with text searched and replaced
168
*/
169
function cbstr_ireplace( $search, $replace, $subject ) {
170
        if ( function_exists('str_ireplace') ) {
171
                return str_ireplace($search,$replace,$subject);                // php 5 only
172
        }
173
        $srchlen = strlen($search);    // lenght of searched string
174
        $result  = "";
175

    
176
        while ( true == ( $find = stristr( $subject, $search ) ) ) {        // find $search text in $subject - case insensitiv
177
                $srchtxt = substr($find,0,$srchlen);                            // get new case-sensitively-correct search text
178
                $pos         = strpos( $subject, $srchtxt );                        // stripos is php5 only...
179
                $result         .= substr( $subject, 0, $pos ) . $replace;        // replace found case insensitive search text with $replace
180
                $subject = substr( $subject, $pos + $srchlen );
181
        }
182
        return $result . $subject;
183
}
184

    
185
/**
186
 * Translates text strings from CB and core cms ('_UE_....') into current language
187
 *
188
 * @param  string  $text
189
 * @return string
190
 */
191
function getLangDefinition($text) {
192
        // check for '::' as a workaround of bug #42770 in PHP 5.2.4 with optimizers:
193
        if ( ( strpos( $text, '::' ) === false ) && defined( $text ) ) {
194
                $returnText                =        constant( $text );
195
        } else {
196
                $returnText                =        $text;                        // not yet: CBTxt::T( $text );
197
        }
198
        return $returnText;
199
}
200

    
201
/**
202
 * Check Mambo/Joomla/others version for API
203
 *
204
 * @param  string  $info  'api', 'product', 'release'
205
 * @return mixed          'api'     : API version: =0 = mambo 4.5.0-4.5.3+Joomla 1.0.x, =1 = Joomla! 1.1, >1 newever ones: maybe compatible, <0: -1: Mambo 4.6
206
 *                        'product' : product name
207
 *                        'release' : php-style release number
208
 */
209
function checkJversion( $info = 'api' ) {
210
        static $version                                                =        array();
211

    
212
        if ( isset( $version[$info] ) ) {
213
                return $version[$info];
214
        }
215

    
216
        if ( class_exists( 'JVersion' ) ) {
217
                $VO                                                                =        new JVersion();
218
        } else {
219
                global $_VERSION;
220

    
221
                if ( $_VERSION ) {
222
                        $VO                                                        =        $_VERSION;
223
                } else {
224
                        trigger_error( 'Unable to determine CMS version.', E_USER_ERROR );
225
                        die();
226
                }
227
        }
228

    
229
        switch ( $info ) {
230
                case 'api':
231
                        $cms_version                                =        substr( $VO->RELEASE, 0, 3 );
232

    
233
                        if ( $VO->PRODUCT == 'Mambo' ) {
234
                                if ( strcasecmp( $cms_version, '4.6' ) < 0 ) {
235
                                        $version[$info]                =        0;
236
                                } else {
237
                                        $version[$info]                =        -1;
238
                                }
239
                        } elseif ( $VO->PRODUCT == 'Elxis' ) {
240
                                $version[$info]                        =        0;
241
                        } elseif ( $VO->PRODUCT == 'MiaCMS' ) {
242
                                $version[$info]                        =        -1;
243
                        } elseif ( ( $VO->PRODUCT == 'Joomla!' ) || ( $VO->PRODUCT == 'Accessible Joomla!' ) ) {
244
                                if ( strcasecmp( $cms_version, '1.6' ) >= 0 ) {
245
                                        $version[$info]                =        2;
246
                                } elseif ( strcasecmp( $cms_version, '1.5' ) == 0 ) {
247
                                        $version[$info]                =        1;
248
                                } else {
249
                                        $version[$info]                =        0;
250
                                }
251
                        } else {
252
                                $version[$info]                        =        0;
253
                        }
254
                        break;
255
                case 'product':
256
                        $version[$info]                                =        $VO->PRODUCT;
257
                        break;
258
                case 'release':
259
                        $version[$info]                                =        $VO->RELEASE;
260
                        break;
261
                case 'dev_level':
262
                        $version[$info]                                =        $VO->DEV_LEVEL;
263
                        break;
264
                default:
265
                        break;
266
        }
267
        return $version[$info];
268
}
269

    
270
/**
271
 * Utility function to return a value from a named array or a specified default.
272
 * TO CONTRARY OF MAMBO AND JOOMLA mos Get Param:
273
 * 1) DOES NOT MODIFY ORIGINAL ARRAY
274
 * 2) Does sanitize ints
275
 * 3) Does return default array() for a default value array(0) which indicates sanitizing an array of ints.
276
 *
277
 * @param array A named array
278
 * @param string The key to search for
279
 * @param mixed The default value to give if no key found
280
 * @param int An options mask: _MOS_NOTRIM prevents trim, _MOS_ALLOWHTML allows safe html, _MOS_ALLOWRAW allows raw input
281
 */
282
define( "_CB_NOTRIM", 0x0001 );
283
//define( "_MOS_ALLOWHTML", 0x0002 );
284
define( "_CB_ALLOWRAW", 0x0004 );
285
function cbGetParam( &$arr, $name, $def=null, $mask=0 ) {
286
        static $noHtmlFilter        =        null;
287

    
288
        if ( isset( $arr[$name] ) ) {
289
        if ( is_array( $arr[$name] ) ) {
290
                $ret                        =        array();
291
                foreach ( array_keys( $arr[$name] ) as $k ) {
292
                        $ret[$k]        =        cbGetParam( $arr[$name], $k, $def, $mask);
293
                        if ( $def === array( 0 ) ) {
294
                                $ret[$k] =        (int) $ret[$k];
295
                        }
296
                }
297
        } else {
298
                        $ret                        =        $arr[$name];
299
                        if ( is_string( $ret ) ) {
300
                                if ( ! ( $mask & _CB_NOTRIM ) ) {
301
                                        $ret        =        trim( $ret );
302
                                }
303
                                if ( ! ( $mask & _CB_ALLOWRAW ) ) {
304
                                        if ( is_null( $noHtmlFilter ) ) {
305
                                                cbimport( 'phpinputfilter.inputfilter' );
306
                                                $noHtmlFilter = new CBInputFilter( /* $tags, $attr, $tag_method, $attr_method, $xss_auto */ );
307
                                        }
308
                                        $ret        =        $noHtmlFilter->process( $ret );
309
                                }
310
                                if ( is_int( $def ) ) {
311
                                        $ret        =        (int) $ret;
312
                                } elseif ( is_float( $def ) ) {
313
                                        $ret        =        (float) $ret;
314
                                } elseif ( !  get_magic_quotes_gpc() ) {
315
                                        $ret        =        addslashes( $ret );
316
                                }
317
                        }
318
        }
319
                return $ret;
320
        } elseif ( false !== ( $firstSeparator = strpos( $name, '[' )  ) ) {
321
                // html-input-name-encoded array selection, e.g. a[b][c]
322
                $indexes                        =        null;
323
                $mainArrName                =        substr( $name, 0, $firstSeparator );
324
                $count                                =        preg_match_all( '/\\[([^\\[\\]]+)\\]/', substr( $name, $firstSeparator ), $indexes );
325
                if ( isset( $arr[$mainArrName] ) && ( $count > 0 ) ) {
326
                        $a                                =        $arr[$mainArrName];
327
                        for ( $i = 0; $i < ( $count - 1 ); $i++ ) {
328
                                if ( ! isset( $a[$indexes[1][$i]] ) ) {
329
                                        $a                =        null;
330
                                        break;
331
                                }
332
                                $a                        =        $a[$indexes[1][$i]];
333
                        }
334
                } else {
335
                        $a                                =        null;
336
                }
337
                if ( $a !== null ) {
338
                        return cbGetParam( $a, $indexes[1][$i], $def, $mask );
339
                }
340
        }
341
        if ( $def === array( 0 ) ) {
342
                return array();
343
        }
344
        return $def;
345
}
346

    
347
/**
348
 * Redirects browser to new $url with a $message .
349
 * No return from this function !
350
 *
351
 * @param  string  $url
352
 * @param  string  $message
353
 * @param  string  $messageType  'message', 'error'
354
 */
355
function cbRedirect( $url, $message = '', $messageType = 'message' ) {
356
        global $_CB_framework, $_CB_database;
357

    
358
        if ( ( $_CB_framework->getCfg( 'debug' ) > 0 ) && ( ob_get_length() || ( $_CB_framework->getCfg( 'debug' ) > 1 ) ) ) {
359
                $outputBufferLength                =        ob_get_length();
360
                $ticker                                        =        ( checkJversion() == 2 ? $_CB_database->_db->getTicker() : $_CB_database->_db->_ticker );
361
                $log                                        =        ( checkJversion() == 2 ? $_CB_database->_db->getLog() : $_CB_database->_db->_log );
362
                echo '<br /><br /><strong>Site Debug mode: CB redirection';
363
                if ( $message ) {
364
                        echo ' with ' . $messageType . ' "' . $message . '"';
365
                }
366
                if ( $outputBufferLength ) {
367
                        echo ' <u>without empty output</u>';
368
                }
369
                echo "<br /><p><em>During its normal operations Community Builder often redirects you between pages and this causes potentially interesting debug information to be missed. "
370
                        . "When your site is in debug mode (global joomla/mambo config is site debug ON), some of these automatic redirects are disabled. "
371
                        . "This is a normal feature of the debug mode and does not directly mean that you have any problems.</em></p>"
372
                        . '</strong>Click this link to proceed with the next page (in non-debug mode this is automatic): ';
373
                echo '<a href="' . $url . '">' . htmlspecialchars( $url ) . '</a><br /><br /><hr />';
374

    
375
                echo $ticker . ' queries executed'
376
                        . '<pre>';
377
                 foreach ( $log as $k => $sql ) {
378
                         echo $k + 1 . "\n" . htmlspecialchars( $sql ) . '<hr />';
379
                }
380
                echo '</hr>'
381
                        . '</hr>POST: ';
382
                var_export( $_POST );
383
                echo '</pre>';
384
                die();
385
        } else {
386
                $_CB_framework->redirect( $url, $message, $messageType );
387
        }
388
}
389

    
390
/**
391
 * stripslashes() string or nested array of strings
392
 *
393
 * @param  string|array  with slashes
394
 * @return string|array  without slashes
395
 */
396
function cbStripslashes( $value ) {
397
        $striped                                        =        '';
398
        if ( is_string( $value ) ) {
399
                $striped                                =        stripslashes( $value );
400
        } else {
401
                if ( is_array( $value ) ) {
402
                        $striped                        =        array();
403
                        foreach ( array_keys( $value ) as $k ) {
404
                                $striped[$k]        =        cbStripslashes( $value[$k] );
405
                        }
406
                } else {
407
                        $striped                        =        $value;
408
                }
409
        }
410
        return $striped;
411
}
412

    
413
/**
414
* Returns full path to template directory, as live URL (live_site, by default), absolute directory path
415
*
416
* @param  string  $output        'live_site' (with trailing /), 'absolute_path' (without trailing /), 'dir' name only (depreciated was: int  DEPRECIATED: info for backwards-compatibility: user interface : 1: frontend, 2: backend (not used anymore)
417
* @param  string  $templateName  null: according to settings, string: name of template (directory)
418
* @return string                 Template directory path with trailing '/'
419
*/
420
function selectTemplate( $output = 'live_site', $templateName = null ) {
421
        global $_CB_framework, $ueConfig;
422

    
423
        if ( $templateName == null ) {
424
                if ( $_CB_framework->getUi() == 1 ) {
425
                        $templateName        =        $ueConfig['templatedir'];
426
                } else {
427
                        $templateName        =        'luna';
428
                }
429
        }
430
        if ( $output == 'dir' ) {
431
                return $templateName;
432
        } elseif ( $output == 'absolute_path' ) {
433
                return $_CB_framework->getCfg( 'absolute_path' ) . '/components/com_comprofiler/plugin/templates/' . $templateName;
434
        } else {
435
                return ( $_CB_framework->getUi() == 2 ? '..' : $_CB_framework->getCfg( 'live_site' ) ) . '/components/com_comprofiler/plugin/templates/' . $templateName . '/';
436
        }
437
}
438

    
439

    
440

    
441
function cbSpoofString( $string = null, $secret = null ) {
442
        global $_CB_framework;
443

    
444
        $date                        =        date( 'dmY' );
445
        if ( $string === null ) {
446
                $salt                =        array();
447
                $salt[0]        =        mt_rand( 1, 2147483647 );
448
                $salt[1]        =        mt_rand( 1, 2147483647 );                // 2 * 31 bits random
449
        } else {
450
                $salt                =        sscanf( $string, 'cbm_%08x_%08x_%s' );
451
                if ( $string != sprintf( 'cbm_%08x_%08x_%s', $salt[0], $salt[1], md5( $salt[0] . $date . $_CB_framework->getUi() . $_CB_framework->getCfg( 'db' ) . $_CB_framework->getCfg('secret') . $secret . $salt[1] ) ) ) {
452
                        $date        =        date( 'dmY', time() - 64800 );        // 18 extra-hours of grace after midnight.
453
                }
454
        }
455
        return sprintf( 'cbm_%08x_%08x_%s', $salt[0], $salt[1], md5( $salt[0] . $date . $_CB_framework->getUi() . $_CB_framework->getCfg( 'db' ) . $_CB_framework->getCfg('secret') . $secret . $salt[1] ) );
456
}
457
function cbSpoofField() {
458
        return 'cbsecuritym3';
459
}
460
/**
461
 * Computes and returns an antifspoofing additional input tag
462
 *
463
 * @return string "<input type="hidden...\n" tag
464
 */
465
function cbGetSpoofInputTag( $secret = null, $cbSpoofString = null ) {
466
        if ( $cbSpoofString === null ) {
467
                $cbSpoofString                =        cbSpoofString( null, $secret );
468
        }
469
        return "<input type=\"hidden\" name=\"" . cbSpoofField() . "\" value=\"" .  $cbSpoofString . "\" />\n";
470
}
471

    
472
function _cbjosSpoofCheck($array, $badStrings) {
473
        foreach ($array as $v) {
474
                foreach ($badStrings as $v2) {
475
                        if (is_array($v)) {
476
                                _cbjosSpoofCheck($v, $badStrings);
477
                        } else if (strpos( $v, $v2 ) !== false) {
478
                                header( "HTTP/1.0 403 Forbidden" );
479
                                exit( _UE_NOT_AUTHORIZED );
480
                        }
481
                }
482
        }
483
}
484
/**
485
 * Checks spoof value and other spoofing and injection tricks
486
 *
487
 * @param  string   $secret   extra-hashing value for this particular spoofCheck
488
 * @param  string   $var      'POST', 'GET', 'REQUEST'
489
 * @param  int      $mode     1: exits with script to display error and go back, 2: returns true or false.
490
 * @return boolean  or exit   If $mode = 2 : returns false if session expired.
491
 */
492
function cbSpoofCheck( $secret = null, $var = 'POST', $mode = 1 ) {
493
        global $_POST, $_GET, $_REQUEST;
494

    
495
        if ( _CB_SPOOFCHECKS ) {
496
                if ( $var == 'GET' ) {
497
                        $validateValue         =        cbGetParam( $_GET,     cbSpoofField(), '' );
498
                } elseif ( $var == 'REQUEST' ) {
499
                        $validateValue         =        cbGetParam( $_REQUEST, cbSpoofField(), '' );
500
                } else {
501
                        $validateValue         =        cbGetParam( $_POST,    cbSpoofField(), '' );
502
                }
503
                if ( ( ! $validateValue ) || ( $validateValue != cbSpoofString( $validateValue, $secret ) ) ) {
504
                        if ( $mode == 2 ) {
505
                                return false;
506
                        }
507
                        _cbExpiredSessionJSterminate( 200 );
508
                        exit;
509
                }
510
        }
511
        // First, make sure the form was posted from a browser.
512
        // For basic web-forms, we don't care about anything
513
        // other than requests from a browser:
514
        if (!isset( $_SERVER['HTTP_USER_AGENT'] )) {
515
                header( 'HTTP/1.0 403 Forbidden' );
516
                exit( _UE_NOT_AUTHORIZED );
517
        }
518

    
519
        // Make sure the form was indeed POST'ed:
520
        //  (requires your html form to use: action="post")
521
        if (!$_SERVER['REQUEST_METHOD'] == 'POST' ) {
522
                header( 'HTTP/1.0 403 Forbidden' );
523
                exit( _UE_NOT_AUTHORIZED );
524
        }
525

    
526
        // Attempt to defend against header injections:
527
        $badStrings = array(
528
                'Content-Type:',
529
                'MIME-Version:',
530
                'Content-Transfer-Encoding:',
531
                'bcc:',
532
                'cc:'
533
        );
534

    
535
        // Loop through each POST'ed value and test if it contains
536
        // one of the $badStrings:
537
        foreach ($_POST as $v){
538
                foreach ($badStrings as $v2) {
539
                        if (is_array($v)) {
540
                                _cbjosSpoofCheck($v, $badStrings);
541
                        } else if (strpos( $v, $v2 ) !== false) {
542
                                header( "HTTP/1.0 403 Forbidden" );
543
                                exit( _UE_NOT_AUTHORIZED );
544
                        }
545
                }
546
        }
547

    
548
        // Made it past spammer test, free up some memory
549
        // and continue rest of script:
550
        unset( $v, $v2, $badStrings );
551
        return true;
552
}
553
function _cbExpiredSessionJSterminate( $code = 403 ) {
554
        if ( $code == 403 ) {
555
                header( 'HTTP/1.0 403 Forbidden' );
556
        }
557
        echo "<script type=\"text/javascript\">alert('" . addslashes( _UE_SESSION_EXPIRED . ' ' . _UE_PLEASE_REFRESH ) . "'); window.history.go(-1);</script> \n";
558
        exit;
559
}
560

    
561
/**
562
 * CB Classes
563
 */
564
class cbObject {
565
        /**
566
        * Gets a param value
567
        *
568
        * @param  string  $key      The name of the param
569
        * @param  mixed   $default  The default value if not found (if array(), the return will be an array too)
570
        * @return string|array
571
        */
572
        function get( $key, $default = null ) {
573
                if ( isset( $this->$key ) ) {
574
                        return $this->$key;
575
                }
576
                return $default;
577
        }
578
        /**
579
        * Sets a value to a param
580
        *
581
        * @param  string  $key    The name of the param
582
        * @param  string  $value  The value of the parameter
583
        * @return cbObject        For chaining
584
        */
585
        function set( $key, $value='' ) {
586
                $this->$key                =        $value;
587
                return $this;
588
        }
589
}
590
/**
591
* Parameters handler
592
* @package Joomla/Mambo Community Builder
593
*/
594
class cbParamsBase {
595
        /** @var object */
596
        var $_params = null;
597
        /** @var string The raw params string */
598
        var $_raw = null;
599
        /**
600
        * Constructor
601
        *
602
        * @param  string  $paramsValues  The raw parms text
603
        */
604
        function cbParamsBase( $paramsValues ) {
605
            $this->_params = $this->parse( $paramsValues );
606
            $this->_raw = $paramsValues;
607
        }
608
        /**
609
        * Loads from the plugins database
610
        *
611
        * @param  string   $element  The plugin element name
612
        * @return boolean            true: could load, false: query error.
613
        */
614
        function loadFromDB( $element ) {
615
                global $_CB_database;
616

    
617
            $_CB_database->setQuery("SELECT params FROM `#__comprofiler_plugin` WHERE element = '" . $_CB_database->getEscaped( $element ) . "'" );
618
            $text = $_CB_database->loadResult();
619
            $this->_params = $this->parse( $text );
620
            $this->_raw = $text;
621
            return ( $text !== null );
622
        }
623
        /**
624
        * Transforms the existing params to a ini string
625
        * @since 1.2.1
626
        *
627
        * @return string
628
        */
629
        function toIniString() {
630
                $txt                =        array();
631
                foreach ( get_object_vars( $this->_params ) as $k => $v ) {
632
                        if ( strstr( $v, "\n" ) ) {
633
                                $v = str_replace( array( "\\", "\n", "\r" ), array( "\\\\", '\\n', '\\r'  ) , $v );
634
                        }
635
                        $txt[] = $k . '=' . $v;
636
                }
637
                return implode( "\n", $txt );
638
        }
639
        /**
640
         * Returns an array of all current params
641
         *
642
         * @return array
643
         */
644
        function toParamsArray( ) {
645
                return get_object_vars( $this->_params );
646
        }
647
        /**
648
        * Sets a value to a param
649
        *
650
        * @param  string  $key    The name of the param
651
        * @param  string  $value  The value of the parameter
652
        * @return string  The set value
653
        */
654
        function set( $key, $value='' ) {
655
                $this->_params->$key = $value;
656
                return $value;
657
        }
658
        /**
659
        * Un-Sets a param
660
        * @since 1.2.1
661
        *
662
        * @param  string  $key    The name of the param
663
        */
664
        function unsetParam( $key ) {
665
                unset( $this->_params->$key );
666
        }
667
        /**
668
        * Sets a default value to param if not alreay assigned
669
        *
670
        * @param  string  $key    The name of the param
671
        * @param  string  $value  The value of the parameter
672
        * @return string  The set value
673
        */
674
        function def( $key, $value='' ) {
675
            return $this->set( $key, $this->get( $key, $value ) );
676
        }
677
        /**
678
        * Gets a param value
679
        *
680
        * @param  string  $key      The name of the param
681
        * @param  mixed   $default  The default value if not found (if array(), the return will be an array too)
682
        * @return string|array
683
        */
684
        function get( $key, $default = null ) {
685
            if ( isset( $this->_params->$key ) ) {
686
                    if ( is_array( $default ) ) {
687
                            if ( strpos( $this->_params->$key, '|**|' ) === 0 ) {
688
                                    // indexed array:
689
                                    $parts                                =        explode( '|**|', substr( $this->_params->$key, 4 ) );
690
                                    $r                                        =        array();
691
                                        foreach ( $parts as $v ) {
692
                                                $p                                =        explode( '=', $v, 2 );
693
                                                if ( isset( $p[1] ) ) {
694
                                                        $r[$p[0]]        =        $p[1];
695
                                                }
696
                                        }
697
                                        return $r;
698
                            } else {
699
                                    // non-indexed array:
700
                                    return explode( '|*|', $this->_params->$key );
701
                            }
702
                    } else {
703
                        return $this->_params->$key;
704
                    }
705
                } else {
706
                        $isArray                =        strpos( $key, '[' );
707
                        if ( $isArray ) {
708
                                // case of indexed arrays:
709
                                $value                =        $default;
710
                                $arrayString =        $this->get( substr( $key, 0, $isArray ) );
711
                                if ( $arrayString && ( strpos( $arrayString, '|**|' ) === 0 ) ) {
712
                                        $index        =        substr( $key, $isArray + 1, strpos( $key, ']' ) - $isArray -1 );
713
                                        $parts        =        explode( '|**|', substr( $arrayString, 4 ) );
714
                                        foreach ( $parts as $v ) {
715
                                                $p        =        explode( '=', $v, 2 );
716
                                                if ( $p[0] == $index ) {
717
                                                        if ( isset( $p[1] ) ) {
718
                                                                return $p[1];
719
                                                        }
720
                                                }
721
                                        }
722
                                }
723
                        }
724
                        return $default;
725
                }
726
        }
727
        /**
728
        * Parse an JSON (PHP >=5.2) string or an .ini string, based on phpDocumentor phpDocumentor_parse_ini_file function
729
        *
730
        * @param  mixed    $txt               The ini string (or, deprecated as works only for ini: array of lines)
731
        * @param  boolean  $process_sections  Add an associative index for each section [in brackets]
732
        * @param  boolean  $asArray           Returns an array instead of an object
733
        * @return object|array
734
        */
735
        function parse( $txt, $process_sections = false, $asArray = false ) {
736
                if (is_string( $txt )) {
737
                        if ( isset( $txt[0] ) && ( $txt[0] === '{' ) ) {
738
                                // JSON encoding: requires PHP 5.2, and used in Joomla 1.6+:
739
                                return json_decode( $txt, $asArray );
740
                        }
741
                        // ini string: rest of function is for INI string processing:
742
                        $lines = explode( "\n", $txt );
743
                } else if (is_array( $txt )) {
744
                        $lines = $txt;
745
                } else {
746
                        $lines = array();
747
                }
748
                $obj = $asArray ? array() : new cbObject();
749

    
750
                $sec_name = '';
751
                $unparsed = 0;
752
                if (!$lines) {
753
                        return $obj;
754
                }
755
                foreach ($lines as $line) {
756
                        // ignore comments
757
                        if ($line && $line[0] == ';') {
758
                                continue;
759
                        }
760
                        $line = trim( $line );
761

    
762
                        if ($line == '') {
763
                                continue;
764
                        }
765
                        if ($line && $line[0] == '[' && $line[strlen($line) - 1] == ']') {
766
                                $sec_name = substr( $line, 1, strlen($line) - 2 );
767
                                if ($process_sections) {
768
                                        if ($asArray) {
769
                                                $obj[$sec_name] = array();
770
                                        } else {
771
                                                $obj->$sec_name = new cbObject();
772
                                        }
773
                                }
774
                        } else {
775
                                if ( false !== ( $pos = strpos( $line, '=' ) ) ) {
776
                                        $property = trim( substr( $line, 0, $pos ) );
777

    
778
                                        if (substr($property, 0, 1) == '"' && substr($property, -1) == '"') {
779
                                                $property = stripcslashes(substr($property,1,count($property) - 2));
780
                                        }
781
                                        $value = trim( substr( $line, $pos + 1 ) );
782
                                        if ($value == 'false') {
783
                                                $value = false;
784
                                        }
785
                                        if ($value == 'true') {
786
                                                $value = true;
787
                                        }
788
                                        if (substr( $value, 0, 1 ) == '"' && substr( $value, -1 ) == '"') {
789
                                                $value = stripcslashes( substr( $value, 1, count( $value ) - 2 ) );
790
                                        }
791

    
792
                                        if ($process_sections) {
793
                                                $value = str_replace( array( '\n', '\r', '\\\\' ), array( "\n", "\r", '\\' ), $value );
794
                                                if ($sec_name != '') {
795
                                                        if ($asArray) {
796
                                                                $obj[$sec_name][$property] = $value;
797
                                                        } else {
798
                                                                $obj->$sec_name->$property = $value;
799
                                                        }
800
                                                } else {
801
                                                        if ($asArray) {
802
                                                                $obj[$property] = $value;
803
                                                        } else {
804
                                                                $obj->$property = $value;
805
                                                        }
806
                                                }
807
                                        } else {
808
                                                $value = str_replace( array( '\n', '\r', '\\\\' ), array( "\n", "\r", '\\' ), $value );
809
                                                if ($asArray) {
810
                                                        $obj[$property] = $value;
811
                                                } else {
812
                                                        $obj->$property = $value;
813
                                                }
814
                                        }
815
                                } else {
816
                                        if ($line && trim($line[0]) == ';') {
817
                                                continue;
818
                                        }
819
                                        if ($process_sections) {
820
                                                $property = '__invalid' . $unparsed++ . '__';
821
                                                if ($process_sections) {
822
                                                        if ($sec_name != '') {
823
                                                                if ($asArray) {
824
                                                                        $obj[$sec_name][$property] = trim($line);
825
                                                                } else {
826
                                                                        $obj->$sec_name->$property = trim($line);
827
                                                                }
828
                                                        } else {
829
                                                                if ($asArray) {
830
                                                                        $obj[$property] = trim($line);
831
                                                                } else {
832
                                                                        $obj->$property = trim($line);
833
                                                                }
834
                                                        }
835
                                                } else {
836
                                                        if ($asArray) {
837
                                                                $obj[$property] = trim($line);
838
                                                        } else {
839
                                                                $obj->$property = trim($line);
840
                                                        }
841
                                                }
842
                                        }
843
                                }
844
                        }
845
                }
846
                return $obj;
847
        }
848
}
849

    
850
/**
851
 * Lightweight CB user class read-only for use outside CB
852
 *
853
 * @author Beat
854
 * @license GPL v2
855
 */
856
class CBuser {
857
        /**
858
         * CB user object for database tables
859
         * @var moscomprofilerUser
860
         */
861
        var $_cbuser;
862
        /**
863
         * the CB tabs object for that user
864
         * @var cbTabs
865
         */
866
        var $_cbtabs        =        null;
867
        /** Db
868
         * @var CBdatabase */
869
        var $_db;
870
        /**
871
         * For function advanceNoticeOfUsersNeeded( $usersIds )
872
         * @var array of int  id to load at next needed SQL query
873
         */
874
        private static $idsToLoad                                                =        array();
875
        /**
876
         * Constructor
877
         */
878
        function CBuser( ) {
879
/*
880
                 global $_CB_database, $database;
881
                if ( $_CB_database ) {
882
                        $this->_db        =&        $_CB_database;
883
                } else {
884
                        $this->_db        =&        $database;
885
                }
886
*/
887
                global $_CB_database;
888

    
889
                $this->_db                        =&        $_CB_database;
890
        }
891
/*
892
         * Gets The reference instance of CBuser for user id, or a new instance if $userId == 0
893
         *
894
         * @param  int  $userId
895
         * @return CBUser|NULL   Returns NULL if Id is specified, but not loaded.
896
         *
897
        function & getInstance( $userId ) {
898
                static $instances                =        array();
899

900
                $userIdInt                                =        (int) $userId;
901
                if ( $userIdInt ) {
902
                        if ( ! isset( $instances[$userIdInt] ) ) {
903
                                $instances[$userIdInt]        =        new CBuser();
904
                                if ( ! $instances[$userIdInt]->load( $userId ) ) {
905
                                        $null                =        null;
906
                                        return $null;
907
                                }
908
                        }
909
                        return $instances[$userIdInt];
910
                } else {
911
                        $cbUser                                =        new CBuser();
912
                        $cbUser->_cbuser        =        new moscomprofilerUser( $cbUser->_db );
913
                        return $cbUser;
914
                }
915
        }
916
*/
917
        /**
918
         * Gets The reference instance of CBuser for user id, or a new instance if $userId == 0
919
         * @static
920
         *
921
         * @param  int|null     $userId
922
         * @return CBuser | null  Returns NULL if Id is specified, but not loaded.
923
         */
924
        static function & getInstance( $userId ) {
925
                if ( $userId !== null ) {
926
                        $userId                                =        (int) $userId;
927
                }
928
                $user        =& CBuser::_getOrSetInstance( $userId );
929
                return $user;
930
        }
931
        /**
932
         * Gets The reference instance of moscomprofilerUser for user id, or a new instance if $userId == 0
933
         * @since CB 1.2.3
934
         * @static
935
         *
936
         * @param  int|null     $userId
937
         * @return moscomprofilerUser  Check $user->id if Id is specified, but not loaded.
938
         */
939
        static function & getUserDataInstance( $userId ) {
940
                $cbUser                =        CBuser::getInstance( (int) $userId );
941
                if ( $cbUser ) {
942
                        $user        =&        $cbUser->getUserData();
943
                } else {
944
                        global $_CB_database;
945
                        $user        =        new moscomprofilerUser( $_CB_database );
946
                }
947
                return $user;
948
        }
949
        /**
950
         * Creates and sets a new instance of CBuser to $user
951
         * @static
952
         *
953
         * @param  moscomprofilerUser  $user
954
         * @return CBuser
955
         */
956
        function & setUserGetCBUserInstance( & $user ) {
957
                if ( is_object( $user ) ) {
958
                        return CBuser::_getOrSetInstance( $user );
959
                } else {
960
                        trigger_error( 'CBUser::setUserGetCBUserInstance called without object', E_USER_ERROR );
961
                        $null                                =        null;
962
                        return $null;
963
                }
964
        }
965
        /**
966
         * Private storage holder of the instances of CBUser
967
         * @access private
968
         * @static
969
         *
970
         * @param  int|moscomprofilerUser|null   $userOrValidId
971
         * @return CBUser|null
972
         */
973
        static function & _getOrSetInstance( & $userOrValidId ) {
974
                static $instances                                                        =        array();
975

    
976
                if ( is_int( $userOrValidId ) && ( $userOrValidId !== 0 ) ) {
977
                        if ( ! isset( $instances[$userOrValidId] ) ) {
978
                                if ( count( self::$idsToLoad ) == 0 ) {
979
                                        $instances[$userOrValidId]                =        new CBuser();
980
                                        if ( ! $instances[$userOrValidId]->load( $userOrValidId ) ) {
981
                                                unset( $instances[$userOrValidId] );
982
                                                $null                                                =        null;
983
                                                return $null;
984
                                        }
985
                                } else {
986
                                        self::loadUsersMatchingIdIntoList( self::$idsToLoad, $instances );
987
                                        self::$idsToLoad                                =        array();
988
                                        if ( ! isset( $instances[$userOrValidId] ) ) {
989
                                                $null                                                =        null;
990
                                                return $null;
991
                                        }
992
                                }
993
                        }
994
                        return $instances[$userOrValidId];
995
                } elseif ( is_object( $userOrValidId ) && isset( $userOrValidId->id ) && $userOrValidId->id ) {
996
                        // overwrite on purpose previous cached user, if any:
997
                        $instances[(int) $userOrValidId->id]        =        new CBuser();
998
                        $instances[(int) $userOrValidId->id]->loadCbRow( $userOrValidId );
999
                        return $instances[(int) $userOrValidId->id];
1000
                } else {
1001
                        $cbUser                                                                        =        new CBuser();
1002
                        $cbUser->_cbuser                                                =        new moscomprofilerUser( $cbUser->_db );
1003
                        return $cbUser;
1004
                }
1005
        }
1006
        function load( $cbUserId ) {
1007
                cbimport( 'cb.tables' );
1008

    
1009
                $this->_cbuser                =        new moscomprofilerUser( $this->_db );
1010
                return  $this->_cbuser->load( $cbUserId );
1011
        }
1012
        /**
1013
         * Loads a list of moscomprofilerUser into an existing array if they are not already in it
1014
         * (indexed by key of this table)
1015
         * @since 1.4 (experimental)
1016
         *
1017
         * @param  array    $usersIds      array of id to load
1018
         * @param  array    $objectsArray  IN/OUT   (int) id => moscomprofilerUser users
1019
         */
1020
        private static function loadUsersMatchingIdIntoList( $usersIds, &$objectsArray ) {
1021
                $cbUser                                                                        =        new CBuser();
1022
                $cbUser->_cbuser                                                =        new moscomprofilerUser( $cbUser->_db );
1023
                $cbUser->_cbuser->loadUsersMatchingIdIntoList( $usersIds, $objectsArray, 'CBuser' );
1024
        }
1025
        /**
1026
        * Copy the named array or object content into this object as vars
1027
        * All $arr values are filled in vars of $this->_cbuser
1028
        * @access private this is just for moscomprofilerUser::loadUsersMatchingIdIntoList()'s use
1029
        * @param  array               $arr    The input array
1030
        */
1031
        function bindThisUserFromDbArray( $arr ) {
1032
                $this->_cbuser                                                        =        new moscomprofilerUser( $this->_db );
1033
                $this->_cbuser->bindThisUserFromDbArray( $arr );
1034
        }
1035
        /**
1036
         * Sets an additional list of user records to also load and cache with next SQL query
1037
         * e.g.:
1038
         * CBuser::advanceNoticeOfUsersNeeded( array( 66, 67, 65 ) );                // just remembers
1039
         * CBuser::advanceNoticeOfUsersNeeded( array( 64, 65 ) );                        // just remembers
1040
         * echo CBuser::getUserDataInstance( 64 )->id;                // echo's 64        // and loads 64-67
1041
         * CBuser::advanceNoticeOfUsersNeeded( array( 68, 67, 69, 71 ) );        // just remembers
1042
         * echo CBuser::getUserDataInstance( 67 )->id;                // echos 67                // and doesn't load
1043
         * echo CBuser::getUserDataInstance( 69 )->username;        // echos        // and loads 68,69,71
1044
         *
1045
         * @param  array of int   $usersIds
1046
         */
1047
        public static function advanceNoticeOfUsersNeeded( $usersIds ) {
1048
                self::$idsToLoad        =        array_unique( array_merge( self::$idsToLoad, $usersIds ) );
1049
        }
1050
        function loadCmsUser( $cmsUserId ) {
1051
                return $this->load( $cmsUserId );        // for now it's the same but use right one please
1052
        }
1053
        function loadCbRow( &$row ) {
1054
                $this->_cbuser        =&        $row;
1055
        }
1056
        /**
1057
         * Returns the User's profile data
1058
         *
1059
         * @return moscomprofilerUser
1060
         */
1061
        function & getUserData( ) {
1062
                return $this->_cbuser;
1063
        }
1064
        // EXPERIMENTAL STUFF NEW IN 1.2 RC 3:
1065
        /**
1066
         * Creates if needed cbTabs object
1067
         *
1068
         * @param  boolean  $outputTabpaneScript
1069
         * @return cbTabs
1070
         */
1071
        function & _getCbTabs( $outputTabpaneScript = true ) {
1072
                if ( $this->_cbtabs === null ) {
1073
                        global $_CB_framework;
1074

    
1075
                        cbimport('cb.tabs');
1076
                        $this->_cbtabs        =        new cbTabs( 0, $_CB_framework->getUi(), null, $outputTabpaneScript );
1077
                }
1078
                return $this->_cbtabs;
1079
        }
1080
        /**
1081
         * Formatter:
1082
         * Returns a field in specified format
1083
         *
1084
         * @param  string                $fieldName     Name of field to render
1085
         * @param  mixed                 $defaultValue  Value if field is not in reach of viewer user or innexistant
1086
         * @param  string                $output        'html', 'xml', 'json', 'php', 'csvheader', 'csv', 'rss', 'fieldslist', 'htmledit'
1087
         * @param  string                $formatting    'tr', 'td', 'div', 'span', 'none',   'table'??
1088
         * @param  string                $reason        'profile' for user profile view and edit, 'register' for registration, 'search' for searches
1089
         * @param  int                   $list_compare_types   IF reason == 'search' : 0 : simple 'is' search, 1 : advanced search with modes, 2 : simple 'any' search
1090
         * @param  boolean               $fullAccess    IF true do not take in account current user's viewing rights
1091
         * @return mixed
1092
         */
1093
        function getField( $fieldName, $defaultValue = null, $output = 'html', $formatting = 'none', $reason = 'profile', $list_compare_types = 0, $fullAccess = false ) {
1094
                global $_CB_framework, $_PLUGINS;
1095

    
1096
                $tabs                        =&        $this->_getCbTabs();
1097
                $fields                        =        $tabs->_getTabFieldsDb( null, $this->getInstance( $_CB_framework->myId() ), $reason, $fieldName, true, $fullAccess );
1098
                if ( isset( $fields[0] ) ) {
1099
                        $field                =        $fields[0];
1100
                        $value                =        $_PLUGINS->callField( $field->type, 'getFieldRow', array( &$field, &$this->_cbuser, $output, $formatting, $reason, $list_compare_types ), $field );
1101
                } else {
1102
                        $value                =        $defaultValue;
1103
                }
1104
                return $value;
1105
        }
1106
        function getPosition( $position ) {
1107
                $userViewTabs        =        $this->getProfileView( $position );
1108
                if ( isset( $userViewTabs[$position] ) ) {
1109
                        return $userViewTabs[$position];
1110
                } else {
1111
                        return null;
1112
                }
1113
        }
1114
        function getTab( $tab, $defaultValue = null, $output = 'html', $formatting = null, $reason = 'profile' ) {
1115
                $tabs                        =&        $this->_getCbTabs();
1116
                $tabs->generateViewTabsContent( $this->_cbuser, '', $tab, $output, $formatting, $reason );
1117
                return $tabs->getProfileTabHtml( $tab, $defaultValue );
1118
        }
1119
        function getProfileView( $position = '' ) {
1120
                $tabs                        =&        $this->_getCbTabs();
1121
                return $tabs->getViewTabs( $this->_cbuser, $position );
1122
        }
1123
        /**
1124
         * DO NOT USE: This function will disapear in favor of a new one in very next minor release.
1125
         * you should use
1126
         * cbUser->getField( 'avatar' , null, 'csv', 'none', 'list' );
1127
         * instead of this derpreciated call !
1128
         *
1129
         * @param unknown_type $show_avatar
1130
         * @return unknown
1131
         */
1132
        function avatarFilePath( $show_avatar = 2 ) {
1133
                global $_CB_framework;
1134

    
1135
                $oValue                                =        null;
1136
                if ( $this->_cbuser ) {
1137
                        if ( $this->_cbuser->id ) {
1138
                                $avatar                        =        $this->_cbuser->avatar;
1139
                                $avatarapproved        =        $this->_cbuser->avatarapproved;
1140

    
1141
                                $absolute_path        =        $_CB_framework->getCfg( 'absolute_path' );
1142
                                $live_site                =        $_CB_framework->getCfg( 'live_site' );
1143

    
1144
                                if ( $avatarapproved == 0 ) {
1145
                                        return selectTemplate() . 'images/avatar/tnpending_n.png';
1146
                                } elseif ( ( $avatar == '' ) && $avatarapproved == 1 ) {
1147
                                        $oValue                =        null;
1148
                                } elseif ( strpos( $avatar, 'gallery/' ) === false ) {
1149
                                        $oValue                =        'images/comprofiler/tn' . $avatar;
1150
                                } else {
1151
                                        $oValue                =        'images/comprofiler/' . $avatar;
1152
                                }
1153
                                if ( ! is_file( $absolute_path . '/' . $oValue ) ) {
1154
                                        $oValue                =        null;
1155
                                }
1156
                        }
1157
                        if ( ( ! $oValue ) && ( $show_avatar == 2 ) ) {
1158
                                return selectTemplate() . 'images/avatar/tnnophoto_n.png';
1159
                        }
1160
                }
1161
                if ( $oValue ) {
1162
                        $oValue                        =        $live_site . '/' . $oValue;
1163
                }
1164
                return $oValue;
1165
        }
1166
        /**
1167
         * Replaces [fieldname] by the content of the user row (except for [password])
1168
         *
1169
         * @param  string         $msg
1170
         * @param  boolean|array  $htmlspecialchars  on replaced values only: FALSE : no htmlspecialchars, TRUE: do htmlspecialchars, ARRAY: callback method
1171
         * @param  boolean        $menuStats
1172
         * @param  array          $extraStrings
1173
         * @param  boolean        $translateLanguage  on $msg only
1174
         * @return string
1175
         */
1176
        function replaceUserVars( $msg, $htmlspecialchars = true, $menuStats = true, $extraStrings = null, $translateLanguage = true ){
1177
                if ( $extraStrings === null ) {
1178
                        $extraStrings        =        array();
1179
                }
1180
                if ( $translateLanguage ) {
1181
                        $msg                        =        getLangDefinition( $msg );
1182
                }
1183
                if ( strpos( $msg, '[' ) === false ) {
1184
                        return $msg;
1185
                }
1186
                $row                                =&        $this->_cbuser;
1187

    
1188
                $msg                                =        $this->_evaluateIfs( $msg );
1189
                $msg                                =        $this->_evaluateCbTags( $msg );
1190
                if ( is_object( $row ) ) {
1191
                        $msg                        =        $this->_evaluateCbFields( $msg, $htmlspecialchars );
1192
                }
1193

    
1194
                foreach( $extraStrings AS $k => $v ) {
1195
                        if( ( ! is_object( $v ) ) && ( ! is_array( $v ) ) ) {
1196
                                if ( is_array( $htmlspecialchars ) ) {
1197
                                        $v                =        call_user_func_array( $htmlspecialchars, array( $v ) );
1198
                                }
1199
                                $msg                =        cbstr_ireplace("[".$k."]", $htmlspecialchars === true ? htmlspecialchars( $v ) : $v, $msg );
1200
                        }
1201
                }
1202
                if ( $menuStats ) {
1203
                        // find [menu .... : path1:path2:path3 /] and replace with HTML code if menu active, otherwise remove it all
1204
                        $msg = $this->_replacePragma( $msg, $row, 'menu', 'menuBar' );
1205
                        // no more [status ] as they are standard fields !                $msg = $this->_replacePragma( $msg, $row, 'status', 'menuList' );
1206
                }
1207
                $msg = str_replace( array( "&91;", "&93;" ), array( "[", "]" ), $msg );
1208
                return $msg;
1209
        }
1210

    
1211
        /**
1212
         * INTERNAL PRIVATE METHODS:
1213
         */
1214

    
1215
        /**
1216
         * Explodes a text like: href="text1" img="text'it" alt='alt"joe'   into an array with defined keys and values, but null for missing ones.
1217
         * @access private
1218
         *
1219
         * @param string $text        text to parse
1220
         * @param array of string $validTags        valid tag names
1221
         * @return array of string        array( "tagname" => "tagvalue", "notsetTagname" => null)
1222
         */
1223
        function _explodeTags( $text, $validTags ) {
1224
                $text = trim($text);
1225
                $result = array();
1226
                foreach ($validTags as $tagName) {
1227
                        $result[$tagName] = null;
1228
                }
1229
                while ( $text != "" ) {
1230
                        $posEqual = strpos( $text, "=" );
1231
                        if ( $posEqual !== false ) {
1232
                                $tagName        = trim( substr( $text, 0, $posEqual ) );
1233
                                $text                = trim( substr( $text, $posEqual + 1 ) );
1234
                                $quoteMark        = substr( $text, 0, 1);
1235
                                $posEndQuote        = strpos( $text, $quoteMark, 1 );
1236
                                $tagValue        = false;
1237
                                if ( ($posEndQuote !== false) && in_array( $quoteMark, array( "'", '"' ) ) ) {
1238
                                        $tagValue        = substr( $text, 1, $posEndQuote - 1 );
1239
                                        $text                = trim( substr( $text, $posEndQuote + 1 ) );
1240
                                        if ( in_array( $tagName, $validTags ) ) {
1241
                                                $result[$tagName] = $tagValue;
1242
                                        }
1243
                                } else {
1244
                                        break;
1245
                                }
1246
                        } else {
1247
                                break;
1248
                        }
1249
                }
1250
                return $result;
1251
        }
1252
        /**
1253
         * Replaces "$1" in $text with $cbMenuTagsArray[$cbMenuTagsArrayKey] if non-null but doesn't tag if empty
1254
         * otherwise replace by $cbMenu[$cbMenuKey] if set and non-empty
1255
         * @access private
1256
         *
1257
         * @param array of string        $cbMenuTagsArray
1258
         * @param string                        $cbMenuTagsArrayKey
1259
         * @param array of string        $cbMenu
1260
         * @param string                        $cbMenuKey
1261
         * @param string                        $text
1262
         * @return string
1263
         */
1264
        function _placeTags( $cbMenuTagsArray, $cbMenuTagsArrayKey, $cbMenu, $cbMenuKey, $text ) {
1265
                if ( $cbMenuTagsArray[$cbMenuTagsArrayKey] !== null) {
1266
                        if ( $cbMenuTagsArray[$cbMenuTagsArrayKey] != "" ) {
1267
                                return str_replace( '$1', /*allow tags! htmlspecialchars */ ( $cbMenuTagsArray[$cbMenuTagsArrayKey] ), $text );
1268
                        } else {
1269
                                return null;
1270
                        }
1271
                } elseif ( isset($cbMenu[$cbMenuKey]) && ( $cbMenu[$cbMenuKey] !== null ) && ( $cbMenu[$cbMenuKey] !== "" ) ) {
1272
                        return str_replace( '$1', $cbMenu[$cbMenuKey], $text );
1273
                } else {
1274
                        return null;
1275
                }
1276
        }
1277
        /**
1278
         * Replaces complex pragmas
1279
         *
1280
         * @param  string    $msg
1281
         * @param  stdClass  $row
1282
         * @param  string    $pragma           the tag between the brackets "[$pragma]"
1283
         * @param  string    $position       the CB menu position
1284
         * @param  boolean   $htmlspecialcharsEncoded  True if menu tags should remain htmlspecialchared
1285
         * @return unknown
1286
         */
1287
        function _replacePragma( $msg, $row, $pragma, $position, $htmlspecialcharsEncoded = true ) {
1288
                global $_PLUGINS;
1289

    
1290
                $msgResult = "";
1291
                $pragmaLen = strlen( $pragma );
1292
            while ( ( $foundPosBegin = strpos( $msg, "[" . $pragma ) ) !== false ) {
1293
                           $foundPosEnd = strpos( $msg, "[/" . $pragma . "]", $foundPosBegin + $pragmaLen + 1 );
1294
                        if ( $foundPosEnd !== false ) {
1295
                                $foundPosTagEnd = strpos( $msg, "]", $foundPosBegin + $pragmaLen + 1 );
1296
                                if ( ( $foundPosTagEnd !== false ) && ( $foundPosTagEnd < $foundPosEnd ) ) {
1297
                                        // found [menu .... : $cbMenuTreePath /] : check to see if $cbMenuTreePath is in current menu:
1298
                                    $cbMenuTreePath = substr( $msg, $foundPosTagEnd + 1, $foundPosEnd - ($foundPosTagEnd + 1) );
1299
                                    $cbMenuTreePathArray = explode( ":", $cbMenuTreePath );
1300
                                    $pm = $_PLUGINS->getMenus();
1301
                                    $pmc=count($pm);
1302
                                        for ( $i=0; $i<$pmc; $i++ ) {
1303
                                                if ( $pm[$i]['position'] == $position ) {
1304
                                                        $arrayPos = $pm[$i]['arrayPos'];
1305
                                                        foreach ( $cbMenuTreePathArray as $menuName ) {
1306
                                                                if ( key( $arrayPos ) == trim( $menuName ) ) {
1307
                                                                        $arrayPos = $arrayPos[key( $arrayPos )];
1308
                                                                } else {
1309
                                                                        // not matching full menu path: check next:
1310
                                                                        break;
1311
                                                                }
1312
                                                        }
1313
                                                        if ( !is_array( $arrayPos ) ) {
1314
                                                                // came to end of path: match found: stop searching:
1315
                                                                break;
1316
                                                        }
1317
                                                }
1318
                                        }
1319
                                        // replace by nothing in case not found:
1320
                                        $replaceString = "";
1321
                                        if ( $i < $pmc ) {
1322
                                                // found: replace with menu item: first check for qualifiers for special changes:
1323
                                            $cbMenuTags = substr( $msg, $foundPosBegin + $pragmaLen + 1, $foundPosTagEnd - ($foundPosBegin + $pragmaLen + 1) );
1324
                                            if ($htmlspecialcharsEncoded) {
1325
                                                    $cbMenuTags = cbUnHtmlspecialchars( $cbMenuTags );
1326
                                            }
1327
                                                $cbMenuTagsArray = $this->_explodeTags( $cbMenuTags, array( "href", "target", "title", "class", "style", "img", "caption") );
1328
                                                if (substr(ltrim( $pm[$i]['url'] ),0,2) == '<a') {
1329
                                                        $matches                        =        null;
1330
                                                        if ( preg_match( '/ href="([^"]+)"/i', $pm[$i]['url'], $matches ) ) {
1331
                                                                $pm[$i]['url']        =        $matches[1];
1332
                                                        }
1333
                                                }
1334
                                                $replaceString .= $this->_placeTags( $cbMenuTagsArray, 'href', $pm[$i], 'url', '<a href="$1"'
1335
                                                                                                        . $this->_placeTags( $cbMenuTagsArray, 'target', $pm[$i], 'target', ' target="$1"' )
1336
                                                                                                        . $this->_placeTags( $cbMenuTagsArray, 'title', $pm[$i], 'tooltip', ' title="$1"' )
1337
                                                                                                        . $this->_placeTags( $cbMenuTagsArray, 'class', $pm[$i], 'undef', ' class="$1"' )
1338
                                                                                                        . $this->_placeTags( $cbMenuTagsArray, 'style', $pm[$i], 'undef', ' style="$1"' )
1339
                                                                                                        . ">"
1340
                                                                                                  );
1341
                                                $replaceString .= $this->_placeTags( $cbMenuTagsArray, 'img', $pm[$i], 'img', '$1' );
1342
                                                $replaceString .= $this->_placeTags( $cbMenuTagsArray, 'caption', $pm[$i], 'caption', '$1' );
1343
                                                $replaceString .= $this->_placeTags( $cbMenuTagsArray, 'href', $pm[$i], 'url', '</a>' );
1344

    
1345
                                                                /*        $this->menuBar->addObjectItem( $pm[$i]['arrayPos'], $pm[$i]['caption'],
1346
                                                                        isset($pm[$i]['url'])        ?$pm[$i]['url']                :"",
1347
                                                                        isset($pm[$i]['target'])?$pm[$i]['target']        :"",
1348
                                                                        isset($pm[$i]['img'])        ?$pm[$i]['img']                :null,
1349
                                                                        isset($pm[$i]['alt'])        ?$pm[$i]['alt']                :null,
1350
                                                                        isset($pm[$i]['tooltip'])?$pm[$i]['tooltip']:null,
1351
                                                                        isset($pm[$i]['keystroke'])?$pm[$i]['keystroke']:null );
1352
                                                                */
1353
                                        }
1354
                                        $msgResult .= substr( $msg, 0, $foundPosBegin );
1355
                                        $msgResult .= $replaceString;
1356
                                        $msg                = substr( $msg, $foundPosEnd + $pragmaLen + 3 );
1357
                        //        $srchtxt = "[menu:".$cbMenuTreePath."]";    // get new search text
1358
                        //        $msg = str_replace($srchtxt,$replaceString,$msg);    // replace founded case insensitive search text with $replace
1359
                                } else {
1360
                                        break;
1361
                                }
1362
                    } else {
1363
                            break;
1364
                    }
1365
            }
1366
                   return $msgResult . $msg;
1367
        }
1368

    
1369
        function & _evaluateUserAttrib( $userAttrVal ) {
1370
                global $_CB_framework;
1371

    
1372
                if ( $userAttrVal !== '' ) {
1373
                        $uid                        =        null;
1374
                        if ( ( $userAttrVal == '#displayed' ) || ( $userAttrVal == '#displayedOrMe' ) ) {
1375
                                $uid                =        $_CB_framework->displayedUser();
1376
                        }
1377
                        if ( ( $uid === null ) && ( ( $userAttrVal == '#displayedOrMe' ) || ( $userAttrVal == '#me' ) ) ) {
1378
                                $uid                =        $_CB_framework->myId();
1379
                        }
1380
                        if ( ( $uid === null ) && preg_match( '/^[1-9][0-9]*$/', $userAttrVal ) ) {
1381
                                $uid                =        (int) $userAttrVal;
1382
                        }
1383
                        if ( $uid ) {
1384
                                if ( $uid == $this->_cbuser->id ) {
1385
                                        $user        =&        $this;
1386
                                } else {
1387
                                        $user        =&        CBuser::getInstance( (int) $uid );
1388
                                }
1389
                        } else {
1390
                                $user                =        null;
1391
                        }
1392

    
1393
                } else {
1394
                        $user                        =&        $this;
1395
                }
1396
                return $user;
1397
        }
1398

    
1399
        function _evaluateIfs( $input ) {
1400
//                $regex                =        "#\[if ([^\]]+)\](.*?)\[/if\]#s";
1401
//                $regex = '#\[indent]((?:[^[]|\[(?!/?indent])|(?R))+)\[/indent]#s';
1402
                $regex = '#\[cb:if(?: +user="([^"/\[\] ]+)")?( +[^\]]+)\]((?:[^\[]|\[(?!/?cb:if[^\]]*])|(?R))+)\[/cb:if]#';
1403
                if ( is_array( $input ) ) {
1404
                        $regex2                                        =        '# +(?:(&&|and|\|\||or|) +)?([^=<!>~ ]+) *(=|<|>|>=|<=|<>|!=|=~|!~) *"([^"]*)"#';
1405
                        $conditions                                =        null;
1406
                        if (preg_match_all( $regex2, $input[2], $conditions ) ) {
1407
                                $user                                =&        $this->_evaluateUserAttrib( $input[1] );
1408
                                if ( ( $user !== null ) || ( ( count( $conditions[0] ) == 1 ) && ( $conditions[2][0] == 'user_id' ) && ( $conditions[4][0] === '0' ) ) ) {
1409
                                        $resultsIdx                =        0;
1410
                                        $results                =        array( $resultsIdx => true );
1411
                                        for ( $i = 0, $n = count( $conditions[0] ); $i < $n; $i++ ) {
1412
                                                $operator        =        $conditions[1][$i];
1413
                                                $field                =        $conditions[2][$i];
1414
                                                $compare        =        $conditions[3][$i];
1415
                                                $value                =        $conditions[4][$i];
1416
                                                if ( $user === null ) {
1417
                                                        $var        =        '0';
1418
                                                } elseif ( $field && isset( $user->_cbuser ) ) {
1419
                                                        $var        =        $user->getField( $field, null, 'php', 'none', 'profile', 0, true );                // allow accessing all fields in the if
1420
                                                        if ( is_array( $var ) ) {
1421
                                                                $var =        array_shift( $var );
1422
                                                        } elseif ( isset( $user->_cbuser->$field ) ) {
1423
                                                                // fall-back to the record if it exists:
1424
                                                                $var =        $user->_cbuser->$field;
1425
                                                        } else {
1426
                                                                $fieldLower        =        strtolower( $field );
1427
                                                                if ( isset( $user->_cbuser->$fieldLower ) ) {
1428
                                                                // second fall-back to the record if it exists:
1429
                                                                        $var        =        $user->_cbuser->$fieldLower;
1430
                                                                } else {
1431
                                                                        $var        =        null;
1432
                                                                }
1433
                                                        }
1434
                                                } else {
1435
                                                        $var        =        null;
1436
                                                }
1437
                                                if ( ( $field == 'user_id' ) && ( $value == 'myid' ) ) {
1438
                                                        global $_CB_framework;
1439
                                                        $value        =        $_CB_framework->myId();
1440
                                                }
1441
                                                switch ( $compare ) {
1442
                                                        case '=':
1443
                                                                $r        =        ( $var == $value );
1444
                                                                break;
1445
                                                        case '<':
1446
                                                                $r        =        ( $var < $value );
1447
                                                                break;
1448
                                                        case '>':
1449
                                                                $r        =        ( $var > $value );
1450
                                                                break;
1451
                                                        case '>=':
1452
                                                                $r        =        ( $var >= $value );
1453
                                                                break;
1454
                                                        case '<=':
1455
                                                                $r        =        ( $var <= $value );
1456
                                                                break;
1457
                                                        case '<>':
1458
                                                        case '!=':
1459
                                                                $r        =        ( $var != $value );
1460
                                                                break;
1461
                                                        case '=~':
1462
                                                        case '!~':
1463
                                                                $ma        =        @preg_match( $value, $var );
1464
                                                                $r        =        ( $compare == '=~' ? ( $ma === 1 ) : ( $ma == 0 ) );
1465
                                                                if ( $ma === false ) {
1466
                                                                        // error in regexp itself:
1467
                                                                        global $_CB_framework;
1468
                                                                        if ( $_CB_framework->getCfg( 'debug' ) > 0 ) {
1469
                                                                                echo sprintf( CBTxt::T("CB Regexp Error %s in expression %s"), ( ( ! is_callable( 'preg_last_error' ) ) ? '' : preg_last_error() ), htmlspecialchars( $value ) );
1470
                                                                        }
1471
                                                                }
1472
                                                                break;
1473
                                                }
1474
                                                if ( in_array( $operator, array( 'or', '||' ) ) ) {
1475
                                                        $resultsIdx++;
1476
                                                        $results[++$resultsIdx]        =        true;
1477
                                                }
1478
                                                // combine and:
1479
                                                $results[$resultsIdx]        =        $results[$resultsIdx] && $r;
1480
                                        }
1481
                                        // combine or:
1482
                                        $r                                =        false;
1483
                                        foreach ( $results as $rr ) {
1484
                                                $r                        =        $r || $rr;
1485
                                        }
1486
                                        $input                =        ( $r ? $input[3] : '' );
1487
                                } else {
1488
                                        $input                =        '';
1489
                                }
1490
                        } else {
1491
                                $input                =        '';
1492
                        }
1493
                }
1494
                return preg_replace_callback( $regex, array( $this, '_evaluateIfs' ), $input );
1495
        }
1496
        /**
1497
         * 
1498
         * 
1499
         * @param  string|array   $input
1500
         * @param  boolean|array  $htmlspecialcharsParam  on replaced values only: FALSE : no htmlspecialchars, TRUE: do htmlspecialchars, ARRAY: callback method
1501
         * @return string
1502
         */
1503
        function _evaluateCbFields( $input, $htmlspecialcharsParam = null ) {
1504
                static $htmlspecialchars                =        null;
1505

    
1506
                $regex                                                        =        '/\[([\w-]+)\]/';
1507

    
1508
                if ( is_array( $input ) ) {
1509
                        if ( ( $this !== null ) && is_object( $this->_cbuser ) && isset( $this->_cbuser->id ) ) {
1510
                                $val                                        =        $this->getField( $input[1], null, 'php', 'none', 'profile', 0, true );                // allow accessing all fields in the data
1511

    
1512
                                if ( is_array( $val ) ) {
1513
                                        $val                                =        array_shift( $val );
1514

    
1515
                                        if ( is_array( $val ) ) {
1516
                                                $val                        =        implode( '|*|', $val );
1517
                                        }
1518
                                } elseif ( isset( $this->_cbuser->$input[1] ) ) {
1519
                                        $val                                =        $this->_cbuser->get( $input[1] );
1520
                                } else {
1521
                                        $lowercaseVarName        =        strtolower( $input[1] );
1522
                                        if ( isset( $this->_cbuser->$lowercaseVarName ) ) {
1523
                                                $val                        =        $this->_cbuser->get( $lowercaseVarName );
1524
                                        } else {
1525
                                                $val                        =        array();                // avoid substitution
1526
                                        }
1527
                                }
1528
                                if( ( ! is_object( $val ) ) && ( ! is_array( $val ) ) ) {
1529
                                        if ( ! ( ( strtolower( $input[1] ) == 'password' ) && ( strlen( $val ) >= 32 ) ) ) {
1530
                                                if ( is_array( $htmlspecialchars ) ) {
1531
                                                        $val        =        call_user_func_array( $htmlspecialchars, array( $val ) );
1532
                                                } elseif ( $htmlspecialchars ) {
1533
                                                        $val        =        htmlspecialchars( $val );
1534
                                                }
1535
                                                return $val;
1536
                                        }
1537
                                }
1538
                        }
1539
                        return '[' . $input[1] . ']';
1540
                }
1541
                $htmlspecialchars                                =        $htmlspecialcharsParam;
1542
                return preg_replace_callback( $regex, array( $this, '_evaluateCbFields' ), $input );
1543
        }
1544

    
1545
        function _evaluateCbTags( $input ) {
1546
                global $_CB_framework;
1547

    
1548
                $regex                                =        '#\[cb:(userdata +field|userfield +field|usertab +tab|userposition +position|date +format|url +location|config +param)="((?:[^"]|\\\\")+)"(?: +user="([^"/\] ]+)")?(?: +default="((?:[^"]|\\\\")+)")?(?: +output="([a-zA-Z]+)")?(?: +formatting="([a-zA-Z]+)")?(?: +reason="([a-zA-Z]+)")?(?: +list="([0-9]+)")? */\]#';
1549
                if ( is_array( $input ) ) {
1550
                        if ( isset( $input[3] ) ) {
1551
                                $user                =&        $this->_evaluateUserAttrib( $input[3] );
1552
                        } else {
1553
                                $user                =&        $this;
1554
                        }
1555
                        if ( ( $user !== null ) && is_object( $user->_cbuser ) && isset( $user->_cbuser->id ) ) {
1556
                                $type                =        array_shift( explode( ' ', $input[1] ) );
1557

    
1558
                                switch ( $type ) {
1559
                                        case 'userdata':
1560
                                                $field                        =        $input[2];
1561
                                                $default                =        ( isset( $input[4] ) ? CBTxt::T( str_replace( '\"', '"', $input[4] ) ) : null );
1562
                                                $reason                        =        ( isset( $input[7] ) ? ( $input[7] !== '' ? $input[7] : 'profile' ) : 'profile' );
1563
                                                $var                        =        $user->getField( $field, $default, 'php', 'none', $reason, 0, true );                // allow accessing all fields in the data
1564
                                                if ( is_array( $var ) ) {
1565
                                                        $var                =        array_shift( $var );
1566

    
1567
                                                        if ( is_array( $var ) ) {
1568
                                                                $var        =        implode( '|*|', $var );
1569
                                                        }
1570
                                                } elseif ( isset( $user->_cbuser->$field ) ) {
1571
                                                        // fall-back to the record if it exists:
1572
                                                        $var                =        $user->_cbuser->get( $field );
1573
                                                } else {
1574
                                                        $fieldLower        =        strtolower( $field );
1575
                                                        if ( isset( $user->_cbuser->$fieldLower ) ) {
1576
                                                        // second fall-back to the record if it exists:
1577
                                                                $var        =        $user->_cbuser->get( $fieldLower );
1578
                                                        } else {
1579
                                                                $var        =        null;
1580
                                                        }
1581
                                                }
1582
                                                return $var;
1583
                                                break;
1584
                                        case 'userfield':
1585
                                        case 'usertab':
1586
                                                $default                =        ( isset( $input[4] ) ? CBTxt::T( str_replace( '\"', '"', $input[4] ) ) : null );
1587
                                                $output                        =        ( isset( $input[5] ) ? ( $input[5] !== '' ? $input[5] : 'html' ) : 'html' );
1588
                                                $formatting                =        ( isset( $input[6] ) ? ( $input[6] !== '' ? $input[6] : 'none' ) : 'none' );
1589
                                                $reason                        =        ( isset( $input[7] ) ? ( $input[7] !== '' ? $input[7] : 'profile' ) : 'profile' );
1590
                                                if ( $type == 'userfield' ) {
1591
                                                        $field                =        $user->getField( $input[2], $default, $output, $formatting, $reason, 0, false );                // do not allow accessing all fields in the fields
1592
                                                        if ( ( $output == 'php' ) && ( is_array( $field ) ) ) {
1593
                                                                $field        =        array_shift( $field );
1594
                                                        }
1595
                                                        return $field;
1596
                                                } else {
1597
                                                        return $user->getTab( $input[2], $default, ( $output == 'none' ? null : $output ), $formatting, $reason );
1598
                                                }
1599
                                                break;
1600
                                        case 'userposition':
1601
                                                return $user->getPosition( $input[2] );
1602
                                                break;
1603
                                        case 'date':
1604
                                                return date( $input[2], $_CB_framework->now() );
1605
                                                break;
1606
                                        case 'url':
1607
                                                switch ( $input[2] ) {
1608
                                                        case 'login':
1609
                                                        case 'logout':
1610
                                                        case 'registers':
1611
                                                        case 'lostpassword':
1612
                                                        case 'manageconnections':
1613
                                                                return $_CB_framework->viewUrl( $input[2], false );
1614
                                                                break;
1615
                                                        case 'profile_view':
1616
                                                                return $_CB_framework->userProfileUrl( $user->_cbuser->id, false );
1617
                                                                break;
1618
                                                        case 'profile_edit':
1619
                                                                return $_CB_framework->userProfileEditUrl( $user->_cbuser->id, false );
1620
                                                                break;
1621
                                                        case 'list':
1622
                                                                $list                =        ( isset( $input[8] ) ? ( $input[8] !== '' ? $input[8] : null ) : null );
1623
                                                                return $_CB_framework->userProfilesListUrl( $list, false );
1624
                                                                break;
1625
                                                        case 'itemid':
1626
                                                                return getCBprofileItemid( false );
1627
                                                                break;
1628
                                                        default:
1629
                                                                return '';
1630
                                                }
1631
                                                break;
1632
                                        case 'config':
1633
                                                switch ( $input[2] ) {
1634
                                                        case 'live_site':
1635
                                                        case 'sitename':
1636
                                                        case 'lang':
1637
                                                        case 'lang_name':
1638
                                                        case 'lang_tag':
1639
                                                                return $_CB_framework->getCfg( $input[2] );
1640
                                                                break;
1641
                                                        default:
1642
                                                                return '';
1643
                                                }
1644
                                                break;
1645
                                        default:
1646
                                                return '';
1647
                                }
1648
                        }
1649
                        return '';
1650
                }
1651
                return preg_replace_callback( $regex, array( $this, '_evaluateCbTags' ), $input );
1652
        }
1653
}
1654
/**
1655
 * CB HTML document class for Mambo 4.5.2+
1656
 * This class is experimental and not part as is of CB 1.2 !
1657
 * Use only $_CB_framework->document to access its public functions
1658
 * @author Beat
1659
 * @license GPL v2
1660
 */
1661
class CBdocumentHtml {
1662
        var $_output                                        =        'html';
1663
        var $_head;
1664
        var $_cmsDoc                                        =        null;
1665
        var $_headsOutputed                                =        true;
1666
        var $_direction                                        =        null;
1667
        /**
1668
         * Constructor
1669
         * @access private
1670
         *
1671
         * @param  callHandler      $getDocFunction
1672
         * @return CBdocumentHtml
1673
         */
1674
        function CBdocumentHtml( &$getDocFunction ) {
1675
                if ( $getDocFunction ) {
1676
                        $this->_cmsDoc                        =        call_user_func_array( $getDocFunction, array() );
1677
                }
1678
                $this->_renderingInit();
1679
        }
1680
        /**
1681
         * Sets a cms doc object for headers
1682
         *
1683
         * @param  object  $cmsDoc
1684
         */
1685
        function setCmsDoc( $cmsDoc = null ) {
1686
                $this->_cmsDoc                                =        $cmsDoc;
1687
        }
1688
        /**
1689
         * Sets or alters a meta tag.
1690
         *
1691
         * @param  string  $name        MUST BE LOWERCASE: Name or http-equiv tag: 'generator', 'description', ...
1692
         * @param  string  $content     Content tag value
1693
         * @param  boolean $http_equiv  META type "http-equiv" defaults to null
1694
         */
1695
        function addHeadMetaData( $name, $content, $http_equiv = false ) {
1696
                if ( ! $this->_tryCmsDoc( 'setMetaData', array( $name, $content, $http_equiv ) ) ) {
1697
                        if ( $http_equiv ) {
1698
                                $metaTag        =        array( 'http-equiv' => $name, 'content' => $content );
1699
                        } else {
1700
                                $metaTag        =        array( 'name' => $name, 'content' => $content );
1701
                        }
1702

    
1703
                        $this->_head['metaTags'][$http_equiv][$name]        =        $metaTag;
1704
                        $this->_renderCheckOutput();
1705
                }
1706
        }
1707
        /**
1708
         * Adds <link $relType="$relation" href="$url" associativeImplode($attribs) />
1709
         *
1710
         * @param  string  $url       Href URL to the linked style sheet
1711
         * @param  string  $relation  Relation to link
1712
         * @param  string  $relType   'rel' (default) for forward, or 'rev' for reverse relation
1713
         * @param  array   $attribs   Additional attributes ( 'attrName' => 'attrValue' )
1714
         */
1715
        function addHeadLinkCustom( $url, $relation, $relType = 'rel', $attribs = null ) {
1716
                static $i                =        0;
1717
                if ( $attribs === null ) {
1718
                        $attribs        =        array();
1719
                }
1720
                if ( ! $this->_tryCmsDoc( 'addHeadLink', array( $url, $relation, $relType, $attribs ) ) ) {
1721
                        $this->_head['linksCustom']['link'][$i]                =        array( $relType => $relation, 'href' => $url );
1722
                        if ( count( $attribs ) > 0 ) {
1723
                                $this->_head['linksCustom']['link'][$i]        =        array_merge( $this->_head['linksCustom']['link'][$i], $attribs );
1724
                        }
1725
                        $i                        +=        1;
1726
                        $this->_renderCheckOutput();
1727
                }
1728
        }
1729
        /**
1730
         * Adds <link type="$type" rel="stylesheet" href="$url" media="$media" />
1731
         *
1732
         * @param  string  $url    Href URL to the linked style sheet (either full url, or if starting with '/', live_site will be prepended)
1733
         * @param  boolean $minVersion  If a minified version ".min.css" exists, will use that one when not debugging
1734
         * @param  string  $media  Media type for stylesheet
1735
         * @param  array   $attribs   Additional attributes ( 'attrName' => 'attrValue' )
1736
         * @param  string  $type   MUST BE LOWERCASE: Mime type ('text/css' by default)
1737
         */
1738
        function addHeadStyleSheet( $url, $minVersion = false, $media = null, $attribs = null, $type = 'text/css' ) {
1739
                global $_CB_framework;
1740

    
1741
                if ( $attribs === null ) {
1742
                        $attribs        =        array();
1743
                }
1744
                if ( $url[0] == '/' ) {
1745
                        if ( substr( $url, -4 ) == '.css' ) {
1746
                                $file                =        $_CB_framework->getCfg( 'absolute_path' ) . $url;
1747
                                if ( file_exists( $file ) ) {
1748
                                        $url        =        $this->addVersionFileUrl( $url, $file );
1749
                                }
1750
                        }
1751
                        if ( $_CB_framework->getUi() == 2 ) {
1752
                                $url        =        '..' . $url;                // relative paths in backend
1753
                        } else {
1754
                                $url        =        $_CB_framework->getCfg( 'live_site' ) . $url;
1755
                        }
1756
                }
1757
                if ( ! $this->_tryCmsDoc( 'addStyleSheet', array( $url, $type, $media, $attribs ) ) ) {
1758
                        $this->_head['stylesheets'][$url]        =        array( 'type' => $type, 'rel' => 'stylesheet', 'href' => $url );
1759
                        if ( $media ) {
1760
                                $this->_head['stylesheets'][$url]['media']                =        $media;
1761
                        }
1762
                        if ( count( $attribs ) > 0 ) {
1763
                                $this->_head['stylesheets'][$url]        =        array_merge( $this->_head['stylesheets'][$url], $attribs );
1764
                        }
1765
                        $this->_renderCheckOutput();
1766
                }
1767
        }
1768
         /**
1769
         * Adds <style type="$type">$content</style>
1770
         *
1771
         * @param        string  $content   Style declarations
1772
         * @param        string  $type                Type of stylesheet (defaults to 'text/css')
1773
         * @return   void
1774
         */
1775
        function addHeadStyleInline( $content, $type = 'text/css' ) {
1776
                if ( ! $this->_tryCmsDoc( 'addStyleDeclaration', array( $content, $type ) ) ) {
1777
                        $this->_head['styles'][$type][]        =        $content;
1778
                        $this->_renderCheckOutput();
1779
                }
1780
        }
1781
        function addVersionFileUrl( $url, $file ) {
1782
                global $_CB_framework, $ueConfig;
1783

    
1784
                return $url . '?v=' . substr( md5( $ueConfig['version'] . filemtime( $file ) . filemtime( __FILE__ ) . $_CB_framework->getCfg( 'live_site' ) ), 0, 16 );
1785
        }
1786
         /**
1787
         * Adds <script type="$type" src="$url"></script>
1788
         *
1789
         * @param  string        $url           Src of script (either full url, or if starting with '/', live_site will be prepended) DO htmlspecialchars BEFORE calling if needed (&->&amp;)
1790
         * @param  boolean       $minVersion    Minified version exist, named .min.js
1791
         * @param  string        $preScript     Script that must be just before the file inclusion
1792
         * @param  string        $postScript    Script that must be just after the file
1793
         * @param  string        $preCustom     Any html code just before the scripts incl. pre
1794
         * @param  string        $postCustom    Any html code just after the scripts incl. post
1795
         * @param  string|array  $type          String: type="$type" : MUST BE LOWERCASE: Type of script ('text/javascript' by default), Array: e.g. array( 'type' => 'text/javascript', 'charset' => 'utf-8' )
1796
         */
1797
        function addHeadScriptUrl( $url, $minVersion = false, $preScript = null, $postScript = null, $preCustom = null, $postCustom = null, $type = 'text/javascript' ) {
1798
                global $_CB_framework;
1799

    
1800
                if ( $minVersion && ! $_CB_framework->getCfg( 'debug' ) ) {
1801
                        $url                =        str_replace( '.js', '.min.js', $url );
1802
                }
1803
                if ( $url[0] == '/' ) {
1804
                        if ( substr( $url, -3 ) == '.js' ) {
1805
                                $file                =        $_CB_framework->getCfg( 'absolute_path' ) . $url;
1806
                                if ( file_exists( $file ) ) {
1807
                                        $url        =        $this->addVersionFileUrl( $url, $file );
1808
                                }
1809
                        }
1810
                        if ( $_CB_framework->getUi() == 2 ) {
1811
                                $url        =        '..' . $url;                // relative paths in backend
1812
                        } else {
1813
                                $url        =        $_CB_framework->getCfg( 'live_site' ) . $url;
1814
                        }
1815
                }
1816
//                if ( ! $this->_tryCmsDoc( 'addScript', array( $url, $type ) ) ) {                                                        // The core ones are broken as they do not keep the strict ordering of scripts
1817
                        $this->_head['scriptsUrl'][$url]                =        array( 'pre' => $preScript, 'post' => $postScript, 'preC' => $preCustom, 'postC' => $postCustom, 'type' => $type );
1818
                        $this->_renderCheckOutput();
1819
//                }
1820
        }
1821
        /**
1822
         * Adds <script type="$type">$content</script>
1823
         *
1824
         * @param  string  $content  Script
1825
         * @param  string  $type     MUST BE LOWERCASE: Mime type ('text/javascript' by default)
1826
         */
1827
        function addHeadScriptDeclaration( $content, $type = 'text/javascript' ) {
1828
//                if ( ! $this->_tryCmsDoc( 'addScriptDeclaration', array( $content, $type ) ) ) {                        // The core ones are broken as they do not keep the strict ordering of scripts
1829
                        $this->_head['scripts'][$type][]                =        $content;
1830
                        $this->_renderCheckOutput();
1831
//                }
1832
        }
1833
        /**
1834
         * Adds custom $html into <head> portion
1835
         *
1836
         * @param  string  $html
1837
         */
1838
        function addHeadCustomHtml( $html ) {
1839
//                if ( ! $this->_tryCmsDoc( 'addCustomTag', array( $html ) ) ) {                                                        // The core ones are broken as they do not keep the strict ordering of scripts
1840
                        $this->_head['custom'][]                                =        $html;
1841
                        $this->_renderCheckOutput();
1842
//                }
1843
        }
1844
         /**
1845
         * Returns direction 'ltr' or 'rtl' for global document
1846
         *
1847
         * @return   string  'ltr' for left-to-right or 'rtl' for right-to-left texts globally on the page
1848
         */
1849
        function getDirection( ) {
1850
                if ( $this->_direction === null ) {
1851
                        if ( $this->_cmsDoc ) {
1852
                                $this->_direction        =        call_user_func_array( array( $this->_cmsDoc, 'getDirection' ), array() );
1853
                        } else {
1854
                                $this->_direction        =        'ltr';
1855
                        }
1856
                }
1857
                return $this->_direction;
1858
        }
1859
         /**
1860
         * Sets direction 'ltr' or 'rtl' for global document
1861
         *
1862
         * @param  string  $textDirection  'ltr' for left-to-right or 'rtl' for right-to-left texts globally on the page
1863
         */
1864
        function setDirection( $textDirection = 'ltr' ) {
1865
                $this->_direction                        =        $textDirection;
1866
        }
1867
        /**
1868
         * Tries to add head tags to CMS document.
1869
         * @access private
1870
         *
1871
         * @param  string   $type
1872
         * @param  array    $params
1873
         * @return boolean           Returns true for success and false if it couldn't use.
1874
         */
1875
        function _tryCmsDoc( $type, $params ) {
1876
                if ( $this->_cmsDoc ) {
1877
                        call_user_func_array( array( $this->_cmsDoc, $type ), $params );
1878
                        return true;
1879
                } elseif ( $this->_cmsDoc === false ) {
1880
                        // no html headers to output: do as if outputed so they get ignored:
1881
                        return true;
1882
                }
1883
                return false;
1884
        }
1885
        function _outputToHeadCollectionStart( ) {
1886
                $this->_headsOutputed                =        false;
1887
        }
1888
        /**
1889
         * Outputs the headers to the CMS handler or returns them if it can't
1890
         * @access private
1891
         *
1892
         * @return string|null   string for header to be echoed worst case, null if it could echo
1893
         */
1894
        function _outputToHead( ) {
1895
                global $_CB_framework, $ueConfig;
1896

    
1897
                $jVersion                =        checkJversion();
1898
                $customHead                =        $this->_renderHead();
1899
                if ( $this->_headsOutputed && ( $jVersion == 0 ) ) {
1900
                        return $customHead . "\n";
1901
                }
1902
                if ( ! $this->_tryCmsDoc( 'addCustomTag', array( $customHead ) ) ) {
1903
                        if ( isset( $ueConfig['xhtmlComply'] ) && $ueConfig['xhtmlComply']
1904
                                && ( ( ( $_CB_framework->getUi() == 1 ) || ( ( $jVersion == 0 ) && function_exists( 'josHashPassword' ) ) ) && method_exists( $_CB_framework->_baseFramework, 'addCustomHeadTag' ) ) )
1905
                        {
1906
                                // versions 1.0.13 (in fact 1.0.12 too) and above have it in backend too:
1907
                                $_CB_framework->_baseFramework->addCustomHeadTag( $customHead );
1908
                        } else {
1909
                                return $customHead . "\n";
1910
                        }
1911
                }
1912
                $this->_headsOutputed        =        true;
1913
                return null;
1914
        }
1915
        function _renderCheckOutput( ) {
1916
                if ( $this->_headsOutputed && ( $this->_cmsDoc !== false ) ) {
1917
//                        $customHead                        =        $this->_renderHead();
1918
//                        echo $customHead;                // better late than never...
1919
                        echo $this->_outputToHead();
1920
                }
1921
        }
1922
        function _renderingInit() {
1923
                $this->_head                                =        array( 'metaTags' => array(), 'linksCustom' => array(), 'stylesheets' => array(), 'styles' => array(), 'scriptsUrl' => array(), 'scripts' => array(), 'custom' => array() );
1924
        }
1925
        /**
1926
         * Renders the portion going into the <head> if CMS doesn't support correct ordering
1927
         * @access private
1928
         *
1929
         * @return string    HTML for <head> or NULL if done by CMS
1930
         */
1931
        function _renderHead( ) {
1932
                $html                                        =        null;
1933
                if ( $this->_output == 'html' ) {
1934
                        if ( $this->_cmsDoc === null ) {
1935
                                // <base> is done outside
1936
                                // metaTags:
1937
                                foreach ( $this->_head['metaTags'] as $namContentArray ) {
1938
                                        foreach ( $namContentArray as $metaTagAttrs ) {
1939
                                                $html[]        =        $this->_renderTag( 'meta', $metaTagAttrs );
1940
                                        }
1941
                                }
1942
                                // <title> is done outside
1943
                                // links, custom ones:
1944
                                foreach ( $this->_head['linksCustom'] as $tagName => $attributes ) {
1945
                                        $html[]                =        $this->_renderTag( $tagName, $attributes );
1946
                                }
1947
                                // styleSheets first:
1948
                                foreach ( $this->_head['stylesheets'] as $url => $styleSheet ) {
1949
                                        $html[]                =        $this->_renderTag( 'link', $styleSheet );
1950
                                }
1951
                                // style inline:
1952
                                $html[]                        =        $this->_renderInlineHelper( 'style', 'styles' );
1953
                        }
1954
                        // The core SCRIPT handlers are broken as they do not keep the strict ordering of scripts: so do it here as custom:
1955
                        // scriptsUrl:
1956
                        foreach ( $this->_head['scriptsUrl'] as $url => $tpp ) {
1957
                                $html[]                        =        $tpp['preC']
1958
                                                                .        $this->_renderInlineScript( $tpp['pre'] )
1959
                                                                .        $this->_renderScriptUrlTag( $url, $tpp['type'] )
1960
                                                                .        $this->_renderInlineScript( $tpp['post'] )
1961
                                                                .        $tpp['postC']
1962
                                                                ;
1963
                        }
1964
                        // scripts inline
1965
                        $html[]                                =        $this->_renderInlineHelper( 'script', 'scripts' );
1966
                        ;
1967
                        // if there are custom things:
1968
                        foreach ( $this->_head['custom'] as $custom ) {
1969
                                $html[]                        =        $custom;
1970
                        }
1971
                }
1972
                // reset the headers, in case we get late callers from outside the component (modules):
1973
                $this->_renderingInit();
1974
                // finally transform to a string:
1975
                return implode( "\n\t", $html );
1976
        }
1977
        /**
1978
         * Internal utility to render <$tag implode($attributes) />
1979
         * (NOT PART of CB API)
1980
         * @access private
1981
         *
1982
         * @param  string  $tag
1983
         * @param  array   $attributes
1984
         * @param  string  $tagClose    '/>' (default) or '>'
1985
         * @return string
1986
         */
1987
        function _renderTag( $tag, $attributes, $tagClose = '/>' ) {
1988
                $html                                =        '<' . $tag .' ';
1989
                foreach ( $attributes as $attr => $val ) {
1990
                        $html                        .= ' ' . $attr . '="' . $val . '"';
1991
                }
1992
                $html                                .=        $tagClose;
1993
                return $html;
1994
        }
1995
        /**
1996
         * Internal utility to render <script type="$type" src="$url"></script>
1997
         * (NOT PART of CB API)
1998
         * @access private
1999
         *
2000
         * @param  string  $url
2001
         * @param  array   $type
2002
         * @return string
2003
         */
2004
        function _renderScriptUrlTag( $url, $type ) {
2005
                if ( is_string( $type ) ) {
2006
                        return '<script type="' . $type . '" src="' . $url . '"></script>';
2007
                } else {
2008
                        $type['src']        =        $url;
2009
                        return $this->_renderTag( 'script', $type, '>' ) . '</script>';
2010
                }
2011

    
2012
        }
2013
        /**
2014
         * Internal utility to render <$tag type="$type"><!-- implode($attributes) --></$tag>
2015
         * (NOT PART of CB API)
2016
         * @access private
2017
         *
2018
         * @param  string  $tag
2019
         * @param  string  $content
2020
         * @param  string  $type
2021
         * @return string
2022
         */
2023
        function _renderInlineScript( $content, $tag = 'script', $type = 'text/javascript' ) {
2024
                if ( $content ) {
2025
                        return '<' . $tag . ' type="' . $type . '">'
2026
                        .        ( $this->_output == 'html' ? "<!--\n" : "<![CDATA[\n" )
2027
                        .        $content
2028
                        .        ( $this->_output == 'html' ? "\n-->" : "\n]]>" )
2029
                        .        '</' . $tag . '>'
2030
                        ;
2031
                }
2032
                return null;
2033
        }
2034
        /**
2035
         * Internal utility to render an inline head portion (<style> or <script>)
2036
         * @access private
2037
         *
2038
         * @param  string  $tag  <$tag
2039
         * @param  string $head  index in $this->_head[$head] as array( $type => array( $contents ) )
2040
         * @return string        HTML
2041
         */
2042
        function _renderInlineHelper( $tag, $head ) {
2043
                $html                                =        null;
2044
                foreach ( $this->_head[$head] as $type => $contentsArray ) {
2045
                        $html[]                        =        $this->_renderInlineScript( implode( "\n\n", $contentsArray ), $tag, $type );
2046
                }
2047
                if ( $html !== null ) {
2048
                        return implode( "\n\t", $html );
2049
                }
2050
                return null;
2051
        }
2052
}        // class CBdocumentHtml
2053
/**
2054
 * CB Framework class for Mambo 4.5.2+
2055
 * @author Beat
2056
 * @license GPL v2
2057
 */
2058
class CBframework {
2059
        /** Base framework class
2060
         * @var mosMainFrame */
2061
        var $_baseFramework;
2062
        var $_cmsDatabase;
2063
        var $_ui                                                =        1;
2064
        var $_now;
2065
        var $_myId;
2066
        var $_myUsername;
2067
        var $_myUserType;
2068
        var $_myCmsGid;
2069
        var $_myLanguage                                =        null;
2070
        var $_myLanguageTag                                =        null;
2071
        /** php gacl compatible instance:
2072
         * @var CBACL $acl */
2073
        var $acl;
2074
        var $_aclParams                                        =        array();
2075
        var $_cmsSefFunction;
2076
        var $_sefFuncHtmlEnt;
2077
        var $_cmsUserClassName;
2078
        var $_cmsUserNeedsDb;
2079
        var $_cmsRedirectFunction;
2080
        var $_cbUrlRouting;                        //        = array( 'option' => 'com_comprofiler' )
2081
        var $_getVarFunction;
2082
        var $_outputCharset;
2083
        var $_editorDisplay;
2084

    
2085
        var $_redirectUrl                                =        null;
2086
        var $_redirectMessage                        =        null;
2087
        var $_redirectMessageType                =        'message';
2088
        /** php gacl instance:
2089
         * @var CBdocumentHtml */
2090
        var $document;
2091

    
2092
        function CBframework( &$baseFramework, &$cmsDatabase, &$acl, &$aclParams, $cmsSefFunction, $sefFuncHtmlEnt, $cmsUserClassName, $cmsUserNeedsDb, $cmsRedirectFunction, $myId, $myUsername, $myUserType, $myCmsGid, $myLanguage, $myLanguageTag, $cbUrlRouting, $getVarFunction, &$getDocFunction, $outputCharset, $editorDisplay ) {
2093
                $this->_baseFramework                =&        $baseFramework;
2094
                $this->_cmsDatabase                        =&        $cmsDatabase;
2095
                // $this->acl                                        =&        $acl;
2096
                $this->_aclParams                        =&        $aclParams;
2097
                $this->_cmsSefFunction                =        $cmsSefFunction;
2098
                $this->_cmsUserClassName        =        $cmsUserClassName;
2099
                $this->_cmsUserNeedsDb                =        $cmsUserNeedsDb;
2100
                $this->_cmsRedirectFunction        =        $cmsRedirectFunction;
2101
                $this->_myId                                =        (int) $myId;
2102
                $this->_myUsername                        =        $myUsername;
2103
                $this->_myUserType                        =        $myUserType;
2104
                $this->_myCmsGid                        =        $myCmsGid;
2105
                $this->_myLanguage                        =        $myLanguage;
2106
                $this->_myLanguageTag                =        $myLanguageTag;
2107
                $this->_cbUrlRouting                =        $cbUrlRouting;
2108
                $this->_getVarFunction                =        $getVarFunction;
2109
                $this->_outputCharset                =        $outputCharset;
2110
                $this->_editorDisplay                =        $editorDisplay;
2111
                $this->_now                                        =        time();
2112
                $this->document                                =        new CBdocumentHtml( $getDocFunction );
2113
        }
2114
        /**
2115
         * Returns the global $_CB_framework object
2116
         * @since 1.7
2117
         *
2118
         * @return CBframework
2119
         */
2120
        public static function & framework( ) {
2121
                global $_CB_framework;
2122
                return $_CB_framework;
2123
        }
2124
        /**
2125
         * Returns the global $_CB_database object
2126
         * @since 1.7
2127
         *
2128
         * @return CBdatabase
2129
         */
2130
        public static function & database( ) {
2131
                global $_CB_database;
2132
                return $_CB_database;
2133
        }
2134
        /**
2135
         * Returns a config from gloabal CB Configuration
2136
         * 
2137
         * @param  string  $name
2138
         * @return string
2139
         */
2140
        public function cbConfig( $name ) {
2141
                global $ueConfig;
2142
                return $ueConfig[$name];
2143
        }
2144
        /**
2145
         * User login into CMS framework
2146
         *
2147
         * @param  string          $username    The username
2148
         * @param  string|boolean  $password    if boolean FALSE: login without password if possible
2149
         * @param  booleean        $rememberme  1 for "remember-me" cookie method
2150
         * @param  int             $userId      used for "remember-me" login function only
2151
         * @return boolean                      Login success
2152
         */
2153
        function login( $username, $password, $rememberme = 0, $userId = null ) {
2154
                header('P3P: CP="NOI ADM DEV PSAi COM NAV OUR OTRo STP IND DEM"');              // needed for IE6 to accept this anti-spam cookie in higher security setting.
2155

    
2156
                if ( checkJversion() >= 1 ) {                // Joomla 1.5 RC and above:
2157
                        if ( $password !== false ) {
2158
                                $result                                =        $this->_baseFramework->login( array( 'username' => $username, 'password' => $password ), array( 'remember' => $rememberme ) );
2159
                        } else {
2160
                                // login without password:
2161
                                jimport( 'joomla.user.authentication' );
2162
                                // load user plugins:
2163
                                JPluginHelper::importPlugin( 'user' );
2164
                                // get JAuthentication object:
2165
                                $authenticate                =&        JAuthentication::getInstance();
2166
                                $dispatcher                        =&        JDispatcher::getInstance();
2167
                                $response                        =        new JAuthenticationResponse();
2168
                                // prepare our SUCCESS login response including user data:
2169
                                global $_CB_database;
2170
                                $row                                =        new moscomprofilerUser( $_CB_database );
2171
                                $row->loadByUsername( stripslashes( $username ) );
2172
                                $response->status        =        JAUTHENTICATE_STATUS_SUCCESS;
2173
                                $response->username        =        $username;
2174
                                $response->fullname        =        $row->name;
2175
                                // now we attempt user login and check results:
2176
                                if ( checkJversion() == 2 ) {
2177
                                        $login                        =        $dispatcher->trigger( 'onUserLogin', array( (array) $response, array( 'action' => 'core.login.site' ) ) );
2178
                                } else {
2179
                                        $login                        =        $dispatcher->trigger( 'onLoginUser', array( (array) $response, array() ) );
2180
                                }
2181
                                $result                                =        ! in_array( false, $login, true );
2182
                        }
2183
                        if ( $result ) {
2184
                                $user                                =&        JFactory::getUser();
2185
                                $this->_myId                =        (int) $user->id;
2186
                                $this->_myUsername        =        $user->username;
2187
                                $this->_myUserType        =        $user->usertype;
2188
                                $this->_myCmsGid        =        $user->get('aid', 0);
2189
                                $lang                                =&        JFactory::getLanguage();
2190

    
2191
                                if ( checkJversion() == 2 ) {
2192
                                        $this->_myLanguage        =        strtolower( preg_replace( '/^(\w+).*$/i', '\1', $lang->getName() ) );
2193
                                } else {
2194
                                        $this->_myLanguage        =        $lang->getBackwardLang();
2195
                                }
2196
                        }
2197
                } else {
2198
                        // Mambo 4.5.x and Joomla before 1.0.13+ (in fact RC3+) do need hashed password for login() method:
2199
                        if ( $password !== false ) {
2200
                                $hashedPwdLogin                =        ( ( checkJversion() == 0 ) && ! function_exists( 'josHashPassword' ) );        // more reliable version-checking than the often hacked version.php file!
2201
                                if ( $hashedPwdLogin ) {                                // Joomla 1.0.12 and below:
2202
                                        $dummyRow                =        new moscomprofilerUser( $_CB_database );
2203
                                        $this->_baseFramework->login( $username, $dummyRow->hashAndSaltPassword( $password ), $rememberme, $userId );
2204
                                } else {
2205
                                        $this->_baseFramework->login( $username, $password, $rememberme, $userId );
2206
                                }
2207

    
2208
                                // Joomla 1.0 redirects bluntly if login fails! so we need to check by ourselves below:
2209
                                $result                                =        true;
2210
                        } else {
2211
                                // login without password:                //TBD MAMBO 4.6 support here !
2212
                                global $_CB_database, $mainframe, $_VERSION;
2213

    
2214
                                $row                                =        new moscomprofilerUser( $_CB_database );
2215
                                $row->loadByUsername( stripslashes( $username ) );
2216

    
2217
                                // prepare login session with user data:
2218
                                $session                        =&        $mainframe->_session;
2219
                                $session->guest                =        0;
2220
                                $session->username        =        $row->username;
2221
                                $session->userid        =        (int) $row->id;
2222
                                $session->usertype        =        $row->usertype;
2223
                                $session->gid                =        (int) $row->gid;
2224

    
2225
                                // attempt to login user:
2226
                                if ( $session->update() ) {
2227
                                        $result                        =        true;
2228
                                }
2229

    
2230
                                // check if site is demo or production:
2231
                                if ( $_VERSION->SITE ) {
2232
                                        // site is production; remove duplicate sessions:
2233
                                        $query                        =        'DELETE FROM ' . $_CB_database->NameQuote( '#__session' )
2234
                                                                        .        "\n WHERE " . $_CB_database->NameQuote( 'session_id' ) . ' != ' . $_CB_database->Quote( $session->session_id )
2235
                                                                        .        "\n AND " . $_CB_database->NameQuote( 'username' ) . ' = ' . $_CB_database->Quote( $row->username )
2236
                                                                        .        "\n AND " . $_CB_database->NameQuote( 'userid' ) . ' = ' . (int) $row->id
2237
                                                                        .        "\n AND " . $_CB_database->NameQuote( 'gid' ) . ' = ' . (int) $row->gid
2238
                                                                        .        "\n AND " . $_CB_database->NameQuote( 'guest' ) . ' = 0';
2239
                                        $_CB_database->setQuery( $query );
2240
                                        if ( ! $_CB_database->query() ) {
2241
                                                trigger_error( 'loginUser 1 SQL error: ' . $_CB_database->stderr( true ), E_USER_WARNING );
2242
                                        }
2243
                                }
2244

    
2245
                                // get current datetime:
2246
                                $currentDate                =        date( 'Y-m-d H:i:s', $this->now() );
2247

    
2248
                                // update user last login with current datetime:
2249
                                $query                                =        'UPDATE ' . $_CB_database->NameQuote( '#__users' )
2250
                                                                        .        "\n SET " . $_CB_database->NameQuote( 'lastvisitDate' ) . " = " . $_CB_database->Quote( $currentDate )
2251
                                                                        .        "\n WHERE " . $_CB_database->NameQuote( 'id' ) . " = " . (int) $session->userid;
2252
                                $_CB_database->setQuery( $query );
2253
                                if ( ! $_CB_database->query() ) {
2254
                                        trigger_error( 'loginUser 2 SQL error: ' . $_CB_database->stderr( true ), E_USER_WARNING );
2255
                                }
2256

    
2257
                                // clean old cache:
2258
                                mosCache::cleanCache();
2259
                        }
2260
                        if ( checkJversion() == 0 ) {
2261
                                global $mainframe;
2262
                                $mymy                                =        $mainframe->getUser();
2263
                                $this->_myId                =        (int) $mymy->id;
2264
                                $this->_myUsername        =        $mymy->username;
2265
                                $this->_myUserType        =        $mymy->usertype;
2266
                                $this->_myCmsGid        =        $mymy->gid;
2267
                                if ( ! $this->_myId ) {
2268
                                        $result                        =        false;
2269
                                }
2270
                        }
2271
                        //TBD MAMBO 4.6 support here !
2272
                }
2273
                return $result;
2274
        }
2275
        function logout() {
2276
                header('P3P: CP="NOI ADM DEV PSAi COM NAV OUR OTRo STP IND DEM"');              // needed for IE6 to accept this anti-spam cookie in higher security setting.
2277
                $this->_baseFramework->logout();
2278
        }
2279
        function getCfg( $config ) {
2280
                switch ( $config ) {
2281
                        case 'absolute_path':
2282
                                if ( checkJversion() >= 1 ) {
2283
                                        return JPATH_SITE;
2284
                                }
2285
                                break;
2286
                        case 'live_site':
2287
                                if ( checkJversion() >= 1 ) {
2288
                                        if ( $this->getUi() == 1 ) {
2289
                                                $live_site        =        JURI::base();
2290
                                        } elseif ( checkJversion() == 2 ) {
2291
                                                $live_site        =        preg_replace( '%administrator/%', '', JURI::base() );
2292
                                        } else {
2293
                                                $live_site        =        $this->_baseFramework->getSiteURL();
2294
                                        }
2295
                                        if ( substr( $live_site, -1, 1 ) == '/' ) {
2296
                                                // fix erroneous ending / in some joomla 1.5 versions:
2297
                                                return substr( $live_site, 0, -1 );
2298
                                        } else {
2299
                                                return $live_site;
2300
                                        }
2301
                                }
2302
                                break;
2303
                        case 'lang':
2304
                                return $this->_myLanguage;
2305
                                break;
2306
                        case 'lang_tag':
2307
                                return $this->_myLanguageTag;
2308
                                break;
2309
                        case 'uniquemail':
2310
                                if ( checkJversion() >= 1 ) {
2311
                                        return '1';
2312
                                }
2313
                                break;
2314
                        case 'frontend_userparams':
2315
                                if ( checkJversion() == -1 ) {
2316
                                        return '0';
2317
                                }
2318
                                // NO break; on purpose for fall-through:
2319
                        case 'allowUserRegistration':
2320
                        case 'useractivation':
2321
                        case 'new_usertype':
2322
                                if ( checkJversion() >= 1 ) {
2323
                                        $usersConfig        =        &JComponentHelper::getParams( 'com_users' );
2324
                                        $setting                =        $usersConfig->get( $config );
2325
                                        if ( ( $config == 'new_usertype' ) && ( checkJversion() == 2 ) ) {
2326
                                                $query                =        'SELECT ' . $this->_cmsDatabase->NameQuote( 'title' )
2327
                                                                        .        "\n FROM " . $this->_cmsDatabase->NameQuote( '#__usergroups' )
2328
                                                                        .        "\n WHERE " . $this->_cmsDatabase->NameQuote( 'id' ) . " = " . (int) $setting;
2329
                                                $this->_cmsDatabase->setQuery( $query );
2330
                                                $setting        =        $this->_cmsDatabase->loadResult();
2331
                                        }
2332
                                        if ( ( $config == 'new_usertype' ) && ! $setting ) {
2333
                                                $setting        =        'Registered';
2334
                                        }
2335
                                        return $setting;
2336
                                } else {
2337
                                        if ( $config == 'new_usertype' ) {
2338
                                                return 'Registered';
2339
                                        }
2340
                                }
2341
                                break;
2342
                        case 'hits':
2343
                        case 'vote':
2344
                                if ( checkJversion() >= 1 ) {
2345
                                        $contentConfig        =        &JComponentHelper::getParams( 'com_content' );
2346
                                        return $contentConfig->get( 'show_' . $config );
2347
                                }
2348
                                break;
2349
                        case 'dirperms':
2350
                        case 'fileperms':
2351
                                if ( checkJversion() >= 1 ) {
2352
                                        return '';                //TBD: these two missing configs should one day go to CB
2353
                                }
2354
                                break;
2355
                        // CB-Specific config params:
2356
                        case 'tmp_path':
2357
                                $abs_path                        =        $this->getCfg('absolute_path');
2358
                                $tmpDir                                =        $abs_path . '/tmp';
2359
                                if ( @is_dir( $tmpDir ) && @is_writable( $tmpDir ) ) {
2360
                                        return $tmpDir;
2361
                                }
2362
                                $tmpDir                                =        $abs_path . '/media';
2363
                                if ( @is_dir( $tmpDir ) && @is_writable( $tmpDir ) ) {
2364
                                        return $tmpDir;
2365
                                }
2366
                                // First try the new PHP 5.2.1+ function:
2367
                                if ( function_exists( 'sys_get_temp_dir' ) ) {
2368
                                        $tmpDir                =        @sys_get_temp_dir();
2369
                                        if ( @is_dir( $tmpDir ) && @is_writable( $tmpDir ) ) {
2370
                                                return $tmpDir;
2371
                                        }
2372
                                }
2373
                                // Based on http://www.phpit.net/article/creating-zip-tar-archives-dynamically-php/2/
2374
                                $varsToTry        =        array( 'TMP', 'TMPDIR', 'TEMP' );
2375
                                foreach ( $varsToTry as $v ) {
2376
                                        if ( ! empty( $_ENV[$v] ) ) {
2377
                                                $tmpDir                =        realpath( $v );
2378
                                                if ( @is_dir( $tmpDir ) && @is_writable( $tmpDir ) ) {
2379
                                                        return $tmpDir;
2380
                                                }
2381
                                        }
2382
                                }
2383
                                // Try the CMS cache directory and other directories desperately:
2384
                                $tmpDirToTry                =        array( $this->getCfg( 'cachepath' ), realpath( '/tmp' ), $abs_path.'/tmp', $abs_path.'/images', $abs_path.'/images/stories', $abs_path.'/images/comprofiler' );
2385
                                foreach ( $tmpDirToTry as $tmpDir ) {
2386
                                        if ( @is_dir( $tmpDir ) && @is_writable( $tmpDir ) ) {
2387
                                                return $tmpDir;
2388
                                        }
2389
                                }
2390
                                return null;
2391
                                break;
2392
                        case 'offset':
2393
                                if ( checkJversion() == 2 ) {
2394
                                        static $jOffset                        =        null;
2395
                                        if ( $jOffset === null ) {
2396
                                                $dateTimeZoneUTC                =        new DateTimeZone( 'UTC' );
2397
                                                $dateTimeZoneCurrent        =        new DateTimeZone( $this->_baseFramework->getCfg( 'offset' ) );
2398
                                                $dateTimeUTC                        =        new DateTime( 'now', $dateTimeZoneUTC );
2399
                                                $timeOffset                                =        $dateTimeZoneCurrent->getOffset( $dateTimeUTC );
2400
                                                $jOffset                                =        $timeOffset / 3600;
2401
                                        }
2402
                                        return $jOffset;
2403
                                }
2404
                                break;
2405
                        default:
2406
                                break;
2407
                }
2408
                return $this->_baseFramework->getCfg( $config );
2409

    
2410
        }
2411
        function getUi( ) {
2412
                return $this->_ui;
2413
        }
2414
        function myId( ) {
2415
                return $this->_myId;
2416
        }
2417
        function myUsername( ) {
2418
                return $this->_myUsername;
2419
        }
2420
        function myUserType( ) {
2421
                return $this->_myUserType;
2422
        }
2423
        function myCmsGid( ) {
2424
                if ( ( checkJversion() == 0 ) && ( $this->getUi() == 2 ) ) {
2425
                        // joomla 1.0 backend has a bug:
2426
                        return 2;
2427
                }
2428
                return $this->_myCmsGid;
2429
        }
2430
        function _cms_all_acl( ) {
2431
                return $this->_aclParams;
2432
        }
2433
        function _cms_acl( $action ) {
2434
                if ( isset( $this->_aclParams[$action] ) ) {
2435
                        return $this->_aclParams[$action];
2436
                }
2437
                trigger_error( 'acl_check undefined', E_USER_ERROR );
2438
                exit;
2439
        }
2440
        /**
2441
         * Checks rights of user $userType to perform a $action.
2442
         *
2443
         * @param  string  $action  'canEditUsers', 'canBlockUsers', 'canManageUsers', 'canReceiveAdminEmails','canInstallPlugins'
2444
         *                          'canEditOwnContent', 'canAddAllContent', 'canEditAllContent', 'canPublishContent'
2445
         * @param  string  $userTye
2446
         * @return boolean           TRUE: Yes, user can do that, FALSE: forbidden.
2447
         */
2448
        function check_acl( $action, $userTye ) {
2449
                $aclParams                                                =        $this->_cms_acl( $action );
2450
                $aclParams[3]                                        =        $userTye;
2451
                return ( true == call_user_func_array( array( $this->acl, 'acl_check' ), $aclParams ) );
2452
        }
2453
        function outputCharset( ) {
2454
                return $this->_outputCharset;
2455
        }
2456
        function getUrlRoutingOfCb( ) {
2457
                return $this->_cbUrlRouting;
2458
        }
2459
        function getRequestVar( $name, $default = null ) {
2460
                if ( $this->_getVarFunction ) {
2461
                        return call_user_func_array( $this->_getVarFunction, array( $name, $default ) );
2462
                } else {
2463
                        global $_REQUEST;
2464
                        return stripslashes( cbGetParam( $_REQUEST, $name, $default ) );
2465
                }
2466
        }
2467
        function setRedirect( $url, $message = null, $messageType = 'message' ) {        // or 'error'
2468
                $this->_redirectUrl                                =        $url;
2469
                $this->_redirectMessage                        =        $message;
2470
                $this->_redirectMessageType                =        $messageType;
2471
        }
2472
        function redirect( $url = null, $message = null, $messageType = null ) {
2473
                if ( $url ) {
2474
                        $this->_redirectUrl                        =        $url;
2475
                }
2476
                if ( $message !== null ) {
2477
                        $this->_redirectMessage                =        $message;
2478
                }
2479
                if ( $messageType !== null ) {
2480
                        $this->_redirectMessageType        =        $messageType;
2481
                }
2482
                call_user_func_array( $this->_cmsRedirectFunction, array( $this->_redirectUrl, $this->_redirectMessage, $this->_redirectMessageType ) );
2483
        }
2484
        /**
2485
         * changes "index.php?....." into what's needed for the CMS
2486
         * @since CB 1.2.3
2487
         *
2488
         * @param  string   $link       This URL should be htmlspecialchared already IF $htmlSpecials = TRUE, but NOT if = FALSE
2489
         * @param  boolean  $htmlSpecials
2490
         * @param  string   $format         'html', 'component', 'raw', 'rawrel' (same as 'raw' in backend for now)
2491
         * @return string
2492
         */
2493
        function backendUrl( $link, $htmlSpecials = true, $format = 'html' ) {
2494
                if ( checkJversion() >= 1 ) {
2495
                        // Joomla 1.5, 1.6:
2496
                        if ( $format == 'component' ) {
2497
                                $link                                        .=        ( $htmlSpecials ? '&amp;' : '&' ) . 'tmpl=' . $format;
2498
                        }
2499
                        if ( $format == 'rawrel' ) {
2500
                                $format                        =        'raw';
2501
                        }
2502
                        if ( $format == 'raw' ) {
2503
                                $link                                        .=        ( $htmlSpecials ? '&amp;' : '&' ) . 'format=' . $format;
2504
                        }
2505
                } else {
2506
                        // Mambo 4.5, 4.6, Joomla 1.0:
2507
                        if ( substr( $link, 0, 9 ) == 'index.php' ) {
2508
                                if ( $format == 'raw' ) {
2509
                                        $link                                        =        'index3.php' . substr( $link, 9 )
2510
                                                                                        .        ( $htmlSpecials ? '&amp;' : '&' ) . 'no_html=1'
2511
                                                                                        .        ( $htmlSpecials ? '&amp;' : '&' ) . 'format=' . $format;
2512
                                } else {
2513
                                        $link                                        =        'index2.php' . substr( $link, 9 );
2514
                                }
2515
                        }
2516
                }
2517
                return $link;
2518
        }
2519
        /**
2520
         * Converts an URL to an absolute URI with SEF format
2521
         *
2522
         * @param  string  $string        The relative URL
2523
         * @param  string  $htmlSpecials  TRUE (default): apply htmlspecialchars to sefed URL, FALSE: don't.
2524
         * @param  string  $format        'html', 'component', 'raw', 'rawrel'                (added in CB 1.2.3)
2525
         * @return string                 The absolute URL (relative if rawrel)
2526
         */
2527
        function cbSef( $string, $htmlSpecials = true, $format = 'html' ) {
2528
                if ( $format == 'html' ) {
2529
                        if ( ( $string == 'index.php' ) || ( $string == '' ) ) {
2530
                                $uri                                =        $this->getCfg( 'live_site' ) . '/';
2531
                        } else {
2532
                                if ( ( $this->getUi() == 1 )
2533
                                         && ( ( substr( $string, 0, 9 ) == 'index.php' ) || ( $string[0] == '?' ) )
2534
                                         && is_callable( $this->_cmsSefFunction )
2535
                                         && ( ! ( ( checkJversion() == 0 ) && ( strpos( $string, '[' ) !== false ) ) ) )                        // this is due to a bug in joomla 1.0 includes/sef.php line 426 and 501 not handling arrays at all.
2536
                                {
2537
                                        $uri                        =        call_user_func_array( $this->_cmsSefFunction, array( $this->_sefFuncHtmlEnt ? $string : cbUnHtmlspecialchars( $string ) ) );
2538
                                } else {
2539
                                        $uri                        =        $string;
2540
                                }
2541
                                if ( ! in_array( substr( $uri, 0, 4 ), array( 'http', 'java' ) ) ) {
2542
                                        if ( ( strlen( $uri ) > 1 ) && ( $uri[0] == '/' ) ) {
2543
                                                // we got special case of an absolute link without live_site, but an eventual subdirectory of live_site is included...need to strip live_site:
2544
                                                $matches        =        array();
2545
                                                if (        ( preg_match( '!^([^:]+://)([^/]+)(/.*)$!', $this->getCfg( 'live_site' ), $matches ) )
2546
                                                        &&        ( $matches[3] == substr( $uri, 0, strlen( $matches[3] ) ) ) )
2547
                                                {
2548
                                                        $uri        =        $matches[1] . $matches[2] . $uri;                // 'http://' . 'site.com' . '/......
2549
                                                } else {
2550
                                                        $uri        =        $this->getCfg( 'live_site' ) . $uri;
2551
                                                }
2552
                                        } else {
2553
                                                $uri                =        $this->getCfg( 'live_site' ) . '/' . $uri;
2554
                                        }
2555
                                }
2556
                        }
2557
                } else /* if ( $format == 'raw' || $format == 'rawrel' || $format == 'component' ) */ {
2558
                        if ( substr( $string, 0, 9 ) == 'index.php' ) {
2559
                                if ( $format == 'rawrel' ) {
2560
                                        $format                        =        'raw';
2561
                                        $uri                        =        '';
2562
                                } else {
2563
                                        $uri                        =        $this->getCfg( 'live_site' ) . '/';
2564
                                }
2565
                                if ( checkJversion() >= 1 ) {
2566
                                        // Joomla 1.5, 1.6:
2567
                                        if ( $format == 'component' ) {
2568
                                                $uri                .=        $string . '&amp;tmpl=' . $format;
2569
                                        } else {
2570
                                                $uri                .=        $string . '&amp;format=' . $format;
2571
                                        }
2572
                                } else {
2573
                                        // Mambo 4.5, 4.6, Joomla 1.0:
2574
                                        $uri                        .=        'index2.php' . substr( $string, 9 );
2575
                                        if ( $format == 'component' ) {
2576
                                                $uri                .=        '&amp;tmpl=' . $format;
2577
                                        } else {
2578
                                                $uri                .=        '&amp;no_html=1&amp;format=' . $format;
2579
                                        }
2580
                                }
2581
                        } else {
2582
                                $uri                                =        $string;
2583
                        }
2584
                }
2585
                if ( ! $htmlSpecials ) {
2586
                        $uri                                        =        cbUnHtmlspecialchars( $uri );
2587
                } else {
2588
                        $uri                                        =        htmlspecialchars( cbUnHtmlspecialchars( $uri ) );        // quite a few sefs, including Mambo and Joomla's non-sef are buggy.
2589
                }
2590
                return $uri;
2591
        }
2592
        /**
2593
         * Returns the called page's Itemid (or int 0)
2594
         * @since 1.7
2595
         *
2596
         * @return int   Always returns int
2597
         */
2598
        public function itemid( ) {
2599
                static $idCache                                =        null;
2600
                if ( $idCache === null ) {
2601
                        if ( checkJversion() >= 2 ) {
2602
                                $idCache                        =        (int) JFactory::getURI()->getVar( 'Itemid' );
2603
                        }  else {
2604
                                global $Itemid;
2605
                                $idCache                        =        (int) $Itemid;
2606
                        }
2607
                }
2608
                return $idCache;
2609
        }
2610
        /**
2611
         * gets URL to view a profie
2612
         * @static
2613
         *
2614
         * @param  int     $userId        The user's id (if null, my profile)
2615
         * @param  string  $htmlSpecials  TRUE (default): apply htmlspecialchars to sefed URL, FALSE: don't.
2616
         * @param  string  $tab           The tab to open directly
2617
         * @param  string  $format        'html', 'component', 'raw', 'rawrel'   (since CB 1.2.3)
2618
         * @return string                 The absolute URL (relative if rawrel)
2619
         */
2620
        function userProfileUrl( $userId = null, $htmlSpecials = true, $tab = null, $format = 'html' ) {
2621
                if ( $userId && ( $userId == $this->myId() ) ) {
2622
                        $userId                =        null;
2623
                }
2624
                return $this->cbSef( 'index.php?option=com_comprofiler' . ( $userId ? '&task=userprofile&user=' . (int) $userId : '' ) . ( $tab ? '&tab=' . urlencode( $tab ) : '' ) . getCBprofileItemid( false ), $htmlSpecials, $format );
2625
        }
2626
        /**
2627
         * gets URL to edit a profie
2628
         * @static
2629
         * @since CB 1.2.3
2630
         *
2631
         * @param  int     $userId        The user's id (if null, my profile)
2632
         * @param  string  $htmlSpecials  TRUE (default): apply htmlspecialchars to sefed URL, FALSE: don't.
2633
         * @param  string  $tab           The tab to open directly
2634
         * @param  string  $format        'html', 'component', 'raw', 'rawrel'
2635
         * @return string                 The absolute URL (relative if rawrel)
2636
         */
2637
        function userProfileEditUrl( $userId = null, $htmlSpecials = true, $tab = null, $format = 'html' ) {
2638
                if ( $userId && ( $userId == $this->myId() ) ) {
2639
                        $userId                =        null;
2640
                }
2641
                return $this->cbSef( 'index.php?option=com_comprofiler&task=userdetails' . ( $userId ? '&uid=' . (int) $userId : '' ) . ( $tab ? '&tab=' . urlencode( $tab ) : '' ) . getCBprofileItemid( false ), $htmlSpecials, $format );
2642
        }
2643
        /**
2644
         * gets URL to view list of profies
2645
         * @static
2646
         * @since CB 1.2.3
2647
         *
2648
         * @param  int     $listId        The list id (if null, default list)
2649
         * @param  string  $htmlSpecials  TRUE (default): apply htmlspecialchars to sefed URL, FALSE: don't.
2650
         * @param  int     $searchMode    1 for search only, 0 for list (default)
2651
         * @param  string  $format        'html', 'component', 'raw', 'rawrel'
2652
         * @return string                 The absolute URL (relative if rawrel)
2653
         */
2654
        function userProfilesListUrl( $listId = null, $htmlSpecials = true, $searchMode = null, $format = 'html' ) {
2655
                return $this->cbSef( 'index.php?option=com_comprofiler&task=userslist' . ( $listId ? '&listid=' . (int) $listId : '' ) . ( $searchMode ? '&searchmode=' . urlencode( $searchMode ) : '' ) . getCBprofileItemid( false, 'userslist' ), $htmlSpecials, $format );
2656
        }
2657
        /**
2658
         * gets URL to render a CB view
2659
         * @static
2660
         * @since CB 1.2.3
2661
         *
2662
         * @param  string  $task          task/view  e.g. 'manageconnections', 'registers', 'lostpassword', 'login', 'logout', 'moderateimages', 'moderatereports', 'moderatebans', 'viewreports', 'processreports', 'pendingapprovaluser'
2663
         * @param  string  $htmlSpecials  TRUE (default): apply htmlspecialchars to sefed URL, FALSE: don't.
2664
         * @param  string  $formId        Reserved for future use: If applicable: form id
2665
         * @param  string  $format        'html', 'component', 'raw', 'rawrel'
2666
         * @return string                 The absolute URL (relative if rawrel)
2667
         */
2668
        function viewUrl( $task, $htmlSpecials = true, $formId = null, $format = 'html' ) {
2669
                return $this->cbSef( 'index.php?option=com_comprofiler&task=' . urlencode( $task ) . ( $formId ? '&formid=' . urlencode( $formId ) : '' ) . getCBprofileItemid( false, 'registers' ), $htmlSpecials, $format );
2670
        }
2671
        function & _getCmsUserObject( $cmsUserId = null ) {
2672
                if ( $this->_cmsUserNeedsDb ) {
2673
                        global $_CB_database;
2674
                        $obj                                =        new $this->_cmsUserClassName( $_CB_database );
2675
                } else {
2676
                        $obj                                =        new $this->_cmsUserClassName();
2677
                }
2678
                if ( $cmsUserId !== null ) {
2679
                        if ( ! $obj->load( (int) $cmsUserId ) ) {
2680
                                $obj                        =        null;
2681
                        } else {
2682
                                if ( checkJversion() == 2 ) {
2683
                                        global $_CB_framework;
2684
                                        $obj->gid        =        (int) $_CB_framework->acl->getBackwardsCompatibleGid( array_values( (array) $obj->groups ) );
2685
                        }
2686
                }
2687
                }
2688
                return $obj;
2689
        }
2690
        function getUserIdFrom( $field, $value ) {
2691
                global $_CB_database;
2692

    
2693
                $_CB_database->setQuery( 'SELECT id FROM #__users u WHERE u.' . $_CB_database->NameQuote( $field ) . ' = ' . $_CB_database->Quote( $value ), 0, 1 );
2694
                $results                =        $_CB_database->loadResultArray();
2695
                if ( $results && ( count( $results ) == 1 ) ) {
2696
                        return $results[0];
2697
                }
2698
                return null;
2699
        }
2700
        /**
2701
         * Returns is user is "online" and last time online of the user
2702
         *
2703
         * @param  int  $userId
2704
         * @return int|null      last online time of the user
2705
         */
2706
        function userOnlineLastTime( $userId ) {
2707
                static $cache                                =        array();
2708
                if ( ! array_key_exists( (int) $userId, $cache ) ) {        // isset doesn't work as offline users return null
2709
                        global $_CB_database;
2710
                        $_CB_database->setQuery( 'SELECT MAX(time) FROM #__session WHERE userid = ' . (int) $userId . ' AND guest = 0');
2711
                        $cache[(int) $userId]        =        $_CB_database->loadResult();
2712
                }
2713
                return $cache[(int) $userId];
2714
        }
2715
        function displayCmsEditor( $hiddenField, $content, $width, $height, $col, $row ) {
2716
                if ( ! $this->_editorDisplay['returns'] ) {
2717
                        ob_start();
2718
                }
2719
                if ( $this->_editorDisplay['display']['args'] == 'withid' ) {
2720
                        $args                =        array( 'editor' . $hiddenField, htmlspecialchars( $content ), $hiddenField, $width, $height, $col, $row );
2721
                } else {
2722
                        $args                =        array( $hiddenField, htmlspecialchars( $content ), $width, $height, $col, $row );
2723
                }
2724
                $return                        =        call_user_func_array( $this->_editorDisplay['display']['call'], $args );
2725
                if ( ! $this->_editorDisplay['returns'] ) {
2726
                        $return                =        ob_get_contents();
2727
                        ob_end_clean();
2728
                }
2729
                return $return;
2730
        }
2731
        function saveCmsEditorJS( $hiddenField, $outputId = 0, $outputOnce = true ) {
2732
                static $outputsDone                =        array();
2733

    
2734
                if ( ! $this->_editorDisplay['returns'] ) {
2735
                        ob_start();
2736
                }
2737
                if ( $this->_editorDisplay['save']['args'] == 'withid' ) {
2738
                        $args                        =        array( 'editor' . $hiddenField, $hiddenField );
2739
                } else {
2740
                        $args                        =        array( $hiddenField );
2741
                }
2742
                $return                                =        call_user_func_array( $this->_editorDisplay['save']['call'], $args );
2743
                if ( ! $this->_editorDisplay['returns'] ) {
2744
                        $return                        =        ob_get_contents();
2745
                        ob_end_clean();
2746
                }
2747

    
2748
                if ( $outputOnce ) {
2749
                        if ( isset( $outputsDone[$outputId] ) && ( $return == $outputsDone[$outputId] ) ) {
2750
                                // in case the save function is identical for all HTML editor fields:
2751
                                $return                                =        null;
2752
                        } else {
2753
                                $outputsDone[$outputId]        =        $return;
2754
                        }
2755
                }
2756
                return $return;
2757
        }
2758

    
2759
        /**
2760
         * Returns the start time of CB's pageload
2761
         *
2762
         * @return int     Unix-time in seconds
2763
         */
2764
        function now( ) {
2765
                return $this->_now;
2766
        }
2767
        /**
2768
         * Returns date( 'Y-m-d H:i:s' ) but taking in account system offset for database's NOW()
2769
         *
2770
         * @return string 'YYYY-MM-DD HH:mm:ss'
2771
         */
2772
        function dateDbOfNow( ) {
2773
                return date( 'Y-m-d H:i:s', $this->now() - ( 3600 * $this->getCfg( 'offset' ) ) );
2774
        }
2775
        function setPageTitle( $title ) {
2776
                if ( method_exists( $this->document->_cmsDoc, 'setTitle' ) ) {
2777
                        return $this->document->_cmsDoc->setTitle( $title );        // J1.6 (and 1.5?)
2778
                } elseif ( method_exists( $this->_baseFramework, 'setPageTitle' ) ) {
2779
                        return $this->_baseFramework->setPageTitle( $title );        // J1.0 and Mambo (and 1.5?)
2780
                } else {
2781
                        return null;
2782
                }
2783
        }
2784
        function appendPathWay( $title, $link = null ) {
2785
                if ( method_exists( $this->_baseFramework, 'appendPathWay' ) ) {
2786
                        if ( checkJversion() == 1 ) {
2787
                                return $this->_baseFramework->appendPathWay( $title, $link );
2788
                        } else {
2789
                                // don't process link, as some version do htmlspecialchar those:
2790
                                // if ( $link ) {
2791
                                //        $title        =        '<a href="' . $link . '">' . $title . '</a>';
2792
                                // }
2793
                                return $this->_baseFramework->appendPathWay( $title );
2794
                        }
2795
                } else {
2796
                        return null;
2797
                }
2798
        }
2799
        /**
2800
         * DEPRECIATED: DO NOT USE.
2801
         * Use: addHeadStyleSheet, addHeadScriptUrl, and other $_CB_framework->document->addHead functions.
2802
         * This was an temporary function for CB 1.2 RC: DO NOT USE
2803
         * @since      CB 1.2 RC
2804
         * @deprecated CB 1.2
2805
         *
2806
         * @param      string  $tag
2807
         * @return     void
2808
         */
2809
        function addCustomHeadTag( $tag ) {
2810
                global $_CB_framework;
2811

    
2812
                if ( $_CB_framework->getCfg( 'debug' ) == 1 ) {
2813
                        $bt                =        @debug_backtrace();
2814
                        trigger_error( sprintf('$_CB_framework->addCustomHeadTag CALLED FROM: %s line %s (function %s). This is old depreciated old CB 1.2 RC API. (Use: addHeadStyleSheet, addHeadScriptUrl, and other $_CB_framework->document->addHead functions).' . "\n", @$bt[0]['file'], @$bt[0]['line'], @$bt[1]['class'] . ':' . @$bt[1]['function'] ), E_USER_WARNING );
2815
                }
2816
                $this->document->addHeadCustomHtml( $tag );
2817
                return null;
2818
        }
2819
        function getUserState( $stateName ) {
2820
                return $this->_baseFramework->getUserState( $stateName );
2821
        }
2822
        function getUserStateFromRequest( $stateName, $reqName, $default = null ) {
2823
                return $this->_baseFramework->getUserStateFromRequest( $stateName, $reqName, $default );
2824
        }
2825
        function setUserState( $stateName, $stateValue ) {
2826
                return $this->_baseFramework->setUserState( $stateName, $stateValue );
2827
        }
2828
        function displayedUser( $uid = null ) {
2829
                static $profileOnDisplay = null;
2830
                if ( $uid ) {
2831
                        $profileOnDisplay        =        $uid;
2832
                }
2833
                return $profileOnDisplay;
2834
        }
2835
        function cbset( $name, $value ) {
2836
                $this->$name                        =        $value;
2837
        }
2838
        function outputCbJs( $javascriptCode ) {
2839
                $this->_jsCodes[]                =        $javascriptCode;
2840
        }
2841
        /**
2842
         * JS + JQUERY LIB:
2843
         *
2844
         */
2845
        var $_jsCodes                                =        array();
2846
        var $_jQueryCodes                        =        array();
2847
        var $_jQueryPlugins                        =        array();
2848
        var $_jQueryPluginsSent        =        array();
2849
        var $_jqueryDependencies        =        array(        'flot'                =>        array( 1        =>        array( 'excanvas' ) ),
2850
                                                                                        'rating'        =>        array( -1        =>        array( 'metadata' ) ) );
2851
        var $_jqueryCssFiles                =        array(        'slimbox2'        =>        array( 'lightbox.css' => array( false, 'screen' ) ),
2852
                                                                                        'ui-all'        =>        array( 'jqueryui/ui.all.css' => array( false, null ) ) );
2853

    
2854
        function _coreJQueryFilePath( $jQueryPlugin, $pathType = 'live_site' ) {
2855
                if ( $pathType == 'live_site' ) {
2856
                        $base                                =        '';                        // paths are calculated at output in $this->document->addHeadScriptUrl()
2857
                } else {
2858
                        $base                                =        $this->getCfg( $pathType );
2859
                }
2860
                return $base . '/components/com_comprofiler/js/jquery-' . _CB_JQUERY_VERSION . '/jquery.' . $jQueryPlugin . '.js';
2861
        }
2862
        /**
2863
         * Adds an external JQuery plugin to the known JQuery plugins (if not already known)
2864
         *
2865
         * @param  string|array   $jQueryPlugins  Short Name of plugin or array of short names
2866
         * @param  string|boolean $path           Path to file from root of website (including leading / ) so that it can be appended to absolute_path or live_site (OR TRUE: part of core)
2867
         * @param  array          $dependencies   array( 1        =>        array( pluginNames ) ) for plugins to load after and -1 for plugins to load before.
2868
         * @param  array          $cssfiles       array( filename => array( minVersionExists, media ) ) : media = null or 'screen'.
2869
         */
2870
        function addJQueryPlugin( $jQueryPlugins, $path, $dependencies = null, $cssfiles = null ) {
2871

    
2872
                $jQueryPlugins                                                                                =        (array) $jQueryPlugins;
2873
                foreach ( $jQueryPlugins as $jQueryPlugin ) {
2874

    
2875
                        if ( ( $path === true ) || file_exists( $this->_coreJQueryFilePath( $jQueryPlugin, 'absolute_path' ) ) ) {
2876
                                $path                                                                                =        $this->_coreJQueryFilePath( $jQueryPlugin );
2877
                        } else {
2878
                                if ( $dependencies !== null ) {
2879
                                        $this->_jqueryDependencies                                =        array_merge( $this->_jqueryDependencies, array( $jQueryPlugin => $dependencies ) );
2880
                                }
2881
                                if ( $cssfiles !== null ) {
2882
                                        $this->_jqueryCssFiles                                        =        array_merge( $this->_jqueryCssFiles, array( $jQueryPlugin => $cssfiles ) );
2883
                                }
2884
                        }
2885

    
2886
                        if ( ! isset( $this->_jQueryPlugins[$jQueryPlugin] ) ) {
2887
                                // not yet configured for loading: check dependencies: -1: before:
2888
                                if ( isset( $this->_jqueryDependencies[$jQueryPlugin][-1] ) ) {
2889
                                        foreach ( $this->_jqueryDependencies[$jQueryPlugin][-1] as $jLib ) {
2890
                                                if ( ! isset( $this->_jQueryPlugins[$jLib] ) ) {
2891
                                                        $this->_jQueryPlugins[$jLib]        =        $this->_coreJQueryFilePath( $jLib );
2892
                                                }
2893
                                        }
2894
                                }
2895
                                $this->_jQueryPlugins[$jQueryPlugin]                =        $path;
2896
                                // +1: dependencies after:
2897
                                if ( isset( $this->_jqueryDependencies[$jQueryPlugin][1] ) ) {
2898
                                        foreach ( $this->_jqueryDependencies[$jQueryPlugin][1] as $jLib ) {
2899
                                                if ( ! isset( $this->_jQueryPlugins[$jLib] ) ) {
2900
                                                        $this->_jQueryPlugins[$jLib]        =        $this->_coreJQueryFilePath( $jLib );
2901
                                                }
2902
                                        }
2903
                                }
2904
                        }
2905
                }
2906
        }
2907
        /**
2908
         * Outputs a JQuery init string into JQuery strings at end of page,
2909
         * and adds if needed JS file inclusions at begin of page.
2910
         * Pro-memo, JQuery runs in CB in noConflict mode.
2911
         *
2912
         * @param  string  $javascriptCode  Javascript code ended by ; which will be put in between jQuery(document).ready(function($){ AND });
2913
         * @param  string  $jQueryPlugin    (optional) name of plugin to auto-load (if core plugin, or call first addJQueryPlugin).
2914
         */
2915
        function outputCbJQuery( $javascriptCode, $jQueryPlugin = null ) {
2916
                if ( $jQueryPlugin ) {
2917
                        $this->addJQueryPlugin( $jQueryPlugin, true );
2918
                }
2919
                $this->_jQueryCodes[]        =        $javascriptCode;
2920
                if ( $this->document->_headsOutputed ) {
2921
                        $this->getAllJsPageCodes();
2922
                }
2923
        }
2924
        function getAllJsPageCodes( ) {
2925
                $jsCodeTxt                        =        '';
2926

    
2927
                // jQuery code loading:
2928

    
2929
                if ( count( $this->_jQueryCodes ) > 0 ) {
2930
                        foreach ( array_keys( $this->_jQueryPlugins ) as $plugin ) {
2931
                                if ( isset( $this->_jqueryCssFiles[$plugin] ) ) {
2932
                                        foreach ( $this->_jqueryCssFiles[$plugin] as $templateFile => $minExistsmedia ) {
2933
                                                $templateFileWPath        =        selectTemplate( 'absolute_path' ) . '/' . $templateFile;
2934
                                                if ( file_exists( $templateFileWPath ) ) {
2935
                                                        $templateFileUrl        =        selectTemplate( 'live_site' ) . $templateFile;
2936
                                                } else {
2937
                                                        $templateFileUrl        =        selectTemplate( 'live_site', 'default' ) . $templateFile;
2938
                                                }
2939
                                                if ( ! isset( $this->_jQueryPluginsSent[$templateFileUrl] ) ) {
2940
                                                        $this->document->addHeadStyleSheet( $templateFileUrl, $minExistsmedia[0], $minExistsmedia[1] );
2941
                                                        $this->_jQueryPluginsSent[$templateFileUrl]                =        true;
2942
                                                }
2943
                                        }
2944
                                }
2945
                        }
2946
                        if ( ! defined( 'J_JQUERY_LOADED' ) ) {
2947
                                $this->document->addHeadScriptUrl( '/components/com_comprofiler/js/jquery-' . _CB_JQUERY_VERSION . '/jquery-' . _CB_JQUERY_VERSION . '.js', true, null, 'jQuery.noConflict();' );
2948
                                define( 'J_JQUERY_LOADED', 1 );
2949
                        }
2950
                        foreach ( $this->_jQueryPlugins as $plugin => $pluginPath ) {
2951
                                if ( ! isset( $this->_jQueryPluginsSent[$plugin] ) ) {
2952
                                        $this->document->addHeadScriptUrl( $pluginPath, true, null, null, ( $plugin == 'excanvas' ? '<!--[if lte IE 8]>' : '' ), ( $plugin == 'excanvas' ? '<![endif]-->' : '' ) );
2953
                                        $this->_jQueryPluginsSent[$plugin]                =        true;
2954
                                }
2955
                        }
2956
/*
2957
                        $jsCodeTxt                =        "var cbJFrame = window.cbJFrame = function() { return new cbJFrame.prototype.init(); };\n"
2958
                                                        .        "cbJFrame.fn = cbJFrame.prototype = {\n"
2959
                                                        .        "  init: function() { return this; },\n"
2960
                                                        .        "  cbjframe: '" . $ueConfig['version'] . "',\n"
2961
                                                        .        "  jquery: null\n"
2962
                                                        .        "};\n"
2963
                                                        .        "cbJFrame.prototype.init.prototype = cbJFrame.prototype;\n"
2964
                                                        //.        "cbJFrame.jquery = jQuery.noConflict();\n"
2965
                                                        .        'cbJFrame.jquery(document).ready(function($){' . "\n"
2966
                                                        .        implode( "\n", $this->_jQueryCodes )
2967
                                                        .        "});\n";
2968
*/
2969
                        $jQcodes                =        trim( implode( "\n", $this->_jQueryCodes ) );
2970
                        if ( $jQcodes !== '' ) {
2971
                                $jsCodeTxt        =        'jQuery(document).ready(function($){' . "\n"
2972
                                                        .        $jQcodes
2973
                                                        .        "});"
2974
                                                        ;
2975
                                $this->document->addHeadScriptDeclaration( $jsCodeTxt );
2976
                        }
2977
                        $this->_jQueryCodes                =        array();
2978
                }
2979

    
2980
                // classical standalone javascript loading (for compatibility), depreciated ! :
2981

    
2982
                if ( count( $this->_jsCodes ) > 0 ) {
2983
                        $this->document->addHeadScriptDeclaration( implode( "\n", $this->_jsCodes ) );
2984
                        $this->_jsCodes        =        array();
2985
                }
2986
        }
2987
}
2988

    
2989
/**
2990
 * Converts an URL to an absolute URI with SEF format
2991
 *
2992
 * @param  string  $string        The relative URL
2993
 * @param  string  $htmlSpecials  TRUE (default): apply htmlspecialchars to sefed URL, FALSE: don't.
2994
 * @param  string  $format        'html', 'component', 'raw', 'rawrel'                (added in CB 1.2.3)
2995
 * @return string                 The absolute URL (relative if rawrel)
2996
 */
2997
function cbSef( $string, $htmlSpecials = true, $format = 'html' ) {
2998
        global $_CB_framework;
2999
        return $_CB_framework->cbSef( $string, $htmlSpecials, $format );
3000
}
3001
/**
3002
 * Displays "Not authorized", and if not logged-in "you need to login"
3003
 *
3004
 */
3005
function cbNotAuth() {
3006
        global $_CB_framework;
3007

    
3008
        echo '<div class="error">' . _UE_NOT_AUTHORIZED . '</div>';
3009
        if ($_CB_framework->myId() < 1 ) {
3010
                echo '<div class="error">' . _UE_DO_LOGIN . '</div>';
3011
        }
3012
}
3013

    
3014

    
3015
/**
3016
 * Text classes and old function
3017
 *
3018
 */
3019

    
3020
class CBTxtStorage {
3021
        var $_iso;                                        // 'UTF-8', 'ISO-8859-1', ...
3022
        var $_mode;                                        // 1: debug, 2: edit
3023
        var $_lang                                        =        'en-GB';
3024
        var $_langOld                                =        'english';
3025
        var $_strings                                =        array();
3026
        var $_usedStrings                        =        array();
3027

    
3028
        function CBTxtStorage( $iso, $mode ) {
3029
                $this->_iso                                =        $iso;
3030
                $this->_mode                        =        $mode;
3031
                if ( ( $mode > 2 ) && defined( 'JPATH_ADMINISTRATOR' ) ) {
3032
                        jimport( 'joomla.plugin.plugin' );
3033
                        $app                =&        JFactory::getApplication();
3034
                        $app->registerEvent( 'onAfterRender', '_onAfterRender_CB_Txt_display_translations_table' );
3035
                }
3036
        }
3037
        function recordUsedString( $english ) {
3038
                if ( $this->_mode == 3 ) {
3039
                        if ( ! isset( $this->_strings[$english] ) ) {
3040
                                $this->_usedStrings[$english]        =        null;
3041
                        }
3042
                } elseif ( $this->_mode == 4 ) {
3043
                        $this->_usedStrings[$english]        =        ( isset( $this->_strings[$english] ) ? $this->_strings[$english] : null );
3044
                }
3045
        }
3046
        function listUsedStrings() {
3047
                $r                =        null;
3048
                if ( $this->_usedStrings ) {
3049
                        cbimport( 'language.cbteamplugins' );
3050
                        $r        = '<table class="adminlist" id="cbtranslatedstrings"><tr class="sectiontableheader"><th>'
3051
                        .        ( $this->_mode == 3 ? CBTxt::Th('Untranslated strings on this page')
3052
                                : CBTxt::Th('Translations on this page') )
3053
                        .        ': '
3054
                        .        CBTxt::Th('English string')
3055
                        .        '</th><th>'
3056
                        .        CBTxt::Th('Translated string')
3057
                        .        '</th></tr>'
3058
                        ;
3059
                        $s        =        0;
3060
                        foreach ( $this->_usedStrings as $k => $v ) {
3061
                                $r .= '<tr class="sectiontableentry' . ( ( $s & 1 ) + 1 ) . ' row' . ( $s++ & 1 ) . '"><td>'
3062
                                .        htmlspecialchars( $k )
3063
                                .        '</td><td>'
3064
                                .        ( $v === null ? '-' : htmlspecialchars( $v ) )
3065
                                .        '</td></tr>'
3066
                                ;
3067
                        }
3068
                        $r        .=        '</table>';
3069
                }
3070
                return $r;
3071
        }
3072
}
3073
/**
3074
 * Translations debug: can not be a method because of joomla restriction to functions
3075
 */
3076
function _onAfterRender_CB_Txt_display_translations_table() {
3077
        global $_CB_TxtIntStore;
3078

    
3079
        $html        =        $_CB_TxtIntStore->listUsedStrings();
3080
        if ( $html ) {
3081
                JResponse::setBody( str_replace( '</body>', $html . '</body>', JResponse::getBody() ) );
3082
        }
3083
}
3084
class CBTxt {
3085
        static function T( $english ) {
3086
                global $_CB_TxtIntStore;
3087

    
3088
                if ( $_CB_TxtIntStore->_mode == 0 ) {
3089
                        if ( isset( $_CB_TxtIntStore->_strings[$english] ) ) {
3090
                                return CBTxt::utf8ToISO( $_CB_TxtIntStore->_strings[$english] );
3091
                        } else {
3092
                                return $english;
3093
                        }
3094
                } else {
3095
                        $_CB_TxtIntStore->recordUsedString( $english );
3096
                        if ( isset( $_CB_TxtIntStore->_strings[$english] ) ) {
3097
                                return CBTxt::utf8ToISO( '*' . $_CB_TxtIntStore->_strings[$english] . '*' );
3098
                        } else {
3099
                                return '===\\' . str_replace( '%s', '[%s]', $english ) . '/---';
3100
                        }
3101
                }
3102
        }
3103
        static function Th( $english ) {
3104
                global $_CB_TxtIntStore;
3105

    
3106
                if ( $_CB_TxtIntStore->_mode == 0 ) {
3107
                        if ( isset( $_CB_TxtIntStore->_strings[$english] ) ) {
3108
                                return CBTxt::utf8ToISO( $_CB_TxtIntStore->_strings[$english] );
3109
                        } else {
3110
                                return $english;
3111
                        }
3112
                } elseif ( $_CB_TxtIntStore->_mode == 1 ) {
3113
                        if ( isset( $_CB_TxtIntStore->_strings[$english] ) ) {
3114
                                return CBTxt::utf8ToISO( '*' . $_CB_TxtIntStore->_strings[$english] . '*' );
3115
                        } else {
3116
                                return '===&gt;' . str_replace( '%s', '[%s]', $english ) . '&lt;===';
3117
                        }
3118
                } else {
3119
                        $_CB_TxtIntStore->recordUsedString( $english );
3120
                        if ( isset( $_CB_TxtIntStore->_strings[$english] ) ) {
3121
                                return '<span style="color:#CCC;font-style:italic">' . CBTxt::utf8ToISO( $_CB_TxtIntStore->_strings[$english] ) . '</span>';
3122
                        } else {
3123
                                return '<span style="color:#FF0000;font-weight:bold">' . '===>' . $english . '<===' . '</span>';
3124
                        }
3125
                }
3126
        }
3127
        static function Tutf8( $english ) {
3128
                global $_CB_TxtIntStore;
3129

    
3130
                if ( $_CB_TxtIntStore->_mode == 0 ) {
3131
                        if ( isset( $_CB_TxtIntStore->_strings[$english] ) ) {
3132
                                return $_CB_TxtIntStore->_strings[$english];
3133
                        } else {
3134
                                return $english;
3135
                        }
3136
                } else {
3137
                        $_CB_TxtIntStore->recordUsedString( $english );
3138
                        if ( isset( $_CB_TxtIntStore->_strings[$english] ) ) {
3139
                                return '*' . $_CB_TxtIntStore->_strings[$english] . '*';
3140
                        } else {
3141
                                return '===\\' . str_replace( '%s', '[%s]', $english ) . '/---';
3142
                        }
3143
                }
3144
        }
3145
        /**
3146
         * Parse the string through CBTxt::T.
3147
         * That is, for a particular string find the corresponding translation.
3148
         * Variable subsitution is performed for the $args parameter.
3149
         * @since 1.3
3150
         *
3151
         * @param string   $english  the string to translate
3152
         * @param array    $args     a strtr-formatted array of string substitutions
3153
         * @return string
3154
        */
3155
        static function P( $english, $args = null ) {
3156
                return CBTxt::_parseReplaceString( CBTxt::T( $english ), $args );
3157
        }
3158
        /**
3159
         * Parse the string through CBTxt::Th.
3160
         * That is, for a particular string find the corresponding translation.
3161
         * Variable subsitution is performed for the $args parameter.
3162
         * @since 1.3
3163
         *
3164
         * @param string   $english  the string to translate
3165
         * @param array    $args     a strtr-formatted array of string substitutions
3166
         * @return string
3167
        */
3168
        static function Ph( $english, $args = null ) {
3169
                return CBTxt::_parseReplaceString( CBTxt::Th( $english ), $args );
3170
        }
3171
        /**
3172
         * Parse the string through CBTxt::Tutf8.
3173
         * That is, for a particular string find the corresponding translation.
3174
         * Variable subsitution is performed for the $args parameter.
3175
         * @since 1.3
3176
         *
3177
         * @param string   $english  the string to translate
3178
         * @param array    $args     a strtr-formatted array of string substitutions
3179
         * @return string
3180
        */
3181
        static function Putf8( $english, $args = null ) {
3182
                return CBTxt::_parseReplaceString( CBTxt::Tutf8( $english ), $args );
3183
        }
3184
        /**
3185
         * Parse the translated string with strtr
3186
         * That is, for a particular string find the corresponding translation.
3187
         * Variable subsitution is performed for the $args parameter.
3188
         * @since 1.3
3189
         *
3190
         * @param string   $string   the string to substitute
3191
         * @param array    $args     a strtr-formatted array of string substitutions
3192
         * @return string
3193
        */
3194
        private static function _parseReplaceString( $string, $args ) {
3195
                if ( $args === null ) {
3196
                        $args                =        array();
3197
                }
3198
                return strtr( $string, $args );
3199
        }
3200
        /**
3201
         * Adds strings to the translations. Used by language plugins
3202
         *
3203
         * @param  array  $array
3204
         */
3205
        static function addStrings( $array ) {
3206
                global $_CB_TxtIntStore;
3207
                $_CB_TxtIntStore->_strings                        =        array_merge( $_CB_TxtIntStore->_strings, $array );
3208
        }
3209
        /**
3210
         * Converts UTF-8 string to CMS charset
3211
         *
3212
         * @param  string  $string
3213
         * @return string
3214
         */
3215
        static function utf8ToISO( $string ) {
3216
                global $_CB_TxtIntStore;
3217

    
3218
                if ( $_CB_TxtIntStore->_iso == 'UTF-8' ) {
3219
                        return $string;
3220
                } else {
3221
                        return CBTxt::charsetConv( $string, 'UTF-8', $_CB_TxtIntStore->_iso );
3222
                }
3223
        }
3224
        /**
3225
         * Converts or cleans charsets (e.g. 'ISO-8859-1', 'UTF-8')
3226
         * @since CB 1.2.2
3227
         *
3228
         * @param $string
3229
         * @param $from
3230
         * @param $to
3231
         */
3232
        static function charsetConv( $string, $from, $to ) {
3233
                if ( ( $from == 'UTF-8' ) && ( strncmp( $to, 'ISO-8859-1', 9 ) == 0 ) ) {
3234
                        return utf8_decode( $string );
3235
                } elseif ( ( $to == 'UTF-8' ) && ( strncmp( $from, 'ISO-8859-1', 9 ) == 0 ) ) {
3236
                        return utf8_encode($string);
3237
                } else {
3238
                        return CBTxt::_unhtmlentities( htmlentities($string,ENT_NOQUOTES,$from),ENT_NOQUOTES,$to);
3239
                }
3240
        }
3241
        /**
3242
         * Equivalent of html_entity_decode( $string ) using ENT_COMPAT and the charset of the system
3243
         * @since 1.2.2
3244
         *
3245
         * @param  string  $string
3246
         * @return string
3247
         */
3248
        static function html_entity_decode( $string ) {
3249
                global $_CB_TxtIntStore;
3250
                return CBTxt::_unhtmlentities( $string, ENT_COMPAT, $_CB_TxtIntStore->_iso );
3251
        }
3252
        /**
3253
         * @deprecated CB 1.2.2 : keep in CB 1.x, remove in 2.0, but use without _ as of 1.2.2
3254
         */
3255
        function _unhtmlentities( $string, $quotes = ENT_COMPAT, $charset = "ISO-8859-1" ) {
3256
                $phpv = phpversion();
3257
                if ( version_compare( $phpv, '4.4.3', '<' )
3258
                         || ( version_compare( $phpv, '5.0.0', '>=' ) && version_compare( $phpv, '5.1.3', '<' ) )
3259
                     || ( version_compare( $phpv, '5.0.0', '<'  ) && ( ! in_array( $charset, array( "ISO-8859-1", "ISO-8859-15", "cp866", "cp1251", "cp1252" ) ) ) )
3260
                     || ( version_compare( $phpv, '5.1.3', '>=' ) && ( ! in_array( $charset, array( "ISO-8859-1", "ISO-8859-15", "cp866", "cp1251", "cp1252",
3261
                                                                                        "KOI8-R", "BIG5", "GB2312", "UTF-8", "BIG5-HKSCS", "Shift_JIS", "EUC-JP" ) ) ) )
3262
                   ) {
3263
                        // For 4.1.0 =< PHP < 4.3.0 use this function instead of html_entity_decode: also php < 5.0 does not support UTF-8 outputs !
3264
                        // Plus up to 4.4.2 and 5.1.2 html_entity_decode is deadly buggy
3265
                        $trans_tbl = get_html_translation_table( HTML_ENTITIES );
3266
                        if ( $charset == "UTF-8" ) {
3267
                                foreach ( $trans_tbl as $k => $v ) {
3268
                                        $ttr[$v] = utf8_encode($k);
3269
                                }
3270
                        } else {
3271
                                $ttr = array_flip( $trans_tbl );
3272
                        }
3273
                        return strtr( $string, $ttr );
3274
                } else  {
3275
                        return html_entity_decode( $string, $quotes, $charset );
3276
                }
3277
        }
3278

    
3279
}
3280

    
3281
/**
3282
 * CB GLOBALS and initializations
3283
 */
3284

    
3285
// ----- NO MORE CLASSES OR FUNCTIONS PASSED THIS POINT -----
3286
// Post class declaration initialisations
3287
// some version of PHP don't allow the instantiation of classes
3288
// before they are defined
3289

    
3290
switch ( checkJversion() ) {
3291
        case 2:
3292
                global $mainframe;
3293

    
3294
                $mainframe                        =&        JFactory::getApplication();
3295
                $tmpDatabase                =&        JFactory::getDBO();
3296
                $my                                        =&        JFactory::getUser();
3297
                $acl                                =&        JFactory::getACL();
3298
                $myAid                                =        null;
3299
                $sefFunc                        =        array( 'JRoute', '_' );
3300
                $sefFuncHtmlEnt                =        false;
3301
                $cmsUser                        =        'JUser';
3302
                $cmsUserNeedsDb                =        false;
3303
                $cmsRedirectFunc        =        array( $mainframe, 'redirect' );
3304
                $lang                                =&        JFactory::getLanguage();
3305
                $myLanguage                        =        strtolower( preg_replace( '/^(\w+).*$/i', '\1', $lang->getName() ) );
3306
                $myLanguageTag                =        $lang->getTag();
3307
                $outputCharst                =        'UTF-8';
3308
                $getVarFunction                =        array( 'JRequest', 'getVar' );
3309
                $Jdocument                        =&        JFactory::getDocument();
3310

    
3311
                if ( $Jdocument->getType() == 'html' ) {
3312
                        $getDocFunction        =        array( 'JFactory', 'getDocument' );
3313
                } else {
3314
                        $getDocFunction        =        false;
3315
                }
3316

    
3317
                $editor                                =&        JFactory::getEditor();
3318
                $editorDisplay                =        array(        'display' => array( 'call' => array( $editor , 'display' ), 'args' => 'noid' ),
3319
                                                                                  'save' => array( 'call' => array( $editor , 'save' ), 'args' => 'noid' ),
3320
                                                                                  'returns' => true
3321
                                                                                );
3322
                break;
3323
        case 1:
3324
                global $mainframe;                //                 $mainframe                =&        JFactory::getApplication();
3325
                $tmpDatabase        =&        JFactory::getDBO();
3326
                $my                                =&        JFactory::getUser();
3327
                $acl                        =&        JFactory::getACL();
3328
                $myAid                        =        $my->get('aid', 0);
3329
                $sefFunc                =        array( 'JRoute', '_' );
3330
                $sefFuncHtmlEnt        =        false;
3331
                $cmsUser                =        'JUser';
3332
                $cmsUserNeedsDb        =        false;
3333
                $cmsRedirectFunc =        array( $mainframe, 'redirect' );
3334
                $lang                        =&        JFactory::getLanguage();
3335
                $myLanguage                =        $lang->getBackwardLang();
3336
                $myLanguageTag        =        $lang->getTag();
3337
                $outputCharst        =        'UTF-8';
3338
                $getVarFunction        =        array( 'JRequest', 'getVar' );
3339
                $Jdocument                =&        JFactory::getDocument();
3340
                if ( $Jdocument->getType() == 'html' ) {
3341
                        $getDocFunction        =        array( 'JFactory', 'getDocument' );
3342
                } else {
3343
                        $getDocFunction        =        false;
3344
                }
3345

    
3346
                $editor                        =&        JFactory::getEditor();
3347
                //$editor->initialise();
3348
                $editorDisplay        =        array( 'display' => array( 'call' => array( $editor , 'display' ),        'args' => 'noid' ),
3349
                                                                   'save'         => array( 'call' => array( $editor , 'save' ),                'args' => 'noid' ),
3350
                                                                   'returns' => true );
3351
                // no$editorDisplay        =        array( 'JEditor' , 'display' );
3352
                break;
3353
        case 0:
3354
                global $mainframe, $database, $my, $acl;
3355
                $tmpDatabase        =&        $database;
3356
                $myAid                        =        $my->gid;
3357
                $sefFunc                =        'sefRelToAbs';
3358
                $sefFuncHtmlEnt        =        true;
3359
                $cmsUser                =        'mosUser';
3360
                $cmsUserNeedsDb        =        true;
3361
                $cmsRedirectFunc =        'mosRedirect';
3362
                $myLanguage                =        $mainframe->getCfg( 'lang' );
3363
                $myLanguageTag        =        null;
3364
                $outputCharst        =        ( defined( '_ISO' ) ? strtoupper( str_replace( "charset=", "", _ISO ) ) : 'ISO-8859-1' );
3365
                $getVarFunction        =        null;
3366
                $getDocFunction        =        null;
3367
                $editorDisplay        =        array( 'display' => array( 'call' => 'editorArea',                  'args' => 'withid' ),
3368
                                                                   'save'         => array( 'call' => 'getEditorContents', 'args' => 'withid' ),
3369
                                                                   'returns' => false );
3370
                break;
3371
        case -1:
3372
        default:
3373
                global $mainframe, $database, $my, $acl;
3374
                $tmpDatabase        =&        $database;
3375
                $myAid                        =        $my->gid;
3376
                $sefFunc                =        'sefRelToAbs';
3377
                $sefFuncHtmlEnt        =        true;
3378
                $cmsUser                =        'mosUser';
3379
                $cmsUserNeedsDb        =        true;
3380
                $cmsRedirectFunc =        'mosRedirect';
3381
                $myLanguage                =        $mainframe->getCfg( 'locale' );
3382
                $myLanguageTag        =        null;
3383
                $outputCharst        =        ( defined( '_ISO' ) ? strtoupper( str_replace( "charset=", "", _ISO ) ) : 'UTF-8' );
3384
                $getVarFunction        =        null;
3385
                $getDocFunction        =        null;
3386
                $editorDisplay        =        array( 'display' => array( 'call' => 'editorArea',                  'args' => 'withid' ),
3387
                                                                   'save'         => array( 'call' => 'getEditorContents', 'args' => 'withid' ),
3388
                                                                   'returns' => false );
3389
                break;
3390
}
3391
switch ( checkJversion() ) {
3392
        case 2:
3393
        $aclParams                        =        array(        'canEditUsers'                        =>        array( 'com_user', 'core.edit', 'users', null ),
3394
                                                                        'canBlockUsers'                        =>        array( 'com_users', 'core.edit.state', 'users', null ),
3395
                                                                        'canReceiveAdminEmails'        =>        array( 'com_users', 'core.admin', 'users', null ),
3396
                                                                        'canEditOwnContent'                =>        array( 'com_content', 'core.edit', 'users', null, 'content', 'own' ),
3397
                                                                        'canAddAllContent'                 =>        array( 'com_content', 'core.create', 'users', null, 'content', 'all' ),
3398
                                                                        'canEditAllContent'         =>        array( 'com_content', 'core.edit', 'users', null, 'content', 'all' ),
3399
                                                                        'canPublishContent'                =>        array( 'com_content', 'core.edit.state', 'users', null, 'content', 'all' ),
3400
                                                                        'canInstallPlugins'                =>        array( 'com_installer', 'core.manage', 'users', null ),
3401
                                                                        'canManageUsers'                =>        array( 'com_users', 'core.manage', 'users', null )
3402
                                                        );
3403
        break;
3404
        case 1:
3405
        $aclParams                        =        array(        'canEditUsers'                        =>        array( 'com_user', 'edit', 'users', null ),
3406
                                                                        'canBlockUsers'                        =>        array( 'com_users', 'block user', 'users', null ),
3407
                                                                        'canReceiveAdminEmails'        =>        array( 'com_users', 'email_events', 'users', null ),
3408
                                                                        'canEditOwnContent'                =>        array( 'com_content', 'edit', 'users', null, 'content', 'own' ),
3409
                                                                        'canAddAllContent'                 =>        array( 'com_content', 'add', 'users', null, 'content', 'all' ),
3410
                                                                        'canEditAllContent'         =>        array( 'com_content', 'edit', 'users', null, 'content', 'all' ),
3411