Esempio n. 1
0
	/**
	* @param  string   $sql        SQL with ordering As value and 'name field' AS text
	* @param  int      $chop       The length of the truncated headline
	* @param  boolean  $translate  translate to CB language
	* @return array                of makeOption
	* @access private
	*/
	function _cbGetOrderingList( $sql, $chop = 30, $translate = true ) {
		global $_CB_database;
	
		$order				=	array();
		$_CB_database->setQuery( $sql );
		$orders				= $_CB_database->loadObjectList();
		if ( $_CB_database->getErrorNum() ) {
			echo $_CB_database->stderr();
			return false;
		}
		if ( count( $orders ) == 0 ) {
			$order[]	=	moscomprofilerHTML::makeOption( 1, CBTxt::T('first') );
			return $order;
		}
		$order[]			=	moscomprofilerHTML::makeOption( 0, '0 ' . CBTxt::T('first') );
		for ( $i=0, $n = count( $orders ); $i < $n; $i++ ) {
			if ( $translate ) {
				$text		=	getLangDefinition( $orders[$i]->text );
			} else {
				$text		=	$orders[$i]->text;
			}
			if ( cbIsoUtf_strlen( $text ) > $chop ) {
	        	$text		=	cbIsoUtf_substr( $text, 0, $chop ) . '...';
	        }
	
			$order[]		=	moscomprofilerHTML::makeOption( $orders[$i]->value, $orders[$i]->value . ' (' . $text . ')' );
		}
		if ( isset( $orders[$i - 1] ) ) {
			$order[]		=	moscomprofilerHTML::makeOption( $orders[$i - 1]->value + 1, ( $orders[$i - 1]->value + 1 ) . ' ' . CBTxt::T('last') );
		}
		return $order;
	}
	/**
	 * output form validation jquery
	 *
	 * @param string $selector
	 * @param string $params
	 */
	static function loadJquery( $selector, $params ) {
		global $_CB_framework;

		if ( ! $selector ) {
			$selector	=	'#gjForm';
		}

		$js				=	"$( '" . addslashes( $selector ) . "' ).validate( {"
						.		"submitHandler: function( form ) {"
						.			"$( form ).find( 'input[type=\"submit\"]' ).attr( 'disabled', 'disabled' ).addClass( 'disabled' ).val( '" . addslashes( CBTxt::T( 'Loading...' ) ) . "' );"
						.			"form.submit();"
						.		"},";

		if ( $params ) {
			$js			.=		$params . ( ( cbIsoUtf_substr( trim( $params ), -1 ) != ',' ) ? ',' : null );
		}

		$js				.=		"ignoreTitle: true,"
						.		"errorClass: 'gjValidationError',"
						.		"highlight: function( element, errorClass ) {"
						.			"$( element ).parent().parent().addClass( 'error');"
						.		"},"
						.		"unhighlight: function( element, errorClass ) {"
						.			"$( element ).parent().parent().removeClass( 'error' );"
						.		"},"
						.		"errorElement: 'div',"
						.		"errorPlacement: function( error, element ) {"
						.			"$( element ).parent().children().last().after( error );"
						.		"}"
						.	"});"
						.	"$.extend( jQuery.validator.messages, {"
						.		"required: '" . addslashes( CBTxt::T( 'This input is required.' ) ) . "',"
						.		"remote: '" . addslashes( CBTxt::T( 'Please fix this input.' ) ) . "',"
						.		"email: '" . addslashes( CBTxt::T( 'Please input a valid email address.' ) ) . "',"
						.		"url: '" . addslashes( CBTxt::T( 'Please input a valid URL.' ) ) . "',"
						.		"date: '" . addslashes( CBTxt::T( 'Please input a valid date.' ) ) . "',"
						.		"dateISO: '" . addslashes( CBTxt::T( 'Please input a valid date (ISO).' ) ) . "',"
						.		"number: '" . addslashes( CBTxt::T( 'Please input a valid number.' ) ) . "',"
						.		"digits: '" . addslashes( CBTxt::T( 'Please input only digits.' ) ) . "',"
						.		"creditcard: '" . addslashes( CBTxt::T( 'Please input a valid credit card number.' ) ) . "',"
						.		"equalTo: '" . addslashes( CBTxt::T( 'Please input the same value again.' ) ) . "',"
						.		"accept: '" . addslashes( CBTxt::T( 'Please input a value with a valid extension.' ) ) . "',"
						.		"maxlength: $.validator.format('" . addslashes( CBTxt::T( 'Please input no more than {0} characters.' ) ) . "'),"
						.		"minlength: $.validator.format('" . addslashes( CBTxt::T( 'Please input at least {0} characters.' ) ) . "'),"
						.		"rangelength: $.validator.format('" . addslashes( CBTxt::T( 'Please input a value between {0} and {1} characters long.' ) ) . "'),"
						.		"range: $.validator.format('" . addslashes( CBTxt::T( 'Please input a value between {0} and {1}.' ) ) . "'),"
						.		"max: $.validator.format('" . addslashes( CBTxt::T( 'Please input a value less than or equal to {0}.' ) ) . "'),"
						.		"min: $.validator.format('" . addslashes( CBTxt::T( 'Please input a value greater than or equal to {0}.' ) ) . "')"
						.	"});";

		$_CB_framework->outputCbJQuery( $js, 'validate' );
	}
Esempio n. 3
0
 /**
  * returns plugins xml version
  *
  * @param  null|PluginTable|int  $plugin    The plugin id or object to check version for
  * @param  bool                  $raw       1/True: version only (no farm), 0/False: Formatted version (green/red/shortened), 2: array of version information ( $version, $latestVersion, $isLatest, $latestURL )
  * @param  int                   $duration  The duration to cache the plugin version xml file (null/0 for no limit)
  * @param  int                   $length    The maximum version length to display (null/0 for no limit)
  * @return null|string
  */
 public function getPluginVersion($plugin, $raw = false, $duration = 24, $length = 0)
 {
     global $_CB_framework, $ueConfig;
     cbimport('cb.snoopy');
     static $plgVersions = null;
     if ($plgVersions === null) {
         $cacheFile = $_CB_framework->getCfg('absolute_path') . '/cache/cbpluginsversions.xml';
         $plgVersionsXML = null;
         if (file_exists($cacheFile)) {
             if (!$duration || intval(($_CB_framework->now() - filemtime($cacheFile)) / 3600) > $duration) {
                 $request = true;
             } else {
                 $plgVersionsXML = new SimpleXMLElement(trim(file_get_contents($cacheFile)));
                 $request = false;
             }
         } else {
             $request = true;
         }
         if ($request) {
             $s = new CBSnoopy();
             $s->read_timeout = 30;
             $s->referer = $_CB_framework->getCfg('live_site');
             @$s->fetch('http://update.joomlapolis.net/cbpluginsversions20.xml');
             if ((int) $s->status == 200) {
                 try {
                     $plgVersionsXML = new SimpleXMLElement($s->results);
                     $plgVersionsXML->saveXML($cacheFile);
                 } catch (Exception $e) {
                 }
             }
         }
         if ($plgVersionsXML) {
             $plgVersions = $plgVersionsXML->getElementByPath('cb_plugins/' . (checkJversion() >= 2 ? 'j30' : 'j15'));
         } else {
             $plgVersions = false;
         }
     }
     $plugin = $this->getCachedPluginObject($plugin);
     if (!$plugin) {
         return $raw === 2 ? array(null, null, null, null) : null;
     }
     static $cache = array();
     $pluginId = (int) $plugin->id;
     if (!isset($cache[$pluginId][$raw])) {
         $xmlFile = $this->getPluginXmlPath($plugin);
         $version = null;
         $latestVersion = null;
         $isLatest = null;
         $latestURL = null;
         if (file_exists($xmlFile)) {
             try {
                 $xml = new SimpleXMLElement(trim(file_get_contents($xmlFile)));
             } catch (\Exception $e) {
                 $xml = null;
                 echo "{$xmlFile} not an XML file!!!";
             }
             if ($xml !== null) {
                 $ver = null;
                 if (isset($xml->release)) {
                     // New release XML variable used by incubator projects:
                     $ver = $xml->release;
                 } elseif (isset($xml->cbsubsversion)) {
                     // CBSubs plugin versions are same as the CBSubs version; lets grab them:
                     $cbsubsVer = $xml->cbsubsversion->attributes();
                     if (isset($cbsubsVer['version'])) {
                         $ver = $cbsubsVer['version'];
                     }
                 } elseif (isset($xml->description)) {
                     // Attempt to parse plugin description for a version using logical naming:
                     if (preg_match('/(?:plugin|field|fieldtype|ver|version|' . preg_quote($plugin->name) . ') ((?:[0-9]+(?:\\.)?(?:(?: )?RC)?(?:(?: )?B)?(?:(?: )?BETA)?)+)/i', $xml->description, $matches)) {
                         $ver = $matches[1];
                     }
                 }
                 // Check if version was found; if it was lets clean it up:
                 if ($ver) {
                     if (preg_match('/^\\d+(\\.\\d+)+(-[a-z]+\\.\\d+)?(\\+\\w)?$/', $ver)) {
                         $version = $ver;
                     } else {
                         $version = preg_replace('/\\.*([a-zA-Z]+)\\.*/i', '.$1.', preg_replace('/^[a-zA-Z]+/i', '', str_replace(array('-', '_', '+'), '.', str_replace(' ', '', strtoupper($ver)))));
                     }
                     if (is_integer($version)) {
                         $version = implode('.', str_split($version));
                     } elseif (preg_match('/^(\\d{2,})(\\.[a-zA-Z].+)/i', $version, $matches)) {
                         $version = implode('.', str_split($matches[1])) . $matches[2];
                     }
                     $version = trim(str_replace('..', '.', $version), '.');
                     // Encase the version is too long lets cut it short for readability and display full version as mouseover title:
                     if ($version && $length && cbIsoUtf_strlen($version) > $length) {
                         $versionName = rtrim(trim(cbIsoUtf_substr($version, 0, $length)), '.') . '&hellip;';
                         $versionShort = true;
                     } else {
                         $versionName = $version;
                         $versionShort = false;
                     }
                     // Lets try and parse out latest version and latest url from versions xml data:
                     if ($plgVersions) {
                         foreach ($plgVersions as $plgVersion) {
                             $plgName = (string) $plgVersion->name;
                             $plgFile = (string) $plgVersion->file;
                             if ($plgName == $plugin->name || strpos($plgName, $plugin->name) !== false || strpos($plgFile, $plugin->folder) !== false) {
                                 $latestVersion = (string) $plgVersion->version;
                                 $latestURL = (string) $plgVersion->url;
                             }
                         }
                     }
                     if ($latestVersion) {
                         if (version_compare($version, $latestVersion) >= 0) {
                             $isLatest = true;
                         } else {
                             $isLatest = false;
                         }
                     }
                     // Format version display:
                     if (!$raw) {
                         if ($latestVersion) {
                             if ($isLatest) {
                                 $version = '<span class="text-success"' . ($versionShort ? ' title="' . htmlspecialchars($version) . '"' : null) . '><strong>' . $versionName . '</strong></span>';
                             } else {
                                 $version = '<span class="text-danger" title="' . htmlspecialchars($latestVersion) . '"><strong>' . $versionName . '</strong></span>';
                                 if ($latestURL) {
                                     $version = '<a href="' . htmlspecialchars($latestURL) . '" target="_blank">' . $version . '</a>';
                                 }
                             }
                         } else {
                             if ($versionShort) {
                                 $version = '<span title="' . htmlspecialchars($version) . '">' . $versionName . '</span>';
                             } else {
                                 $version = $versionName;
                             }
                         }
                     }
                 }
             }
         }
         if (!$version && !$raw) {
             if ($plugin->iscore) {
                 // core plugins are same version as CB it self:
                 if ($length && cbIsoUtf_strlen($ueConfig['version']) > $length) {
                     $version = '<span title="' . htmlspecialchars($ueConfig['version']) . '">' . rtrim(trim(cbIsoUtf_substr($ueConfig['version'], 0, $length)), '.') . '&hellip;</span>';
                 } else {
                     $version = $ueConfig['version'];
                 }
             } else {
                 $version = '-';
             }
         }
         if ($raw === 2) {
             $version = array($version, $latestVersion, $isLatest, $latestURL);
         }
         $cache[$pluginId][$raw] = $version;
     }
     return $cache[$pluginId][$raw];
 }
	/**
	 * Implements a form firstwords field
	 *
	 * @param  string              $name          The name of the form element
	 * @param  string              $value         The value of the element
	 * @param  SimpleXMLElement  $node          The xml element for the parameter
	 * @param  string              $control_name  The control name
	 * @return string                             The html for the element
	 */
	function _form_firstwords( $name, $value, &$node, $control_name ) {
		if ( $this->_view ) {
			$size				=	$node->attributes( 'size' );

			if ( ! $size ) {
				$size			=	45;
			}

			$strippedContent	=	trim( strip_tags( cbUnHtmlspecialchars( $value ) ) );

			if ( cbIsoUtf_strlen( $strippedContent ) > $size ) {
				$content		=	'<span title="' . htmlspecialchars($strippedContent ) . '">' . htmlspecialchars( cbIsoUtf_substr( $strippedContent, 0, $size ) . '...' ) . '</span>';
			} else {
				$content		=	htmlspecialchars( $strippedContent );
			}

			return $content;
		} else {
			return $this->_form_textarea($name, $value, $node, $control_name );
		}
	}
	/**
	 * Prepares and signs payflow payment $requestParams
	 *
	 * @param cbpaidPaymentBasket $paymentBasket
	 * @param bool $subscription
	 * @return array $requestParams
	 */
	private function _payflowPayment( $paymentBasket, $subscription = false )
	{
		$requestParams									=	array();

		if ( $this->hasPaypalPayflow() ) {
			$countries									=	new cbpaidCountries();

			if ( $paymentBasket->period3 ) {
				if ( $paymentBasket->period1 ) {
					$amount								=	sprintf( '%.2f', $paymentBasket->mc_amount1 );
				} else {
					$amount								=	sprintf( '%.2f', $paymentBasket->mc_amount3 );
				}
			} else {
				$amount									=	sprintf( '%.2f', $paymentBasket->mc_gross );
			}

			if ( $this->getAccountParam( 'normal_gateway' ) == '0' ) {
				$requestParams['MODE']					=	'TEST';
			}

			$request									=	array(	'PARTNER' => 'PayPal',
																	'VENDOR' => $this->getAccountParam( 'paypal_payflow_vendor' ),
																	'USER' => $this->getAccountParam( 'paypal_payflow_user' ),
																	'PWD' => $this->getAccountParam( 'paypal_payflow_password' ),
																	'TRXTYPE' => 'S',
																	'AMT' => $amount,
																	'CREATESECURETOKEN' => 'Y',
																	'SECURETOKENID' => uniqid(),
																	'TEMPLATE' => $this->getAccountParam( 'template_layout', 'MINLAYOUT' ),
																	'ORDERDESC' => $paymentBasket->item_name,
																	'INVNUM' => $paymentBasket->invoice,
																	'CURRENCY' => $paymentBasket->mc_currency,
																	'USER1' => $paymentBasket->id,
																	'USER2' => $paymentBasket->user_id,
																	'USER3' => $paymentBasket->item_number,
																	'USER4' => ( $subscription ? 'R' : 'S' )
																);

			if ( $subscription ) {
				$request['RECURRING']					=	'Y';
			}

			if ( $this->getAccountParam( 'givehiddenbillemail' ) && ( strlen( $paymentBasket->payer_email ) <= 127 ) ) {
				$request['EMAIL']						=	$paymentBasket->payer_email;
			}

			if ( $this->getAccountParam( 'givehiddenbilladdress' ) ) {
				cbimport( 'cb.tabs' );

				$addressFields							=	array(	'BILLTOFIRSTNAME' => array( $paymentBasket->first_name, 30 ),
																	'BILLTOLASTNAME' => array( $paymentBasket->last_name, 30 ),
																	'BILLTOSTREET' => array( $paymentBasket->address_street, 150 ),
																	'BILLTOZIP' => array( $paymentBasket->address_zip, 9 ),
																	'BILLTOCITY' => array( $paymentBasket->address_city, 45 ),
																	'BILLTOCOUNTRY' => array( $countries->countryToTwoLetters( $paymentBasket->address_country ), 2 )
																);

				if ( $paymentBasket->address_state != 'other' ) {
					$addressFields['BILLTOSTATE']		=	array( substr( $paymentBasket->address_state, -2 ), 2 );
				}

				foreach ( $addressFields as $k => $valueMaxlength ) {
					$adrField							=	cbIsoUtf_substr( $valueMaxlength[0], 0, $valueMaxlength[1] );

					if ( $adrField ) {
						$request[$k]					=	$adrField;
					}
				}
			}

			if ( $this->getAccountParam( 'givehiddenbilltelno' ) && ( strlen( $paymentBasket->contact_phone ) <= 50 ) ) {
				$request['BILLTOPHONENUM']				=	$paymentBasket->contact_phone;
			}

			if ( $this->getAccountParam( 'givehiddenshipemail' ) && ( strlen( $paymentBasket->payer_email ) <= 127 ) ) {
				$request['SHIPTOEMAIL']					=	$paymentBasket->payer_email;
			}

			if ( $this->getAccountParam( 'givehiddenshipaddress' ) ) {
				cbimport( 'cb.tabs' );

				$addressFields							=	array(	'SHIPTOFIRSTNAME' => array( $paymentBasket->first_name, 30 ),
																	'SHIPTOLASTNAME' => array( $paymentBasket->last_name, 30 ),
																	'SHIPTOSTREET' => array( $paymentBasket->address_street, 150 ),
																	'SHIPTOZIP' => array( $paymentBasket->address_zip, 9 ),
																	'SHIPTOCITY' => array( $paymentBasket->address_city, 45 ),
																	'SHIPTOCOUNTRY' => array( $countries->countryToThreeLetters( $paymentBasket->address_country ), 3 )
																);

				if ( $paymentBasket->address_state != 'other' ) {
					$addressFields['SHIPTOSTATE']		=	array( substr( $paymentBasket->address_state, -2 ), 2 );
				}

				foreach ( $addressFields as $k => $valueMaxlength ) {
					$adrField							=	cbIsoUtf_substr( $valueMaxlength[0], 0, $valueMaxlength[1] );

					if ( $adrField ) {
						$request[$k]					=	$adrField;
					}
				}
			}

			if ( $this->getAccountParam( 'givehiddenshiptelno' ) && ( strlen( $paymentBasket->contact_phone ) <= 50 ) ) {
				$request['SHIPTOPHONENUM']				=	$paymentBasket->contact_phone;
			}

			$formUrl									=	array();

			foreach ( $request as $k => $v ) {
				$formUrl[$k]							=	$k . '=' . $v;
			}

			$formUrl									=	implode( '&', $formUrl );

			$results									=	array();
			$response									=	null;
			$status										=	null;
			$error										=	$this->_httpsRequest( $this->gatewayUrl( 'psp' ), $formUrl, 105, $response, $status, 'post', 'normal' );

			if ( $response ) {
				parse_str( $response, $results );
			}

			if ( $error || ( $status != 200 ) || ( ! $response ) ) {
				$this->_setLogErrorMSG( 3, null, $this->getPayName() . ' HTTPS POST request to payment gateway server failed.', CBPTXT::T( "Submitted subscription payment didn't return an error but didn't complete." ) . ' ' . CBPTXT::T( 'Please contact site administrator to check error log.' ) );
			} else {
				if ( cbGetParam( $results, 'RESULT' ) == '0' ) {
					$requestParams['SECURETOKEN']		=	cbGetParam( $results, 'SECURETOKEN' );
					$requestParams['SECURETOKENID']		=	cbGetParam( $results, 'SECURETOKENID' );
				} else{
					$this->_setLogErrorMSG( 3, null, $this->getPayName() . ' Paypal Payflow error returned. ERROR: ' . cbGetParam( $results, 'RESPMSG' ), CBPTXT::T( 'Please contact site administrator to check error log.' ) );
				}
			}
		}

		return $requestParams;
	}
Esempio n. 6
0
    /**
     * Generic function to get an array of option values for lists, radios, checkboxes params and filter fields:
     *
     * @param  SimpleXMLElement  $o
     * @param  string              $basetype   RETURNED: base type
     * @param  string              $valueType  RETURNED: valuetype type
     * @return array|null
     */
    protected function _getFieldValues(&$o, &$basetype, &$valueType)
    {
        $valueType = $o->attributes('valuetype');
        $fieldValuesInDb = null;
        $this->registryEditVew->resolveXmlParamType($o);
        if ($o->attributes('base')) {
            $basetype = $o->attributes('base');
        } else {
            $basetype = $o->attributes('type');
        }
        switch ($o->attributes('type')) {
            case 'data':
                $data = $o->getElementByPath('data');
                if ($data) {
                    $dataTable = $data->attributes('table');
                    if (!$dataTable) {
                        $dataTable = $this->table;
                    }
                    $xmlsql = new XmlQuery($this->_db, $dataTable, $this->_pluginParams);
                    $xmlsql->process_orderby($data->getElementByPath('orderby'));
                    // <data><orderby><field> fields
                    $xmlsql->process_fields($data->getElementByPath('rows'));
                    // <data><rows><field> fields
                    $xmlsql->process_where($data->getElementByPath('where'));
                    // <data><where><column> fields
                    $groupby = $data->getElementByPath('groupby');
                    $xmlsql->process_groupby($groupby ? $groupby : 'value');
                    // <data><groupby><field> fields
                    $fieldValuesInDb = $xmlsql->queryLoadObjectsList($data);
                    // get the records
                    // check for type="firstwords":
                    $rows = $data->getElementByPath('rows');
                    /** @var $rows SimpleXMLElement|null */
                    if ($rows) {
                        $textField = $rows->getChildByNameAttr('field', 'as', 'text');
                        /** @var $textField SimpleXMLElement|null */
                        if ($textField) {
                            if ($textField->attributes('type') == 'firstwords') {
                                $size = $textField->attributes('size');
                                if (!$size) {
                                    $size = 45;
                                }
                                foreach (array_keys($fieldValuesInDb) as $k) {
                                    $strippedContent = trim($fieldValuesInDb[$k]->text);
                                    if (cbIsoUtf_strlen($strippedContent) > $size) {
                                        $strippedContent = cbIsoUtf_substr($strippedContent, 0, $size) . '...';
                                    }
                                    $fieldValuesInDb[$k]->text = $strippedContent;
                                }
                            }
                        }
                    }
                    $data->addAttribute('dataprocessed', 'true');
                } else {
                    // echo 'filter type is data but no child data present !';
                    $fieldName = $o->attributes('name');
                    if ($o->attributes('value')) {
                        $valueFieldName = $o->attributes('value');
                    } else {
                        $valueFieldName = $fieldName;
                    }
                    $dataTable = $o->attributes('table');
                    if (!$dataTable) {
                        $dataTable = $this->table;
                    }
                    $data = new SimpleXMLElement(<<<EOT
<?xml version="1.0" encoding="UTF-8"?>
<table table="{$dataTable}">
\t<rows>
\t\t<field name="{$valueFieldName}" as="value" type="sql:field" />
\t\t<field name="{$fieldName}" as="text" type="sql:field" />
\t</rows>
\t<orderby>
\t\t<field name="{$fieldName}" ordering="ASC" />
\t</orderby>
\t<groupby>
\t\t<field name="{$fieldName}" />
\t</groupby>
</table>
EOT
);
                    $xmlsql = new XmlQuery($this->_db, $dataTable, $this->_pluginParams);
                    $xmlsql->process_orderby($data->getElementByPath('orderby'));
                    // <data><orderby><field> fields
                    $xmlsql->process_fields($data->getElementByPath('rows'));
                    // <data><rows><field> fields
                    $xmlsql->process_where($data->getElementByPath('where'));
                    // <data><where><column> fields
                    $groupby = $data->getElementByPath('groupby');
                    $xmlsql->process_groupby($groupby ? $groupby : 'value');
                    // <data><groupby><field> fields
                    $fieldValuesInDb = $xmlsql->queryLoadObjectsList($data);
                    // get the records
                }
                break;
            case 'field_show_only_if_selected':
                break;
            case 'list':
            case 'radio':
            case 'checkbox':
            case 'checkmark':
            case 'published':
            case 'usergroup':
            case 'viewaccesslevel':
            case 'tag':
                foreach ($o->children() as $option) {
                    /** @var $option SimpleXMLElement */
                    if ($option->getName() == 'option') {
                        $hasIndex = $option->attributes('index') !== '' && $option->attributes('index') !== null;
                        $selObj = new \stdClass();
                        $selObj->value = $hasIndex ? $option->attributes('index') : $option->attributes('value');
                        if ($hasIndex) {
                            $selObj->internalvalue = $option->attributes('value');
                        }
                        $selObj->operator = $option->attributes('operator');
                        $selObj->text = $option->data();
                        $fieldValuesInDb[] = $selObj;
                    }
                }
                break;
            case 'field':
                global $_CB_database;
                $where = array();
                $where[] = "f." . $_CB_database->NameQuote('published') . " = 1";
                $where[] = "f." . $_CB_database->NameQuote('name') . " != " . $_CB_database->Quote('NA');
                $query = "SELECT f." . $_CB_database->NameQuote('fieldid') . " AS value" . ", f." . $_CB_database->NameQuote('name') . ' AS ' . $_CB_database->NameQuote('index') . ", f." . $_CB_database->NameQuote('title') . ' AS ' . $_CB_database->NameQuote('text') . ", f." . $_CB_database->NameQuote('table') . ' AS ' . $_CB_database->NameQuote('table') . ", " . $_CB_database->Quote('id') . ' AS ' . $_CB_database->NameQuote('table_key') . ", " . $_CB_database->Quote('=') . " AS operator" . "\n FROM " . $_CB_database->NameQuote('#__comprofiler_fields') . " AS f" . "\n LEFT JOIN " . $_CB_database->NameQuote('#__comprofiler_tabs') . " AS t" . " ON t." . $_CB_database->NameQuote('tabid') . " = f." . $_CB_database->NameQuote('tabid') . "\n WHERE " . implode("\n AND ", $where) . "\n ORDER BY t." . $_CB_database->NameQuote('position') . ", t." . $_CB_database->NameQuote('ordering') . ", f." . $_CB_database->NameQuote('ordering');
                $_CB_database->setQuery($query);
                $fieldValuesInDb = $_CB_database->loadObjectList();
                break;
            default:
                if (substr($o->attributes('type'), 0, 4) == 'sql:') {
                    // get list for dropdown filter
                    $fieldName = $o->attributes('name');
                    if ($o->attributes('value')) {
                        $valueFieldName = $o->attributes('value');
                    } else {
                        $valueFieldName = $fieldName;
                    }
                    $dataTable = $o->attributes('table');
                    if (!$dataTable) {
                        $dataTable = $this->table;
                    }
                    $data = new SimpleXMLElement(<<<EOT
<?xml version="1.0" encoding="UTF-8"?>
<table table="{$dataTable}">
\t<rows>
\t\t<field name="{$valueFieldName}" as="value" type="sql:field" />
\t\t<field name="{$fieldName}" as="text" type="sql:field" />
\t</rows>
\t<orderby>
\t\t<field name="{$fieldName}" ordering="ASC" />
\t</orderby>
\t<groupby>
\t\t<field name="{$fieldName}" />
\t</groupby>
</table>
EOT
);
                    $xmlsql = new XmlQuery($this->_db, $dataTable, $this->_pluginParams);
                    $xmlsql->process_orderby($data->getElementByPath('orderby'));
                    // <data><orderby><field> fields
                    $xmlsql->process_fields($data->getElementByPath('rows'));
                    // <data><rows><field> fields
                    $xmlsql->process_where($data->getElementByPath('where'));
                    // <data><where><column> fields
                    $groupby = $data->getElementByPath('groupby');
                    $xmlsql->process_groupby($groupby ? $groupby : 'value');
                    // <data><groupby><field> fields
                    $fieldValuesInDb = $xmlsql->queryLoadObjectsList($data);
                    // get the records
                    $o->addAttribute('type', 'list');
                    /*
                    					$fieldName	= $this->_db->getEscaped( $o->attributes( 'name' ) );
                    					if ( $o->attributes( 'value' ) ) {
                    						$valueFieldName		=	$this->_db->getEscaped( $o->attributes( 'value' ) );
                    					} else {
                    						$valueFieldName		=	$fieldName;
                    					}
                    					$tableName				=	$this->_db->getEscaped( $this->table );
                    					$query = "SELECT `" . $valueFieldName . "` AS value, `" . $fieldName . "` AS text"
                    					. "\n FROM `" . $tableName . "`"
                    					. "\n GROUP BY " . $fieldName
                    					. "\n ORDER BY " . $fieldName
                    					;
                    					$this->_db->setQuery( $query );
                    					$fieldValuesInDb = $this->_db->loadObjectList();
                    */
                }
                break;
        }
        return $fieldValuesInDb;
    }
	/**
	 * Attempts to subscribe a credit card for recurring subscription of a payment basket.
	 *
	 * @param array $card                           contains type, number, firstname, lastname, expmonth, expyear, and optionally: address, zip, country
	 * @param cbpaidPaymentBasket $paymentBasket
	 * @param int $now                              unix timestamp of now
	 * @param cbpaidsubscriptionsNotification $ipn  returns the stored notification
	 * @param int $occurrences                      returns the number of occurences pay-subscribed firmly
	 * @param int $autorecurring_type               returns:  0: not auto-recurring, 1: auto-recurring without payment processor notifications, 2: auto-renewing with processor notifications updating $expiry_date
	 * @param int $autorenew_type                   returns:  0: not auto-renewing (manual renewals), 1: asked for by user, 2: mandatory by configuration
	 * @return mixed                                subscriptionId if subscription request succeeded, otherwise ARRAY( 'level' => 'inform', 'spurious' or 'fatal', 'errorText', 'errorCode' => string ) of error to display
	 */
	protected function processSubscriptionPayment( $card, $paymentBasket, $now, &$ipn, &$occurrences, &$autorecurring_type, &$autorenew_type )
	{
		$return											=	false;

		if ( $this->hasPaypalApi() ) {
			$countries									=	new cbpaidCountries();

			list( $p3, $t3, $start )					=	$this->_paypalPeriodsLimits( explode( ' ', $paymentBasket->period3 ), $now );

			if ( $paymentBasket->period1 ) {
				list( /* $p1 */, /* $t1 */, $start )	=	$this->_paypalPeriodsLimits( explode( ' ', $paymentBasket->period1 ), $now );

				$initialAmount							=	$paymentBasket->mc_amount1;
			} else {
				$initialAmount							=	$paymentBasket->mc_amount3;
			}

			$requestParams								=	array(	'METHOD' => 'CreateRecurringPaymentsProfile',
																	'SUBSCRIBERNAME' => cbIsoUtf_substr( $card['firstname'] . ' ' . $card['lastname'], 0, 32 ),
																	'PROFILESTARTDATE' => substr( date( 'c', $start ), 0, 19 ),
																	'PROFILEREFERENCE' => $paymentBasket->invoice,
																	'DESC' => cbIsoUtf_substr( $paymentBasket->item_name, 0, 127 ),
																	'BILLINGPERIOD' => $t3,
																	'BILLINGFREQUENCY' => $p3,
																	'INITAMT' => sprintf( '%.2f', $initialAmount ),
																	'AMT' => sprintf( '%.2f', $paymentBasket->mc_amount3 ),
																	'CURRENCYCODE' => $paymentBasket->mc_currency,
																	'CREDITCARDTYPE' => cbIsoUtf_substr( $card['type'], 0, 10 ),
																	'ACCT' => substr( preg_replace ( '/[^0-9]+/', '', strval( $card['number'] ) ), 0, 22 ),
																	'EXPDATE' => substr( sprintf( '%02d', intval( $card['expmonth'] ) ), 0, 2 ) . substr( strval( intval( $card['expyear'] ) ), 0, 4 ),
																	'CVV2' => substr( preg_replace ( '/[^0-9]+/', '', strval( $card['cvv'] ) ), 0, 4 ),
																	'EMAIL' => cbIsoUtf_substr( $paymentBasket->payer_email, 0, 127 ),
																	'PAYERID' => $paymentBasket->user_id,
																	'FIRSTNAME' => cbIsoUtf_substr( $card['firstname'], 0, 25 ),
																	'LASTNAME' => cbIsoUtf_substr( $card['lastname'], 0, 25 ),
																	'STREET' => cbIsoUtf_substr( $paymentBasket->address_street, 0, 100 ),
																	'CITY' => cbIsoUtf_substr( $paymentBasket->address_city, 0, 40 ),
																	'STATE' => cbIsoUtf_substr( substr( $paymentBasket->address_state, -2 ), 0, 2 ),
																	'COUNTRYCODE' => $countries->countryToTwoLetters( $paymentBasket->address_country ),
																	'ZIP' => cbIsoUtf_substr( $paymentBasket->address_zip, 0, 20 )
																);

			if ( $paymentBasket->recur_times ) {
				$requestParams['TOTALBILLINGCYCLES']	=	$paymentBasket->recur_times;
			}

			$this->_signRequestParams( $requestParams );

			$results									=	array();
			$response									=	null;
			$status										=	null;
			$error										=	$this->_httpsRequest( str_replace( 'www', 'api-3t', $this->gatewayUrl( 'psp' ) . '/nvp' ), $requestParams, 105, $response, $status, 'post', 'normal' );

			if ( $response ) {
				parse_str( $response, $results );
			}

			if ( $error || ( $status != 200 ) || ( ! $response ) ) {
				$this->_setLogErrorMSG( 3, $ipn, $this->getPayName() . ' HTTPS POST request to payment gateway server failed.', CBPTXT::T( "Submitted subscription payment didn't return an error but didn't complete." ) . ' ' . CBPTXT::T( 'Please contact site administrator to check error log.' ) );

				$logType								=	'C';
			} else {
				if ( cbGetParam( $results, 'ACK' ) == 'Success' ) {
					$autorecurring_type					=	2;
					$autorenew_type						=	( $autorecurring_type ? ( ( $this->getAccountParam( 'enabled', 0 ) == 3 ) && ( $paymentBasket->isAnyAutoRecurring() == 2 ) ? 1 : 2 ) : 0 );

					$return								=	cbGetParam( $results, 'PROFILEID' );

					$logType							=	'A';
				} else {
					$this->_setLogErrorMSG( 3, $ipn, $this->getPayName() . ' Paypal API error returned. ERROR: ' . cbGetParam( $results, 'L_LONGMESSAGE0' ) . ' CODE: ' . cbGetParam( $results, 'L_ERRORCODE0' ), cbGetParam( $results, 'L_SHORTMESSAGE0' ) . '. ' . CBPTXT::T( 'Please contact site administrator to check error log.' ) );

					$logType							=	'W';
				}
			}

			$ipn										=	$this->_logNotification( $logType, $now, $paymentBasket, $card, $requestParams, $response, $results, $return );
		} else {
			$this->_setLogErrorMSG( 3, $ipn, $this->getPayName() . ' Needed Paypal API username, password and signature not set.', CBPTXT::T( "Submitted subscription payment didn't return an error but didn't complete." ) . ' ' . CBPTXT::T( 'Please contact site administrator to check error log.' ) );
		}

		return $return;
	}
 /**
  * Popoulates basic request parameters for gateway depending on basket (without specifying payment type)
  *
  * @param  cbpaidPaymentBasket  $paymentBasket  paymentBasket object
  * @return array                                $requestParams
  */
 private function _getBasicRequstParams($paymentBasket)
 {
     // Mandatory parameters:
     $requestParams = array();
     $requestParams['PSPID'] = $this->getAccountParam('pspid');
     $requestParams['orderID'] = $paymentBasket->id;
     $requestParams['amount'] = 100 * sprintf('%.2f', $paymentBasket->mc_gross);
     $requestParams['currency'] = $paymentBasket->mc_currency;
     $requestParams['language'] = $this->getAccountParam('language', 'en_US');
     $requestParams['operation'] = $this->getAccountParam('operation', 'SAL');
     // Courtesy field (pre-filled but editable on credit card mask):
     $requestParams['CN'] = $paymentBasket->first_name . ($paymentBasket->first_name && $paymentBasket->last_name ? ' ' : '') . $paymentBasket->last_name;
     // Recommended anti-fraud fields:
     if ($this->getAccountParam('givehiddenemail') && strlen($paymentBasket->payer_email) <= 50) {
         $requestParams['EMAIL'] = $paymentBasket->payer_email;
     }
     if ($this->getAccountParam('givehiddenaddress')) {
         cbimport('cb.tabs');
         // needed for cbIsoUtf_substr()
         $addressFields = array('owneraddress' => array($paymentBasket->address_street, 35), 'ownerZIP' => array($paymentBasket->address_zip, 10), 'ownertown' => array($paymentBasket->address_city, 25), 'ownercty' => array($this->countryToLetters($paymentBasket->address_country, 2), 2));
         foreach ($addressFields as $k => $value_maxlength) {
             $adrField = cbIsoUtf_substr($value_maxlength[0], 0, $value_maxlength[1]);
             if ($adrField) {
                 $requestParams[$k] = $adrField;
             }
         }
     }
     if ($this->getAccountParam('givehiddentelno') && strlen($paymentBasket->contact_phone) <= 50) {
         $requestParams['ownertelno'] = $paymentBasket->contact_phone;
     }
     // Recommended anti-fraud fields:
     if ($this->getAccountParam('givedescription')) {
         cbimport('cb.tabs');
         $item_name = cbIsoUtf_substr($paymentBasket->item_name, 0, 100);
         if ($item_name) {
             $requestParams['COM'] = $item_name;
         }
     }
     // Alias Manager option:
     $alias_manager = $this->getAccountParam('alias_manager');
     if ($alias_manager) {
         $existing_alias = $this->getFinancialCoordinatesAlias($paymentBasket->user_id);
         if ($existing_alias && isset($existing_alias['alias'])) {
             $requestParams['ALIAS'] = $existing_alias['alias'];
             $requestParams['ALIASUSAGE'] = $this->getAccountParam('aliasusage_already_existing');
         } else {
             if ($alias_manager == 1) {
                 // Enabled only for recurring payments: let's see if it is allowed to be autorecurring:
                 $enable_processor = 3;
                 // we allow autorecurring but let user choose, as choice is at payment gateway and enforcement is only settable at processor in this processor...
                 $pay1subscribe2 = $this->_getPaySubscribePossibilities($enable_processor, $paymentBasket);
                 if ($pay1subscribe2 & 0x2) {
                     // a payment subscription is possible:
                     $alias_manager = 2;
                 }
             }
             if ($alias_manager == 2) {
                 $requestParams['ALIASUSAGE'] = $this->getAccountParam('aliasusage');
                 if ($this->getAccountParam('aliasdeterminedby') == 'psp') {
                     $requestParams['ALIASOPERATION'] = 'BYOGONE';
                 } else {
                     $requestParams['ALIAS'] = 'cbsubs_customer_' . $paymentBasket->user_id . '_card_' . 1;
                 }
             }
         }
     }
     return $requestParams;
 }
	/**
	* Generates the HTML to display the user profile tab
	* @param object tab reflecting the tab database entry
	* @param object mosUser reflecting the user being displayed
	* @param int 1 for front-end, 2 for back-end
	* @returns mixed : either string HTML for tab content, or false if Error generated
	*/
	function getDisplayTab($tab,$user,$ui) {
		global $_CB_database,$ueConfig,$_CB_framework;
						
		// Setup image storage paths
		$PGImagesPath			=	'/components/com_comprofiler/plugin/user/plug_cbprofilegallery/images/';
		$PGImagesAbsolutePath	=	$_CB_framework->getCfg( 'absolute_path' ) . $PGImagesPath;
		$PGImagesLivePath		=	$_CB_framework->getCfg( 'absolute_path' ) . $PGImagesPath;
		$PGItemAbsolutePath		=	$_CB_framework->GetCfg( 'absolute_path' ) . '/images/comprofiler/plug_profilegallery/';
		$PGItemPath				=	'images/comprofiler/plug_profilegallery/';
	
		$tabparams = $this->_pgGetTabParameters($user);
		//print_r($tabparams);
		
		// Return if the user doesn't have the ProfileGallery enabled no need to go any further
		// Does not even display the tab
		if(!$tabparams["cbpgenable"]) return "";
		
		$htmltext0 = "";
		$htmltext1 = ""; // first part of html code to display in the tab
		$htmltext2 = ""; // second part of html code to display in the tab
		$pgWHERE = "";
		$pgORDERBY = "";
		
		//Check to see if there are actions that need to be executed
		$action = $this->_getReqParam("PGformaction", null);
		$id = $this->_getReqParam("id",0);
		//$showform = $this->_getReqParam("showform", 0);

		switch ($tabparams["pgsortoption"]) {
			case 'DATEDESC':
				$pgORDERBY = ",pgitemdate desc";
				break;
			case 'DATEASC':
				$pgORDERBY = ",pgitemdate asc";
				break;
			default:
				$pgORDERBY = ",pgitemdate desc";
				break;
		}
		// Is profile owner viewing or not?
		// If not then set additional WHERE clause to only gather published images
		$isModerator=isModerator($_CB_framework->myId());
		
		if(($_CB_framework->myId() != $user->id) && !$isModerator) {
			$isME=false;
			$pgWHERE = "\n AND pgitempublished=1";
			$pgWHERE .= "\n AND pgitemapproved=1";
		} else {
			if ($_CB_framework->myId() == $user->id) {
				$isME=true;
			} else {
				$isME=false;
			}
			//LOGIC FOR ACTIONS HERE
			//Take necessary profile owner action if there is
			//Check to see if there are actions that need to be executed
			$action = $this->_getReqParam("PGformaction", null);
			$id = $this->_getReqParam("id",0);
					
			switch ($action) {
				CASE 'delete':
					$this->pgDelete($id,$user);
					break;
				CASE 'update':
					$updatetitle = $this->_getReqParam("pguitemtitle",null);
					$updatedescription = $this->_getReqParam("pguitemdescription",null);
					$this->pgUpdate($id,$updatetitle,$updatedescription);
					//print "Updating gallery item id:".$id;
					break;
				CASE 'publish':
					$this->pgPublish($id);
					//print "Publishing gallery item id:".$id;
					break;	
				CASE 'unpublish':
					$this->pgUnPublish($id);
					//print "Unpublishing gallery item id:".$id;
					break;	
				CASE 'approve':
                    if ($isModerator) {
					    $this->pgApprove($id,$user);
                    }
					//print "Approving gallery item id:".$id;
					break;
				CASE 'revoke':
                    if ($isModerator) {
					    $this->pgRevoke($id,$user);
                    }
					//print "Revoking gallery item id:".$id;
					break;
				DEFAULT:
					//print "I'm doing nothing:".$id." action:".$action;
					break;
			}
		}
		
		// if moderator viewing display extra info for front-end moderation activities
		if ($isModerator && !$isME) {
			$moderatorviewmessage = sprintf(    CBTxt::Th('<font color="red">Moderator data:<br />'
                                                .'Items - %1$d<br />'
                                                .'Item Quota - %2$d<br />'
                                                .'Storage - %3$d<br />'
                                                .'Storage Quota - %4$d<br />'
                                                .'Access Mode - %5$s<br />'
                                                .'Display Mode - %6$s<br /></font>'
                                                ),(int) $user->cb_pgtotalitems,
				                                $tabparams["cbpgtotalquotaitems"],
				                                $user->cb_pgtotalsize/1024,
				                                $tabparams["cbpgtotalquotasize"],
				                                $tabparams[$tabparams["cbpgaccessmode"]],
				                                $tabparams[$tabparams["cbpgdisplayformat"]],
                                                $tabparams["cbpguploadsize"]
                                                );
			$htmltext1 .= $moderatorviewmessage . "<br />";
		}
		
		// First thing to do is to display the correct tab description if not empty
		if($tab->description != null) {
			$htmltext1 .= "\t\t<div class=\"tab_Description\">";
			$htmltext1 .= cbUnHtmlspecialchars(getLangDefinition($tab->description));
			$htmltext1 .= "</div>\n";
		}
		
		
		// if connections restriction enable
		// and connections enabled on the system
		// and its not me viewing then
		// check if current viewer is connected with
		// profile owner
		
		if($_CB_framework->myId()==0) {
			$isAnonymous = true;
		} else {
			$isAnonymous = false;
		}
		$check4connection = 0;

		switch ($tabparams["cbpgaccessmode"]) {
			case 'PUB':
				break;
			case 'REG':
				if ($isAnonymous) {
					
					$htmltext1 .= "<p>" 
						. sprintf(CBTxt::Th("Only Registered Members Allowed to view the %1\$d items in this Gallery!"), (int) $user->cb_pgtotalitems)
						. "</p>";
					return $htmltext1;
				}
				break;
			case 'REG-S':
				if ($isAnonymous) return "";
				break;
			case 'CON':
				if ($isAnonymous) {
					$htmltext1 .= "<p>" 
						. sprintf(CBTxt::Th("Sorry - connections only viewing enabled for this gallery that currently has %1\$d items in it."), (int) $user->cb_pgtotalitems)
						. "</p>";
					return $htmltext1;
				}
				$check4connection = 1;
				break;
			case 'CON-S':
				if ($isAnonymous) {
					return $htmltext1;
				}
				$check4connection = 1;
				break;
			default:
				break;	
		}
		
		if ($check4connection && !$isAnonymous && !$isModerator && !$isME) {
			if ($ueConfig['allowConnections']) {	
				$query="SELECT COUNT(*)"
					. "\n FROM #__comprofiler_members"
					. "\n WHERE memberid=" . (int) $user->id
					. "\n AND referenceid=" . (int) $_CB_framework->myId()
					. "\n AND accepted=1 AND pending=0";
				$_CB_database->setQuery($query);
				$isconnected = $_CB_database->loadResult();
				if (!$isconnected) {
					if ($tabparams["cbpgaccessmode"] == 'CON-S') return "";
					$htmltext1 .= "<p>" . sprintf(CBTxt::Th("Sorry - connections only viewing enabled for this gallery that currently has %1\$d items in it."), (int) $user->cb_pgtotalitems) . "</p>";
					return $htmltext1;
				}
			} else {
				if ($tabparams["cbpgaccessmode"] == 'CON-S') return "";
				$htmltext1 .= "<p>" . sprintf(CBTxt::Th("Sorry - connections only viewing enabled for this gallery that currently has %1\$d items in it."), (int) $user->cb_pgtotalitems) . "</p>";
				return $htmltext1;
			}
		}
		
		//Check to see if a user has submitted a new gallery item entry to be processed
		if (($isME || ($tabparams["pgallowaccessmodeoverride"] && $isModerator)) AND isset($_POST[$this->_getPagingParamName("pgitemtitle")])) {
			$htmltext0 .= $this->_pgProcessNewItem($id,$user);
		}
		
		// Find and show posts
		$pagingParams = $this->_getPaging(array(),array("pgposts_"));
				
		//check to see if the Admin enabled pagination
		if ($tabparams["pgpagingenabled"]) {
			//select a count of all applicable entries for pagination
			$query="SELECT count(*)"
				. "\n FROM #__comprofiler_plug_profilegallery"
				. "\n WHERE userid=" . (int) $user->id
				. "\n " . $pgWHERE;
			
			$_CB_database->setQuery($query);
			$pgtotal = $_CB_database->loadResult();
			
			if (!is_numeric($pgtotal)) $pgtotal = 0;

			if ($pagingParams["pgposts_limitstart"] === null) $pagingParams["pgposts_limitstart"] = "0";
			if ($tabparams["pgentriesperpage"] > $pgtotal) $pagingParams["pgposts_limitstart"] = "0";
		} else {
			$pagingParams["pgposts_limitstart"] = "0";
		}
		
		$PGItemAbsoluteUserPath = $PGItemAbsolutePath . $user->id . "/";
		$PGItemUserPath = $PGItemPath . $user->id . "/";

        $lastitemid = $this->_pgLastItemId($user->id);
            
		// Select all entries to be displayed
		$query="SELECT *"
			. "\n FROM #__comprofiler_plug_profilegallery"
			. "\n WHERE userid=" . (int) $user->id
			. "\n " . $pgWHERE
			. "\n ORDER BY pgitemorder"
			. "\n " . $pgORDERBY
			;
		$_CB_database->setQuery($query, (int) ( $pagingParams["pgposts_limitstart"] ? $pagingParams["pgposts_limitstart"] : 0 ), (int) $tabparams["pgentriesperpage"] );
		//print $database->getQuery();
		$pgitems=$_CB_database->loadObjectList();
		$pgdisplaycount=count($pgitems);

		// Display welcome message
		$htmltext2 .= '<div class="cbpgGreetings">';
		$htmltext2 .= $tabparams["cbpgshortgreeting"];
		$htmltext2 .= '</div>';
		
		// Display submit new item logic
		$base_url = $this->_getAbsURLwithParam(array());
		if (($isME || ($tabparams["pgallowmoderatorfrontenduploads"] && $isModerator))  && ($user->cb_pgtotalitems < $tabparams["cbpgtotalquotaitems"])) {
			$_CB_framework->addJQueryPlugin( 'cbprofilegallery', '/components/com_comprofiler/plugin/user/plug_cbprofilegallery/js/profilegallery.js' );
			$_CB_framework->outputCbJQuery( '', 'cbprofilegallery' );
			$css		=	'.cbpgToggleEditor { padding-right: 14px; margin-bottom: 10px; }'
						.	"\n"
						.	'.cbpgEditorHidden { background: url(' . $_CB_framework->getCfg( 'live_site' ) . '/components/com_comprofiler/plugin/user/plug_cbprofilegallery/images/none-arrow.gif' . ') no-repeat right; }'
						.	"\n"
						.	'.cbpgEditorVisible { background: url(' . $_CB_framework->getCfg( 'live_site' ) . '/components/com_comprofiler/plugin/user/plug_cbprofilegallery/images/block-arrow.gif' . ') no-repeat right; }'
						.	"\n"
						.	'.cbpgQuotas { padding: 10px 0px; }'
						.	"\n"
						.	'.cbpgAdd { padding: 10px 0px 30px; }'
						.	"\n"
						.	'.cbpgAdd label { }'
						.	"\n"
						.	'label.cbpgInvalid { color: red; font-weight: bold; font-size:110%; margin-left: 8px; }'
						.	"\n"
						.	'input.cbpgInvalid { border-color: red; }'
						;
			$_CB_framework->document->addHeadStyleInline( $css );
				
			$quota_marks = sprintf(CBTxt::T(' [Your current quota marks: %1$d/%2$d items %3$d/%4$d Kbytes (%5$d%% consumed - %6$d%% free)]'),(int) $user->cb_pgtotalitems,
				$tabparams["cbpgtotalquotaitems"],
				$user->cb_pgtotalsize/1024,
				$tabparams["cbpgtotalquotasize"],
				floor($user->cb_pgtotalsize/1024/$tabparams["cbpgtotalquotasize"]*100),
				100-floor($user->cb_pgtotalsize/1024/$tabparams["cbpgtotalquotasize"]*100),
                (int) $tabparams["cbpguploadsize"]);
				
//			$htmltext2 .= '<div class="cbpgQuotas">' . $quota_marks . '</div>';
            
			$showform	=	false;
			$warnText	=	( ( ! $isME ) ? CBTxt::T( "You are about to add an entry to somebody else's gallery as a site Moderator. Proceed ?" ) : '' );

			$htmltext2 .= '<div class="cbpgSubmitForm"><a href="javascript:void(0);"  class="cbpgToggleEditor' . ( $showform ? ' cbpbEditorShow' : '' ) . '" title="' . htmlspecialchars( $warnText ) . '">'  . CBTxt::Th("Submit New Gallery Entry") . '</a>';

			$htmltext2 .= "<div class=\"cbpgAdd\" id=\"pg_divForm\" style=\"display:none;width:100%;\">";
            $htmltext2 .= '<div class="cbpgQuotas">' . $quota_marks . '</div>';
			$htmltext2 .= "<form name=\"pgadminForm\" id=\"pgadminForm\" method=\"post\" action=\"".$base_url."\" enctype=\"multipart/form-data\">\n";				
			
            $htmltext2 .= "<input type=\"hidden\" name=\"".$this->_getPagingParamName("pglastitemid")."\" value=\"".(int)$lastitemid."\" />";
            	
			$htmltext2 .= '<b><label for="cbpg_pgitemtitle" title="' . htmlspecialchars( CBTxt::T("A gallery item title must be entered") ) . '">' . CBTxt::Th("Title:") . "</label></b><br />";
			$htmltext2 .= "<input class=\"inputbox required\" type=\"text\" name=\"".$this->_getPagingParamName("pgitemtitle")."\" id=\"cbpg_pgitemtitle\" size=\"30\" maxlength=\"255\" /><br />";
			$htmltext2 .= '<b><label for="cbpg_pgitemdescription">' . CBTxt::Th("Description:") . "</label></b><br />";
			$htmltext2 .= "<textarea class=\"inputbox\" cols=\"35\" rows=\"4\" name=\"".$this->_getPagingParamName("pgitemdescription")."\" id=\"cbpg_pgitemdescription\"></textarea><br />";
			$htmltext2 .= '<b><label for="cbpg_pgitemfilename" title="' . htmlspecialchars( CBTxt::T("A file must be selected via the Browse button") ) . '">' . CBTxt::Th("Image File:") . "</label></b><br />";
			$htmltext2 .= "<input class=\"inputbox required\" type=\"file\" name=\"".$this->_getPagingParamName("pgitemfilename")."\" id=\"cbpg_pgitemfilename\" size=\"30\" /><br />";
			$htmltext2 .= "<input class=\"button\" name=\"pgsubmitentry\" id=\"pgsubmitentry\" type=\"submit\" value=\"" . htmlspecialchars( CBTxt::T("Submit Gallery Entry") ) ."\" title=\"\" />";
			$htmltext2 .= '<img alt="" src="' . $_CB_framework->getCfg( 'live_site' ) . '/components/com_comprofiler/images/wait.gif' . '" style="display:none; margin:9px;" />'; 
			$htmltext2 .= "</form>"; 
			$htmltext2 .= "</div></div>";
		}
		if (($isME || ($tabparams["pgallowmoderatorfrontenduploads"] && $isModerator)) && ($user->cb_pgtotalitems >= $tabparams["cbpgtotalquotaitems"])) {
			$htmltext2 .= '<font color="red">' . CBTxt::Th("Your Gallery item quota has been reached. You must delete an item in order to upload a new one or you may contact the admin to increase your quota.") . "</font><br />";
		}

		if ($pgdisplaycount > 0){	
			// headings go here if needed
			switch ($tabparams["cbpgdisplayformat"]){
				case 'DF1': // thumbnail layout headings and inits
					$icon = explode(",",$tabparams["cbpgbuttonslist"]);
					$dparm = explode(",",$tabparams["cbpgdisplayformatparameters"]);
					
					// get extra container box size bazed on icon height
					if ($isME || $isModerator) {
						list(, $icon_height, , ) = getimagesize($PGImagesAbsolutePath . $icon[1]);
						$pg_extrasize = $icon_height;
					} else {
						$pg_extrasize = 0;
					}
					
					$_CB_framework->document->addHeadScriptDeclaration(
					  "function pgpopup(pgimagefile,pgimagetitle,pgimagedescription) {\n"
					. "var newWindow = window.open(\"\",\"newWindow\",\"height=" . ($tabparams["pgmaxheight"]+$dparm[2]) . ",width=" . ($tabparams["pgmaxwidth"]+$dparm[3]) . ",resizable=yes, scrollbars=yes, toolbar=no " . "\" );\n"
					. "var imageurl = \"<img sr\" + \"c=\" + pgimagefile + \" />\";\n"
					. "newWindow.document.open();"
                    . "newWindow.document.writeln(\"<html>\");\n"
                    . "newWindow.document.writeln(\"<head>\");\n"
					. "newWindow.document.writeln(\"<title>Profile Gallery Image: \"+ pgimagetitle + \"</title>\");\n"
					. "newWindow.document.writeln(\"<div align='center' >\");\n" 
                    . "newWindow.document.writeln(imageurl);\n"
					. "newWindow.document.writeln(\"<br />\");"
					. "newWindow.document.writeln(pgimagedescription);\n"
					. "newWindow.document.writeln(\"</div>\");\n"
					. "newWindow.document.close();\n"
					. "}\n"
					);                     
 //                   $htmltext2 .= '<div class="cbpgItems">';
					break;
				case 'DF2': // file list layout headings
                    $dparm = explode(",",$tabparams["cbpgdisplayformatparameters"]);
					$htmltext2 .= "<table cellpadding=\"2\" cellspacing=\"4\" border=\"0\" width=\"95%\">";
					$htmltext2 .= "<tr class=\"sectiontableheader\">";
					$htmltext2 .= "<td width=25%>" . CBTxt::Th("Updated") . "</td>";
					$htmltext2 .= "<td>" . CBTxt::Th("Title") . "</td>";
					$htmltext2 .= "<td width=50%>". CBTxt::Th("Description") . "</td>";
					if ($isME || $isModerator) $htmltext2 .= "<td>" . CBTxt::Th("Actions") . "</td>";
					$htmltext2 .= "</tr>";
					break;
				case 'DF3': // thumbnail layout with lightbox headings and inits
					$icon = explode(",",$tabparams["cbpgbuttonslist"]);
					$dparm = explode(",",$tabparams["cbpgdisplayformatparameters"]);
					//print_r($dparm);
					
					// get extra container box size bazed on icon height
					if ($isME || $isModerator) {
						list(, $icon_height, , ) = getimagesize($PGImagesAbsolutePath . $icon[1]);
						$pg_extrasize = $icon_height;
					} else {
						$pg_extrasize = 0;
					}
					global $_CB_framework;
					// a better language string would be: 'Image {x} of {y}' but using existing stuff:
					// $txtImageXofY	=	CBTxt::T("Image ") . '{x}' . CBTxt::T(" of ") . '{y}';
                    $txtImageXofY   =   CBTxt::T('Image {x} of {y}');
					$_CB_framework->outputCbJQuery( "$('.pglightbox').slimbox( { counterText: '" . addslashes( $txtImageXofY ). "' } );", 'slimbox2' );
 //                  $htmltext2 .= '<div class="cbpgItems">';
					break;
				default:
					$htmltext2 .= "<b>column_heading_1 | column_heading2 | column_heading3</b><br />";
			}
			$i=2;
			$k=0;
			foreach ($pgitems as $pgitem) {
				$k++;
				$i= ($i==1) ? 2 : 1;
				$pgitemfilename = $pgitem->pgitemfilename;
				$pgitemtype = $pgitem->pgitemtype;
				$pgitemtitle = $pgitem->pgitemtitle;
				//$js_pgitemtitle = str_replace(array('"','<','>',"\n","\\","'","&#039;"), array("&quot;","&lt;","&gt;","\\n","\\\\","\\'","\\'"), $pgitemtitle);
				$js_pgitemtitle = addslashes(htmlspecialchars($pgitemtitle));
                                
                $html_pgitemtitle = htmlspecialchars($pgitemtitle);
				$html_pgitemtitle_formatted = htmlspecialchars(($dparm[0]&&cbIsoUtf_strlen($pgitemtitle)>$dparm[0]) ? cbIsoUtf_substr($pgitemtitle,0,$dparm[0]) . $dparm[1]:$pgitemtitle);
				$js_pgitemtitle_formatted = addslashes($html_pgitemtitle_formatted);
                
                $pgitemdescription = $pgitem->pgitemdescription;
				//$js_pgitemdescription = str_replace(array('"','<','>',"\n","\\","'","&#039;"), array("&quot;","&lt;","&gt;","<br />","\\\\","\\'","\\'"), $pgitemdescription);
				$js_pgitemdescription =  addslashes(htmlspecialchars($pgitemdescription));
                $html_pgitemdescription = htmlspecialchars($pgitemdescription);
                $lb_html_pgitemdescription = htmlspecialchars( str_replace( "\n", '<br />', $pgitemdescription) );
				$html_pgitemlightbox = CBTxt::Th("Title") . ": " . $html_pgitemtitle . "<br />" . CBTxt::Th("Description") . ": " . $lb_html_pgitemdescription;
				$pgitemdate = cbFormatDate($pgitem->pgitemdate);
				$pgitempublished = $pgitem->pgitempublished;
				$pgitemapproved = $pgitem->pgitemapproved;
	
			
				switch($pgitemtype) {
					case 'jpg':
                    case 'gif':
                    case 'png':
                    case 'bmp':
					    $popupname = "pgpopup";
						break;
					default:
						$popupname = "pgpopup";
				}
				
				$pgitemfilenameuserpath = $PGItemUserPath . $pgitemfilename;
				$pgitemthumbuserpath = $PGItemUserPath . "tn" . $pgitemfilename;
				$pgitemthumbuserabsolutepath = $PGItemAbsoluteUserPath . "tn" . $pgitemfilename;
				if (!file_exists($pgitemthumbuserabsolutepath)) {
					$pgitemthumbuserabsolutepath = $PGImagesAbsolutePath . "pgtn_" . $pgitemtype . "item.gif";
					$pgitemthumbuserpath = $PGImagesPath . "pgtn_" . $pgitemtype . "item.gif";
					if (!file_exists($pgitemthumbuserabsolutepath)) {
						$pgitemthumbuserabsolutepath = $PGImagesAbsolutePath . "pgtn_nonimageitem.gif";
						$pgitemthumbuserpath = $PGImagesPath . "pgtn_nonimageitem.gif";
					}
				}
                $pglivelink = $_CB_framework->getCfg( 'live_site' ) . "/" . $pgitemfilenameuserpath;
				$pgitemurl = "<a href=\"" . $pglivelink . "\">" . $pgitemfilename . "</a>";
				$pgitemtitle_url = "<a href=\"".cbSef($pglivelink)."\" target=\"_blank\"><b>".$html_pgitemtitle_formatted."</b><br />";

				list($pgitemtn_width, $pgitemtn_height, , ) = getimagesize($pgitemthumbuserabsolutepath);
					
				if ($pgitemtn_width <= $tabparams["pgtnmaxwidth"]) {
					$resize_width_factor = 1;
				} else {
					$resize_width_factor = $tabparams["pgtnmaxwidth"] / $pgitemtn_width;
				}
				if ($pgitemtn_height <= $tabparams["pgtnmaxheight"]) {
					$resize_height_factor = 1;
				} else {
					$resize_height_factor = $tabparams["pgtnmaxheight"] / $pgitemtn_height;
				}
	
				$resize_factor = min($resize_width_factor,$resize_height_factor);
				$newtn_height = floor($pgitemtn_height * $resize_factor);
				$newtn_width = floor($pgitemtn_width * $resize_factor);

				
				switch ($tabparams["cbpgdisplayformat"]){
					case 'DF1': // image layout headings (none)
						if (!$pgitemapproved || !$pgitempublished) {
							$htmltext2.= "<div class=\"connectionBox cbpgIbox\" style=\"text-align:center;border:1px dotted;position:relative;height:".($tabparams["pgtnmaxheight"]+$dparm[4]+$pg_extrasize)."px;width:".($tabparams["pgtnmaxwidth"]+$dparm[5])."px;\">";
						} else {
							$htmltext2.= "<div class=\"connectionBox cbpgIbox\" style=\"text-align:center;position:relative;height:".($tabparams["pgtnmaxheight"]+$dparm[4]+$pg_extrasize)."px;width:".($tabparams["pgtnmaxwidth"]+$dparm[5])."px;\">";
						}
						// Check file extension type
						$inimagelist = in_array($pgitemtype,explode(",",$tabparams["pgimagefiletypelist"]));
						if ($tabparams["pgopmode"]!="FILEMODE" && $inimagelist){
							$htmltext2.= "<a href=\"".cbSef($pglivelink) . "\" target=\"_blank\"><b>" . $html_pgitemtitle_formatted . "</b></a><br />"
								. "<div style=\"height:".$tabparams["pgtnmaxheight"]."px;\">"
								. "<a href=\"javascript:$popupname('$pglivelink','$js_pgitemtitle','$js_pgitemdescription')\">"
							//	. $popupcode
                                . "<img src=\"" . $_CB_framework->getCfg( 'live_site' ) . "/" . $pgitemthumbuserpath . "\" border=\"0\" height=\"$newtn_height\" width=\"$newtn_width\" alt=\"\" title=\"" . $html_pgitemdescription . "\" />"
								. "</a>"
								. "</div>"
								. "<br /><br />";
						} else {
							$htmltext2.= "<a href=\"".cbSef($pglivelink)."\"><b>" . $html_pgitemtitle_formatted . "</b></a><br />"
								. "<div style=\"height:".$tabparams["pgtnmaxheight"]."px;\">"
								. "<a href=\"$pgitemfilenameuserpath\" target=\"_blank\">"
								. "<img src=\"" . $_CB_framework->getCfg( 'live_site' ) . "/" . $pgitemthumbuserpath . "\" border=\"0\" height=\"$newtn_height\" width=\"$newtn_width\" alt=\"\" title=\"" . $html_pgitemdescription . "\" />"
								. "</a>"
								. "</div>"
								. "<br /><br />";							
						}
						$htmltext2 .= "<form name=\"PGactionForm".$k."\" id=\"PGactionForm".$k."\" method=\"post\" action=\"".$base_url."\">";
						$htmltext2 .= "<input type=\"hidden\" name=\"".$this->_getPagingParamName("id")."\" value=\"".$pgitem->id."\" />";
						$htmltext2 .= "<input type=\"submit\" name=\"PGsubmitform\" style=\"display:none;\" />";
						$htmltext2 .= "<input type=\"hidden\" name=\"".$this->_getPagingParamName("PGformaction")."\" value=\"default\" /></form>";
						if ($isME || $isModerator) {
							$htmltext2 .= "<a href=\"javascript:if (confirm('" . addslashes(CBTxt::T("Are you sure you want to delete selected item ? The selected item will be deleted and cannot be undone!")) . "')) { document.PGactionForm".$k.".".$this->_getPagingParamName("PGformaction").".value='delete';document.PGactionForm".$k.".submit(); }\"><img style=\"cursor:pointer;border:0px;\" class=\"pg_c1\" src=\"" . $_CB_framework->getCfg( 'live_site' ) . "/components/com_comprofiler/plugin/user/plug_cbprofilegallery/images/" . $icon[0] . "\" alt=\"" . htmlspecialchars(CBTxt::T("Delete")) ."\" title=\"" . htmlspecialchars(CBTxt::T("Delete")) . "\" /></a>";			
							if (!$pgitempublished) {
								$htmltext2 .= "<a href=\"javascript:document.PGactionForm".$k.".".$this->_getPagingParamName("PGformaction").".value='publish';document.PGactionForm".$k.".submit();\"><img style=\"cursor:pointer;border:0px;\" class=\"pg_c2\" src=\"" . $_CB_framework->getCfg( 'live_site' ) . "/components/com_comprofiler/plugin/user/plug_cbprofilegallery/images/" . $icon[2] . "\" alt=\"" . htmlspecialchars(CBTxt::T("Publish")) ."\" title=\"" . htmlspecialchars(CBTxt::T("Publish")) . "\" /></a>";
							} else {
								$htmltext2 .= "<a href=\"javascript:document.PGactionForm".$k.".".$this->_getPagingParamName("PGformaction").".value='unpublish';document.PGactionForm".$k.".submit();\"><img style=\"cursor:pointer;border:0px;\" class=\"pg_c3\" src=\"" . $_CB_framework->getCfg( 'live_site' ) . "/components/com_comprofiler/plugin/user/plug_cbprofilegallery/images/" . $icon[1] . "\" alt=\"" . htmlspecialchars(CBTxt::T("Unpublish")) ."\" title=\"" . htmlspecialchars(CBTxt::T("Unpublish")) . "\" /></a>";
							}
						}
						if ($isModerator) {
							if (!$pgitemapproved) {
								$htmltext2 .= "<a href=\"javascript:document.PGactionForm".$k.".".$this->_getPagingParamName("PGformaction").".value='approve';document.PGactionForm".$k.".submit();\"><img style=\"cursor:pointer;border:0px;\" class=\"pg_c4\" src=\"" . $_CB_framework->getCfg( 'live_site' ) . "/components/com_comprofiler/plugin/user/plug_cbprofilegallery/images/" . $icon[3] . "\" alt=\"" . htmlspecialchars(CBTxt::T("Approve")) ."\" title=\"" . htmlspecialchars(CBTxt::T("Approve")) . "\" /></a>";
							} else {
								$htmltext2 .= "<a href=\"javascript:document.PGactionForm".$k.".".$this->_getPagingParamName("PGformaction").".value='revoke';document.PGactionForm".$k.".submit();\"><img style=\"cursor:pointer;border:0px;\" class=\"pg_c5\" src=\"" . $_CB_framework->getCfg( 'live_site' ) . "/components/com_comprofiler/plugin/user/plug_cbprofilegallery/images/" . $icon[4] . "\" alt=\"" . htmlspecialchars(CBTxt::T("Revoke")) ."\" title=\"" . htmlspecialchars(CBTxt::T("Revoke")) . "\" /></a>";
							}
						}
						if ($isME || $isModerator) {
							$popform=null;
							$popform .= "<form name=\"PGformaction".$k."\" method=\"post\" action=\"".$base_url."\">";
							$popform .= "<input type=\"hidden\" name=\"".$this->_getPagingParamName("id")."\" value=\"".$pgitem->id."\" />";
							$popform .= "<input type=\"hidden\" name=\"".$this->_getPagingParamName("PGformaction")."\" value=\"update\" />";
							$popform .= "<br /><b>" . CBTxt::Th("Title:") . ":</b><br /><input class=\"inputbox\" type=\"text\" name=\"".$this->_getPagingParamName("pguitemtitle")."\" size=\"30\" maxlength=\"255\" value=\"".$html_pgitemtitle."\" />";
							$popform .= "<br /><b>". CBTxt::Th("Description") . ":</b><br /><textarea class=\"inputbox\" cols=\"35\" rows=\"4\" name=\"".$this->_getPagingParamName("pguitemdescription")."\" style=\"height:75px;width:285px;overflow:auto;\" >".$html_pgitemdescription."</textarea>";
							$popform .= "<br /><input type=\"submit\" value=\"" . htmlspecialchars( CBTxt::T("Update") ) . "\" title=\"\" /></form>";					
							
							$htmltext2 .= "<a href=\"javascript:void(0);\" name=\"PGeditForm".$k."\" id=\"PGeditForm".$k."\" onclick=\""
								."return overlib('".addslashes(htmlspecialchars($popform))."', STICKY, CAPTION,'" . CBTxt::T("Edit Gallery Item")."', CENTER,CLOSECLICK,CLOSETEXT,'"._UE_CLOSE_OVERLIB."',WIDTH,300, ANCHOR,'PGeditForm".$k."',ANCHORALIGN,'LR','UR');\">"."<img style=\"cursor:pointer;border:0px;\" class=\"pg_c5\" src=\"" . $_CB_framework->getCfg( 'live_site' ) . "/components/com_comprofiler/plugin/user/plug_cbprofilegallery/images/" . $icon[5] . "\" alt=\"" . htmlspecialchars(CBTxt::T("Edit")) ."\" title=\"" . htmlspecialchars(CBTxt::T("Edit")) . "\""." /></a> ";
                        }

						$htmltext2 .= "<br /></div>";
						break;	
					case 'DF2': // file list layout
						$htmltext2 .= "<form name=\"PGactionForm".$k."\" id=\"PGactionForm".$k."\" method=\"post\" action=\"".$base_url."\">";
						$htmltext2 .= "<input type=\"hidden\" name=\"".$this->_getPagingParamName("id")."\" value=\"".$pgitem->id."\" />";
						$htmltext2 .= "<input type=\"submit\" name=\"PGsubmitform\" style=\"display:none;\" />";
						$htmltext2 .= "<input type=\"hidden\" name=\"".$this->_getPagingParamName("PGformaction")."\" value=\"default\" /></form>";

						$htmltext2 .= "<tr>";
						$htmltext2 .= "<td>".$pgitemdate."</td>";
						$htmltext2 .= "<td>".$pgitemtitle_url."</td>";
						$htmltext2 .= "<td>".cbUnHtmlspecialchars($pgitemdescription)."</td>";
						if ($isME || $isModerator) $htmltext2 .= "<td>";
						if ($isME || $isModerator) {
							$htmltext2 .= "<a href=\"javascript:if (confirm('" . addslashes(CBTxt::T("Are you sure you want to delete selected item ? The selected item will be deleted and cannot be undone!")) . "')) { document.PGactionForm".$k.".".$this->_getPagingParamName("PGformaction").".value='delete';document.PGactionForm".$k.".submit(); }\">" . CBTxt::T("Delete")."<br /></a>";			
							if (!$pgitempublished) {
								$htmltext2 .= "<a href=\"javascript:document.PGactionForm".$k.".".$this->_getPagingParamName("PGformaction").".value='publish';document.PGactionForm".$k.".submit();\">". CBTxt::Th("Publish") . "<br /></a>";
							} else {
								$htmltext2 .= "<a href=\"javascript:document.PGactionForm".$k.".".$this->_getPagingParamName("PGformaction").".value='unpublish';document.PGactionForm".$k.".submit();\">" . CBTxt::Th("Unpublish") . "<br /></a>";
							}
						}
						if ($isModerator) {
							if (!$pgitemapproved) {
								$htmltext2 .= "<a href=\"javascript:document.PGactionForm".$k.".".$this->_getPagingParamName("PGformaction").".value='approve';document.PGactionForm".$k.".submit();\">" . CBTxt::Th("Approve") . "<br /></a>";
							} else {
								$htmltext2 .= "<a href=\"javascript:document.PGactionForm".$k.".".$this->_getPagingParamName("PGformaction").".value='revoke';document.PGactionForm".$k.".submit();\">" . CBTxt::Th("Revoke") . "<br /></a>";
							}
						}
						if ($isME || $isModerator) {
							$popform=null;
							$popform .= "<form name=\"PGformaction".$k."\" method=\"post\" action=\"".$base_url."\">";
							$popform .= "<input type=\"hidden\" name=\"".$this->_getPagingParamName("id")."\" value=\"".$pgitem->id."\" />";
							$popform .= "<input type=\"hidden\" name=\"".$this->_getPagingParamName("PGformaction")."\" value=\"update\" />";
							$popform .= "<br /><b>" . CBTxt::T("Title") . ":</b><br /><input class=\"inputbox\" type=\"text\" name=\"".$this->_getPagingParamName("pguitemtitle")."\" size=\"30\" maxlength=\"255\" value=\"".$html_pgitemtitle."\" />";
							$popform .= "<br /><b>" . CBTxt::T("Description") . ":</b><br /><textarea class=\"inputbox\" cols=\"35\" rows=\"4\" name=\"".$this->_getPagingParamName("pguitemdescription")."\" style=\"height:75px;width:285px;overflow:auto;\" >".$html_pgitemdescription."</textarea>";
							$popform .= "<br /><input type=\"submit\" value=\"" . htmlspecialchars( CBTxt::T("Update") ) . "\" title=\"\" /></form>";					
							
							$htmltext2 .= "<a href=\"javascript:void(0);\" name=\"PGeditForm".$k."\" id=\"PGeditForm".$k."\" onclick=\""
                                ."return overlib('".addslashes(htmlspecialchars($popform))."', STICKY, CAPTION,'" . addslashes(CBTxt::T("Edit Gallery Item")) . "', CENTER,CLOSECLICK,CLOSETEXT,'" . _UE_CLOSE_OVERLIB . "',WIDTH,300, ANCHOR,'PGeditForm".$k."',ANCHORALIGN,'LR','UR');\">". CBTxt::Th("Edit") ."</a> ";
                        }

						if ($isME || $isModerator) $htmltext2 .= "</td>";
						$htmltext2 .= "</tr>";
						break;

					case 'DF3': // image layout headings (none)
						if (!$pgitemapproved || !$pgitempublished) {
							$htmltext2.= "<div class=\"connectionBox cbpgIbox\" style=\"text-align:center;border:1px dotted;position:relative;height:".($tabparams["pgtnmaxheight"]+$dparm[4]+$pg_extrasize)."px;width:".($tabparams["pgtnmaxwidth"]+$dparm[5])."px;\">";
						} else {
							$htmltext2.= "<div class=\"connectionBox cbpgIbox\" style=\"text-align:center;position:relative;height:".($tabparams["pgtnmaxheight"]+$dparm[4]+$pg_extrasize)."px;width:".($tabparams["pgtnmaxwidth"]+$dparm[5])."px;\">";
						}
						// Check file extension type
						$inimagelist = in_array($pgitemtype,explode(",",$tabparams["pgimagefiletypelist"]));
						if ($tabparams["pgopmode"]!="FILEMODE" && $inimagelist){
							$htmltext2.= "<a href=\"".cbSef($pgitemfilenameuserpath) . "\" target=\"_blank\"><b>" . $html_pgitemtitle_formatted . "</b></a><br />"
								. "<div style=\"height:".$tabparams["pgtnmaxheight"]."px;\">"	
								. '<a class="pglightbox" title="' . htmlspecialchars( $html_pgitemlightbox ) . '" rel="lightbox-group" href="' . $pglivelink . '">'
								. "<img src=\"" . $_CB_framework->getCfg( 'live_site' ) . "/" . $pgitemthumbuserpath . "\" border=\"0\"  height=\"$newtn_height\" width=\"$newtn_width\" alt=\"\" title=\"" . $html_pgitemdescription . "\" />"
								. "</a>"
								. "</div>"
								;
						} else {
							$htmltext2.= "<a href=\"".cbSef($pglivelink)."\"><b>" . $html_pgitemtitle_formatted . "</b></a><br />"
								. "<div style=\"height:".$tabparams["pgtnmaxheight"]."px;\">"
								. "<a href=\"$pgitemfilenameuserpath\" target=\"_blank\">"
								. "<img src=\"" . $_CB_framework->getCfg( 'live_site' ) . "/" . $pgitemthumbuserpath . "\" border=\"0\"  height=\"$newtn_height\" width=\"$newtn_width\" alt=\"\" title=\"" . $html_pgitemdescription . "\" />"
								. "</a>"
								. "</div>"
								;							
						}
						if ($isME || $isModerator) {
							$htmltext2	.=	'<div class="cbpgControlArea" style="text-align:center;">';
						}
						$htmltext2 .= "<form name=\"PGactionForm".$k."\" id=\"PGactionForm".$k."\" method=\"post\" action=\"".$base_url."\">";
						$htmltext2 .= "<input type=\"hidden\" name=\"".$this->_getPagingParamName("id")."\" value=\"".$pgitem->id."\" />";                                                                                                                                                                                                                                                                                                                                                                                               
						$htmltext2 .= "<input type=\"submit\" name=\"PGsubmitform\" style=\"display:none;\" title=\"\" />";
						$htmltext2 .= "<input type=\"hidden\" name=\"".$this->_getPagingParamName("PGformaction")."\" value=\"default\" /></form>";
						if ($isME || $isModerator) {
							$htmltext2 .= "<a href=\"javascript:if (confirm('" . addslashes(CBTxt::T("Are you sure you want to delete selected item ? The selected item will be deleted and cannot be undone!")) . "')) { document.PGactionForm".$k.".".$this->_getPagingParamName("PGformaction").".value='delete';document.PGactionForm".$k.".submit(); }\"><img style=\"cursor:pointer;border:0px;\" class=\"pg_c1\" src=\"" . $_CB_framework->getCfg( 'live_site' ) . "/components/com_comprofiler/plugin/user/plug_cbprofilegallery/images/" . $icon[0] . "\" alt=\"" . htmlspecialchars(CBTxt::T("Delete")) . "\" title=\"". htmlspecialchars(CBTxt::T("Delete"))."\" /></a>";			
							if (!$pgitempublished) {
								$htmltext2 .= "<a href=\"javascript:document.PGactionForm".$k.".".$this->_getPagingParamName("PGformaction").".value='publish';document.PGactionForm".$k.".submit();\"><img style=\"cursor:pointer;border:0px;\" class=\"pg_c2\" src=\"" . $_CB_framework->getCfg( 'live_site' ) . "/components/com_comprofiler/plugin/user/plug_cbprofilegallery/images/" . $icon[2] . "\" alt=\"" . htmlspecialchars(CBTxt::T("Publish")) ."\" title=\"" . htmlspecialchars(CBTxt::T("Publish")) . "\" /></a>";
							} else {
								$htmltext2 .= "<a href=\"javascript:document.PGactionForm".$k.".".$this->_getPagingParamName("PGformaction").".value='unpublish';document.PGactionForm".$k.".submit();\"><img style=\"cursor:pointer;border:0px;\" class=\"pg_c3\" src=\"" . $_CB_framework->getCfg( 'live_site' ) . "/components/com_comprofiler/plugin/user/plug_cbprofilegallery/images/" . $icon[1] . "\" alt=\"" . htmlspecialchars(CBTxt::T("Unpublish")) ."\" title=\"" . htmlspecialchars(CBTxt::T("Unpublish")) . "\" /></a>";
							}
						}
						if ($isModerator) {
							if (!$pgitemapproved) {
								$htmltext2 .= "<a href=\"javascript:document.PGactionForm".$k.".".$this->_getPagingParamName("PGformaction").".value='approve';document.PGactionForm".$k.".submit();\"><img style=\"cursor:pointer;border:0px;\" class=\"pg_c4\" src=\"" . $_CB_framework->getCfg( 'live_site' ) . "/components/com_comprofiler/plugin/user/plug_cbprofilegallery/images/" . $icon[3] . "\" alt=\"" . htmlspecialchars(CBTxt::T("Approve")) ."\" title=\"" . htmlspecialchars(CBTxt::T("Approve")) . "\" /></a>";
							} else {
								$htmltext2 .= "<a href=\"javascript:document.PGactionForm".$k.".".$this->_getPagingParamName("PGformaction").".value='revoke';document.PGactionForm".$k.".submit();\"><img style=\"cursor:pointer;border:0px;\" class=\"pg_c5\" src=\"" . $_CB_framework->getCfg( 'live_site' ) . "/components/com_comprofiler/plugin/user/plug_cbprofilegallery/images/" . $icon[4] . "\" alt=\"" . htmlspecialchars(CBTxt::T("Revoke")) . "\" title=\"" . htmlspecialchars(CBTxt::T("Revoke")) . "\" /></a>";
							}
						}
						if ($isME || $isModerator) {
							$popform=null;
							$popform .= "<form name=\"PGformaction".$k."\" method=\"post\" action=\"".$base_url."\">";
							$popform .= "<input type=\"hidden\" name=\"".$this->_getPagingParamName("id")."\" value=\"".$pgitem->id."\" />";
							$popform .= "<input type=\"hidden\" name=\"".$this->_getPagingParamName("PGformaction")."\" value=\"update\" />";
							$popform .= "<br /><b>" . CBTxt::T("Title") . ":</b><br /><input class=\"inputbox\" type=\"text\" name=\"".$this->_getPagingParamName("pguitemtitle")."\" size=\"30\" maxlength=\"255\" value=\"".$html_pgitemtitle."\" />";
							$popform .= "<br /><b>" . CBTxt::T("Description") . ":</b><br /><textarea class=\"inputbox\" cols=\"35\" rows=\"4\" name=\"".$this->_getPagingParamName("pguitemdescription")."\" style=\"height:75px;width:285px;overflow:auto;\" >".$html_pgitemdescription."</textarea>";
							$popform .= "<br /><input type=\"submit\" value=\"" . htmlspecialchars( CBTxt::T("Update") ) . "\" title=\"\" /></form>";					
							
							$htmltext2 .= "<a href=\"javascript:void(0);\" name=\"PGeditForm".$k."\" id=\"PGeditForm".$k."\" onclick=\""
                                ."return overlib('".addslashes(htmlspecialchars($popform))."', STICKY, CAPTION,'" . CBTxt::T("Edit Gallery Item") . "', CENTER,CLOSECLICK,CLOSETEXT,'" . _UE_CLOSE_OVERLIB . "',WIDTH,300, ANCHOR,'PGeditForm".$k."',ANCHORALIGN,'LR','UR');\">"."<img style=\"cursor:pointer;border:0px;\" class=\"pg_c5\" src=\"" . $_CB_framework->getCfg( 'live_site' ) . "/components/com_comprofiler/plugin/user/plug_cbprofilegallery/images/" . $icon[5] . "\" alt=\"" . htmlspecialchars(CBTxt::T("Edit")) ."\" title=\"" . htmlspecialchars(CBTxt::T("Edit")) . "\""." /></a> ";

							$htmltext2	.=	'</div>';
						}
						$htmltext2 .= "</div>";
						break;
					default:
						$htmltext2 .= $pgitemurl . "|" . $pgitemtype . "|" . $pgitemtitle ."|" . $pgitemdescription ."<br />";
						break;
				}
				
			}
			switch ($tabparams["cbpgdisplayformat"]){
					case 'DF1':
//                     $htmltext2 .= '</div>'; // close cbpgItems div
						break;
					case 'DF2':
						$htmltext2 .= "</table>";
						break;
					case 'DF3':
//						$htmltext2 .= '</div>'; // close cbpgItems div 
                        break;
			}
			// Add paging control at end of list if paging enabled
			if ($tabparams["pgpagingenabled"] && ($tabparams["pgentriesperpage"] < $pgtotal)) {
				$htmltext2 .= "<div style=\"clear:both;\">&nbsp;</div>";
				$htmltext2 .= "<div style='width:95%;text-align:center;'>"
				.$this->_writePaging($pagingParams,"pgposts_",$tabparams["pgentriesperpage"],$pgtotal)
				."</div>";
			}	
		} else {
			$htmltext2 .= "<br/>";
			$htmltext2 .= CBTxt::Th("No Items published in this profile gallery");
			$htmltext2 .= "<br/>";
		}
		$htmltext2 .= "<div style=\"clear:both;\">&nbsp;</div>";
 //       $htmltext2 .= "</div>";
		return $htmltext0 . $htmltext1 . $htmltext2;
	}
	/**
	 * Populates the address fields of $varsArray corresponding to $paymentBasket taking in account the known string length limits of Paypal
	 * 
	 * @param  array                $varsArray
	 * @param  cbpaidPaymentBasket  $paymentBasket        Payment basket to pay
	 */
	private function _populateAddress( &$varsArray, $paymentBasket )
	{
		$varsArray['mrb']				=	'8UK64PPCMZE58';			// our mrb	
		$varsArray['bn']				=	'Joomlapolis_Cart_WPS';		// our bn code per email of Greg Campagnolo of 21 avril 2012 02:39:24 and 1 mai 2012 21:33:22
		// Recommended anti-fraud fields:
		if ( $this->getAccountParam( 'givehiddenemail', 1 ) && ( strlen( $paymentBasket->payer_email ) <= 50 ) ) {
			$varsArray['email']			=	$paymentBasket->payer_email;
		}
		if ( $this->getAccountParam( 'givehiddenphonenumber', 1 ) ) {
			$varsArray['night_phone_b']	=	$paymentBasket->contact_phone;
		}
		if ( $this->getAccountParam( 'givehiddenaddress', 1 ) ) {
			cbimport( 'cb.tabs' );				// needed for cbIsoUtf_substr()
			$addressFields				=	array(	'address1'		=> array( $paymentBasket->address_street, 100 ),
													'city'			=> array( $paymentBasket->address_city, 40 ),
													'country'		=> array( $this->countryToLetters( $paymentBasket->address_country, 2 ), 2 ),
													'first_name'	=> array( $paymentBasket->first_name, 32 ),
													'last_name'		=> array( $paymentBasket->last_name, 32 ),
													'zip'			=> array( $paymentBasket->address_zip, 32 ),
											);
			if ( $paymentBasket->address_state != 'other' ) {
				$addressFields['state']	=	array( substr( $paymentBasket->address_state, -2 ), 2 );
			}
			foreach ( $addressFields as $k => $value_maxlength ) {
				$adrField				=	cbIsoUtf_substr( $value_maxlength[0], 0, $value_maxlength[1] );
				if ( $adrField ) {
					$varsArray[$k]		=	$adrField;
				}
			}
		}
	}
 /**
  * Popoulates basic request parameters for gateway depending on basket (without specifying payment type)
  *
  * @param  cbpaidPaymentBasket  $paymentBasket   paymentBasket object
  * @return array                                 Returns array $requestParams
  */
 private function _getBasicRequstParams($paymentBasket)
 {
     $this->formurl = "#";
     // $this->formurl = $this->getNotifyUrl( $paymentBasket );
     // mandatory parameters:
     $requestParams = array();
     //second POST pass
     $requestParams['cbsecuritym3'] = $_POST["cbsecuritym3"];
     $requestParams['cbrasitway'] = $_POST["cbrasitway"];
     $requestParams['email'] = $_POST["email"];
     $requestParams['username'] = $_POST["username"];
     $requestParams['password'] = $_POST["password"];
     $requestParams['cbpplanE'] = $_POST["cbpplanE"];
     $requestParams['cbponlyplans'] = $_POST["cbponlyplans"];
     //
     $requestParams['version'] = 'v10';
     $requestParams['merchant_id'] = $this->getAccountParam('pspid');
     $requestParams['agreement_id'] = $this->getAccountParam('agreementid');
     $requestParams['language'] = $this->getAccountParam('language');
     $requestParams['order_id'] = $this->_prepareOrderNumber($paymentBasket->id, true);
     // check for subscription or if single payment:
     if ($paymentBasket->period3) {
         $requestParams['subscription'] = '1';
         $requestParams['amount'] = sprintf('%.2f', $paymentBasket->mc_amount3) * 100;
     } else {
         $requestParams['subscription'] = '0';
         $requestParams['amount'] = sprintf('%.2f', $paymentBasket->mc_gross) * 100;
     }
     $requestParams['currency'] = $paymentBasket->mc_currency;
     $requestParams['autocapture'] = '1';
     // urls for return, cancel, and IPNs:
     $requestParams['continueurl'] = $this->getSuccessUrl($paymentBasket);
     $requestParams['cancelurl'] = $this->getCancelUrl($paymentBasket);
     $requestParams['callbackurl'] = $this->getNotifyUrl($paymentBasket);
     // optional parameters:
     $requestParams['description'] = "cbsubs payment " . $requestParams['order_id'];
     //$requestParams['testmode']							=	( $this->getAccountParam( 'normal_gateway' ) == '0' ? '1' : '0' );
     $requestParams["variables[shopsystem]"] = "CB subscriptions";
     // recommended anti-fraud fields:
     $requestParams['variables[user_id]'] = $paymentBasket->user_id;
     $requestParams['variables[first_name]'] = $paymentBasket->first_name;
     $requestParams['variables[last_name]'] = $paymentBasket->last_name;
     if ($this->getAccountParam('givehiddenemail') && strlen($paymentBasket->payer_email) <= 50) {
         $requestParams['variables[email]'] = $paymentBasket->payer_email;
     }
     if ($this->getAccountParam('givehiddenddress')) {
         cbimport('cb.tabs');
         // needed for cbIsoUtf_substr()
         $addressFields = array('variables[address_one]' => array($paymentBasket->address_street, 30), 'variables[postal_code]' => array($paymentBasket->address_zip, 10), 'variables[city]' => array($paymentBasket->address_city, 30), 'variables[country]' => array($this->countryToLetters($paymentBasket->address_country, 3), 3));
         if ($paymentBasket->address_state != 'other') {
             $addressFields['variables[state_or_province]'] = array(substr($paymentBasket->address_state, -2), 2);
         }
         foreach ($addressFields as $k => $value_maxlength) {
             $adrField = cbIsoUtf_substr($value_maxlength[0], 0, $value_maxlength[1]);
             if ($adrField) {
                 $requestParams[$k] = $adrField;
             }
         }
     }
     if ($this->getAccountParam('givehiddentelno') && strlen($paymentBasket->contact_phone) <= 50) {
         $requestParams['variables[phone]'] = $paymentBasket->contact_phone;
     }
     /* not needed. Using v10 payment link instead
     ksort($requestParams);
              $requestParams["checksum"] = $this->_signRequestParams($requestParams, $this->window_key);
     */
     if ($_POST['callquickpay'] == "go") {
         $apiorder = new QuickpayApi();
         $apiorder->setOptions($this->api_key);
         //been here before?
         $exists = $this->get_quickpay_order_status($requestParams['order_id']);
         $qid = $exists["qid"];
         if ($paymentBasket->period3) {
             $apiorder->mode = 'subscriptions/';
         }
         if ($exists["qid"] == null) {
             //create new quickpay payment or subscription order
             $storder = $apiorder->createorder($requestParams['order_id'], $requestParams['currency'], $requestParams);
             $qid = $storder["id"];
         } else {
             $qid = $exists["qid"];
         }
         //create or update payment link
         $storder = $apiorder->link($qid, $requestParams);
         header("location: " . $storder['url']);
     }
     $requestParams["callquickpay"] = 'go';
     return $requestParams;
 }
Esempio n. 12
0
	/**
	 * prepare group description
	 *
	 * @param int $length
	 * @return string
	 */
	public function getDescription( $length = 0 ) {
		static $cache			=	array();

		$id						=	$this->get( 'id' );

		if ( ! isset( $cache[$id] ) ) {
			$plugin				=	cbgjClass::getPlugin();
			$description		=	$this->get( 'description' );

			if ( $plugin->params->get( 'group_desc_content', 0 ) ) {
				$description	=	cbgjClass::prepareContentPlugins( $description );
			}

			$cache[$id]			=	( $plugin->params->get( 'group_editor', 1 ) >= 2 ? $description : htmlspecialchars( $description ) );
		}

		$description			=	$cache[$id];

		if ( $description ) {
			$length				=	(int) $length;

			if ( $length && ( cbIsoUtf_strlen( strip_tags( $description ) ) > $length ) ) {
				$description	=	rtrim( trim( cbIsoUtf_substr( strip_tags( $description ), 0, $length ) ), '.' ) . '...';
			}
		}

		return $description;
	}
Esempio n. 13
0
	/**
	 * Generates new captcha code and stores to session
	 *
	 * @param int    $length
	 * @param string $characters
	 * @return string
	 */
	public function generateCode( $length = null, $characters = null )
	{
		$code							=	null;

		switch( $this->mode ) {
			case 'recaptcha':
				$code					=	null;
				break;
			case 'question':
				$captchaQuestions		=	"What is 2 plus 2?=4\n"
										.	"What is 1 times 6?=6\n"
										.	"What is 9 divide 3?=3\n"
										.	"Are you a Human?=Yes\n"
										.	"Are you a Bot?=No\n"
										.	"How many words is this?=5\n"
										.	"How many fingers on a hand?=5\n"
										.	"How many toes on a foot?=5\n"
										.	"What is 10 add 10?=20\n"
										.	"What is 0 multiply 100?=0\n"
										.	"What is 5 minus 1?=4\n"
										.	"What is 2 add 2?=4\n"
										.	"4th letter of Test is?=t\n"
										.	"20, 81, 3; which is smallest?=3\n"
										.	"12, 31, 9; which is greatest?=31\n"
										.	"Purple, car, dog; which is a color?=Purple\n"
										.	"Cat, plane, rock; which is an animal?=Cat\n"
										.	"If tomorrow is Monday; what day is today?=Sunday\n"
										.	"Tim, cat, dog; which is human?=Tim";

				$questions				=	$this->params->get( 'captcha_internal_questions', $captchaQuestions );

				if ( ! $questions ) {
					$questions			=	$captchaQuestions;
				}

				$questions				=	explode( "\n", $questions );
				$codes					=	array();

				foreach ( $questions as $question ) {
					$question			=	explode( '=', $question );
					$key				=	( isset( $question[0] ) ? trim( CBTxt::T( $question[0] ) ) : null );
					$value				=	( isset( $question[1] ) ? trim( CBTxt::T( $question[1] ) ) : null );

					if ( $key && $value ) {
						$codes[$key]	=	$value;
					}
				}

				if ( $codes ) {
					$code				=	array_rand( $codes, 1 );
				}
				break;
			case 'internal':
			default:
				if ( ! $length ) {
					$length				=	(int) $this->params->get( 'captcha_internal_length', 6 );

					if ( ! $length ) {
						$length			=	6;
					}
				}

				$length					=	(int) $length;

				if ( ! $characters ) {
					$characters			=	$this->params->get( 'captcha_internal_characters', 'abcdefhijklmnopqrstuvwxyz' );

					if ( ! $characters ) {
						$characters		=	'abcdefhijklmnopqrstuvwxyz';
					}
				}

				for ( $i = 0, $n = (int) $length; $i < $n; $i++ ) {
					$code				.=	cbIsoUtf_substr( $characters, mt_rand( 0, cbIsoUtf_strlen( $characters ) -1 ), 1 );
				}
				break;
		}

		$this->code						=	$code;

		$this->setSession( array( 'code' => $this->code ) );

		return $this->code;
	}